You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1658 lines
52 KiB

35 years ago
35 years ago
35 years ago
35 years ago
35 years ago
35 years ago
35 years ago
35 years ago
35 years ago
35 years ago
35 years ago
35 years ago
26 years ago
35 years ago
35 years ago
26 years ago
35 years ago
35 years ago
26 years ago
26 years ago
35 years ago
35 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
26 years ago
35 years ago
35 years ago
26 years ago
35 years ago
35 years ago
26 years ago
35 years ago
35 years ago
26 years ago
35 years ago
35 years ago
26 years ago
35 years ago
35 years ago
26 years ago
35 years ago
35 years ago
26 years ago
26 years ago
26 years ago
26 years ago
35 years ago
35 years ago
26 years ago
35 years ago
35 years ago
26 years ago
26 years ago
35 years ago
35 years ago
35 years ago
  1. /* audioopmodule - Module to detect peak values in arrays */
  2. #define PY_SSIZE_T_CLEAN
  3. #include "Python.h"
  4. #if SIZEOF_INT == 4
  5. typedef int Py_Int32;
  6. typedef unsigned int Py_UInt32;
  7. #else
  8. #if SIZEOF_LONG == 4
  9. typedef long Py_Int32;
  10. typedef unsigned long Py_UInt32;
  11. #else
  12. #error "No 4-byte integral type"
  13. #endif
  14. #endif
  15. typedef short PyInt16;
  16. #if defined(__CHAR_UNSIGNED__)
  17. #if defined(signed)
  18. /* This module currently does not work on systems where only unsigned
  19. characters are available. Take it out of Setup. Sorry. */
  20. #endif
  21. #endif
  22. static const int maxvals[] = {0, 0x7F, 0x7FFF, 0x7FFFFF, 0x7FFFFFFF};
  23. static const int minvals[] = {0, -0x80, -0x8000, -0x800000, -0x80000000};
  24. static const unsigned int masks[] = {0, 0xFF, 0xFFFF, 0xFFFFFF, 0xFFFFFFFF};
  25. static int
  26. fbound(double val, double minval, double maxval)
  27. {
  28. if (val > maxval)
  29. val = maxval;
  30. else if (val < minval + 1)
  31. val = minval;
  32. return (int)val;
  33. }
  34. /* Code shamelessly stolen from sox, 12.17.7, g711.c
  35. ** (c) Craig Reese, Joe Campbell and Jeff Poskanzer 1989 */
  36. /* From g711.c:
  37. *
  38. * December 30, 1994:
  39. * Functions linear2alaw, linear2ulaw have been updated to correctly
  40. * convert unquantized 16 bit values.
  41. * Tables for direct u- to A-law and A- to u-law conversions have been
  42. * corrected.
  43. * Borge Lindberg, Center for PersonKommunikation, Aalborg University.
  44. * bli@cpk.auc.dk
  45. *
  46. */
  47. #define BIAS 0x84 /* define the add-in bias for 16 bit samples */
  48. #define CLIP 32635
  49. #define SIGN_BIT (0x80) /* Sign bit for a A-law byte. */
  50. #define QUANT_MASK (0xf) /* Quantization field mask. */
  51. #define SEG_SHIFT (4) /* Left shift for segment number. */
  52. #define SEG_MASK (0x70) /* Segment field mask. */
  53. static PyInt16 seg_aend[8] = {0x1F, 0x3F, 0x7F, 0xFF,
  54. 0x1FF, 0x3FF, 0x7FF, 0xFFF};
  55. static PyInt16 seg_uend[8] = {0x3F, 0x7F, 0xFF, 0x1FF,
  56. 0x3FF, 0x7FF, 0xFFF, 0x1FFF};
  57. static PyInt16
  58. search(PyInt16 val, PyInt16 *table, int size)
  59. {
  60. int i;
  61. for (i = 0; i < size; i++) {
  62. if (val <= *table++)
  63. return (i);
  64. }
  65. return (size);
  66. }
  67. #define st_ulaw2linear16(uc) (_st_ulaw2linear16[uc])
  68. #define st_alaw2linear16(uc) (_st_alaw2linear16[uc])
  69. static PyInt16 _st_ulaw2linear16[256] = {
  70. -32124, -31100, -30076, -29052, -28028, -27004, -25980,
  71. -24956, -23932, -22908, -21884, -20860, -19836, -18812,
  72. -17788, -16764, -15996, -15484, -14972, -14460, -13948,
  73. -13436, -12924, -12412, -11900, -11388, -10876, -10364,
  74. -9852, -9340, -8828, -8316, -7932, -7676, -7420,
  75. -7164, -6908, -6652, -6396, -6140, -5884, -5628,
  76. -5372, -5116, -4860, -4604, -4348, -4092, -3900,
  77. -3772, -3644, -3516, -3388, -3260, -3132, -3004,
  78. -2876, -2748, -2620, -2492, -2364, -2236, -2108,
  79. -1980, -1884, -1820, -1756, -1692, -1628, -1564,
  80. -1500, -1436, -1372, -1308, -1244, -1180, -1116,
  81. -1052, -988, -924, -876, -844, -812, -780,
  82. -748, -716, -684, -652, -620, -588, -556,
  83. -524, -492, -460, -428, -396, -372, -356,
  84. -340, -324, -308, -292, -276, -260, -244,
  85. -228, -212, -196, -180, -164, -148, -132,
  86. -120, -112, -104, -96, -88, -80, -72,
  87. -64, -56, -48, -40, -32, -24, -16,
  88. -8, 0, 32124, 31100, 30076, 29052, 28028,
  89. 27004, 25980, 24956, 23932, 22908, 21884, 20860,
  90. 19836, 18812, 17788, 16764, 15996, 15484, 14972,
  91. 14460, 13948, 13436, 12924, 12412, 11900, 11388,
  92. 10876, 10364, 9852, 9340, 8828, 8316, 7932,
  93. 7676, 7420, 7164, 6908, 6652, 6396, 6140,
  94. 5884, 5628, 5372, 5116, 4860, 4604, 4348,
  95. 4092, 3900, 3772, 3644, 3516, 3388, 3260,
  96. 3132, 3004, 2876, 2748, 2620, 2492, 2364,
  97. 2236, 2108, 1980, 1884, 1820, 1756, 1692,
  98. 1628, 1564, 1500, 1436, 1372, 1308, 1244,
  99. 1180, 1116, 1052, 988, 924, 876, 844,
  100. 812, 780, 748, 716, 684, 652, 620,
  101. 588, 556, 524, 492, 460, 428, 396,
  102. 372, 356, 340, 324, 308, 292, 276,
  103. 260, 244, 228, 212, 196, 180, 164,
  104. 148, 132, 120, 112, 104, 96, 88,
  105. 80, 72, 64, 56, 48, 40, 32,
  106. 24, 16, 8, 0
  107. };
  108. /*
  109. * linear2ulaw() accepts a 14-bit signed integer and encodes it as u-law data
  110. * stored in a unsigned char. This function should only be called with
  111. * the data shifted such that it only contains information in the lower
  112. * 14-bits.
  113. *
  114. * In order to simplify the encoding process, the original linear magnitude
  115. * is biased by adding 33 which shifts the encoding range from (0 - 8158) to
  116. * (33 - 8191). The result can be seen in the following encoding table:
  117. *
  118. * Biased Linear Input Code Compressed Code
  119. * ------------------------ ---------------
  120. * 00000001wxyza 000wxyz
  121. * 0000001wxyzab 001wxyz
  122. * 000001wxyzabc 010wxyz
  123. * 00001wxyzabcd 011wxyz
  124. * 0001wxyzabcde 100wxyz
  125. * 001wxyzabcdef 101wxyz
  126. * 01wxyzabcdefg 110wxyz
  127. * 1wxyzabcdefgh 111wxyz
  128. *
  129. * Each biased linear code has a leading 1 which identifies the segment
  130. * number. The value of the segment number is equal to 7 minus the number
  131. * of leading 0's. The quantization interval is directly available as the
  132. * four bits wxyz. * The trailing bits (a - h) are ignored.
  133. *
  134. * Ordinarily the complement of the resulting code word is used for
  135. * transmission, and so the code word is complemented before it is returned.
  136. *
  137. * For further information see John C. Bellamy's Digital Telephony, 1982,
  138. * John Wiley & Sons, pps 98-111 and 472-476.
  139. */
  140. static unsigned char
  141. st_14linear2ulaw(PyInt16 pcm_val) /* 2's complement (14-bit range) */
  142. {
  143. PyInt16 mask;
  144. PyInt16 seg;
  145. unsigned char uval;
  146. /* The original sox code does this in the calling function, not here */
  147. pcm_val = pcm_val >> 2;
  148. /* u-law inverts all bits */
  149. /* Get the sign and the magnitude of the value. */
  150. if (pcm_val < 0) {
  151. pcm_val = -pcm_val;
  152. mask = 0x7F;
  153. } else {
  154. mask = 0xFF;
  155. }
  156. if ( pcm_val > CLIP ) pcm_val = CLIP; /* clip the magnitude */
  157. pcm_val += (BIAS >> 2);
  158. /* Convert the scaled magnitude to segment number. */
  159. seg = search(pcm_val, seg_uend, 8);
  160. /*
  161. * Combine the sign, segment, quantization bits;
  162. * and complement the code word.
  163. */
  164. if (seg >= 8) /* out of range, return maximum value. */
  165. return (unsigned char) (0x7F ^ mask);
  166. else {
  167. uval = (unsigned char) (seg << 4) | ((pcm_val >> (seg + 1)) & 0xF);
  168. return (uval ^ mask);
  169. }
  170. }
  171. static PyInt16 _st_alaw2linear16[256] = {
  172. -5504, -5248, -6016, -5760, -4480, -4224, -4992,
  173. -4736, -7552, -7296, -8064, -7808, -6528, -6272,
  174. -7040, -6784, -2752, -2624, -3008, -2880, -2240,
  175. -2112, -2496, -2368, -3776, -3648, -4032, -3904,
  176. -3264, -3136, -3520, -3392, -22016, -20992, -24064,
  177. -23040, -17920, -16896, -19968, -18944, -30208, -29184,
  178. -32256, -31232, -26112, -25088, -28160, -27136, -11008,
  179. -10496, -12032, -11520, -8960, -8448, -9984, -9472,
  180. -15104, -14592, -16128, -15616, -13056, -12544, -14080,
  181. -13568, -344, -328, -376, -360, -280, -264,
  182. -312, -296, -472, -456, -504, -488, -408,
  183. -392, -440, -424, -88, -72, -120, -104,
  184. -24, -8, -56, -40, -216, -200, -248,
  185. -232, -152, -136, -184, -168, -1376, -1312,
  186. -1504, -1440, -1120, -1056, -1248, -1184, -1888,
  187. -1824, -2016, -1952, -1632, -1568, -1760, -1696,
  188. -688, -656, -752, -720, -560, -528, -624,
  189. -592, -944, -912, -1008, -976, -816, -784,
  190. -880, -848, 5504, 5248, 6016, 5760, 4480,
  191. 4224, 4992, 4736, 7552, 7296, 8064, 7808,
  192. 6528, 6272, 7040, 6784, 2752, 2624, 3008,
  193. 2880, 2240, 2112, 2496, 2368, 3776, 3648,
  194. 4032, 3904, 3264, 3136, 3520, 3392, 22016,
  195. 20992, 24064, 23040, 17920, 16896, 19968, 18944,
  196. 30208, 29184, 32256, 31232, 26112, 25088, 28160,
  197. 27136, 11008, 10496, 12032, 11520, 8960, 8448,
  198. 9984, 9472, 15104, 14592, 16128, 15616, 13056,
  199. 12544, 14080, 13568, 344, 328, 376, 360,
  200. 280, 264, 312, 296, 472, 456, 504,
  201. 488, 408, 392, 440, 424, 88, 72,
  202. 120, 104, 24, 8, 56, 40, 216,
  203. 200, 248, 232, 152, 136, 184, 168,
  204. 1376, 1312, 1504, 1440, 1120, 1056, 1248,
  205. 1184, 1888, 1824, 2016, 1952, 1632, 1568,
  206. 1760, 1696, 688, 656, 752, 720, 560,
  207. 528, 624, 592, 944, 912, 1008, 976,
  208. 816, 784, 880, 848
  209. };
  210. /*
  211. * linear2alaw() accepts an 13-bit signed integer and encodes it as A-law data
  212. * stored in a unsigned char. This function should only be called with
  213. * the data shifted such that it only contains information in the lower
  214. * 13-bits.
  215. *
  216. * Linear Input Code Compressed Code
  217. * ------------------------ ---------------
  218. * 0000000wxyza 000wxyz
  219. * 0000001wxyza 001wxyz
  220. * 000001wxyzab 010wxyz
  221. * 00001wxyzabc 011wxyz
  222. * 0001wxyzabcd 100wxyz
  223. * 001wxyzabcde 101wxyz
  224. * 01wxyzabcdef 110wxyz
  225. * 1wxyzabcdefg 111wxyz
  226. *
  227. * For further information see John C. Bellamy's Digital Telephony, 1982,
  228. * John Wiley & Sons, pps 98-111 and 472-476.
  229. */
  230. static unsigned char
  231. st_linear2alaw(PyInt16 pcm_val) /* 2's complement (13-bit range) */
  232. {
  233. PyInt16 mask;
  234. short seg;
  235. unsigned char aval;
  236. /* The original sox code does this in the calling function, not here */
  237. pcm_val = pcm_val >> 3;
  238. /* A-law using even bit inversion */
  239. if (pcm_val >= 0) {
  240. mask = 0xD5; /* sign (7th) bit = 1 */
  241. } else {
  242. mask = 0x55; /* sign bit = 0 */
  243. pcm_val = -pcm_val - 1;
  244. }
  245. /* Convert the scaled magnitude to segment number. */
  246. seg = search(pcm_val, seg_aend, 8);
  247. /* Combine the sign, segment, and quantization bits. */
  248. if (seg >= 8) /* out of range, return maximum value. */
  249. return (unsigned char) (0x7F ^ mask);
  250. else {
  251. aval = (unsigned char) seg << SEG_SHIFT;
  252. if (seg < 2)
  253. aval |= (pcm_val >> 1) & QUANT_MASK;
  254. else
  255. aval |= (pcm_val >> seg) & QUANT_MASK;
  256. return (aval ^ mask);
  257. }
  258. }
  259. /* End of code taken from sox */
  260. /* Intel ADPCM step variation table */
  261. static int indexTable[16] = {
  262. -1, -1, -1, -1, 2, 4, 6, 8,
  263. -1, -1, -1, -1, 2, 4, 6, 8,
  264. };
  265. static int stepsizeTable[89] = {
  266. 7, 8, 9, 10, 11, 12, 13, 14, 16, 17,
  267. 19, 21, 23, 25, 28, 31, 34, 37, 41, 45,
  268. 50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
  269. 130, 143, 157, 173, 190, 209, 230, 253, 279, 307,
  270. 337, 371, 408, 449, 494, 544, 598, 658, 724, 796,
  271. 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066,
  272. 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358,
  273. 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899,
  274. 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767
  275. };
  276. #define CHARP(cp, i) ((signed char *)(cp+i))
  277. #define SHORTP(cp, i) ((short *)(cp+i))
  278. #define LONGP(cp, i) ((Py_Int32 *)(cp+i))
  279. static PyObject *AudioopError;
  280. static int
  281. audioop_check_size(int size)
  282. {
  283. if (size != 1 && size != 2 && size != 4) {
  284. PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
  285. return 0;
  286. }
  287. else
  288. return 1;
  289. }
  290. static int
  291. audioop_check_parameters(Py_ssize_t len, int size)
  292. {
  293. if (!audioop_check_size(size))
  294. return 0;
  295. if (len % size != 0) {
  296. PyErr_SetString(AudioopError, "not a whole number of frames");
  297. return 0;
  298. }
  299. return 1;
  300. }
  301. static PyObject *
  302. audioop_getsample(PyObject *self, PyObject *args)
  303. {
  304. signed char *cp;
  305. Py_ssize_t len, i;
  306. int size, val = 0;
  307. if ( !PyArg_ParseTuple(args, "s#in:getsample", &cp, &len, &size, &i) )
  308. return 0;
  309. if (!audioop_check_parameters(len, size))
  310. return NULL;
  311. if ( i < 0 || i >= len/size ) {
  312. PyErr_SetString(AudioopError, "Index out of range");
  313. return 0;
  314. }
  315. if ( size == 1 ) val = (int)*CHARP(cp, i);
  316. else if ( size == 2 ) val = (int)*SHORTP(cp, i*2);
  317. else if ( size == 4 ) val = (int)*LONGP(cp, i*4);
  318. return PyLong_FromLong(val);
  319. }
  320. static PyObject *
  321. audioop_max(PyObject *self, PyObject *args)
  322. {
  323. signed char *cp;
  324. Py_ssize_t len, i;
  325. int size, val = 0;
  326. unsigned int absval, max = 0;
  327. if ( !PyArg_ParseTuple(args, "s#i:max", &cp, &len, &size) )
  328. return 0;
  329. if (!audioop_check_parameters(len, size))
  330. return NULL;
  331. for ( i=0; i<len; i+= size) {
  332. if ( size == 1 ) val = (int)*CHARP(cp, i);
  333. else if ( size == 2 ) val = (int)*SHORTP(cp, i);
  334. else if ( size == 4 ) val = (int)*LONGP(cp, i);
  335. if (val < 0) absval = (-val);
  336. else absval = val;
  337. if (absval > max) max = absval;
  338. }
  339. return PyLong_FromUnsignedLong(max);
  340. }
  341. static PyObject *
  342. audioop_minmax(PyObject *self, PyObject *args)
  343. {
  344. signed char *cp;
  345. Py_ssize_t len, i;
  346. int size, val = 0;
  347. int min = 0x7fffffff, max = -0x80000000;
  348. if (!PyArg_ParseTuple(args, "s#i:minmax", &cp, &len, &size))
  349. return NULL;
  350. if (!audioop_check_parameters(len, size))
  351. return NULL;
  352. for (i = 0; i < len; i += size) {
  353. if (size == 1) val = (int) *CHARP(cp, i);
  354. else if (size == 2) val = (int) *SHORTP(cp, i);
  355. else if (size == 4) val = (int) *LONGP(cp, i);
  356. if (val > max) max = val;
  357. if (val < min) min = val;
  358. }
  359. return Py_BuildValue("(ii)", min, max);
  360. }
  361. static PyObject *
  362. audioop_avg(PyObject *self, PyObject *args)
  363. {
  364. signed char *cp;
  365. Py_ssize_t len, i;
  366. int size, val = 0;
  367. double avg = 0.0;
  368. if ( !PyArg_ParseTuple(args, "s#i:avg", &cp, &len, &size) )
  369. return 0;
  370. if (!audioop_check_parameters(len, size))
  371. return NULL;
  372. for ( i=0; i<len; i+= size) {
  373. if ( size == 1 ) val = (int)*CHARP(cp, i);
  374. else if ( size == 2 ) val = (int)*SHORTP(cp, i);
  375. else if ( size == 4 ) val = (int)*LONGP(cp, i);
  376. avg += val;
  377. }
  378. if ( len == 0 )
  379. val = 0;
  380. else
  381. val = (int)floor(avg / (double)(len/size));
  382. return PyLong_FromLong(val);
  383. }
  384. static PyObject *
  385. audioop_rms(PyObject *self, PyObject *args)
  386. {
  387. signed char *cp;
  388. Py_ssize_t len, i;
  389. int size, val = 0;
  390. unsigned int res;
  391. double sum_squares = 0.0;
  392. if ( !PyArg_ParseTuple(args, "s#i:rms", &cp, &len, &size) )
  393. return 0;
  394. if (!audioop_check_parameters(len, size))
  395. return NULL;
  396. for ( i=0; i<len; i+= size) {
  397. if ( size == 1 ) val = (int)*CHARP(cp, i);
  398. else if ( size == 2 ) val = (int)*SHORTP(cp, i);
  399. else if ( size == 4 ) val = (int)*LONGP(cp, i);
  400. sum_squares += (double)val*(double)val;
  401. }
  402. if ( len == 0 )
  403. res = 0;
  404. else
  405. res = (unsigned int)sqrt(sum_squares / (double)(len/size));
  406. return PyLong_FromUnsignedLong(res);
  407. }
  408. static double _sum2(short *a, short *b, Py_ssize_t len)
  409. {
  410. Py_ssize_t i;
  411. double sum = 0.0;
  412. for( i=0; i<len; i++) {
  413. sum = sum + (double)a[i]*(double)b[i];
  414. }
  415. return sum;
  416. }
  417. /*
  418. ** Findfit tries to locate a sample within another sample. Its main use
  419. ** is in echo-cancellation (to find the feedback of the output signal in
  420. ** the input signal).
  421. ** The method used is as follows:
  422. **
  423. ** let R be the reference signal (length n) and A the input signal (length N)
  424. ** with N > n, and let all sums be over i from 0 to n-1.
  425. **
  426. ** Now, for each j in {0..N-n} we compute a factor fj so that -fj*R matches A
  427. ** as good as possible, i.e. sum( (A[j+i]+fj*R[i])^2 ) is minimal. This
  428. ** equation gives fj = sum( A[j+i]R[i] ) / sum(R[i]^2).
  429. **
  430. ** Next, we compute the relative distance between the original signal and
  431. ** the modified signal and minimize that over j:
  432. ** vj = sum( (A[j+i]-fj*R[i])^2 ) / sum( A[j+i]^2 ) =>
  433. ** vj = ( sum(A[j+i]^2)*sum(R[i]^2) - sum(A[j+i]R[i])^2 ) / sum( A[j+i]^2 )
  434. **
  435. ** In the code variables correspond as follows:
  436. ** cp1 A
  437. ** cp2 R
  438. ** len1 N
  439. ** len2 n
  440. ** aj_m1 A[j-1]
  441. ** aj_lm1 A[j+n-1]
  442. ** sum_ri_2 sum(R[i]^2)
  443. ** sum_aij_2 sum(A[i+j]^2)
  444. ** sum_aij_ri sum(A[i+j]R[i])
  445. **
  446. ** sum_ri is calculated once, sum_aij_2 is updated each step and sum_aij_ri
  447. ** is completely recalculated each step.
  448. */
  449. static PyObject *
  450. audioop_findfit(PyObject *self, PyObject *args)
  451. {
  452. short *cp1, *cp2;
  453. Py_ssize_t len1, len2;
  454. Py_ssize_t j, best_j;
  455. double aj_m1, aj_lm1;
  456. double sum_ri_2, sum_aij_2, sum_aij_ri, result, best_result, factor;
  457. /* Passing a short** for an 's' argument is correct only
  458. if the string contents is aligned for interpretation
  459. as short[]. Due to the definition of PyBytesObject,
  460. this is currently (Python 2.6) the case. */
  461. if ( !PyArg_ParseTuple(args, "s#s#:findfit",
  462. (char**)&cp1, &len1, (char**)&cp2, &len2) )
  463. return 0;
  464. if ( len1 & 1 || len2 & 1 ) {
  465. PyErr_SetString(AudioopError, "Strings should be even-sized");
  466. return 0;
  467. }
  468. len1 >>= 1;
  469. len2 >>= 1;
  470. if ( len1 < len2 ) {
  471. PyErr_SetString(AudioopError, "First sample should be longer");
  472. return 0;
  473. }
  474. sum_ri_2 = _sum2(cp2, cp2, len2);
  475. sum_aij_2 = _sum2(cp1, cp1, len2);
  476. sum_aij_ri = _sum2(cp1, cp2, len2);
  477. result = (sum_ri_2*sum_aij_2 - sum_aij_ri*sum_aij_ri) / sum_aij_2;
  478. best_result = result;
  479. best_j = 0;
  480. for ( j=1; j<=len1-len2; j++) {
  481. aj_m1 = (double)cp1[j-1];
  482. aj_lm1 = (double)cp1[j+len2-1];
  483. sum_aij_2 = sum_aij_2 + aj_lm1*aj_lm1 - aj_m1*aj_m1;
  484. sum_aij_ri = _sum2(cp1+j, cp2, len2);
  485. result = (sum_ri_2*sum_aij_2 - sum_aij_ri*sum_aij_ri)
  486. / sum_aij_2;
  487. if ( result < best_result ) {
  488. best_result = result;
  489. best_j = j;
  490. }
  491. }
  492. factor = _sum2(cp1+best_j, cp2, len2) / sum_ri_2;
  493. return Py_BuildValue("(nf)", best_j, factor);
  494. }
  495. /*
  496. ** findfactor finds a factor f so that the energy in A-fB is minimal.
  497. ** See the comment for findfit for details.
  498. */
  499. static PyObject *
  500. audioop_findfactor(PyObject *self, PyObject *args)
  501. {
  502. short *cp1, *cp2;
  503. Py_ssize_t len1, len2;
  504. double sum_ri_2, sum_aij_ri, result;
  505. if ( !PyArg_ParseTuple(args, "s#s#:findfactor",
  506. (char**)&cp1, &len1, (char**)&cp2, &len2) )
  507. return 0;
  508. if ( len1 & 1 || len2 & 1 ) {
  509. PyErr_SetString(AudioopError, "Strings should be even-sized");
  510. return 0;
  511. }
  512. if ( len1 != len2 ) {
  513. PyErr_SetString(AudioopError, "Samples should be same size");
  514. return 0;
  515. }
  516. len2 >>= 1;
  517. sum_ri_2 = _sum2(cp2, cp2, len2);
  518. sum_aij_ri = _sum2(cp1, cp2, len2);
  519. result = sum_aij_ri / sum_ri_2;
  520. return PyFloat_FromDouble(result);
  521. }
  522. /*
  523. ** findmax returns the index of the n-sized segment of the input sample
  524. ** that contains the most energy.
  525. */
  526. static PyObject *
  527. audioop_findmax(PyObject *self, PyObject *args)
  528. {
  529. short *cp1;
  530. Py_ssize_t len1, len2;
  531. Py_ssize_t j, best_j;
  532. double aj_m1, aj_lm1;
  533. double result, best_result;
  534. if ( !PyArg_ParseTuple(args, "s#n:findmax",
  535. (char**)&cp1, &len1, &len2) )
  536. return 0;
  537. if ( len1 & 1 ) {
  538. PyErr_SetString(AudioopError, "Strings should be even-sized");
  539. return 0;
  540. }
  541. len1 >>= 1;
  542. if ( len2 < 0 || len1 < len2 ) {
  543. PyErr_SetString(AudioopError, "Input sample should be longer");
  544. return 0;
  545. }
  546. result = _sum2(cp1, cp1, len2);
  547. best_result = result;
  548. best_j = 0;
  549. for ( j=1; j<=len1-len2; j++) {
  550. aj_m1 = (double)cp1[j-1];
  551. aj_lm1 = (double)cp1[j+len2-1];
  552. result = result + aj_lm1*aj_lm1 - aj_m1*aj_m1;
  553. if ( result > best_result ) {
  554. best_result = result;
  555. best_j = j;
  556. }
  557. }
  558. return PyLong_FromSsize_t(best_j);
  559. }
  560. static PyObject *
  561. audioop_avgpp(PyObject *self, PyObject *args)
  562. {
  563. signed char *cp;
  564. Py_ssize_t len, i;
  565. int size, val = 0, prevval = 0, prevextremevalid = 0,
  566. prevextreme = 0;
  567. double sum = 0.0;
  568. unsigned int avg;
  569. int diff, prevdiff, nextreme = 0;
  570. if ( !PyArg_ParseTuple(args, "s#i:avgpp", &cp, &len, &size) )
  571. return 0;
  572. if (!audioop_check_parameters(len, size))
  573. return NULL;
  574. if (len <= size)
  575. return PyLong_FromLong(0);
  576. if ( size == 1 ) prevval = (int)*CHARP(cp, 0);
  577. else if ( size == 2 ) prevval = (int)*SHORTP(cp, 0);
  578. else if ( size == 4 ) prevval = (int)*LONGP(cp, 0);
  579. prevdiff = 17; /* Anything != 0, 1 */
  580. for ( i=size; i<len; i+= size) {
  581. if ( size == 1 ) val = (int)*CHARP(cp, i);
  582. else if ( size == 2 ) val = (int)*SHORTP(cp, i);
  583. else if ( size == 4 ) val = (int)*LONGP(cp, i);
  584. if (val != prevval) {
  585. diff = val < prevval;
  586. if (prevdiff == !diff) {
  587. /* Derivative changed sign. Compute difference to last
  588. ** extreme value and remember.
  589. */
  590. if (prevextremevalid) {
  591. sum += fabs((double)prevval - (double)prevextreme);
  592. nextreme++;
  593. }
  594. prevextremevalid = 1;
  595. prevextreme = prevval;
  596. }
  597. prevval = val;
  598. prevdiff = diff;
  599. }
  600. }
  601. if ( nextreme == 0 )
  602. avg = 0;
  603. else
  604. avg = (unsigned int)(sum / (double)nextreme);
  605. return PyLong_FromUnsignedLong(avg);
  606. }
  607. static PyObject *
  608. audioop_maxpp(PyObject *self, PyObject *args)
  609. {
  610. signed char *cp;
  611. Py_ssize_t len, i;
  612. int size, val = 0, prevval = 0, prevextremevalid = 0,
  613. prevextreme = 0;
  614. unsigned int max = 0, extremediff;
  615. int diff, prevdiff;
  616. if ( !PyArg_ParseTuple(args, "s#i:maxpp", &cp, &len, &size) )
  617. return 0;
  618. if (!audioop_check_parameters(len, size))
  619. return NULL;
  620. if (len <= size)
  621. return PyLong_FromLong(0);
  622. if ( size == 1 ) prevval = (int)*CHARP(cp, 0);
  623. else if ( size == 2 ) prevval = (int)*SHORTP(cp, 0);
  624. else if ( size == 4 ) prevval = (int)*LONGP(cp, 0);
  625. prevdiff = 17; /* Anything != 0, 1 */
  626. for ( i=size; i<len; i+= size) {
  627. if ( size == 1 ) val = (int)*CHARP(cp, i);
  628. else if ( size == 2 ) val = (int)*SHORTP(cp, i);
  629. else if ( size == 4 ) val = (int)*LONGP(cp, i);
  630. if (val != prevval) {
  631. diff = val < prevval;
  632. if (prevdiff == !diff) {
  633. /* Derivative changed sign. Compute difference to
  634. ** last extreme value and remember.
  635. */
  636. if (prevextremevalid) {
  637. if (prevval < prevextreme)
  638. extremediff = (unsigned int)prevextreme -
  639. (unsigned int)prevval;
  640. else
  641. extremediff = (unsigned int)prevval -
  642. (unsigned int)prevextreme;
  643. if ( extremediff > max )
  644. max = extremediff;
  645. }
  646. prevextremevalid = 1;
  647. prevextreme = prevval;
  648. }
  649. prevval = val;
  650. prevdiff = diff;
  651. }
  652. }
  653. return PyLong_FromUnsignedLong(max);
  654. }
  655. static PyObject *
  656. audioop_cross(PyObject *self, PyObject *args)
  657. {
  658. signed char *cp;
  659. Py_ssize_t len, i;
  660. int size, val = 0;
  661. int prevval;
  662. Py_ssize_t ncross;
  663. if ( !PyArg_ParseTuple(args, "s#i:cross", &cp, &len, &size) )
  664. return 0;
  665. if (!audioop_check_parameters(len, size))
  666. return NULL;
  667. ncross = -1;
  668. prevval = 17; /* Anything <> 0,1 */
  669. for ( i=0; i<len; i+= size) {
  670. if ( size == 1 ) val = ((int)*CHARP(cp, i)) >> 7;
  671. else if ( size == 2 ) val = ((int)*SHORTP(cp, i)) >> 15;
  672. else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 31;
  673. val = val & 1;
  674. if ( val != prevval ) ncross++;
  675. prevval = val;
  676. }
  677. return PyLong_FromSsize_t(ncross);
  678. }
  679. static PyObject *
  680. audioop_mul(PyObject *self, PyObject *args)
  681. {
  682. signed char *cp, *ncp;
  683. Py_ssize_t len, i;
  684. int size, val = 0;
  685. double factor, fval, maxval, minval;
  686. PyObject *rv;
  687. if ( !PyArg_ParseTuple(args, "s#id:mul", &cp, &len, &size, &factor ) )
  688. return 0;
  689. if (!audioop_check_parameters(len, size))
  690. return NULL;
  691. maxval = (double) maxvals[size];
  692. minval = (double) minvals[size];
  693. rv = PyBytes_FromStringAndSize(NULL, len);
  694. if ( rv == 0 )
  695. return 0;
  696. ncp = (signed char *)PyBytes_AsString(rv);
  697. for ( i=0; i < len; i += size ) {
  698. if ( size == 1 ) val = (int)*CHARP(cp, i);
  699. else if ( size == 2 ) val = (int)*SHORTP(cp, i);
  700. else if ( size == 4 ) val = (int)*LONGP(cp, i);
  701. fval = (double)val*factor;
  702. val = (int)floor(fbound(fval, minval, maxval));
  703. if ( size == 1 ) *CHARP(ncp, i) = (signed char)val;
  704. else if ( size == 2 ) *SHORTP(ncp, i) = (short)val;
  705. else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)val;
  706. }
  707. return rv;
  708. }
  709. static PyObject *
  710. audioop_tomono(PyObject *self, PyObject *args)
  711. {
  712. Py_buffer pcp;
  713. signed char *cp, *ncp;
  714. Py_ssize_t len, i;
  715. int size, val1 = 0, val2 = 0;
  716. double fac1, fac2, fval, maxval, minval;
  717. PyObject *rv;
  718. if ( !PyArg_ParseTuple(args, "s*idd:tomono",
  719. &pcp, &size, &fac1, &fac2 ) )
  720. return 0;
  721. cp = pcp.buf;
  722. len = pcp.len;
  723. if (!audioop_check_parameters(len, size)) {
  724. PyBuffer_Release(&pcp);
  725. return NULL;
  726. }
  727. if (((len / size) & 1) != 0) {
  728. PyErr_SetString(AudioopError, "not a whole number of frames");
  729. PyBuffer_Release(&pcp);
  730. return NULL;
  731. }
  732. maxval = (double) maxvals[size];
  733. minval = (double) minvals[size];
  734. rv = PyBytes_FromStringAndSize(NULL, len/2);
  735. if ( rv == 0 ) {
  736. PyBuffer_Release(&pcp);
  737. return 0;
  738. }
  739. ncp = (signed char *)PyBytes_AsString(rv);
  740. for ( i=0; i < len; i += size*2 ) {
  741. if ( size == 1 ) val1 = (int)*CHARP(cp, i);
  742. else if ( size == 2 ) val1 = (int)*SHORTP(cp, i);
  743. else if ( size == 4 ) val1 = (int)*LONGP(cp, i);
  744. if ( size == 1 ) val2 = (int)*CHARP(cp, i+1);
  745. else if ( size == 2 ) val2 = (int)*SHORTP(cp, i+2);
  746. else if ( size == 4 ) val2 = (int)*LONGP(cp, i+4);
  747. fval = (double)val1*fac1 + (double)val2*fac2;
  748. val1 = (int)floor(fbound(fval, minval, maxval));
  749. if ( size == 1 ) *CHARP(ncp, i/2) = (signed char)val1;
  750. else if ( size == 2 ) *SHORTP(ncp, i/2) = (short)val1;
  751. else if ( size == 4 ) *LONGP(ncp, i/2)= (Py_Int32)val1;
  752. }
  753. PyBuffer_Release(&pcp);
  754. return rv;
  755. }
  756. static PyObject *
  757. audioop_tostereo(PyObject *self, PyObject *args)
  758. {
  759. signed char *cp, *ncp;
  760. Py_ssize_t len, i;
  761. int size, val1, val2, val = 0;
  762. double fac1, fac2, fval, maxval, minval;
  763. PyObject *rv;
  764. if ( !PyArg_ParseTuple(args, "s#idd:tostereo",
  765. &cp, &len, &size, &fac1, &fac2 ) )
  766. return 0;
  767. if (!audioop_check_parameters(len, size))
  768. return NULL;
  769. maxval = (double) maxvals[size];
  770. minval = (double) minvals[size];
  771. if (len > PY_SSIZE_T_MAX/2) {
  772. PyErr_SetString(PyExc_MemoryError,
  773. "not enough memory for output buffer");
  774. return 0;
  775. }
  776. rv = PyBytes_FromStringAndSize(NULL, len*2);
  777. if ( rv == 0 )
  778. return 0;
  779. ncp = (signed char *)PyBytes_AsString(rv);
  780. for ( i=0; i < len; i += size ) {
  781. if ( size == 1 ) val = (int)*CHARP(cp, i);
  782. else if ( size == 2 ) val = (int)*SHORTP(cp, i);
  783. else if ( size == 4 ) val = (int)*LONGP(cp, i);
  784. fval = (double)val*fac1;
  785. val1 = (int)floor(fbound(fval, minval, maxval));
  786. fval = (double)val*fac2;
  787. val2 = (int)floor(fbound(fval, minval, maxval));
  788. if ( size == 1 ) *CHARP(ncp, i*2) = (signed char)val1;
  789. else if ( size == 2 ) *SHORTP(ncp, i*2) = (short)val1;
  790. else if ( size == 4 ) *LONGP(ncp, i*2) = (Py_Int32)val1;
  791. if ( size == 1 ) *CHARP(ncp, i*2+1) = (signed char)val2;
  792. else if ( size == 2 ) *SHORTP(ncp, i*2+2) = (short)val2;
  793. else if ( size == 4 ) *LONGP(ncp, i*2+4) = (Py_Int32)val2;
  794. }
  795. return rv;
  796. }
  797. static PyObject *
  798. audioop_add(PyObject *self, PyObject *args)
  799. {
  800. signed char *cp1, *cp2, *ncp;
  801. Py_ssize_t len1, len2, i;
  802. int size, val1 = 0, val2 = 0, minval, maxval, newval;
  803. PyObject *rv;
  804. if ( !PyArg_ParseTuple(args, "s#s#i:add",
  805. &cp1, &len1, &cp2, &len2, &size ) )
  806. return 0;
  807. if (!audioop_check_parameters(len1, size))
  808. return NULL;
  809. if ( len1 != len2 ) {
  810. PyErr_SetString(AudioopError, "Lengths should be the same");
  811. return 0;
  812. }
  813. maxval = maxvals[size];
  814. minval = minvals[size];
  815. rv = PyBytes_FromStringAndSize(NULL, len1);
  816. if ( rv == 0 )
  817. return 0;
  818. ncp = (signed char *)PyBytes_AsString(rv);
  819. for ( i=0; i < len1; i += size ) {
  820. if ( size == 1 ) val1 = (int)*CHARP(cp1, i);
  821. else if ( size == 2 ) val1 = (int)*SHORTP(cp1, i);
  822. else if ( size == 4 ) val1 = (int)*LONGP(cp1, i);
  823. if ( size == 1 ) val2 = (int)*CHARP(cp2, i);
  824. else if ( size == 2 ) val2 = (int)*SHORTP(cp2, i);
  825. else if ( size == 4 ) val2 = (int)*LONGP(cp2, i);
  826. if (size < 4) {
  827. newval = val1 + val2;
  828. /* truncate in case of overflow */
  829. if (newval > maxval)
  830. newval = maxval;
  831. else if (newval < minval)
  832. newval = minval;
  833. }
  834. else {
  835. double fval = (double)val1 + (double)val2;
  836. /* truncate in case of overflow */
  837. newval = (int)floor(fbound(fval, minval, maxval));
  838. }
  839. if ( size == 1 ) *CHARP(ncp, i) = (signed char)newval;
  840. else if ( size == 2 ) *SHORTP(ncp, i) = (short)newval;
  841. else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)newval;
  842. }
  843. return rv;
  844. }
  845. static PyObject *
  846. audioop_bias(PyObject *self, PyObject *args)
  847. {
  848. signed char *cp, *ncp;
  849. Py_ssize_t len, i;
  850. int size, bias;
  851. unsigned int val = 0, mask;
  852. PyObject *rv;
  853. if ( !PyArg_ParseTuple(args, "s#ii:bias",
  854. &cp, &len, &size , &bias) )
  855. return 0;
  856. if (!audioop_check_parameters(len, size))
  857. return NULL;
  858. rv = PyBytes_FromStringAndSize(NULL, len);
  859. if ( rv == 0 )
  860. return 0;
  861. ncp = (signed char *)PyBytes_AsString(rv);
  862. mask = masks[size];
  863. for ( i=0; i < len; i += size ) {
  864. if ( size == 1 ) val = (unsigned int)(unsigned char)*CHARP(cp, i);
  865. else if ( size == 2 ) val = (unsigned int)(unsigned short)*SHORTP(cp, i);
  866. else if ( size == 4 ) val = (unsigned int)(Py_UInt32)*LONGP(cp, i);
  867. val += (unsigned int)bias;
  868. /* wrap around in case of overflow */
  869. val &= mask;
  870. if ( size == 1 ) *CHARP(ncp, i) = (signed char)(unsigned char)val;
  871. else if ( size == 2 ) *SHORTP(ncp, i) = (short)(unsigned short)val;
  872. else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(Py_UInt32)val;
  873. }
  874. return rv;
  875. }
  876. static PyObject *
  877. audioop_reverse(PyObject *self, PyObject *args)
  878. {
  879. signed char *cp;
  880. unsigned char *ncp;
  881. Py_ssize_t len, i, j;
  882. int size, val = 0;
  883. PyObject *rv;
  884. if ( !PyArg_ParseTuple(args, "s#i:reverse",
  885. &cp, &len, &size) )
  886. return 0;
  887. if (!audioop_check_parameters(len, size))
  888. return NULL;
  889. rv = PyBytes_FromStringAndSize(NULL, len);
  890. if ( rv == 0 )
  891. return 0;
  892. ncp = (unsigned char *)PyBytes_AsString(rv);
  893. for ( i=0; i < len; i += size ) {
  894. if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 24;
  895. else if ( size == 2 ) val = ((int)*SHORTP(cp, i)) << 16;
  896. else if ( size == 4 ) val = (int)*LONGP(cp, i);
  897. j = len - i - size;
  898. if ( size == 1 ) *CHARP(ncp, j) = (signed char)(val >> 24);
  899. else if ( size == 2 ) *SHORTP(ncp, j) = (short)(val >> 16);
  900. else if ( size == 4 ) *LONGP(ncp, j) = (Py_Int32)val;
  901. }
  902. return rv;
  903. }
  904. static PyObject *
  905. audioop_lin2lin(PyObject *self, PyObject *args)
  906. {
  907. signed char *cp;
  908. unsigned char *ncp;
  909. Py_ssize_t len, i, j;
  910. int size, size2, val = 0;
  911. PyObject *rv;
  912. if ( !PyArg_ParseTuple(args, "s#ii:lin2lin",
  913. &cp, &len, &size, &size2) )
  914. return 0;
  915. if (!audioop_check_parameters(len, size))
  916. return NULL;
  917. if (!audioop_check_size(size2))
  918. return NULL;
  919. if (len/size > PY_SSIZE_T_MAX/size2) {
  920. PyErr_SetString(PyExc_MemoryError,
  921. "not enough memory for output buffer");
  922. return 0;
  923. }
  924. rv = PyBytes_FromStringAndSize(NULL, (len/size)*size2);
  925. if ( rv == 0 )
  926. return 0;
  927. ncp = (unsigned char *)PyBytes_AsString(rv);
  928. for ( i=0, j=0; i < len; i += size, j += size2 ) {
  929. if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 24;
  930. else if ( size == 2 ) val = ((int)*SHORTP(cp, i)) << 16;
  931. else if ( size == 4 ) val = (int)*LONGP(cp, i);
  932. if ( size2 == 1 ) *CHARP(ncp, j) = (signed char)(val >> 24);
  933. else if ( size2 == 2 ) *SHORTP(ncp, j) = (short)(val >> 16);
  934. else if ( size2 == 4 ) *LONGP(ncp, j) = (Py_Int32)val;
  935. }
  936. return rv;
  937. }
  938. static int
  939. gcd(int a, int b)
  940. {
  941. while (b > 0) {
  942. int tmp = a % b;
  943. a = b;
  944. b = tmp;
  945. }
  946. return a;
  947. }
  948. static PyObject *
  949. audioop_ratecv(PyObject *self, PyObject *args)
  950. {
  951. char *cp, *ncp;
  952. Py_ssize_t len;
  953. int size, nchannels, inrate, outrate, weightA, weightB;
  954. int chan, d, *prev_i, *cur_i, cur_o;
  955. PyObject *state, *samps, *str, *rv = NULL;
  956. int bytes_per_frame;
  957. weightA = 1;
  958. weightB = 0;
  959. if (!PyArg_ParseTuple(args, "s#iiiiO|ii:ratecv", &cp, &len, &size,
  960. &nchannels, &inrate, &outrate, &state,
  961. &weightA, &weightB))
  962. return NULL;
  963. if (!audioop_check_size(size))
  964. return NULL;
  965. if (nchannels < 1) {
  966. PyErr_SetString(AudioopError, "# of channels should be >= 1");
  967. return NULL;
  968. }
  969. if (size > INT_MAX / nchannels) {
  970. /* This overflow test is rigorously correct because
  971. both multiplicands are >= 1. Use the argument names
  972. from the docs for the error msg. */
  973. PyErr_SetString(PyExc_OverflowError,
  974. "width * nchannels too big for a C int");
  975. return NULL;
  976. }
  977. bytes_per_frame = size * nchannels;
  978. if (weightA < 1 || weightB < 0) {
  979. PyErr_SetString(AudioopError,
  980. "weightA should be >= 1, weightB should be >= 0");
  981. return NULL;
  982. }
  983. if (len % bytes_per_frame != 0) {
  984. PyErr_SetString(AudioopError, "not a whole number of frames");
  985. return NULL;
  986. }
  987. if (inrate <= 0 || outrate <= 0) {
  988. PyErr_SetString(AudioopError, "sampling rate not > 0");
  989. return NULL;
  990. }
  991. /* divide inrate and outrate by their greatest common divisor */
  992. d = gcd(inrate, outrate);
  993. inrate /= d;
  994. outrate /= d;
  995. /* divide weightA and weightB by their greatest common divisor */
  996. d = gcd(weightA, weightB);
  997. weightA /= d;
  998. weightA /= d;
  999. if ((size_t)nchannels > PY_SIZE_MAX/sizeof(int)) {
  1000. PyErr_SetString(PyExc_MemoryError,
  1001. "not enough memory for output buffer");
  1002. return 0;
  1003. }
  1004. prev_i = (int *) PyMem_Malloc(nchannels * sizeof(int));
  1005. cur_i = (int *) PyMem_Malloc(nchannels * sizeof(int));
  1006. if (prev_i == NULL || cur_i == NULL) {
  1007. (void) PyErr_NoMemory();
  1008. goto exit;
  1009. }
  1010. len /= bytes_per_frame; /* # of frames */
  1011. if (state == Py_None) {
  1012. d = -outrate;
  1013. for (chan = 0; chan < nchannels; chan++)
  1014. prev_i[chan] = cur_i[chan] = 0;
  1015. }
  1016. else {
  1017. if (!PyArg_ParseTuple(state,
  1018. "iO!;audioop.ratecv: illegal state argument",
  1019. &d, &PyTuple_Type, &samps))
  1020. goto exit;
  1021. if (PyTuple_Size(samps) != nchannels) {
  1022. PyErr_SetString(AudioopError,
  1023. "illegal state argument");
  1024. goto exit;
  1025. }
  1026. for (chan = 0; chan < nchannels; chan++) {
  1027. if (!PyArg_ParseTuple(PyTuple_GetItem(samps, chan),
  1028. "ii:ratecv", &prev_i[chan],
  1029. &cur_i[chan]))
  1030. goto exit;
  1031. }
  1032. }
  1033. /* str <- Space for the output buffer. */
  1034. if (len == 0)
  1035. str = PyBytes_FromStringAndSize(NULL, 0);
  1036. else {
  1037. /* There are len input frames, so we need (mathematically)
  1038. ceiling(len*outrate/inrate) output frames, and each frame
  1039. requires bytes_per_frame bytes. Computing this
  1040. without spurious overflow is the challenge; we can
  1041. settle for a reasonable upper bound, though, in this
  1042. case ceiling(len/inrate) * outrate. */
  1043. /* compute ceiling(len/inrate) without overflow */
  1044. Py_ssize_t q = len > 0 ? 1 + (len - 1) / inrate : 0;
  1045. if (outrate > PY_SSIZE_T_MAX / q / bytes_per_frame)
  1046. str = NULL;
  1047. else
  1048. str = PyBytes_FromStringAndSize(NULL,
  1049. q * outrate * bytes_per_frame);
  1050. }
  1051. if (str == NULL) {
  1052. PyErr_SetString(PyExc_MemoryError,
  1053. "not enough memory for output buffer");
  1054. goto exit;
  1055. }
  1056. ncp = PyBytes_AsString(str);
  1057. for (;;) {
  1058. while (d < 0) {
  1059. if (len == 0) {
  1060. samps = PyTuple_New(nchannels);
  1061. if (samps == NULL)
  1062. goto exit;
  1063. for (chan = 0; chan < nchannels; chan++)
  1064. PyTuple_SetItem(samps, chan,
  1065. Py_BuildValue("(ii)",
  1066. prev_i[chan],
  1067. cur_i[chan]));
  1068. if (PyErr_Occurred())
  1069. goto exit;
  1070. /* We have checked before that the length
  1071. * of the string fits into int. */
  1072. len = (Py_ssize_t)(ncp - PyBytes_AsString(str));
  1073. rv = PyBytes_FromStringAndSize
  1074. (PyBytes_AsString(str), len);
  1075. Py_DECREF(str);
  1076. str = rv;
  1077. if (str == NULL)
  1078. goto exit;
  1079. rv = Py_BuildValue("(O(iO))", str, d, samps);
  1080. Py_DECREF(samps);
  1081. Py_DECREF(str);
  1082. goto exit; /* return rv */
  1083. }
  1084. for (chan = 0; chan < nchannels; chan++) {
  1085. prev_i[chan] = cur_i[chan];
  1086. if (size == 1)
  1087. cur_i[chan] = ((int)*CHARP(cp, 0)) << 24;
  1088. else if (size == 2)
  1089. cur_i[chan] = ((int)*SHORTP(cp, 0)) << 16;
  1090. else if (size == 4)
  1091. cur_i[chan] = (int)*LONGP(cp, 0);
  1092. cp += size;
  1093. /* implements a simple digital filter */
  1094. cur_i[chan] = (int)(
  1095. ((double)weightA * (double)cur_i[chan] +
  1096. (double)weightB * (double)prev_i[chan]) /
  1097. ((double)weightA + (double)weightB));
  1098. }
  1099. len--;
  1100. d += outrate;
  1101. }
  1102. while (d >= 0) {
  1103. for (chan = 0; chan < nchannels; chan++) {
  1104. cur_o = (int)(((double)prev_i[chan] * (double)d +
  1105. (double)cur_i[chan] * (double)(outrate - d)) /
  1106. (double)outrate);
  1107. if (size == 1)
  1108. *CHARP(ncp, 0) = (signed char)(cur_o >> 24);
  1109. else if (size == 2)
  1110. *SHORTP(ncp, 0) = (short)(cur_o >> 16);
  1111. else if (size == 4)
  1112. *LONGP(ncp, 0) = (Py_Int32)(cur_o);
  1113. ncp += size;
  1114. }
  1115. d -= inrate;
  1116. }
  1117. }
  1118. exit:
  1119. PyMem_Free(prev_i);
  1120. PyMem_Free(cur_i);
  1121. return rv;
  1122. }
  1123. static PyObject *
  1124. audioop_lin2ulaw(PyObject *self, PyObject *args)
  1125. {
  1126. signed char *cp;
  1127. unsigned char *ncp;
  1128. Py_ssize_t len, i;
  1129. int size, val = 0;
  1130. PyObject *rv;
  1131. if ( !PyArg_ParseTuple(args, "s#i:lin2ulaw",
  1132. &cp, &len, &size) )
  1133. return 0 ;
  1134. if (!audioop_check_parameters(len, size))
  1135. return NULL;
  1136. rv = PyBytes_FromStringAndSize(NULL, len/size);
  1137. if ( rv == 0 )
  1138. return 0;
  1139. ncp = (unsigned char *)PyBytes_AsString(rv);
  1140. for ( i=0; i < len; i += size ) {
  1141. if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8;
  1142. else if ( size == 2 ) val = (int)*SHORTP(cp, i);
  1143. else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16;
  1144. *ncp++ = st_14linear2ulaw(val);
  1145. }
  1146. return rv;
  1147. }
  1148. static PyObject *
  1149. audioop_ulaw2lin(PyObject *self, PyObject *args)
  1150. {
  1151. unsigned char *cp;
  1152. unsigned char cval;
  1153. signed char *ncp;
  1154. Py_ssize_t len, i;
  1155. int size, val;
  1156. PyObject *rv;
  1157. if ( !PyArg_ParseTuple(args, "s#i:ulaw2lin",
  1158. &cp, &len, &size) )
  1159. return 0;
  1160. if (!audioop_check_size(size))
  1161. return NULL;
  1162. if (len > PY_SSIZE_T_MAX/size) {
  1163. PyErr_SetString(PyExc_MemoryError,
  1164. "not enough memory for output buffer");
  1165. return 0;
  1166. }
  1167. rv = PyBytes_FromStringAndSize(NULL, len*size);
  1168. if ( rv == 0 )
  1169. return 0;
  1170. ncp = (signed char *)PyBytes_AsString(rv);
  1171. for ( i=0; i < len*size; i += size ) {
  1172. cval = *cp++;
  1173. val = st_ulaw2linear16(cval);
  1174. if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val >> 8);
  1175. else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val);
  1176. else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val<<16);
  1177. }
  1178. return rv;
  1179. }
  1180. static PyObject *
  1181. audioop_lin2alaw(PyObject *self, PyObject *args)
  1182. {
  1183. signed char *cp;
  1184. unsigned char *ncp;
  1185. Py_ssize_t len, i;
  1186. int size, val = 0;
  1187. PyObject *rv;
  1188. if ( !PyArg_ParseTuple(args, "s#i:lin2alaw",
  1189. &cp, &len, &size) )
  1190. return 0;
  1191. if (!audioop_check_parameters(len, size))
  1192. return NULL;
  1193. rv = PyBytes_FromStringAndSize(NULL, len/size);
  1194. if ( rv == 0 )
  1195. return 0;
  1196. ncp = (unsigned char *)PyBytes_AsString(rv);
  1197. for ( i=0; i < len; i += size ) {
  1198. if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8;
  1199. else if ( size == 2 ) val = (int)*SHORTP(cp, i);
  1200. else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16;
  1201. *ncp++ = st_linear2alaw(val);
  1202. }
  1203. return rv;
  1204. }
  1205. static PyObject *
  1206. audioop_alaw2lin(PyObject *self, PyObject *args)
  1207. {
  1208. unsigned char *cp;
  1209. unsigned char cval;
  1210. signed char *ncp;
  1211. Py_ssize_t len, i;
  1212. int size, val;
  1213. PyObject *rv;
  1214. if ( !PyArg_ParseTuple(args, "s#i:alaw2lin",
  1215. &cp, &len, &size) )
  1216. return 0;
  1217. if (!audioop_check_size(size))
  1218. return NULL;
  1219. if (len > PY_SSIZE_T_MAX/size) {
  1220. PyErr_SetString(PyExc_MemoryError,
  1221. "not enough memory for output buffer");
  1222. return 0;
  1223. }
  1224. rv = PyBytes_FromStringAndSize(NULL, len*size);
  1225. if ( rv == 0 )
  1226. return 0;
  1227. ncp = (signed char *)PyBytes_AsString(rv);
  1228. for ( i=0; i < len*size; i += size ) {
  1229. cval = *cp++;
  1230. val = st_alaw2linear16(cval);
  1231. if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val >> 8);
  1232. else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val);
  1233. else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val<<16);
  1234. }
  1235. return rv;
  1236. }
  1237. static PyObject *
  1238. audioop_lin2adpcm(PyObject *self, PyObject *args)
  1239. {
  1240. signed char *cp;
  1241. signed char *ncp;
  1242. Py_ssize_t len, i;
  1243. int size, val = 0, step, valpred, delta,
  1244. index, sign, vpdiff, diff;
  1245. PyObject *rv, *state, *str;
  1246. int outputbuffer = 0, bufferstep;
  1247. if ( !PyArg_ParseTuple(args, "s#iO:lin2adpcm",
  1248. &cp, &len, &size, &state) )
  1249. return 0;
  1250. if (!audioop_check_parameters(len, size))
  1251. return NULL;
  1252. str = PyBytes_FromStringAndSize(NULL, len/(size*2));
  1253. if ( str == 0 )
  1254. return 0;
  1255. ncp = (signed char *)PyBytes_AsString(str);
  1256. /* Decode state, should have (value, step) */
  1257. if ( state == Py_None ) {
  1258. /* First time, it seems. Set defaults */
  1259. valpred = 0;
  1260. index = 0;
  1261. } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) )
  1262. return 0;
  1263. step = stepsizeTable[index];
  1264. bufferstep = 1;
  1265. for ( i=0; i < len; i += size ) {
  1266. if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8;
  1267. else if ( size == 2 ) val = (int)*SHORTP(cp, i);
  1268. else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16;
  1269. /* Step 1 - compute difference with previous value */
  1270. diff = val - valpred;
  1271. sign = (diff < 0) ? 8 : 0;
  1272. if ( sign ) diff = (-diff);
  1273. /* Step 2 - Divide and clamp */
  1274. /* Note:
  1275. ** This code *approximately* computes:
  1276. ** delta = diff*4/step;
  1277. ** vpdiff = (delta+0.5)*step/4;
  1278. ** but in shift step bits are dropped. The net result of this
  1279. ** is that even if you have fast mul/div hardware you cannot
  1280. ** put it to good use since the fixup would be too expensive.
  1281. */
  1282. delta = 0;
  1283. vpdiff = (step >> 3);
  1284. if ( diff >= step ) {
  1285. delta = 4;
  1286. diff -= step;
  1287. vpdiff += step;
  1288. }
  1289. step >>= 1;
  1290. if ( diff >= step ) {
  1291. delta |= 2;
  1292. diff -= step;
  1293. vpdiff += step;
  1294. }
  1295. step >>= 1;
  1296. if ( diff >= step ) {
  1297. delta |= 1;
  1298. vpdiff += step;
  1299. }
  1300. /* Step 3 - Update previous value */
  1301. if ( sign )
  1302. valpred -= vpdiff;
  1303. else
  1304. valpred += vpdiff;
  1305. /* Step 4 - Clamp previous value to 16 bits */
  1306. if ( valpred > 32767 )
  1307. valpred = 32767;
  1308. else if ( valpred < -32768 )
  1309. valpred = -32768;
  1310. /* Step 5 - Assemble value, update index and step values */
  1311. delta |= sign;
  1312. index += indexTable[delta];
  1313. if ( index < 0 ) index = 0;
  1314. if ( index > 88 ) index = 88;
  1315. step = stepsizeTable[index];
  1316. /* Step 6 - Output value */
  1317. if ( bufferstep ) {
  1318. outputbuffer = (delta << 4) & 0xf0;
  1319. } else {
  1320. *ncp++ = (delta & 0x0f) | outputbuffer;
  1321. }
  1322. bufferstep = !bufferstep;
  1323. }
  1324. rv = Py_BuildValue("(O(ii))", str, valpred, index);
  1325. Py_DECREF(str);
  1326. return rv;
  1327. }
  1328. static PyObject *
  1329. audioop_adpcm2lin(PyObject *self, PyObject *args)
  1330. {
  1331. signed char *cp;
  1332. signed char *ncp;
  1333. Py_ssize_t len, i;
  1334. int size, valpred, step, delta, index, sign, vpdiff;
  1335. PyObject *rv, *str, *state;
  1336. int inputbuffer = 0, bufferstep;
  1337. if ( !PyArg_ParseTuple(args, "s#iO:adpcm2lin",
  1338. &cp, &len, &size, &state) )
  1339. return 0;
  1340. if (!audioop_check_size(size))
  1341. return NULL;
  1342. /* Decode state, should have (value, step) */
  1343. if ( state == Py_None ) {
  1344. /* First time, it seems. Set defaults */
  1345. valpred = 0;
  1346. index = 0;
  1347. } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) )
  1348. return 0;
  1349. if (len > (PY_SSIZE_T_MAX/2)/size) {
  1350. PyErr_SetString(PyExc_MemoryError,
  1351. "not enough memory for output buffer");
  1352. return 0;
  1353. }
  1354. str = PyBytes_FromStringAndSize(NULL, len*size*2);
  1355. if ( str == 0 )
  1356. return 0;
  1357. ncp = (signed char *)PyBytes_AsString(str);
  1358. step = stepsizeTable[index];
  1359. bufferstep = 0;
  1360. for ( i=0; i < len*size*2; i += size ) {
  1361. /* Step 1 - get the delta value and compute next index */
  1362. if ( bufferstep ) {
  1363. delta = inputbuffer & 0xf;
  1364. } else {
  1365. inputbuffer = *cp++;
  1366. delta = (inputbuffer >> 4) & 0xf;
  1367. }
  1368. bufferstep = !bufferstep;
  1369. /* Step 2 - Find new index value (for later) */
  1370. index += indexTable[delta];
  1371. if ( index < 0 ) index = 0;
  1372. if ( index > 88 ) index = 88;
  1373. /* Step 3 - Separate sign and magnitude */
  1374. sign = delta & 8;
  1375. delta = delta & 7;
  1376. /* Step 4 - Compute difference and new predicted value */
  1377. /*
  1378. ** Computes 'vpdiff = (delta+0.5)*step/4', but see comment
  1379. ** in adpcm_coder.
  1380. */
  1381. vpdiff = step >> 3;
  1382. if ( delta & 4 ) vpdiff += step;
  1383. if ( delta & 2 ) vpdiff += step>>1;
  1384. if ( delta & 1 ) vpdiff += step>>2;
  1385. if ( sign )
  1386. valpred -= vpdiff;
  1387. else
  1388. valpred += vpdiff;
  1389. /* Step 5 - clamp output value */
  1390. if ( valpred > 32767 )
  1391. valpred = 32767;
  1392. else if ( valpred < -32768 )
  1393. valpred = -32768;
  1394. /* Step 6 - Update step value */
  1395. step = stepsizeTable[index];
  1396. /* Step 6 - Output value */
  1397. if ( size == 1 ) *CHARP(ncp, i) = (signed char)(valpred >> 8);
  1398. else if ( size == 2 ) *SHORTP(ncp, i) = (short)(valpred);
  1399. else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(valpred<<16);
  1400. }
  1401. rv = Py_BuildValue("(O(ii))", str, valpred, index);
  1402. Py_DECREF(str);
  1403. return rv;
  1404. }
  1405. static PyMethodDef audioop_methods[] = {
  1406. { "max", audioop_max, METH_VARARGS },
  1407. { "minmax", audioop_minmax, METH_VARARGS },
  1408. { "avg", audioop_avg, METH_VARARGS },
  1409. { "maxpp", audioop_maxpp, METH_VARARGS },
  1410. { "avgpp", audioop_avgpp, METH_VARARGS },
  1411. { "rms", audioop_rms, METH_VARARGS },
  1412. { "findfit", audioop_findfit, METH_VARARGS },
  1413. { "findmax", audioop_findmax, METH_VARARGS },
  1414. { "findfactor", audioop_findfactor, METH_VARARGS },
  1415. { "cross", audioop_cross, METH_VARARGS },
  1416. { "mul", audioop_mul, METH_VARARGS },
  1417. { "add", audioop_add, METH_VARARGS },
  1418. { "bias", audioop_bias, METH_VARARGS },
  1419. { "ulaw2lin", audioop_ulaw2lin, METH_VARARGS },
  1420. { "lin2ulaw", audioop_lin2ulaw, METH_VARARGS },
  1421. { "alaw2lin", audioop_alaw2lin, METH_VARARGS },
  1422. { "lin2alaw", audioop_lin2alaw, METH_VARARGS },
  1423. { "lin2lin", audioop_lin2lin, METH_VARARGS },
  1424. { "adpcm2lin", audioop_adpcm2lin, METH_VARARGS },
  1425. { "lin2adpcm", audioop_lin2adpcm, METH_VARARGS },
  1426. { "tomono", audioop_tomono, METH_VARARGS },
  1427. { "tostereo", audioop_tostereo, METH_VARARGS },
  1428. { "getsample", audioop_getsample, METH_VARARGS },
  1429. { "reverse", audioop_reverse, METH_VARARGS },
  1430. { "ratecv", audioop_ratecv, METH_VARARGS },
  1431. { 0, 0 }
  1432. };
  1433. static struct PyModuleDef audioopmodule = {
  1434. PyModuleDef_HEAD_INIT,
  1435. "audioop",
  1436. NULL,
  1437. -1,
  1438. audioop_methods,
  1439. NULL,
  1440. NULL,
  1441. NULL,
  1442. NULL
  1443. };
  1444. PyMODINIT_FUNC
  1445. PyInit_audioop(void)
  1446. {
  1447. PyObject *m, *d;
  1448. m = PyModule_Create(&audioopmodule);
  1449. if (m == NULL)
  1450. return NULL;
  1451. d = PyModule_GetDict(m);
  1452. if (d == NULL)
  1453. return NULL;
  1454. AudioopError = PyErr_NewException("audioop.error", NULL, NULL);
  1455. if (AudioopError != NULL)
  1456. PyDict_SetItemString(d,"error",AudioopError);
  1457. return m;
  1458. }