ulaw.c 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * Asterisk -- A telephony toolkit for Linux.
  3. *
  4. * u-Law to Signed linear conversion
  5. *
  6. * Copyright (C) 1999, Mark Spencer
  7. *
  8. * Mark Spencer <markster@linux-support.net>
  9. *
  10. * This program is free software, distributed under the terms of
  11. * the GNU General Public License
  12. */
  13. #include <asterisk/ulaw.h>
  14. #define ZEROTRAP /* turn on the trap as per the MIL-STD */
  15. #define BIAS 0x84 /* define the add-in bias for 16 bit samples */
  16. #define CLIP 32635
  17. unsigned char __ast_lin2mu[16384];
  18. short __ast_mulaw[256];
  19. static unsigned char
  20. linear2ulaw(short sample)
  21. {
  22. static int exp_lut[256] = {0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,
  23. 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
  24. 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
  25. 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
  26. 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
  27. 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
  28. 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
  29. 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
  30. 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
  31. 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
  32. 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
  33. 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
  34. 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
  35. 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
  36. 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
  37. 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7};
  38. int sign, exponent, mantissa;
  39. unsigned char ulawbyte;
  40. /* Get the sample into sign-magnitude. */
  41. sign = (sample >> 8) & 0x80; /* set aside the sign */
  42. if (sign != 0) sample = -sample; /* get magnitude */
  43. if (sample > CLIP) sample = CLIP; /* clip the magnitude */
  44. /* Convert from 16 bit linear to ulaw. */
  45. sample = sample + BIAS;
  46. exponent = exp_lut[(sample >> 7) & 0xFF];
  47. mantissa = (sample >> (exponent + 3)) & 0x0F;
  48. ulawbyte = ~(sign | (exponent << 4) | mantissa);
  49. #ifdef ZEROTRAP
  50. if (ulawbyte == 0) ulawbyte = 0x02; /* optional CCITT trap */
  51. #endif
  52. return(ulawbyte);
  53. }
  54. void ast_ulaw_init(void)
  55. {
  56. int i;
  57. /*
  58. * Set up mu-law conversion table
  59. */
  60. for(i = 0;i < 256;i++)
  61. {
  62. short mu,e,f,y;
  63. static short etab[]={0,132,396,924,1980,4092,8316,16764};
  64. mu = 255-i;
  65. e = (mu & 0x70)/16;
  66. f = mu & 0x0f;
  67. y = f * (1 << (e + 3));
  68. y += etab[e];
  69. if (mu & 0x80) y = -y;
  70. __ast_mulaw[i] = y;
  71. }
  72. /* set up the reverse (mu-law) conversion table */
  73. for(i = -32768; i < 32768; i++)
  74. {
  75. __ast_lin2mu[((unsigned short)i) >> 2] = linear2ulaw(i);
  76. }
  77. }