audioop.c 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003
  1. /* The audioop module uses the code base in g777.c file of the Sox project.
  2. Source: https://sourceforge.net/projects/sox/files/sox/12.17.7/sox-12.17.7.tar.gz
  3. Copyright of g771.c:
  4. * This source code is a product of Sun Microsystems, Inc. and is provided
  5. * for unrestricted use. Users may copy or modify this source code without
  6. * charge.
  7. *
  8. * SUN SOURCE CODE IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING
  9. * THE WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
  10. * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
  11. *
  12. * Sun source code is provided with no support and without any obligation on
  13. * the part of Sun Microsystems, Inc. to assist in its use, correction,
  14. * modification or enhancement.
  15. *
  16. * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
  17. * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY THIS SOFTWARE
  18. * OR ANY PART THEREOF.
  19. *
  20. * In no event will Sun Microsystems, Inc. be liable for any lost revenue
  21. * or profits or other special, indirect and consequential damages, even if
  22. * Sun has been advised of the possibility of such damages.
  23. *
  24. * Sun Microsystems, Inc.
  25. * 2550 Garcia Avenue
  26. * Mountain View, California 94043 */
  27. /* audioopmodule - Module to detect peak values in arrays */
  28. #define PY_SSIZE_T_CLEAN
  29. #include "Python.h"
  30. static const int maxvals[] = {0, 0x7F, 0x7FFF, 0x7FFFFF, 0x7FFFFFFF};
  31. /* -1 trick is needed on Windows to support -0x80000000 without a warning */
  32. static const int minvals[] = {0, -0x80, -0x8000, -0x800000, -0x7FFFFFFF-1};
  33. static const unsigned int masks[] = {0, 0xFF, 0xFFFF, 0xFFFFFF, 0xFFFFFFFF};
  34. static int
  35. fbound(double val, double minval, double maxval)
  36. {
  37. if (val > maxval) {
  38. val = maxval;
  39. }
  40. else if (val < minval + 1.0) {
  41. val = minval;
  42. }
  43. /* Round towards minus infinity (-inf) */
  44. val = floor(val);
  45. /* Cast double to integer: round towards zero */
  46. return (int)val;
  47. }
  48. #define BIAS 0x84 /* define the add-in bias for 16 bit samples */
  49. #define CLIP 32635
  50. #define SIGN_BIT (0x80) /* Sign bit for an A-law byte. */
  51. #define QUANT_MASK (0xf) /* Quantization field mask. */
  52. #define SEG_SHIFT (4) /* Left shift for segment number. */
  53. #define SEG_MASK (0x70) /* Segment field mask. */
  54. static const int16_t seg_aend[8] = {
  55. 0x1F, 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF
  56. };
  57. static const int16_t seg_uend[8] = {
  58. 0x3F, 0x7F, 0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF
  59. };
  60. static int16_t
  61. search(int16_t val, const int16_t *table, int size)
  62. {
  63. assert(0 <= size);
  64. assert(size < INT16_MAX);
  65. int i;
  66. for (i = 0; i < size; i++) {
  67. if (val <= *table++)
  68. return (i);
  69. }
  70. return (size);
  71. }
  72. #define st_ulaw2linear16(uc) (_st_ulaw2linear16[uc])
  73. #define st_alaw2linear16(uc) (_st_alaw2linear16[uc])
  74. static const int16_t _st_ulaw2linear16[256] = {
  75. -32124, -31100, -30076, -29052, -28028, -27004, -25980,
  76. -24956, -23932, -22908, -21884, -20860, -19836, -18812,
  77. -17788, -16764, -15996, -15484, -14972, -14460, -13948,
  78. -13436, -12924, -12412, -11900, -11388, -10876, -10364,
  79. -9852, -9340, -8828, -8316, -7932, -7676, -7420,
  80. -7164, -6908, -6652, -6396, -6140, -5884, -5628,
  81. -5372, -5116, -4860, -4604, -4348, -4092, -3900,
  82. -3772, -3644, -3516, -3388, -3260, -3132, -3004,
  83. -2876, -2748, -2620, -2492, -2364, -2236, -2108,
  84. -1980, -1884, -1820, -1756, -1692, -1628, -1564,
  85. -1500, -1436, -1372, -1308, -1244, -1180, -1116,
  86. -1052, -988, -924, -876, -844, -812, -780,
  87. -748, -716, -684, -652, -620, -588, -556,
  88. -524, -492, -460, -428, -396, -372, -356,
  89. -340, -324, -308, -292, -276, -260, -244,
  90. -228, -212, -196, -180, -164, -148, -132,
  91. -120, -112, -104, -96, -88, -80, -72,
  92. -64, -56, -48, -40, -32, -24, -16,
  93. -8, 0, 32124, 31100, 30076, 29052, 28028,
  94. 27004, 25980, 24956, 23932, 22908, 21884, 20860,
  95. 19836, 18812, 17788, 16764, 15996, 15484, 14972,
  96. 14460, 13948, 13436, 12924, 12412, 11900, 11388,
  97. 10876, 10364, 9852, 9340, 8828, 8316, 7932,
  98. 7676, 7420, 7164, 6908, 6652, 6396, 6140,
  99. 5884, 5628, 5372, 5116, 4860, 4604, 4348,
  100. 4092, 3900, 3772, 3644, 3516, 3388, 3260,
  101. 3132, 3004, 2876, 2748, 2620, 2492, 2364,
  102. 2236, 2108, 1980, 1884, 1820, 1756, 1692,
  103. 1628, 1564, 1500, 1436, 1372, 1308, 1244,
  104. 1180, 1116, 1052, 988, 924, 876, 844,
  105. 812, 780, 748, 716, 684, 652, 620,
  106. 588, 556, 524, 492, 460, 428, 396,
  107. 372, 356, 340, 324, 308, 292, 276,
  108. 260, 244, 228, 212, 196, 180, 164,
  109. 148, 132, 120, 112, 104, 96, 88,
  110. 80, 72, 64, 56, 48, 40, 32,
  111. 24, 16, 8, 0
  112. };
  113. /*
  114. * linear2ulaw() accepts a 14-bit signed integer and encodes it as u-law data
  115. * stored in an unsigned char. This function should only be called with
  116. * the data shifted such that it only contains information in the lower
  117. * 14-bits.
  118. *
  119. * In order to simplify the encoding process, the original linear magnitude
  120. * is biased by adding 33 which shifts the encoding range from (0 - 8158) to
  121. * (33 - 8191). The result can be seen in the following encoding table:
  122. *
  123. * Biased Linear Input Code Compressed Code
  124. * ------------------------ ---------------
  125. * 00000001wxyza 000wxyz
  126. * 0000001wxyzab 001wxyz
  127. * 000001wxyzabc 010wxyz
  128. * 00001wxyzabcd 011wxyz
  129. * 0001wxyzabcde 100wxyz
  130. * 001wxyzabcdef 101wxyz
  131. * 01wxyzabcdefg 110wxyz
  132. * 1wxyzabcdefgh 111wxyz
  133. *
  134. * Each biased linear code has a leading 1 which identifies the segment
  135. * number. The value of the segment number is equal to 7 minus the number
  136. * of leading 0's. The quantization interval is directly available as the
  137. * four bits wxyz. * The trailing bits (a - h) are ignored.
  138. *
  139. * Ordinarily the complement of the resulting code word is used for
  140. * transmission, and so the code word is complemented before it is returned.
  141. *
  142. * For further information see John C. Bellamy's Digital Telephony, 1982,
  143. * John Wiley & Sons, pps 98-111 and 472-476.
  144. */
  145. static unsigned char
  146. st_14linear2ulaw(int16_t pcm_val) /* 2's complement (14-bit range) */
  147. {
  148. int16_t mask;
  149. int16_t seg;
  150. unsigned char uval;
  151. /* u-law inverts all bits */
  152. /* Get the sign and the magnitude of the value. */
  153. if (pcm_val < 0) {
  154. pcm_val = -pcm_val;
  155. mask = 0x7F;
  156. } else {
  157. mask = 0xFF;
  158. }
  159. if ( pcm_val > CLIP ) pcm_val = CLIP; /* clip the magnitude */
  160. pcm_val += (BIAS >> 2);
  161. /* Convert the scaled magnitude to segment number. */
  162. seg = search(pcm_val, seg_uend, 8);
  163. /*
  164. * Combine the sign, segment, quantization bits;
  165. * and complement the code word.
  166. */
  167. if (seg >= 8) /* out of range, return maximum value. */
  168. return (unsigned char) (0x7F ^ mask);
  169. else {
  170. assert(seg >= 0);
  171. uval = (unsigned char) (seg << 4) | ((pcm_val >> (seg + 1)) & 0xF);
  172. return (uval ^ mask);
  173. }
  174. }
  175. static const int16_t _st_alaw2linear16[256] = {
  176. -5504, -5248, -6016, -5760, -4480, -4224, -4992,
  177. -4736, -7552, -7296, -8064, -7808, -6528, -6272,
  178. -7040, -6784, -2752, -2624, -3008, -2880, -2240,
  179. -2112, -2496, -2368, -3776, -3648, -4032, -3904,
  180. -3264, -3136, -3520, -3392, -22016, -20992, -24064,
  181. -23040, -17920, -16896, -19968, -18944, -30208, -29184,
  182. -32256, -31232, -26112, -25088, -28160, -27136, -11008,
  183. -10496, -12032, -11520, -8960, -8448, -9984, -9472,
  184. -15104, -14592, -16128, -15616, -13056, -12544, -14080,
  185. -13568, -344, -328, -376, -360, -280, -264,
  186. -312, -296, -472, -456, -504, -488, -408,
  187. -392, -440, -424, -88, -72, -120, -104,
  188. -24, -8, -56, -40, -216, -200, -248,
  189. -232, -152, -136, -184, -168, -1376, -1312,
  190. -1504, -1440, -1120, -1056, -1248, -1184, -1888,
  191. -1824, -2016, -1952, -1632, -1568, -1760, -1696,
  192. -688, -656, -752, -720, -560, -528, -624,
  193. -592, -944, -912, -1008, -976, -816, -784,
  194. -880, -848, 5504, 5248, 6016, 5760, 4480,
  195. 4224, 4992, 4736, 7552, 7296, 8064, 7808,
  196. 6528, 6272, 7040, 6784, 2752, 2624, 3008,
  197. 2880, 2240, 2112, 2496, 2368, 3776, 3648,
  198. 4032, 3904, 3264, 3136, 3520, 3392, 22016,
  199. 20992, 24064, 23040, 17920, 16896, 19968, 18944,
  200. 30208, 29184, 32256, 31232, 26112, 25088, 28160,
  201. 27136, 11008, 10496, 12032, 11520, 8960, 8448,
  202. 9984, 9472, 15104, 14592, 16128, 15616, 13056,
  203. 12544, 14080, 13568, 344, 328, 376, 360,
  204. 280, 264, 312, 296, 472, 456, 504,
  205. 488, 408, 392, 440, 424, 88, 72,
  206. 120, 104, 24, 8, 56, 40, 216,
  207. 200, 248, 232, 152, 136, 184, 168,
  208. 1376, 1312, 1504, 1440, 1120, 1056, 1248,
  209. 1184, 1888, 1824, 2016, 1952, 1632, 1568,
  210. 1760, 1696, 688, 656, 752, 720, 560,
  211. 528, 624, 592, 944, 912, 1008, 976,
  212. 816, 784, 880, 848
  213. };
  214. /*
  215. * linear2alaw() accepts a 13-bit signed integer and encodes it as A-law data
  216. * stored in an unsigned char. This function should only be called with
  217. * the data shifted such that it only contains information in the lower
  218. * 13-bits.
  219. *
  220. * Linear Input Code Compressed Code
  221. * ------------------------ ---------------
  222. * 0000000wxyza 000wxyz
  223. * 0000001wxyza 001wxyz
  224. * 000001wxyzab 010wxyz
  225. * 00001wxyzabc 011wxyz
  226. * 0001wxyzabcd 100wxyz
  227. * 001wxyzabcde 101wxyz
  228. * 01wxyzabcdef 110wxyz
  229. * 1wxyzabcdefg 111wxyz
  230. *
  231. * For further information see John C. Bellamy's Digital Telephony, 1982,
  232. * John Wiley & Sons, pps 98-111 and 472-476.
  233. */
  234. static unsigned char
  235. st_linear2alaw(int16_t pcm_val) /* 2's complement (13-bit range) */
  236. {
  237. int16_t mask;
  238. int16_t seg;
  239. unsigned char aval;
  240. /* A-law using even bit inversion */
  241. if (pcm_val >= 0) {
  242. mask = 0xD5; /* sign (7th) bit = 1 */
  243. } else {
  244. mask = 0x55; /* sign bit = 0 */
  245. pcm_val = -pcm_val - 1;
  246. }
  247. /* Convert the scaled magnitude to segment number. */
  248. seg = search(pcm_val, seg_aend, 8);
  249. /* Combine the sign, segment, and quantization bits. */
  250. if (seg >= 8) /* out of range, return maximum value. */
  251. return (unsigned char) (0x7F ^ mask);
  252. else {
  253. aval = (unsigned char) seg << SEG_SHIFT;
  254. if (seg < 2)
  255. aval |= (pcm_val >> 1) & QUANT_MASK;
  256. else
  257. aval |= (pcm_val >> seg) & QUANT_MASK;
  258. return (aval ^ mask);
  259. }
  260. }
  261. /* End of code taken from sox */
  262. /* Intel ADPCM step variation table */
  263. static const int indexTable[16] = {
  264. -1, -1, -1, -1, 2, 4, 6, 8,
  265. -1, -1, -1, -1, 2, 4, 6, 8,
  266. };
  267. static const int stepsizeTable[89] = {
  268. 7, 8, 9, 10, 11, 12, 13, 14, 16, 17,
  269. 19, 21, 23, 25, 28, 31, 34, 37, 41, 45,
  270. 50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
  271. 130, 143, 157, 173, 190, 209, 230, 253, 279, 307,
  272. 337, 371, 408, 449, 494, 544, 598, 658, 724, 796,
  273. 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066,
  274. 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358,
  275. 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899,
  276. 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767
  277. };
  278. #define GETINTX(T, cp, i) (*(T *)((unsigned char *)(cp) + (i)))
  279. #define SETINTX(T, cp, i, val) do { \
  280. *(T *)((unsigned char *)(cp) + (i)) = (T)(val); \
  281. } while (0)
  282. #define GETINT8(cp, i) GETINTX(signed char, (cp), (i))
  283. #define GETINT16(cp, i) GETINTX(int16_t, (cp), (i))
  284. #define GETINT32(cp, i) GETINTX(int32_t, (cp), (i))
  285. #ifdef WORDS_BIGENDIAN
  286. #define GETINT24(cp, i) ( \
  287. ((unsigned char *)(cp) + (i))[2] + \
  288. (((unsigned char *)(cp) + (i))[1] * (1 << 8)) + \
  289. (((signed char *)(cp) + (i))[0] * (1 << 16)) )
  290. #else
  291. #define GETINT24(cp, i) ( \
  292. ((unsigned char *)(cp) + (i))[0] + \
  293. (((unsigned char *)(cp) + (i))[1] * (1 << 8)) + \
  294. (((signed char *)(cp) + (i))[2] * (1 << 16)) )
  295. #endif
  296. #define SETINT8(cp, i, val) SETINTX(signed char, (cp), (i), (val))
  297. #define SETINT16(cp, i, val) SETINTX(int16_t, (cp), (i), (val))
  298. #define SETINT32(cp, i, val) SETINTX(int32_t, (cp), (i), (val))
  299. #ifdef WORDS_BIGENDIAN
  300. #define SETINT24(cp, i, val) do { \
  301. ((unsigned char *)(cp) + (i))[2] = (int)(val); \
  302. ((unsigned char *)(cp) + (i))[1] = (int)(val) >> 8; \
  303. ((signed char *)(cp) + (i))[0] = (int)(val) >> 16; \
  304. } while (0)
  305. #else
  306. #define SETINT24(cp, i, val) do { \
  307. ((unsigned char *)(cp) + (i))[0] = (int)(val); \
  308. ((unsigned char *)(cp) + (i))[1] = (int)(val) >> 8; \
  309. ((signed char *)(cp) + (i))[2] = (int)(val) >> 16; \
  310. } while (0)
  311. #endif
  312. #define GETRAWSAMPLE(size, cp, i) ( \
  313. (size == 1) ? (int)GETINT8((cp), (i)) : \
  314. (size == 2) ? (int)GETINT16((cp), (i)) : \
  315. (size == 3) ? (int)GETINT24((cp), (i)) : \
  316. (int)GETINT32((cp), (i)))
  317. #define SETRAWSAMPLE(size, cp, i, val) do { \
  318. if (size == 1) \
  319. SETINT8((cp), (i), (val)); \
  320. else if (size == 2) \
  321. SETINT16((cp), (i), (val)); \
  322. else if (size == 3) \
  323. SETINT24((cp), (i), (val)); \
  324. else \
  325. SETINT32((cp), (i), (val)); \
  326. } while(0)
  327. #define GETSAMPLE32(size, cp, i) ( \
  328. (size == 1) ? (int)GETINT8((cp), (i)) * (1 << 24) : \
  329. (size == 2) ? (int)GETINT16((cp), (i)) * (1 << 16) : \
  330. (size == 3) ? (int)GETINT24((cp), (i)) * (1 << 8) : \
  331. (int)GETINT32((cp), (i)))
  332. #define SETSAMPLE32(size, cp, i, val) do { \
  333. if (size == 1) \
  334. SETINT8((cp), (i), (val) >> 24); \
  335. else if (size == 2) \
  336. SETINT16((cp), (i), (val) >> 16); \
  337. else if (size == 3) \
  338. SETINT24((cp), (i), (val) >> 8); \
  339. else \
  340. SETINT32((cp), (i), (val)); \
  341. } while(0)
  342. static PyModuleDef audioopmodule;
  343. typedef struct {
  344. PyObject *AudioopError;
  345. } audioop_state;
  346. static inline audioop_state *
  347. get_audioop_state(PyObject *module)
  348. {
  349. void *state = PyModule_GetState(module);
  350. assert(state != NULL);
  351. return (audioop_state *)state;
  352. }
  353. static int
  354. audioop_check_size(PyObject *module, int size)
  355. {
  356. if (size < 1 || size > 4) {
  357. PyErr_SetString(get_audioop_state(module)->AudioopError,
  358. "Size should be 1, 2, 3 or 4");
  359. return 0;
  360. }
  361. else
  362. return 1;
  363. }
  364. static int
  365. audioop_check_parameters(PyObject *module, Py_ssize_t len, int size)
  366. {
  367. if (!audioop_check_size(module, size))
  368. return 0;
  369. if (len % size != 0) {
  370. PyErr_SetString(get_audioop_state(module)->AudioopError,
  371. "not a whole number of frames");
  372. return 0;
  373. }
  374. return 1;
  375. }
  376. /*[clinic input]
  377. module audioop
  378. [clinic start generated code]*/
  379. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=8fa8f6611be3591a]*/
  380. /*[clinic input]
  381. audioop.getsample
  382. fragment: Py_buffer
  383. width: int
  384. index: Py_ssize_t
  385. /
  386. Return the value of sample index from the fragment.
  387. [clinic start generated code]*/
  388. static PyObject *
  389. audioop_getsample_impl(PyObject *module, Py_buffer *fragment, int width,
  390. Py_ssize_t index)
  391. /*[clinic end generated code: output=8fe1b1775134f39a input=88edbe2871393549]*/
  392. {
  393. int val;
  394. if (!audioop_check_parameters(module, fragment->len, width))
  395. return NULL;
  396. if (index < 0 || index >= fragment->len/width) {
  397. PyErr_SetString(get_audioop_state(module)->AudioopError,
  398. "Index out of range");
  399. return NULL;
  400. }
  401. val = GETRAWSAMPLE(width, fragment->buf, index*width);
  402. return PyLong_FromLong(val);
  403. }
  404. /*[clinic input]
  405. audioop.max
  406. fragment: Py_buffer
  407. width: int
  408. /
  409. Return the maximum of the absolute value of all samples in a fragment.
  410. [clinic start generated code]*/
  411. static PyObject *
  412. audioop_max_impl(PyObject *module, Py_buffer *fragment, int width)
  413. /*[clinic end generated code: output=e6c5952714f1c3f0 input=32bea5ea0ac8c223]*/
  414. {
  415. Py_ssize_t i;
  416. unsigned int absval, max = 0;
  417. if (!audioop_check_parameters(module, fragment->len, width))
  418. return NULL;
  419. for (i = 0; i < fragment->len; i += width) {
  420. int val = GETRAWSAMPLE(width, fragment->buf, i);
  421. /* Cast to unsigned before negating. Unsigned overflow is well-
  422. defined, but signed overflow is not. */
  423. if (val < 0) absval = (unsigned int)-(int64_t)val;
  424. else absval = val;
  425. if (absval > max) max = absval;
  426. }
  427. return PyLong_FromUnsignedLong(max);
  428. }
  429. /*[clinic input]
  430. audioop.minmax
  431. fragment: Py_buffer
  432. width: int
  433. /
  434. Return the minimum and maximum values of all samples in the sound fragment.
  435. [clinic start generated code]*/
  436. static PyObject *
  437. audioop_minmax_impl(PyObject *module, Py_buffer *fragment, int width)
  438. /*[clinic end generated code: output=473fda66b15c836e input=89848e9b927a0696]*/
  439. {
  440. Py_ssize_t i;
  441. /* -1 trick below is needed on Windows to support -0x80000000 without
  442. a warning */
  443. int min = 0x7fffffff, max = -0x7FFFFFFF-1;
  444. if (!audioop_check_parameters(module, fragment->len, width))
  445. return NULL;
  446. for (i = 0; i < fragment->len; i += width) {
  447. int val = GETRAWSAMPLE(width, fragment->buf, i);
  448. if (val > max) max = val;
  449. if (val < min) min = val;
  450. }
  451. return Py_BuildValue("(ii)", min, max);
  452. }
  453. /*[clinic input]
  454. audioop.avg
  455. fragment: Py_buffer
  456. width: int
  457. /
  458. Return the average over all samples in the fragment.
  459. [clinic start generated code]*/
  460. static PyObject *
  461. audioop_avg_impl(PyObject *module, Py_buffer *fragment, int width)
  462. /*[clinic end generated code: output=4410a4c12c3586e6 input=1114493c7611334d]*/
  463. {
  464. Py_ssize_t i;
  465. int avg;
  466. double sum = 0.0;
  467. if (!audioop_check_parameters(module, fragment->len, width))
  468. return NULL;
  469. for (i = 0; i < fragment->len; i += width)
  470. sum += GETRAWSAMPLE(width, fragment->buf, i);
  471. if (fragment->len == 0)
  472. avg = 0;
  473. else
  474. avg = (int)floor(sum / (double)(fragment->len/width));
  475. return PyLong_FromLong(avg);
  476. }
  477. /*[clinic input]
  478. audioop.rms
  479. fragment: Py_buffer
  480. width: int
  481. /
  482. Return the root-mean-square of the fragment, i.e. sqrt(sum(S_i^2)/n).
  483. [clinic start generated code]*/
  484. static PyObject *
  485. audioop_rms_impl(PyObject *module, Py_buffer *fragment, int width)
  486. /*[clinic end generated code: output=1e7871c826445698 input=4cc57c6c94219d78]*/
  487. {
  488. Py_ssize_t i;
  489. unsigned int res;
  490. double sum_squares = 0.0;
  491. if (!audioop_check_parameters(module, fragment->len, width))
  492. return NULL;
  493. for (i = 0; i < fragment->len; i += width) {
  494. double val = GETRAWSAMPLE(width, fragment->buf, i);
  495. sum_squares += val*val;
  496. }
  497. if (fragment->len == 0)
  498. res = 0;
  499. else
  500. res = (unsigned int)sqrt(sum_squares / (double)(fragment->len/width));
  501. return PyLong_FromUnsignedLong(res);
  502. }
  503. static double _sum2(const int16_t *a, const int16_t *b, Py_ssize_t len)
  504. {
  505. Py_ssize_t i;
  506. double sum = 0.0;
  507. for( i=0; i<len; i++) {
  508. sum = sum + (double)a[i]*(double)b[i];
  509. }
  510. return sum;
  511. }
  512. /*
  513. ** Findfit tries to locate a sample within another sample. Its main use
  514. ** is in echo-cancellation (to find the feedback of the output signal in
  515. ** the input signal).
  516. ** The method used is as follows:
  517. **
  518. ** let R be the reference signal (length n) and A the input signal (length N)
  519. ** with N > n, and let all sums be over i from 0 to n-1.
  520. **
  521. ** Now, for each j in {0..N-n} we compute a factor fj so that -fj*R matches A
  522. ** as good as possible, i.e. sum( (A[j+i]+fj*R[i])^2 ) is minimal. This
  523. ** equation gives fj = sum( A[j+i]R[i] ) / sum(R[i]^2).
  524. **
  525. ** Next, we compute the relative distance between the original signal and
  526. ** the modified signal and minimize that over j:
  527. ** vj = sum( (A[j+i]-fj*R[i])^2 ) / sum( A[j+i]^2 ) =>
  528. ** vj = ( sum(A[j+i]^2)*sum(R[i]^2) - sum(A[j+i]R[i])^2 ) / sum( A[j+i]^2 )
  529. **
  530. ** In the code variables correspond as follows:
  531. ** cp1 A
  532. ** cp2 R
  533. ** len1 N
  534. ** len2 n
  535. ** aj_m1 A[j-1]
  536. ** aj_lm1 A[j+n-1]
  537. ** sum_ri_2 sum(R[i]^2)
  538. ** sum_aij_2 sum(A[i+j]^2)
  539. ** sum_aij_ri sum(A[i+j]R[i])
  540. **
  541. ** sum_ri is calculated once, sum_aij_2 is updated each step and sum_aij_ri
  542. ** is completely recalculated each step.
  543. */
  544. /*[clinic input]
  545. audioop.findfit
  546. fragment: Py_buffer
  547. reference: Py_buffer
  548. /
  549. Try to match reference as well as possible to a portion of fragment.
  550. [clinic start generated code]*/
  551. static PyObject *
  552. audioop_findfit_impl(PyObject *module, Py_buffer *fragment,
  553. Py_buffer *reference)
  554. /*[clinic end generated code: output=5752306d83cbbada input=62c305605e183c9a]*/
  555. {
  556. const int16_t *cp1, *cp2;
  557. Py_ssize_t len1, len2;
  558. Py_ssize_t j, best_j;
  559. double aj_m1, aj_lm1;
  560. double sum_ri_2, sum_aij_2, sum_aij_ri, result, best_result, factor;
  561. if (fragment->len & 1 || reference->len & 1) {
  562. PyErr_SetString(get_audioop_state(module)->AudioopError,
  563. "Strings should be even-sized");
  564. return NULL;
  565. }
  566. cp1 = (const int16_t *)fragment->buf;
  567. len1 = fragment->len >> 1;
  568. cp2 = (const int16_t *)reference->buf;
  569. len2 = reference->len >> 1;
  570. if (len1 < len2) {
  571. PyErr_SetString(get_audioop_state(module)->AudioopError,
  572. "First sample should be longer");
  573. return NULL;
  574. }
  575. sum_ri_2 = _sum2(cp2, cp2, len2);
  576. sum_aij_2 = _sum2(cp1, cp1, len2);
  577. sum_aij_ri = _sum2(cp1, cp2, len2);
  578. result = (sum_ri_2*sum_aij_2 - sum_aij_ri*sum_aij_ri) / sum_aij_2;
  579. best_result = result;
  580. best_j = 0;
  581. for ( j=1; j<=len1-len2; j++) {
  582. aj_m1 = (double)cp1[j-1];
  583. aj_lm1 = (double)cp1[j+len2-1];
  584. sum_aij_2 = sum_aij_2 + aj_lm1*aj_lm1 - aj_m1*aj_m1;
  585. sum_aij_ri = _sum2(cp1+j, cp2, len2);
  586. result = (sum_ri_2*sum_aij_2 - sum_aij_ri*sum_aij_ri)
  587. / sum_aij_2;
  588. if ( result < best_result ) {
  589. best_result = result;
  590. best_j = j;
  591. }
  592. }
  593. factor = _sum2(cp1+best_j, cp2, len2) / sum_ri_2;
  594. return Py_BuildValue("(nf)", best_j, factor);
  595. }
  596. /*
  597. ** findfactor finds a factor f so that the energy in A-fB is minimal.
  598. ** See the comment for findfit for details.
  599. */
  600. /*[clinic input]
  601. audioop.findfactor
  602. fragment: Py_buffer
  603. reference: Py_buffer
  604. /
  605. Return a factor F such that rms(add(fragment, mul(reference, -F))) is minimal.
  606. [clinic start generated code]*/
  607. static PyObject *
  608. audioop_findfactor_impl(PyObject *module, Py_buffer *fragment,
  609. Py_buffer *reference)
  610. /*[clinic end generated code: output=14ea95652c1afcf8 input=816680301d012b21]*/
  611. {
  612. const int16_t *cp1, *cp2;
  613. Py_ssize_t len;
  614. double sum_ri_2, sum_aij_ri, result;
  615. if (fragment->len & 1 || reference->len & 1) {
  616. PyErr_SetString(get_audioop_state(module)->AudioopError,
  617. "Strings should be even-sized");
  618. return NULL;
  619. }
  620. if (fragment->len != reference->len) {
  621. PyErr_SetString(get_audioop_state(module)->AudioopError,
  622. "Samples should be same size");
  623. return NULL;
  624. }
  625. cp1 = (const int16_t *)fragment->buf;
  626. cp2 = (const int16_t *)reference->buf;
  627. len = fragment->len >> 1;
  628. sum_ri_2 = _sum2(cp2, cp2, len);
  629. sum_aij_ri = _sum2(cp1, cp2, len);
  630. result = sum_aij_ri / sum_ri_2;
  631. return PyFloat_FromDouble(result);
  632. }
  633. /*
  634. ** findmax returns the index of the n-sized segment of the input sample
  635. ** that contains the most energy.
  636. */
  637. /*[clinic input]
  638. audioop.findmax
  639. fragment: Py_buffer
  640. length: Py_ssize_t
  641. /
  642. Search fragment for a slice of specified number of samples with maximum energy.
  643. [clinic start generated code]*/
  644. static PyObject *
  645. audioop_findmax_impl(PyObject *module, Py_buffer *fragment,
  646. Py_ssize_t length)
  647. /*[clinic end generated code: output=f008128233523040 input=2f304801ed42383c]*/
  648. {
  649. const int16_t *cp1;
  650. Py_ssize_t len1;
  651. Py_ssize_t j, best_j;
  652. double aj_m1, aj_lm1;
  653. double result, best_result;
  654. if (fragment->len & 1) {
  655. PyErr_SetString(get_audioop_state(module)->AudioopError,
  656. "Strings should be even-sized");
  657. return NULL;
  658. }
  659. cp1 = (const int16_t *)fragment->buf;
  660. len1 = fragment->len >> 1;
  661. if (length < 0 || len1 < length) {
  662. PyErr_SetString(get_audioop_state(module)->AudioopError,
  663. "Input sample should be longer");
  664. return NULL;
  665. }
  666. result = _sum2(cp1, cp1, length);
  667. best_result = result;
  668. best_j = 0;
  669. for ( j=1; j<=len1-length; j++) {
  670. aj_m1 = (double)cp1[j-1];
  671. aj_lm1 = (double)cp1[j+length-1];
  672. result = result + aj_lm1*aj_lm1 - aj_m1*aj_m1;
  673. if ( result > best_result ) {
  674. best_result = result;
  675. best_j = j;
  676. }
  677. }
  678. return PyLong_FromSsize_t(best_j);
  679. }
  680. /*[clinic input]
  681. audioop.avgpp
  682. fragment: Py_buffer
  683. width: int
  684. /
  685. Return the average peak-peak value over all samples in the fragment.
  686. [clinic start generated code]*/
  687. static PyObject *
  688. audioop_avgpp_impl(PyObject *module, Py_buffer *fragment, int width)
  689. /*[clinic end generated code: output=269596b0d5ae0b2b input=0b3cceeae420a7d9]*/
  690. {
  691. Py_ssize_t i;
  692. int prevval, prevextremevalid = 0, prevextreme = 0;
  693. double sum = 0.0;
  694. unsigned int avg;
  695. int diff, prevdiff, nextreme = 0;
  696. if (!audioop_check_parameters(module, fragment->len, width))
  697. return NULL;
  698. if (fragment->len <= width)
  699. return PyLong_FromLong(0);
  700. prevval = GETRAWSAMPLE(width, fragment->buf, 0);
  701. prevdiff = 17; /* Anything != 0, 1 */
  702. for (i = width; i < fragment->len; i += width) {
  703. int val = GETRAWSAMPLE(width, fragment->buf, i);
  704. if (val != prevval) {
  705. diff = val < prevval;
  706. if (prevdiff == !diff) {
  707. /* Derivative changed sign. Compute difference to last
  708. ** extreme value and remember.
  709. */
  710. if (prevextremevalid) {
  711. if (prevval < prevextreme)
  712. sum += (double)((unsigned int)prevextreme -
  713. (unsigned int)prevval);
  714. else
  715. sum += (double)((unsigned int)prevval -
  716. (unsigned int)prevextreme);
  717. nextreme++;
  718. }
  719. prevextremevalid = 1;
  720. prevextreme = prevval;
  721. }
  722. prevval = val;
  723. prevdiff = diff;
  724. }
  725. }
  726. if ( nextreme == 0 )
  727. avg = 0;
  728. else
  729. avg = (unsigned int)(sum / (double)nextreme);
  730. return PyLong_FromUnsignedLong(avg);
  731. }
  732. /*[clinic input]
  733. audioop.maxpp
  734. fragment: Py_buffer
  735. width: int
  736. /
  737. Return the maximum peak-peak value in the sound fragment.
  738. [clinic start generated code]*/
  739. static PyObject *
  740. audioop_maxpp_impl(PyObject *module, Py_buffer *fragment, int width)
  741. /*[clinic end generated code: output=5b918ed5dbbdb978 input=671a13e1518f80a1]*/
  742. {
  743. Py_ssize_t i;
  744. int prevval, prevextremevalid = 0, prevextreme = 0;
  745. unsigned int max = 0, extremediff;
  746. int diff, prevdiff;
  747. if (!audioop_check_parameters(module, fragment->len, width))
  748. return NULL;
  749. if (fragment->len <= width)
  750. return PyLong_FromLong(0);
  751. prevval = GETRAWSAMPLE(width, fragment->buf, 0);
  752. prevdiff = 17; /* Anything != 0, 1 */
  753. for (i = width; i < fragment->len; i += width) {
  754. int val = GETRAWSAMPLE(width, fragment->buf, i);
  755. if (val != prevval) {
  756. diff = val < prevval;
  757. if (prevdiff == !diff) {
  758. /* Derivative changed sign. Compute difference to
  759. ** last extreme value and remember.
  760. */
  761. if (prevextremevalid) {
  762. if (prevval < prevextreme)
  763. extremediff = (unsigned int)prevextreme -
  764. (unsigned int)prevval;
  765. else
  766. extremediff = (unsigned int)prevval -
  767. (unsigned int)prevextreme;
  768. if ( extremediff > max )
  769. max = extremediff;
  770. }
  771. prevextremevalid = 1;
  772. prevextreme = prevval;
  773. }
  774. prevval = val;
  775. prevdiff = diff;
  776. }
  777. }
  778. return PyLong_FromUnsignedLong(max);
  779. }
  780. /*[clinic input]
  781. audioop.cross
  782. fragment: Py_buffer
  783. width: int
  784. /
  785. Return the number of zero crossings in the fragment passed as an argument.
  786. [clinic start generated code]*/
  787. static PyObject *
  788. audioop_cross_impl(PyObject *module, Py_buffer *fragment, int width)
  789. /*[clinic end generated code: output=5938dcdd74a1f431 input=b1b3f15b83f6b41a]*/
  790. {
  791. Py_ssize_t i;
  792. int prevval;
  793. Py_ssize_t ncross;
  794. if (!audioop_check_parameters(module, fragment->len, width))
  795. return NULL;
  796. ncross = -1;
  797. prevval = 17; /* Anything <> 0,1 */
  798. for (i = 0; i < fragment->len; i += width) {
  799. int val = GETRAWSAMPLE(width, fragment->buf, i) < 0;
  800. if (val != prevval) ncross++;
  801. prevval = val;
  802. }
  803. return PyLong_FromSsize_t(ncross);
  804. }
  805. /*[clinic input]
  806. audioop.mul
  807. fragment: Py_buffer
  808. width: int
  809. factor: double
  810. /
  811. Return a fragment that has all samples in the original fragment multiplied by the floating-point value factor.
  812. [clinic start generated code]*/
  813. static PyObject *
  814. audioop_mul_impl(PyObject *module, Py_buffer *fragment, int width,
  815. double factor)
  816. /*[clinic end generated code: output=6cd48fe796da0ea4 input=c726667baa157d3c]*/
  817. {
  818. signed char *ncp;
  819. Py_ssize_t i;
  820. double maxval, minval;
  821. PyObject *rv;
  822. if (!audioop_check_parameters(module, fragment->len, width))
  823. return NULL;
  824. maxval = (double) maxvals[width];
  825. minval = (double) minvals[width];
  826. rv = PyBytes_FromStringAndSize(NULL, fragment->len);
  827. if (rv == NULL)
  828. return NULL;
  829. ncp = (signed char *)PyBytes_AsString(rv);
  830. for (i = 0; i < fragment->len; i += width) {
  831. double val = GETRAWSAMPLE(width, fragment->buf, i);
  832. int ival = fbound(val * factor, minval, maxval);
  833. SETRAWSAMPLE(width, ncp, i, ival);
  834. }
  835. return rv;
  836. }
  837. /*[clinic input]
  838. audioop.tomono
  839. fragment: Py_buffer
  840. width: int
  841. lfactor: double
  842. rfactor: double
  843. /
  844. Convert a stereo fragment to a mono fragment.
  845. [clinic start generated code]*/
  846. static PyObject *
  847. audioop_tomono_impl(PyObject *module, Py_buffer *fragment, int width,
  848. double lfactor, double rfactor)
  849. /*[clinic end generated code: output=235c8277216d4e4e input=c4ec949b3f4dddfa]*/
  850. {
  851. signed char *cp, *ncp;
  852. Py_ssize_t len, i;
  853. double maxval, minval;
  854. PyObject *rv;
  855. cp = fragment->buf;
  856. len = fragment->len;
  857. if (!audioop_check_parameters(module, len, width))
  858. return NULL;
  859. if (((len / width) & 1) != 0) {
  860. PyErr_SetString(get_audioop_state(module)->AudioopError,
  861. "not a whole number of frames");
  862. return NULL;
  863. }
  864. maxval = (double) maxvals[width];
  865. minval = (double) minvals[width];
  866. rv = PyBytes_FromStringAndSize(NULL, len/2);
  867. if (rv == NULL)
  868. return NULL;
  869. ncp = (signed char *)PyBytes_AsString(rv);
  870. for (i = 0; i < len; i += width*2) {
  871. double val1 = GETRAWSAMPLE(width, cp, i);
  872. double val2 = GETRAWSAMPLE(width, cp, i + width);
  873. double val = val1 * lfactor + val2 * rfactor;
  874. int ival = fbound(val, minval, maxval);
  875. SETRAWSAMPLE(width, ncp, i/2, ival);
  876. }
  877. return rv;
  878. }
  879. /*[clinic input]
  880. audioop.tostereo
  881. fragment: Py_buffer
  882. width: int
  883. lfactor: double
  884. rfactor: double
  885. /
  886. Generate a stereo fragment from a mono fragment.
  887. [clinic start generated code]*/
  888. static PyObject *
  889. audioop_tostereo_impl(PyObject *module, Py_buffer *fragment, int width,
  890. double lfactor, double rfactor)
  891. /*[clinic end generated code: output=046f13defa5f1595 input=27b6395ebfdff37a]*/
  892. {
  893. signed char *ncp;
  894. Py_ssize_t i;
  895. double maxval, minval;
  896. PyObject *rv;
  897. if (!audioop_check_parameters(module, fragment->len, width))
  898. return NULL;
  899. maxval = (double) maxvals[width];
  900. minval = (double) minvals[width];
  901. if (fragment->len > PY_SSIZE_T_MAX/2) {
  902. PyErr_SetString(PyExc_MemoryError,
  903. "not enough memory for output buffer");
  904. return NULL;
  905. }
  906. rv = PyBytes_FromStringAndSize(NULL, fragment->len*2);
  907. if (rv == NULL)
  908. return NULL;
  909. ncp = (signed char *)PyBytes_AsString(rv);
  910. for (i = 0; i < fragment->len; i += width) {
  911. double val = GETRAWSAMPLE(width, fragment->buf, i);
  912. int val1 = fbound(val * lfactor, minval, maxval);
  913. int val2 = fbound(val * rfactor, minval, maxval);
  914. SETRAWSAMPLE(width, ncp, i*2, val1);
  915. SETRAWSAMPLE(width, ncp, i*2 + width, val2);
  916. }
  917. return rv;
  918. }
  919. /*[clinic input]
  920. audioop.add
  921. fragment1: Py_buffer
  922. fragment2: Py_buffer
  923. width: int
  924. /
  925. Return a fragment which is the addition of the two samples passed as parameters.
  926. [clinic start generated code]*/
  927. static PyObject *
  928. audioop_add_impl(PyObject *module, Py_buffer *fragment1,
  929. Py_buffer *fragment2, int width)
  930. /*[clinic end generated code: output=60140af4d1aab6f2 input=4a8d4bae4c1605c7]*/
  931. {
  932. signed char *ncp;
  933. Py_ssize_t i;
  934. int minval, maxval, newval;
  935. PyObject *rv;
  936. if (!audioop_check_parameters(module, fragment1->len, width))
  937. return NULL;
  938. if (fragment1->len != fragment2->len) {
  939. PyErr_SetString(get_audioop_state(module)->AudioopError,
  940. "Lengths should be the same");
  941. return NULL;
  942. }
  943. maxval = maxvals[width];
  944. minval = minvals[width];
  945. rv = PyBytes_FromStringAndSize(NULL, fragment1->len);
  946. if (rv == NULL)
  947. return NULL;
  948. ncp = (signed char *)PyBytes_AsString(rv);
  949. for (i = 0; i < fragment1->len; i += width) {
  950. int val1 = GETRAWSAMPLE(width, fragment1->buf, i);
  951. int val2 = GETRAWSAMPLE(width, fragment2->buf, i);
  952. if (width < 4) {
  953. newval = val1 + val2;
  954. /* truncate in case of overflow */
  955. if (newval > maxval)
  956. newval = maxval;
  957. else if (newval < minval)
  958. newval = minval;
  959. }
  960. else {
  961. double fval = (double)val1 + (double)val2;
  962. /* truncate in case of overflow */
  963. newval = fbound(fval, minval, maxval);
  964. }
  965. SETRAWSAMPLE(width, ncp, i, newval);
  966. }
  967. return rv;
  968. }
  969. /*[clinic input]
  970. audioop.bias
  971. fragment: Py_buffer
  972. width: int
  973. bias: int
  974. /
  975. Return a fragment that is the original fragment with a bias added to each sample.
  976. [clinic start generated code]*/
  977. static PyObject *
  978. audioop_bias_impl(PyObject *module, Py_buffer *fragment, int width, int bias)
  979. /*[clinic end generated code: output=6e0aa8f68f045093 input=2b5cce5c3bb4838c]*/
  980. {
  981. signed char *ncp;
  982. Py_ssize_t i;
  983. unsigned int val = 0, mask;
  984. PyObject *rv;
  985. if (!audioop_check_parameters(module, fragment->len, width))
  986. return NULL;
  987. rv = PyBytes_FromStringAndSize(NULL, fragment->len);
  988. if (rv == NULL)
  989. return NULL;
  990. ncp = (signed char *)PyBytes_AsString(rv);
  991. mask = masks[width];
  992. for (i = 0; i < fragment->len; i += width) {
  993. if (width == 1)
  994. val = GETINTX(unsigned char, fragment->buf, i);
  995. else if (width == 2)
  996. val = GETINTX(uint16_t, fragment->buf, i);
  997. else if (width == 3)
  998. val = ((unsigned int)GETINT24(fragment->buf, i)) & 0xffffffu;
  999. else {
  1000. assert(width == 4);
  1001. val = GETINTX(uint32_t, fragment->buf, i);
  1002. }
  1003. val += (unsigned int)bias;
  1004. /* wrap around in case of overflow */
  1005. val &= mask;
  1006. if (width == 1)
  1007. SETINTX(unsigned char, ncp, i, val);
  1008. else if (width == 2)
  1009. SETINTX(uint16_t, ncp, i, val);
  1010. else if (width == 3)
  1011. SETINT24(ncp, i, (int)val);
  1012. else {
  1013. assert(width == 4);
  1014. SETINTX(uint32_t, ncp, i, val);
  1015. }
  1016. }
  1017. return rv;
  1018. }
  1019. /*[clinic input]
  1020. audioop.reverse
  1021. fragment: Py_buffer
  1022. width: int
  1023. /
  1024. Reverse the samples in a fragment and returns the modified fragment.
  1025. [clinic start generated code]*/
  1026. static PyObject *
  1027. audioop_reverse_impl(PyObject *module, Py_buffer *fragment, int width)
  1028. /*[clinic end generated code: output=b44135698418da14 input=668f890cf9f9d225]*/
  1029. {
  1030. unsigned char *ncp;
  1031. Py_ssize_t i;
  1032. PyObject *rv;
  1033. if (!audioop_check_parameters(module, fragment->len, width))
  1034. return NULL;
  1035. rv = PyBytes_FromStringAndSize(NULL, fragment->len);
  1036. if (rv == NULL)
  1037. return NULL;
  1038. ncp = (unsigned char *)PyBytes_AsString(rv);
  1039. for (i = 0; i < fragment->len; i += width) {
  1040. int val = GETRAWSAMPLE(width, fragment->buf, i);
  1041. SETRAWSAMPLE(width, ncp, fragment->len - i - width, val);
  1042. }
  1043. return rv;
  1044. }
  1045. /*[clinic input]
  1046. audioop.byteswap
  1047. fragment: Py_buffer
  1048. width: int
  1049. /
  1050. Convert big-endian samples to little-endian and vice versa.
  1051. [clinic start generated code]*/
  1052. static PyObject *
  1053. audioop_byteswap_impl(PyObject *module, Py_buffer *fragment, int width)
  1054. /*[clinic end generated code: output=50838a9e4b87cd4d input=fae7611ceffa5c82]*/
  1055. {
  1056. unsigned char *ncp;
  1057. Py_ssize_t i;
  1058. PyObject *rv;
  1059. if (!audioop_check_parameters(module, fragment->len, width))
  1060. return NULL;
  1061. rv = PyBytes_FromStringAndSize(NULL, fragment->len);
  1062. if (rv == NULL)
  1063. return NULL;
  1064. ncp = (unsigned char *)PyBytes_AsString(rv);
  1065. for (i = 0; i < fragment->len; i += width) {
  1066. int j;
  1067. for (j = 0; j < width; j++)
  1068. ncp[i + width - 1 - j] = ((unsigned char *)fragment->buf)[i + j];
  1069. }
  1070. return rv;
  1071. }
  1072. /*[clinic input]
  1073. audioop.lin2lin
  1074. fragment: Py_buffer
  1075. width: int
  1076. newwidth: int
  1077. /
  1078. Convert samples between 1-, 2-, 3- and 4-byte formats.
  1079. [clinic start generated code]*/
  1080. static PyObject *
  1081. audioop_lin2lin_impl(PyObject *module, Py_buffer *fragment, int width,
  1082. int newwidth)
  1083. /*[clinic end generated code: output=17b14109248f1d99 input=5ce08c8aa2f24d96]*/
  1084. {
  1085. unsigned char *ncp;
  1086. Py_ssize_t i, j;
  1087. PyObject *rv;
  1088. if (!audioop_check_parameters(module, fragment->len, width))
  1089. return NULL;
  1090. if (!audioop_check_size(module, newwidth))
  1091. return NULL;
  1092. if (fragment->len/width > PY_SSIZE_T_MAX/newwidth) {
  1093. PyErr_SetString(PyExc_MemoryError,
  1094. "not enough memory for output buffer");
  1095. return NULL;
  1096. }
  1097. rv = PyBytes_FromStringAndSize(NULL, (fragment->len/width)*newwidth);
  1098. if (rv == NULL)
  1099. return NULL;
  1100. ncp = (unsigned char *)PyBytes_AsString(rv);
  1101. for (i = j = 0; i < fragment->len; i += width, j += newwidth) {
  1102. int val = GETSAMPLE32(width, fragment->buf, i);
  1103. SETSAMPLE32(newwidth, ncp, j, val);
  1104. }
  1105. return rv;
  1106. }
  1107. static int
  1108. gcd(int a, int b)
  1109. {
  1110. while (b > 0) {
  1111. int tmp = a % b;
  1112. a = b;
  1113. b = tmp;
  1114. }
  1115. return a;
  1116. }
  1117. /*[clinic input]
  1118. audioop.ratecv
  1119. fragment: Py_buffer
  1120. width: int
  1121. nchannels: int
  1122. inrate: int
  1123. outrate: int
  1124. state: object
  1125. weightA: int = 1
  1126. weightB: int = 0
  1127. /
  1128. Convert the frame rate of the input fragment.
  1129. [clinic start generated code]*/
  1130. static PyObject *
  1131. audioop_ratecv_impl(PyObject *module, Py_buffer *fragment, int width,
  1132. int nchannels, int inrate, int outrate, PyObject *state,
  1133. int weightA, int weightB)
  1134. /*[clinic end generated code: output=624038e843243139 input=aff3acdc94476191]*/
  1135. {
  1136. char *cp, *ncp;
  1137. Py_ssize_t len;
  1138. int chan, d, *prev_i, *cur_i, cur_o;
  1139. PyObject *samps, *str, *rv = NULL, *channel;
  1140. int bytes_per_frame;
  1141. if (!audioop_check_size(module, width))
  1142. return NULL;
  1143. if (nchannels < 1) {
  1144. PyErr_SetString(get_audioop_state(module)->AudioopError,
  1145. "# of channels should be >= 1");
  1146. return NULL;
  1147. }
  1148. if (width > INT_MAX / nchannels) {
  1149. /* This overflow test is rigorously correct because
  1150. both multiplicands are >= 1. Use the argument names
  1151. from the docs for the error msg. */
  1152. PyErr_SetString(PyExc_OverflowError,
  1153. "width * nchannels too big for a C int");
  1154. return NULL;
  1155. }
  1156. bytes_per_frame = width * nchannels;
  1157. if (weightA < 1 || weightB < 0) {
  1158. PyErr_SetString(get_audioop_state(module)->AudioopError,
  1159. "weightA should be >= 1, weightB should be >= 0");
  1160. return NULL;
  1161. }
  1162. assert(fragment->len >= 0);
  1163. if (fragment->len % bytes_per_frame != 0) {
  1164. PyErr_SetString(get_audioop_state(module)->AudioopError,
  1165. "not a whole number of frames");
  1166. return NULL;
  1167. }
  1168. if (inrate <= 0 || outrate <= 0) {
  1169. PyErr_SetString(get_audioop_state(module)->AudioopError,
  1170. "sampling rate not > 0");
  1171. return NULL;
  1172. }
  1173. /* divide inrate and outrate by their greatest common divisor */
  1174. d = gcd(inrate, outrate);
  1175. inrate /= d;
  1176. outrate /= d;
  1177. /* divide weightA and weightB by their greatest common divisor */
  1178. d = gcd(weightA, weightB);
  1179. weightA /= d;
  1180. weightB /= d;
  1181. if ((size_t)nchannels > SIZE_MAX/sizeof(int)) {
  1182. PyErr_SetString(PyExc_MemoryError,
  1183. "not enough memory for output buffer");
  1184. return NULL;
  1185. }
  1186. prev_i = (int *) PyMem_Malloc(nchannels * sizeof(int));
  1187. cur_i = (int *) PyMem_Malloc(nchannels * sizeof(int));
  1188. if (prev_i == NULL || cur_i == NULL) {
  1189. (void) PyErr_NoMemory();
  1190. goto exit;
  1191. }
  1192. len = fragment->len / bytes_per_frame; /* # of frames */
  1193. if (state == Py_None) {
  1194. d = -outrate;
  1195. for (chan = 0; chan < nchannels; chan++)
  1196. prev_i[chan] = cur_i[chan] = 0;
  1197. }
  1198. else {
  1199. if (!PyTuple_Check(state)) {
  1200. PyErr_SetString(PyExc_TypeError, "state must be a tuple or None");
  1201. goto exit;
  1202. }
  1203. if (!PyArg_ParseTuple(state,
  1204. "iO!;ratecv(): illegal state argument",
  1205. &d, &PyTuple_Type, &samps))
  1206. goto exit;
  1207. if (PyTuple_Size(samps) != nchannels) {
  1208. PyErr_SetString(get_audioop_state(module)->AudioopError,
  1209. "illegal state argument");
  1210. goto exit;
  1211. }
  1212. for (chan = 0; chan < nchannels; chan++) {
  1213. channel = PyTuple_GetItem(samps, chan);
  1214. if (!PyTuple_Check(channel)) {
  1215. PyErr_SetString(PyExc_TypeError,
  1216. "ratecv(): illegal state argument");
  1217. goto exit;
  1218. }
  1219. if (!PyArg_ParseTuple(channel,
  1220. "ii;ratecv(): illegal state argument",
  1221. &prev_i[chan], &cur_i[chan]))
  1222. {
  1223. goto exit;
  1224. }
  1225. }
  1226. }
  1227. /* str <- Space for the output buffer. */
  1228. if (len == 0)
  1229. str = PyBytes_FromStringAndSize(NULL, 0);
  1230. else {
  1231. /* There are len input frames, so we need (mathematically)
  1232. ceiling(len*outrate/inrate) output frames, and each frame
  1233. requires bytes_per_frame bytes. Computing this
  1234. without spurious overflow is the challenge; we can
  1235. settle for a reasonable upper bound, though, in this
  1236. case ceiling(len/inrate) * outrate. */
  1237. /* compute ceiling(len/inrate) without overflow */
  1238. Py_ssize_t q = 1 + (len - 1) / inrate;
  1239. if (outrate > PY_SSIZE_T_MAX / q / bytes_per_frame)
  1240. str = NULL;
  1241. else
  1242. str = PyBytes_FromStringAndSize(NULL,
  1243. q * outrate * bytes_per_frame);
  1244. }
  1245. if (str == NULL) {
  1246. PyErr_SetString(PyExc_MemoryError,
  1247. "not enough memory for output buffer");
  1248. goto exit;
  1249. }
  1250. ncp = PyBytes_AsString(str);
  1251. cp = fragment->buf;
  1252. for (;;) {
  1253. while (d < 0) {
  1254. if (len == 0) {
  1255. samps = PyTuple_New(nchannels);
  1256. if (samps == NULL)
  1257. goto exit;
  1258. for (chan = 0; chan < nchannels; chan++)
  1259. PyTuple_SetItem(samps, chan,
  1260. Py_BuildValue("(ii)",
  1261. prev_i[chan],
  1262. cur_i[chan]));
  1263. if (PyErr_Occurred())
  1264. goto exit;
  1265. /* We have checked before that the length
  1266. * of the string fits into int. */
  1267. len = (Py_ssize_t)(ncp - PyBytes_AsString(str));
  1268. rv = PyBytes_FromStringAndSize
  1269. (PyBytes_AsString(str), len);
  1270. Py_SETREF(str, rv);
  1271. if (str == NULL)
  1272. goto exit;
  1273. rv = Py_BuildValue("(O(iO))", str, d, samps);
  1274. Py_DECREF(samps);
  1275. Py_DECREF(str);
  1276. goto exit; /* return rv */
  1277. }
  1278. for (chan = 0; chan < nchannels; chan++) {
  1279. prev_i[chan] = cur_i[chan];
  1280. cur_i[chan] = GETSAMPLE32(width, cp, 0);
  1281. cp += width;
  1282. /* implements a simple digital filter */
  1283. cur_i[chan] = (int)(
  1284. ((double)weightA * (double)cur_i[chan] +
  1285. (double)weightB * (double)prev_i[chan]) /
  1286. ((double)weightA + (double)weightB));
  1287. }
  1288. len--;
  1289. d += outrate;
  1290. }
  1291. while (d >= 0) {
  1292. for (chan = 0; chan < nchannels; chan++) {
  1293. cur_o = (int)(((double)prev_i[chan] * (double)d +
  1294. (double)cur_i[chan] * (double)(outrate - d)) /
  1295. (double)outrate);
  1296. SETSAMPLE32(width, ncp, 0, cur_o);
  1297. ncp += width;
  1298. }
  1299. d -= inrate;
  1300. }
  1301. }
  1302. exit:
  1303. PyMem_Free(prev_i);
  1304. PyMem_Free(cur_i);
  1305. return rv;
  1306. }
  1307. /*[clinic input]
  1308. audioop.lin2ulaw
  1309. fragment: Py_buffer
  1310. width: int
  1311. /
  1312. Convert samples in the audio fragment to u-LAW encoding.
  1313. [clinic start generated code]*/
  1314. static PyObject *
  1315. audioop_lin2ulaw_impl(PyObject *module, Py_buffer *fragment, int width)
  1316. /*[clinic end generated code: output=14fb62b16fe8ea8e input=2450d1b870b6bac2]*/
  1317. {
  1318. unsigned char *ncp;
  1319. Py_ssize_t i;
  1320. PyObject *rv;
  1321. if (!audioop_check_parameters(module, fragment->len, width))
  1322. return NULL;
  1323. rv = PyBytes_FromStringAndSize(NULL, fragment->len/width);
  1324. if (rv == NULL)
  1325. return NULL;
  1326. ncp = (unsigned char *)PyBytes_AsString(rv);
  1327. for (i = 0; i < fragment->len; i += width) {
  1328. int val = GETSAMPLE32(width, fragment->buf, i);
  1329. *ncp++ = st_14linear2ulaw(val >> 18);
  1330. }
  1331. return rv;
  1332. }
  1333. /*[clinic input]
  1334. audioop.ulaw2lin
  1335. fragment: Py_buffer
  1336. width: int
  1337. /
  1338. Convert sound fragments in u-LAW encoding to linearly encoded sound fragments.
  1339. [clinic start generated code]*/
  1340. static PyObject *
  1341. audioop_ulaw2lin_impl(PyObject *module, Py_buffer *fragment, int width)
  1342. /*[clinic end generated code: output=378356b047521ba2 input=45d53ddce5be7d06]*/
  1343. {
  1344. unsigned char *cp;
  1345. signed char *ncp;
  1346. Py_ssize_t i;
  1347. PyObject *rv;
  1348. if (!audioop_check_size(module, width))
  1349. return NULL;
  1350. if (fragment->len > PY_SSIZE_T_MAX/width) {
  1351. PyErr_SetString(PyExc_MemoryError,
  1352. "not enough memory for output buffer");
  1353. return NULL;
  1354. }
  1355. rv = PyBytes_FromStringAndSize(NULL, fragment->len*width);
  1356. if (rv == NULL)
  1357. return NULL;
  1358. ncp = (signed char *)PyBytes_AsString(rv);
  1359. cp = fragment->buf;
  1360. for (i = 0; i < fragment->len*width; i += width) {
  1361. int val = st_ulaw2linear16(*cp++) * (1 << 16);
  1362. SETSAMPLE32(width, ncp, i, val);
  1363. }
  1364. return rv;
  1365. }
  1366. /*[clinic input]
  1367. audioop.lin2alaw
  1368. fragment: Py_buffer
  1369. width: int
  1370. /
  1371. Convert samples in the audio fragment to a-LAW encoding.
  1372. [clinic start generated code]*/
  1373. static PyObject *
  1374. audioop_lin2alaw_impl(PyObject *module, Py_buffer *fragment, int width)
  1375. /*[clinic end generated code: output=d076f130121a82f0 input=ffb1ef8bb39da945]*/
  1376. {
  1377. unsigned char *ncp;
  1378. Py_ssize_t i;
  1379. PyObject *rv;
  1380. if (!audioop_check_parameters(module, fragment->len, width))
  1381. return NULL;
  1382. rv = PyBytes_FromStringAndSize(NULL, fragment->len/width);
  1383. if (rv == NULL)
  1384. return NULL;
  1385. ncp = (unsigned char *)PyBytes_AsString(rv);
  1386. for (i = 0; i < fragment->len; i += width) {
  1387. int val = GETSAMPLE32(width, fragment->buf, i);
  1388. *ncp++ = st_linear2alaw(val >> 19);
  1389. }
  1390. return rv;
  1391. }
  1392. /*[clinic input]
  1393. audioop.alaw2lin
  1394. fragment: Py_buffer
  1395. width: int
  1396. /
  1397. Convert sound fragments in a-LAW encoding to linearly encoded sound fragments.
  1398. [clinic start generated code]*/
  1399. static PyObject *
  1400. audioop_alaw2lin_impl(PyObject *module, Py_buffer *fragment, int width)
  1401. /*[clinic end generated code: output=85c365ec559df647 input=4140626046cd1772]*/
  1402. {
  1403. unsigned char *cp;
  1404. signed char *ncp;
  1405. Py_ssize_t i;
  1406. int val;
  1407. PyObject *rv;
  1408. if (!audioop_check_size(module, width))
  1409. return NULL;
  1410. if (fragment->len > PY_SSIZE_T_MAX/width) {
  1411. PyErr_SetString(PyExc_MemoryError,
  1412. "not enough memory for output buffer");
  1413. return NULL;
  1414. }
  1415. rv = PyBytes_FromStringAndSize(NULL, fragment->len*width);
  1416. if (rv == NULL)
  1417. return NULL;
  1418. ncp = (signed char *)PyBytes_AsString(rv);
  1419. cp = fragment->buf;
  1420. for (i = 0; i < fragment->len*width; i += width) {
  1421. val = st_alaw2linear16(*cp++) * (1 << 16);
  1422. SETSAMPLE32(width, ncp, i, val);
  1423. }
  1424. return rv;
  1425. }
  1426. /*[clinic input]
  1427. audioop.lin2adpcm
  1428. fragment: Py_buffer
  1429. width: int
  1430. state: object
  1431. /
  1432. Convert samples to 4 bit Intel/DVI ADPCM encoding.
  1433. [clinic start generated code]*/
  1434. static PyObject *
  1435. audioop_lin2adpcm_impl(PyObject *module, Py_buffer *fragment, int width,
  1436. PyObject *state)
  1437. /*[clinic end generated code: output=cc19f159f16c6793 input=12919d549b90c90a]*/
  1438. {
  1439. signed char *ncp;
  1440. Py_ssize_t i;
  1441. int step, valpred, delta,
  1442. index, sign, vpdiff, diff;
  1443. PyObject *rv = NULL, *str;
  1444. int outputbuffer = 0, bufferstep;
  1445. if (!audioop_check_parameters(module, fragment->len, width))
  1446. return NULL;
  1447. /* Decode state, should have (value, step) */
  1448. if ( state == Py_None ) {
  1449. /* First time, it seems. Set defaults */
  1450. valpred = 0;
  1451. index = 0;
  1452. }
  1453. else if (!PyTuple_Check(state)) {
  1454. PyErr_SetString(PyExc_TypeError, "state must be a tuple or None");
  1455. return NULL;
  1456. }
  1457. else if (!PyArg_ParseTuple(state, "ii;lin2adpcm(): illegal state argument",
  1458. &valpred, &index))
  1459. {
  1460. return NULL;
  1461. }
  1462. else if (valpred >= 0x8000 || valpred < -0x8000 ||
  1463. (size_t)index >= Py_ARRAY_LENGTH(stepsizeTable)) {
  1464. PyErr_SetString(PyExc_ValueError, "bad state");
  1465. return NULL;
  1466. }
  1467. str = PyBytes_FromStringAndSize(NULL, fragment->len/(width*2));
  1468. if (str == NULL)
  1469. return NULL;
  1470. ncp = (signed char *)PyBytes_AsString(str);
  1471. step = stepsizeTable[index];
  1472. bufferstep = 1;
  1473. for (i = 0; i < fragment->len; i += width) {
  1474. int val = GETSAMPLE32(width, fragment->buf, i) >> 16;
  1475. /* Step 1 - compute difference with previous value */
  1476. if (val < valpred) {
  1477. diff = valpred - val;
  1478. sign = 8;
  1479. }
  1480. else {
  1481. diff = val - valpred;
  1482. sign = 0;
  1483. }
  1484. /* Step 2 - Divide and clamp */
  1485. /* Note:
  1486. ** This code *approximately* computes:
  1487. ** delta = diff*4/step;
  1488. ** vpdiff = (delta+0.5)*step/4;
  1489. ** but in shift step bits are dropped. The net result of this
  1490. ** is that even if you have fast mul/div hardware you cannot
  1491. ** put it to good use since the fixup would be too expensive.
  1492. */
  1493. delta = 0;
  1494. vpdiff = (step >> 3);
  1495. if ( diff >= step ) {
  1496. delta = 4;
  1497. diff -= step;
  1498. vpdiff += step;
  1499. }
  1500. step >>= 1;
  1501. if ( diff >= step ) {
  1502. delta |= 2;
  1503. diff -= step;
  1504. vpdiff += step;
  1505. }
  1506. step >>= 1;
  1507. if ( diff >= step ) {
  1508. delta |= 1;
  1509. vpdiff += step;
  1510. }
  1511. /* Step 3 - Update previous value */
  1512. if ( sign )
  1513. valpred -= vpdiff;
  1514. else
  1515. valpred += vpdiff;
  1516. /* Step 4 - Clamp previous value to 16 bits */
  1517. if ( valpred > 32767 )
  1518. valpred = 32767;
  1519. else if ( valpred < -32768 )
  1520. valpred = -32768;
  1521. /* Step 5 - Assemble value, update index and step values */
  1522. delta |= sign;
  1523. index += indexTable[delta];
  1524. if ( index < 0 ) index = 0;
  1525. if ( index > 88 ) index = 88;
  1526. step = stepsizeTable[index];
  1527. /* Step 6 - Output value */
  1528. if ( bufferstep ) {
  1529. outputbuffer = (delta * (1 << 4)) & 0xf0;
  1530. } else {
  1531. *ncp++ = (delta & 0x0f) | outputbuffer;
  1532. }
  1533. bufferstep = !bufferstep;
  1534. }
  1535. rv = Py_BuildValue("(O(ii))", str, valpred, index);
  1536. Py_DECREF(str);
  1537. return rv;
  1538. }
  1539. /*[clinic input]
  1540. audioop.adpcm2lin
  1541. fragment: Py_buffer
  1542. width: int
  1543. state: object
  1544. /
  1545. Decode an Intel/DVI ADPCM coded fragment to a linear fragment.
  1546. [clinic start generated code]*/
  1547. static PyObject *
  1548. audioop_adpcm2lin_impl(PyObject *module, Py_buffer *fragment, int width,
  1549. PyObject *state)
  1550. /*[clinic end generated code: output=3440ea105acb3456 input=f5221144f5ca9ef0]*/
  1551. {
  1552. signed char *cp;
  1553. signed char *ncp;
  1554. Py_ssize_t i, outlen;
  1555. int valpred, step, delta, index, sign, vpdiff;
  1556. PyObject *rv, *str;
  1557. int inputbuffer = 0, bufferstep;
  1558. if (!audioop_check_size(module, width))
  1559. return NULL;
  1560. /* Decode state, should have (value, step) */
  1561. if ( state == Py_None ) {
  1562. /* First time, it seems. Set defaults */
  1563. valpred = 0;
  1564. index = 0;
  1565. }
  1566. else if (!PyTuple_Check(state)) {
  1567. PyErr_SetString(PyExc_TypeError, "state must be a tuple or None");
  1568. return NULL;
  1569. }
  1570. else if (!PyArg_ParseTuple(state, "ii;adpcm2lin(): illegal state argument",
  1571. &valpred, &index))
  1572. {
  1573. return NULL;
  1574. }
  1575. else if (valpred >= 0x8000 || valpred < -0x8000 ||
  1576. (size_t)index >= Py_ARRAY_LENGTH(stepsizeTable)) {
  1577. PyErr_SetString(PyExc_ValueError, "bad state");
  1578. return NULL;
  1579. }
  1580. if (fragment->len > (PY_SSIZE_T_MAX/2)/width) {
  1581. PyErr_SetString(PyExc_MemoryError,
  1582. "not enough memory for output buffer");
  1583. return NULL;
  1584. }
  1585. outlen = fragment->len*width*2;
  1586. str = PyBytes_FromStringAndSize(NULL, outlen);
  1587. if (str == NULL)
  1588. return NULL;
  1589. ncp = (signed char *)PyBytes_AsString(str);
  1590. cp = fragment->buf;
  1591. step = stepsizeTable[index];
  1592. bufferstep = 0;
  1593. for (i = 0; i < outlen; i += width) {
  1594. /* Step 1 - get the delta value and compute next index */
  1595. if ( bufferstep ) {
  1596. delta = inputbuffer & 0xf;
  1597. } else {
  1598. inputbuffer = *cp++;
  1599. delta = (inputbuffer >> 4) & 0xf;
  1600. }
  1601. bufferstep = !bufferstep;
  1602. /* Step 2 - Find new index value (for later) */
  1603. index += indexTable[delta];
  1604. if ( index < 0 ) index = 0;
  1605. if ( index > 88 ) index = 88;
  1606. /* Step 3 - Separate sign and magnitude */
  1607. sign = delta & 8;
  1608. delta = delta & 7;
  1609. /* Step 4 - Compute difference and new predicted value */
  1610. /*
  1611. ** Computes 'vpdiff = (delta+0.5)*step/4', but see comment
  1612. ** in adpcm_coder.
  1613. */
  1614. vpdiff = step >> 3;
  1615. if ( delta & 4 ) vpdiff += step;
  1616. if ( delta & 2 ) vpdiff += step>>1;
  1617. if ( delta & 1 ) vpdiff += step>>2;
  1618. if ( sign )
  1619. valpred -= vpdiff;
  1620. else
  1621. valpred += vpdiff;
  1622. /* Step 5 - clamp output value */
  1623. if ( valpred > 32767 )
  1624. valpred = 32767;
  1625. else if ( valpred < -32768 )
  1626. valpred = -32768;
  1627. /* Step 6 - Update step value */
  1628. step = stepsizeTable[index];
  1629. /* Step 6 - Output value */
  1630. SETSAMPLE32(width, ncp, i, valpred * (1 << 16));
  1631. }
  1632. rv = Py_BuildValue("(O(ii))", str, valpred, index);
  1633. Py_DECREF(str);
  1634. return rv;
  1635. }
  1636. #include "clinic/audioop.c.h"
  1637. static PyMethodDef audioop_methods[] = {
  1638. AUDIOOP_MAX_METHODDEF
  1639. AUDIOOP_MINMAX_METHODDEF
  1640. AUDIOOP_AVG_METHODDEF
  1641. AUDIOOP_MAXPP_METHODDEF
  1642. AUDIOOP_AVGPP_METHODDEF
  1643. AUDIOOP_RMS_METHODDEF
  1644. AUDIOOP_FINDFIT_METHODDEF
  1645. AUDIOOP_FINDMAX_METHODDEF
  1646. AUDIOOP_FINDFACTOR_METHODDEF
  1647. AUDIOOP_CROSS_METHODDEF
  1648. AUDIOOP_MUL_METHODDEF
  1649. AUDIOOP_ADD_METHODDEF
  1650. AUDIOOP_BIAS_METHODDEF
  1651. AUDIOOP_ULAW2LIN_METHODDEF
  1652. AUDIOOP_LIN2ULAW_METHODDEF
  1653. AUDIOOP_ALAW2LIN_METHODDEF
  1654. AUDIOOP_LIN2ALAW_METHODDEF
  1655. AUDIOOP_LIN2LIN_METHODDEF
  1656. AUDIOOP_ADPCM2LIN_METHODDEF
  1657. AUDIOOP_LIN2ADPCM_METHODDEF
  1658. AUDIOOP_TOMONO_METHODDEF
  1659. AUDIOOP_TOSTEREO_METHODDEF
  1660. AUDIOOP_GETSAMPLE_METHODDEF
  1661. AUDIOOP_REVERSE_METHODDEF
  1662. AUDIOOP_BYTESWAP_METHODDEF
  1663. AUDIOOP_RATECV_METHODDEF
  1664. { 0, 0 }
  1665. };
  1666. static int
  1667. audioop_traverse(PyObject *module, visitproc visit, void *arg)
  1668. {
  1669. audioop_state *state = get_audioop_state(module);
  1670. Py_VISIT(state->AudioopError);
  1671. return 0;
  1672. }
  1673. static int
  1674. audioop_clear(PyObject *module)
  1675. {
  1676. audioop_state *state = get_audioop_state(module);
  1677. Py_CLEAR(state->AudioopError);
  1678. return 0;
  1679. }
  1680. static void
  1681. audioop_free(void *module) {
  1682. audioop_clear((PyObject *)module);
  1683. }
  1684. static int
  1685. audioop_exec(PyObject* module)
  1686. {
  1687. audioop_state *state = get_audioop_state(module);
  1688. state->AudioopError = PyErr_NewException("audioop.error", NULL, NULL);
  1689. if (state->AudioopError == NULL) {
  1690. return -1;
  1691. }
  1692. Py_INCREF(state->AudioopError);
  1693. if (PyModule_AddObject(module, "error", state->AudioopError) < 0) {
  1694. Py_DECREF(state->AudioopError);
  1695. return -1;
  1696. }
  1697. return 0;
  1698. }
  1699. static PyModuleDef_Slot audioop_slots[] = {
  1700. {Py_mod_exec, audioop_exec},
  1701. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  1702. {0, NULL}
  1703. };
  1704. static struct PyModuleDef audioopmodule = {
  1705. PyModuleDef_HEAD_INIT,
  1706. "audioop",
  1707. NULL,
  1708. sizeof(audioop_state),
  1709. audioop_methods,
  1710. audioop_slots,
  1711. audioop_traverse,
  1712. audioop_clear,
  1713. audioop_free
  1714. };
  1715. PyMODINIT_FUNC
  1716. PyInit_audioop(void)
  1717. {
  1718. if (PyErr_WarnEx(PyExc_DeprecationWarning,
  1719. "'audioop' is deprecated and slated for removal in "
  1720. "Python 3.13",
  1721. 7)) {
  1722. return NULL;
  1723. }
  1724. return PyModuleDef_Init(&audioopmodule);
  1725. }