alaw.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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/alaw.h>
  14. #define AMI_MASK 0x55
  15. static inline unsigned char linear2alaw (short int linear)
  16. {
  17. int mask;
  18. int seg;
  19. int pcm_val;
  20. static int seg_end[8] =
  21. {
  22. 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF
  23. };
  24. pcm_val = linear;
  25. if (pcm_val >= 0)
  26. {
  27. /* Sign (7th) bit = 1 */
  28. mask = AMI_MASK | 0x80;
  29. }
  30. else
  31. {
  32. /* Sign bit = 0 */
  33. mask = AMI_MASK;
  34. pcm_val = -pcm_val;
  35. }
  36. /* Convert the scaled magnitude to segment number. */
  37. for (seg = 0; seg < 8; seg++)
  38. {
  39. if (pcm_val <= seg_end[seg])
  40. break;
  41. }
  42. /* Combine the sign, segment, and quantization bits. */
  43. return ((seg << 4) | ((pcm_val >> ((seg) ? (seg + 3) : 4)) & 0x0F)) ^ mask;
  44. }
  45. /*- End of function --------------------------------------------------------*/
  46. static inline short int alaw2linear (unsigned char alaw)
  47. {
  48. int i;
  49. int seg;
  50. alaw ^= AMI_MASK;
  51. i = ((alaw & 0x0F) << 4);
  52. seg = (((int) alaw & 0x70) >> 4);
  53. if (seg)
  54. i = (i + 0x100) << (seg - 1);
  55. return (short int) ((alaw & 0x80) ? i : -i);
  56. }
  57. unsigned char __ast_lin2a[8192];
  58. short __ast_alaw[256];
  59. void ast_alaw_init(void)
  60. {
  61. int i;
  62. /*
  63. * Set up mu-law conversion table
  64. */
  65. for(i = 0;i < 256;i++)
  66. {
  67. __ast_alaw[i] = alaw2linear(i);
  68. }
  69. /* set up the reverse (mu-law) conversion table */
  70. for(i = -32768; i < 32768; i++)
  71. {
  72. __ast_lin2a[((unsigned short)i) >> 3] = linear2alaw(i);
  73. }
  74. }