SDL_audiocvt.c 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2021 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "../SDL_internal.h"
  19. /* Functions for audio drivers to perform runtime conversion of audio format */
  20. /* FIXME: Channel weights when converting from more channels to fewer may need to be adjusted, see https://msdn.microsoft.com/en-us/library/windows/desktop/ff819070(v=vs.85).aspx
  21. */
  22. #include "SDL.h"
  23. #include "SDL_audio.h"
  24. #include "SDL_audio_c.h"
  25. #include "SDL_loadso.h"
  26. #include "../SDL_dataqueue.h"
  27. #include "SDL_cpuinfo.h"
  28. #define DEBUG_AUDIOSTREAM 0
  29. #ifdef __SSE3__
  30. #define HAVE_SSE3_INTRINSICS 1
  31. #endif
  32. #if HAVE_SSE3_INTRINSICS
  33. /* Convert from stereo to mono. Average left and right. */
  34. static void SDLCALL
  35. SDL_ConvertStereoToMono_SSE3(SDL_AudioCVT * cvt, SDL_AudioFormat format)
  36. {
  37. float *dst = (float *) cvt->buf;
  38. const float *src = dst;
  39. int i = cvt->len_cvt / 8;
  40. LOG_DEBUG_CONVERT("stereo", "mono (using SSE3)");
  41. SDL_assert(format == AUDIO_F32SYS);
  42. /* We can only do this if dst is aligned to 16 bytes; since src is the
  43. same pointer and it moves by 2, it can't be forcibly aligned. */
  44. if ((((size_t) dst) & 15) == 0) {
  45. /* Aligned! Do SSE blocks as long as we have 16 bytes available. */
  46. const __m128 divby2 = _mm_set1_ps(0.5f);
  47. while (i >= 4) { /* 4 * float32 */
  48. _mm_store_ps(dst, _mm_mul_ps(_mm_hadd_ps(_mm_load_ps(src), _mm_load_ps(src+4)), divby2));
  49. i -= 4; src += 8; dst += 4;
  50. }
  51. }
  52. /* Finish off any leftovers with scalar operations. */
  53. while (i) {
  54. *dst = (src[0] + src[1]) * 0.5f;
  55. dst++; i--; src += 2;
  56. }
  57. cvt->len_cvt /= 2;
  58. if (cvt->filters[++cvt->filter_index]) {
  59. cvt->filters[cvt->filter_index] (cvt, format);
  60. }
  61. }
  62. #endif
  63. /* Convert from stereo to mono. Average left and right. */
  64. static void SDLCALL
  65. SDL_ConvertStereoToMono(SDL_AudioCVT * cvt, SDL_AudioFormat format)
  66. {
  67. float *dst = (float *) cvt->buf;
  68. const float *src = dst;
  69. int i;
  70. LOG_DEBUG_CONVERT("stereo", "mono");
  71. SDL_assert(format == AUDIO_F32SYS);
  72. for (i = cvt->len_cvt / 8; i; --i, src += 2) {
  73. *(dst++) = (src[0] + src[1]) * 0.5f;
  74. }
  75. cvt->len_cvt /= 2;
  76. if (cvt->filters[++cvt->filter_index]) {
  77. cvt->filters[cvt->filter_index] (cvt, format);
  78. }
  79. }
  80. /* Convert from 5.1 to stereo. Average left and right, distribute center, discard LFE. */
  81. static void SDLCALL
  82. SDL_Convert51ToStereo(SDL_AudioCVT * cvt, SDL_AudioFormat format)
  83. {
  84. float *dst = (float *) cvt->buf;
  85. const float *src = dst;
  86. int i;
  87. LOG_DEBUG_CONVERT("5.1", "stereo");
  88. SDL_assert(format == AUDIO_F32SYS);
  89. /* SDL's 5.1 layout: FL+FR+FC+LFE+BL+BR */
  90. for (i = cvt->len_cvt / (sizeof (float) * 6); i; --i, src += 6, dst += 2) {
  91. const float front_center_distributed = src[2] * 0.5f;
  92. dst[0] = (src[0] + front_center_distributed + src[4]) / 2.5f; /* left */
  93. dst[1] = (src[1] + front_center_distributed + src[5]) / 2.5f; /* right */
  94. }
  95. cvt->len_cvt /= 3;
  96. if (cvt->filters[++cvt->filter_index]) {
  97. cvt->filters[cvt->filter_index] (cvt, format);
  98. }
  99. }
  100. /* Convert from quad to stereo. Average left and right. */
  101. static void SDLCALL
  102. SDL_ConvertQuadToStereo(SDL_AudioCVT * cvt, SDL_AudioFormat format)
  103. {
  104. float *dst = (float *) cvt->buf;
  105. const float *src = dst;
  106. int i;
  107. LOG_DEBUG_CONVERT("quad", "stereo");
  108. SDL_assert(format == AUDIO_F32SYS);
  109. for (i = cvt->len_cvt / (sizeof (float) * 4); i; --i, src += 4, dst += 2) {
  110. dst[0] = (src[0] + src[2]) * 0.5f; /* left */
  111. dst[1] = (src[1] + src[3]) * 0.5f; /* right */
  112. }
  113. cvt->len_cvt /= 2;
  114. if (cvt->filters[++cvt->filter_index]) {
  115. cvt->filters[cvt->filter_index] (cvt, format);
  116. }
  117. }
  118. /* Convert from 7.1 to 5.1. Distribute sides across front and back. */
  119. static void SDLCALL
  120. SDL_Convert71To51(SDL_AudioCVT * cvt, SDL_AudioFormat format)
  121. {
  122. float *dst = (float *) cvt->buf;
  123. const float *src = dst;
  124. int i;
  125. LOG_DEBUG_CONVERT("7.1", "5.1");
  126. SDL_assert(format == AUDIO_F32SYS);
  127. for (i = cvt->len_cvt / (sizeof (float) * 8); i; --i, src += 8, dst += 6) {
  128. const float surround_left_distributed = src[6] * 0.5f;
  129. const float surround_right_distributed = src[7] * 0.5f;
  130. dst[0] = (src[0] + surround_left_distributed) / 1.5f; /* FL */
  131. dst[1] = (src[1] + surround_right_distributed) / 1.5f; /* FR */
  132. dst[2] = src[2] / 1.5f; /* CC */
  133. dst[3] = src[3] / 1.5f; /* LFE */
  134. dst[4] = (src[4] + surround_left_distributed) / 1.5f; /* BL */
  135. dst[5] = (src[5] + surround_right_distributed) / 1.5f; /* BR */
  136. }
  137. cvt->len_cvt /= 8;
  138. cvt->len_cvt *= 6;
  139. if (cvt->filters[++cvt->filter_index]) {
  140. cvt->filters[cvt->filter_index] (cvt, format);
  141. }
  142. }
  143. /* Convert from 5.1 to quad. Distribute center across front, discard LFE. */
  144. static void SDLCALL
  145. SDL_Convert51ToQuad(SDL_AudioCVT * cvt, SDL_AudioFormat format)
  146. {
  147. float *dst = (float *) cvt->buf;
  148. const float *src = dst;
  149. int i;
  150. LOG_DEBUG_CONVERT("5.1", "quad");
  151. SDL_assert(format == AUDIO_F32SYS);
  152. /* SDL's 4.0 layout: FL+FR+BL+BR */
  153. /* SDL's 5.1 layout: FL+FR+FC+LFE+BL+BR */
  154. for (i = cvt->len_cvt / (sizeof (float) * 6); i; --i, src += 6, dst += 4) {
  155. const float front_center_distributed = src[2] * 0.5f;
  156. dst[0] = (src[0] + front_center_distributed) / 1.5f; /* FL */
  157. dst[1] = (src[1] + front_center_distributed) / 1.5f; /* FR */
  158. dst[2] = src[4] / 1.5f; /* BL */
  159. dst[3] = src[5] / 1.5f; /* BR */
  160. }
  161. cvt->len_cvt /= 6;
  162. cvt->len_cvt *= 4;
  163. if (cvt->filters[++cvt->filter_index]) {
  164. cvt->filters[cvt->filter_index] (cvt, format);
  165. }
  166. }
  167. /* Upmix mono to stereo (by duplication) */
  168. static void SDLCALL
  169. SDL_ConvertMonoToStereo(SDL_AudioCVT * cvt, SDL_AudioFormat format)
  170. {
  171. const float *src = (const float *) (cvt->buf + cvt->len_cvt);
  172. float *dst = (float *) (cvt->buf + cvt->len_cvt * 2);
  173. int i;
  174. LOG_DEBUG_CONVERT("mono", "stereo");
  175. SDL_assert(format == AUDIO_F32SYS);
  176. for (i = cvt->len_cvt / sizeof (float); i; --i) {
  177. src--;
  178. dst -= 2;
  179. dst[0] = dst[1] = *src;
  180. }
  181. cvt->len_cvt *= 2;
  182. if (cvt->filters[++cvt->filter_index]) {
  183. cvt->filters[cvt->filter_index] (cvt, format);
  184. }
  185. }
  186. /* Upmix stereo to a pseudo-5.1 stream */
  187. static void SDLCALL
  188. SDL_ConvertStereoTo51(SDL_AudioCVT * cvt, SDL_AudioFormat format)
  189. {
  190. int i;
  191. float lf, rf, ce;
  192. const float *src = (const float *) (cvt->buf + cvt->len_cvt);
  193. float *dst = (float *) (cvt->buf + cvt->len_cvt * 3);
  194. LOG_DEBUG_CONVERT("stereo", "5.1");
  195. SDL_assert(format == AUDIO_F32SYS);
  196. for (i = cvt->len_cvt / (sizeof(float) * 2); i; --i) {
  197. dst -= 6;
  198. src -= 2;
  199. lf = src[0];
  200. rf = src[1];
  201. ce = (lf + rf) * 0.5f;
  202. dst[0] = 0.5f * (lf + (lf - ce)); /* FL */
  203. dst[1] = 0.5f * (rf + (rf - ce)); /* FR */
  204. dst[2] = ce; /* FC */
  205. dst[3] = 0; /* LFE (only meant for special LFE effects) */
  206. dst[4] = lf; /* BL */
  207. dst[5] = rf; /* BR */
  208. }
  209. cvt->len_cvt *= 3;
  210. if (cvt->filters[++cvt->filter_index]) {
  211. cvt->filters[cvt->filter_index] (cvt, format);
  212. }
  213. }
  214. /* Upmix quad to a pseudo-5.1 stream */
  215. static void SDLCALL
  216. SDL_ConvertQuadTo51(SDL_AudioCVT * cvt, SDL_AudioFormat format)
  217. {
  218. int i;
  219. float lf, rf, lb, rb, ce;
  220. const float *src = (const float *) (cvt->buf + cvt->len_cvt);
  221. float *dst = (float *) (cvt->buf + cvt->len_cvt * 3 / 2);
  222. LOG_DEBUG_CONVERT("quad", "5.1");
  223. SDL_assert(format == AUDIO_F32SYS);
  224. SDL_assert(cvt->len_cvt % (sizeof(float) * 4) == 0);
  225. for (i = cvt->len_cvt / (sizeof(float) * 4); i; --i) {
  226. dst -= 6;
  227. src -= 4;
  228. lf = src[0];
  229. rf = src[1];
  230. lb = src[2];
  231. rb = src[3];
  232. ce = (lf + rf) * 0.5f;
  233. dst[0] = 0.5f * (lf + (lf - ce)); /* FL */
  234. dst[1] = 0.5f * (rf + (rf - ce)); /* FR */
  235. dst[2] = ce; /* FC */
  236. dst[3] = 0; /* LFE (only meant for special LFE effects) */
  237. dst[4] = lb; /* BL */
  238. dst[5] = rb; /* BR */
  239. }
  240. cvt->len_cvt = cvt->len_cvt * 3 / 2;
  241. if (cvt->filters[++cvt->filter_index]) {
  242. cvt->filters[cvt->filter_index] (cvt, format);
  243. }
  244. }
  245. /* Upmix stereo to a pseudo-4.0 stream (by duplication) */
  246. static void SDLCALL
  247. SDL_ConvertStereoToQuad(SDL_AudioCVT * cvt, SDL_AudioFormat format)
  248. {
  249. const float *src = (const float *) (cvt->buf + cvt->len_cvt);
  250. float *dst = (float *) (cvt->buf + cvt->len_cvt * 2);
  251. float lf, rf;
  252. int i;
  253. LOG_DEBUG_CONVERT("stereo", "quad");
  254. SDL_assert(format == AUDIO_F32SYS);
  255. for (i = cvt->len_cvt / (sizeof(float) * 2); i; --i) {
  256. dst -= 4;
  257. src -= 2;
  258. lf = src[0];
  259. rf = src[1];
  260. dst[0] = lf; /* FL */
  261. dst[1] = rf; /* FR */
  262. dst[2] = lf; /* BL */
  263. dst[3] = rf; /* BR */
  264. }
  265. cvt->len_cvt *= 2;
  266. if (cvt->filters[++cvt->filter_index]) {
  267. cvt->filters[cvt->filter_index] (cvt, format);
  268. }
  269. }
  270. /* Upmix 5.1 to 7.1 */
  271. static void SDLCALL
  272. SDL_Convert51To71(SDL_AudioCVT * cvt, SDL_AudioFormat format)
  273. {
  274. float lf, rf, lb, rb, ls, rs;
  275. int i;
  276. const float *src = (const float *) (cvt->buf + cvt->len_cvt);
  277. float *dst = (float *) (cvt->buf + cvt->len_cvt * 4 / 3);
  278. LOG_DEBUG_CONVERT("5.1", "7.1");
  279. SDL_assert(format == AUDIO_F32SYS);
  280. SDL_assert(cvt->len_cvt % (sizeof(float) * 6) == 0);
  281. for (i = cvt->len_cvt / (sizeof(float) * 6); i; --i) {
  282. dst -= 8;
  283. src -= 6;
  284. lf = src[0];
  285. rf = src[1];
  286. lb = src[4];
  287. rb = src[5];
  288. ls = (lf + lb) * 0.5f;
  289. rs = (rf + rb) * 0.5f;
  290. lf += lf - ls;
  291. rf += rf - rs;
  292. lb += lb - ls;
  293. rb += rb - rs;
  294. dst[3] = src[3]; /* LFE */
  295. dst[2] = src[2]; /* FC */
  296. dst[7] = rs; /* SR */
  297. dst[6] = ls; /* SL */
  298. dst[5] = 0.5f * rb; /* BR */
  299. dst[4] = 0.5f * lb; /* BL */
  300. dst[1] = 0.5f * rf; /* FR */
  301. dst[0] = 0.5f * lf; /* FL */
  302. }
  303. cvt->len_cvt = cvt->len_cvt * 4 / 3;
  304. if (cvt->filters[++cvt->filter_index]) {
  305. cvt->filters[cvt->filter_index] (cvt, format);
  306. }
  307. }
  308. /* SDL's resampler uses a "bandlimited interpolation" algorithm:
  309. https://ccrma.stanford.edu/~jos/resample/ */
  310. #define RESAMPLER_ZERO_CROSSINGS 5
  311. #define RESAMPLER_BITS_PER_SAMPLE 16
  312. #define RESAMPLER_SAMPLES_PER_ZERO_CROSSING (1 << ((RESAMPLER_BITS_PER_SAMPLE / 2) + 1))
  313. #define RESAMPLER_FILTER_SIZE ((RESAMPLER_SAMPLES_PER_ZERO_CROSSING * RESAMPLER_ZERO_CROSSINGS) + 1)
  314. /* This is a "modified" bessel function, so you can't use POSIX j0() */
  315. static double
  316. bessel(const double x)
  317. {
  318. const double xdiv2 = x / 2.0;
  319. double i0 = 1.0f;
  320. double f = 1.0f;
  321. int i = 1;
  322. while (SDL_TRUE) {
  323. const double diff = SDL_pow(xdiv2, i * 2) / SDL_pow(f, 2);
  324. if (diff < 1.0e-21f) {
  325. break;
  326. }
  327. i0 += diff;
  328. i++;
  329. f *= (double) i;
  330. }
  331. return i0;
  332. }
  333. /* build kaiser table with cardinal sine applied to it, and array of differences between elements. */
  334. static void
  335. kaiser_and_sinc(float *table, float *diffs, const int tablelen, const double beta)
  336. {
  337. const int lenm1 = tablelen - 1;
  338. const int lenm1div2 = lenm1 / 2;
  339. int i;
  340. table[0] = 1.0f;
  341. for (i = 1; i < tablelen; i++) {
  342. const double kaiser = bessel(beta * SDL_sqrt(1.0 - SDL_pow(((i - lenm1) / 2.0) / lenm1div2, 2.0))) / bessel(beta);
  343. table[tablelen - i] = (float) kaiser;
  344. }
  345. for (i = 1; i < tablelen; i++) {
  346. const float x = (((float) i) / ((float) RESAMPLER_SAMPLES_PER_ZERO_CROSSING)) * ((float) M_PI);
  347. table[i] *= SDL_sinf(x) / x;
  348. diffs[i - 1] = table[i] - table[i - 1];
  349. }
  350. diffs[lenm1] = 0.0f;
  351. }
  352. static SDL_SpinLock ResampleFilterSpinlock = 0;
  353. static float *ResamplerFilter = NULL;
  354. static float *ResamplerFilterDifference = NULL;
  355. int
  356. SDL_PrepareResampleFilter(void)
  357. {
  358. SDL_AtomicLock(&ResampleFilterSpinlock);
  359. if (!ResamplerFilter) {
  360. /* if dB > 50, beta=(0.1102 * (dB - 8.7)), according to Matlab. */
  361. const double dB = 80.0;
  362. const double beta = 0.1102 * (dB - 8.7);
  363. const size_t alloclen = RESAMPLER_FILTER_SIZE * sizeof (float);
  364. ResamplerFilter = (float *) SDL_malloc(alloclen);
  365. if (!ResamplerFilter) {
  366. SDL_AtomicUnlock(&ResampleFilterSpinlock);
  367. return SDL_OutOfMemory();
  368. }
  369. ResamplerFilterDifference = (float *) SDL_malloc(alloclen);
  370. if (!ResamplerFilterDifference) {
  371. SDL_free(ResamplerFilter);
  372. ResamplerFilter = NULL;
  373. SDL_AtomicUnlock(&ResampleFilterSpinlock);
  374. return SDL_OutOfMemory();
  375. }
  376. kaiser_and_sinc(ResamplerFilter, ResamplerFilterDifference, RESAMPLER_FILTER_SIZE, beta);
  377. }
  378. SDL_AtomicUnlock(&ResampleFilterSpinlock);
  379. return 0;
  380. }
  381. void
  382. SDL_FreeResampleFilter(void)
  383. {
  384. SDL_free(ResamplerFilter);
  385. SDL_free(ResamplerFilterDifference);
  386. ResamplerFilter = NULL;
  387. ResamplerFilterDifference = NULL;
  388. }
  389. static int
  390. ResamplerPadding(const int inrate, const int outrate)
  391. {
  392. if (inrate == outrate) {
  393. return 0;
  394. } else if (inrate > outrate) {
  395. return (int) SDL_ceil(((float) (RESAMPLER_SAMPLES_PER_ZERO_CROSSING * inrate) / ((float) outrate)));
  396. }
  397. return RESAMPLER_SAMPLES_PER_ZERO_CROSSING;
  398. }
  399. /* lpadding and rpadding are expected to be buffers of (ResamplePadding(inrate, outrate) * chans * sizeof (float)) bytes. */
  400. static int
  401. SDL_ResampleAudio(const int chans, const int inrate, const int outrate,
  402. const float *lpadding, const float *rpadding,
  403. const float *inbuf, const int inbuflen,
  404. float *outbuf, const int outbuflen)
  405. {
  406. const double finrate = (double) inrate;
  407. const double outtimeincr = 1.0 / ((float) outrate);
  408. const double ratio = ((float) outrate) / ((float) inrate);
  409. const int paddinglen = ResamplerPadding(inrate, outrate);
  410. const int framelen = chans * (int)sizeof (float);
  411. const int inframes = inbuflen / framelen;
  412. const int wantedoutframes = (int) ((inbuflen / framelen) * ratio); /* outbuflen isn't total to write, it's total available. */
  413. const int maxoutframes = outbuflen / framelen;
  414. const int outframes = SDL_min(wantedoutframes, maxoutframes);
  415. float *dst = outbuf;
  416. double outtime = 0.0;
  417. int i, j, chan;
  418. for (i = 0; i < outframes; i++) {
  419. const int srcindex = (int) (outtime * inrate);
  420. const double intime = ((double) srcindex) / finrate;
  421. const double innexttime = ((double) (srcindex + 1)) / finrate;
  422. const double interpolation1 = 1.0 - ((innexttime - outtime) / (innexttime - intime));
  423. const int filterindex1 = (int) (interpolation1 * RESAMPLER_SAMPLES_PER_ZERO_CROSSING);
  424. const double interpolation2 = 1.0 - interpolation1;
  425. const int filterindex2 = (int) (interpolation2 * RESAMPLER_SAMPLES_PER_ZERO_CROSSING);
  426. for (chan = 0; chan < chans; chan++) {
  427. float outsample = 0.0f;
  428. /* do this twice to calculate the sample, once for the "left wing" and then same for the right. */
  429. /* !!! FIXME: do both wings in one loop */
  430. for (j = 0; (filterindex1 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)) < RESAMPLER_FILTER_SIZE; j++) {
  431. const int srcframe = srcindex - j;
  432. /* !!! FIXME: we can bubble this conditional out of here by doing a pre loop. */
  433. const float insample = (srcframe < 0) ? lpadding[((paddinglen + srcframe) * chans) + chan] : inbuf[(srcframe * chans) + chan];
  434. outsample += (float)(insample * (ResamplerFilter[filterindex1 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)] + (interpolation1 * ResamplerFilterDifference[filterindex1 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)])));
  435. }
  436. for (j = 0; (filterindex2 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)) < RESAMPLER_FILTER_SIZE; j++) {
  437. const int srcframe = srcindex + 1 + j;
  438. /* !!! FIXME: we can bubble this conditional out of here by doing a post loop. */
  439. const float insample = (srcframe >= inframes) ? rpadding[((srcframe - inframes) * chans) + chan] : inbuf[(srcframe * chans) + chan];
  440. outsample += (float)(insample * (ResamplerFilter[filterindex2 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)] + (interpolation2 * ResamplerFilterDifference[filterindex2 + (j * RESAMPLER_SAMPLES_PER_ZERO_CROSSING)])));
  441. }
  442. *(dst++) = outsample;
  443. }
  444. outtime += outtimeincr;
  445. }
  446. return outframes * chans * sizeof (float);
  447. }
  448. int
  449. SDL_ConvertAudio(SDL_AudioCVT * cvt)
  450. {
  451. /* !!! FIXME: (cvt) should be const; stack-copy it here. */
  452. /* !!! FIXME: (actually, we can't...len_cvt needs to be updated. Grr.) */
  453. /* Make sure there's data to convert */
  454. if (cvt->buf == NULL) {
  455. return SDL_SetError("No buffer allocated for conversion");
  456. }
  457. /* Return okay if no conversion is necessary */
  458. cvt->len_cvt = cvt->len;
  459. if (cvt->filters[0] == NULL) {
  460. return 0;
  461. }
  462. /* Set up the conversion and go! */
  463. cvt->filter_index = 0;
  464. cvt->filters[0] (cvt, cvt->src_format);
  465. return 0;
  466. }
  467. static void SDLCALL
  468. SDL_Convert_Byteswap(SDL_AudioCVT *cvt, SDL_AudioFormat format)
  469. {
  470. #if DEBUG_CONVERT
  471. printf("Converting byte order\n");
  472. #endif
  473. switch (SDL_AUDIO_BITSIZE(format)) {
  474. #define CASESWAP(b) \
  475. case b: { \
  476. Uint##b *ptr = (Uint##b *) cvt->buf; \
  477. int i; \
  478. for (i = cvt->len_cvt / sizeof (*ptr); i; --i, ++ptr) { \
  479. *ptr = SDL_Swap##b(*ptr); \
  480. } \
  481. break; \
  482. }
  483. CASESWAP(16);
  484. CASESWAP(32);
  485. CASESWAP(64);
  486. #undef CASESWAP
  487. default: SDL_assert(!"unhandled byteswap datatype!"); break;
  488. }
  489. if (cvt->filters[++cvt->filter_index]) {
  490. /* flip endian flag for data. */
  491. if (format & SDL_AUDIO_MASK_ENDIAN) {
  492. format &= ~SDL_AUDIO_MASK_ENDIAN;
  493. } else {
  494. format |= SDL_AUDIO_MASK_ENDIAN;
  495. }
  496. cvt->filters[cvt->filter_index](cvt, format);
  497. }
  498. }
  499. static int
  500. SDL_AddAudioCVTFilter(SDL_AudioCVT *cvt, const SDL_AudioFilter filter)
  501. {
  502. if (cvt->filter_index >= SDL_AUDIOCVT_MAX_FILTERS) {
  503. return SDL_SetError("Too many filters needed for conversion, exceeded maximum of %d", SDL_AUDIOCVT_MAX_FILTERS);
  504. }
  505. if (filter == NULL) {
  506. return SDL_SetError("Audio filter pointer is NULL");
  507. }
  508. cvt->filters[cvt->filter_index++] = filter;
  509. cvt->filters[cvt->filter_index] = NULL; /* Moving terminator */
  510. return 0;
  511. }
  512. static int
  513. SDL_BuildAudioTypeCVTToFloat(SDL_AudioCVT *cvt, const SDL_AudioFormat src_fmt)
  514. {
  515. int retval = 0; /* 0 == no conversion necessary. */
  516. if ((SDL_AUDIO_ISBIGENDIAN(src_fmt) != 0) == (SDL_BYTEORDER == SDL_LIL_ENDIAN)) {
  517. if (SDL_AddAudioCVTFilter(cvt, SDL_Convert_Byteswap) < 0) {
  518. return -1;
  519. }
  520. retval = 1; /* added a converter. */
  521. }
  522. if (!SDL_AUDIO_ISFLOAT(src_fmt)) {
  523. const Uint16 src_bitsize = SDL_AUDIO_BITSIZE(src_fmt);
  524. const Uint16 dst_bitsize = 32;
  525. SDL_AudioFilter filter = NULL;
  526. switch (src_fmt & ~SDL_AUDIO_MASK_ENDIAN) {
  527. case AUDIO_S8: filter = SDL_Convert_S8_to_F32; break;
  528. case AUDIO_U8: filter = SDL_Convert_U8_to_F32; break;
  529. case AUDIO_S16: filter = SDL_Convert_S16_to_F32; break;
  530. case AUDIO_U16: filter = SDL_Convert_U16_to_F32; break;
  531. case AUDIO_S32: filter = SDL_Convert_S32_to_F32; break;
  532. default: SDL_assert(!"Unexpected audio format!"); break;
  533. }
  534. if (!filter) {
  535. return SDL_SetError("No conversion from source format to float available");
  536. }
  537. if (SDL_AddAudioCVTFilter(cvt, filter) < 0) {
  538. return -1;
  539. }
  540. if (src_bitsize < dst_bitsize) {
  541. const int mult = (dst_bitsize / src_bitsize);
  542. cvt->len_mult *= mult;
  543. cvt->len_ratio *= mult;
  544. } else if (src_bitsize > dst_bitsize) {
  545. cvt->len_ratio /= (src_bitsize / dst_bitsize);
  546. }
  547. retval = 1; /* added a converter. */
  548. }
  549. return retval;
  550. }
  551. static int
  552. SDL_BuildAudioTypeCVTFromFloat(SDL_AudioCVT *cvt, const SDL_AudioFormat dst_fmt)
  553. {
  554. int retval = 0; /* 0 == no conversion necessary. */
  555. if (!SDL_AUDIO_ISFLOAT(dst_fmt)) {
  556. const Uint16 dst_bitsize = SDL_AUDIO_BITSIZE(dst_fmt);
  557. const Uint16 src_bitsize = 32;
  558. SDL_AudioFilter filter = NULL;
  559. switch (dst_fmt & ~SDL_AUDIO_MASK_ENDIAN) {
  560. case AUDIO_S8: filter = SDL_Convert_F32_to_S8; break;
  561. case AUDIO_U8: filter = SDL_Convert_F32_to_U8; break;
  562. case AUDIO_S16: filter = SDL_Convert_F32_to_S16; break;
  563. case AUDIO_U16: filter = SDL_Convert_F32_to_U16; break;
  564. case AUDIO_S32: filter = SDL_Convert_F32_to_S32; break;
  565. default: SDL_assert(!"Unexpected audio format!"); break;
  566. }
  567. if (!filter) {
  568. return SDL_SetError("No conversion from float to format 0x%.4x available", dst_fmt);
  569. }
  570. if (SDL_AddAudioCVTFilter(cvt, filter) < 0) {
  571. return -1;
  572. }
  573. if (src_bitsize < dst_bitsize) {
  574. const int mult = (dst_bitsize / src_bitsize);
  575. cvt->len_mult *= mult;
  576. cvt->len_ratio *= mult;
  577. } else if (src_bitsize > dst_bitsize) {
  578. cvt->len_ratio /= (src_bitsize / dst_bitsize);
  579. }
  580. retval = 1; /* added a converter. */
  581. }
  582. if ((SDL_AUDIO_ISBIGENDIAN(dst_fmt) != 0) == (SDL_BYTEORDER == SDL_LIL_ENDIAN)) {
  583. if (SDL_AddAudioCVTFilter(cvt, SDL_Convert_Byteswap) < 0) {
  584. return -1;
  585. }
  586. retval = 1; /* added a converter. */
  587. }
  588. return retval;
  589. }
  590. static void
  591. SDL_ResampleCVT(SDL_AudioCVT *cvt, const int chans, const SDL_AudioFormat format)
  592. {
  593. /* !!! FIXME in 2.1: there are ten slots in the filter list, and the theoretical maximum we use is six (seven with NULL terminator).
  594. !!! FIXME in 2.1: We need to store data for this resampler, because the cvt structure doesn't store the original sample rates,
  595. !!! FIXME in 2.1: so we steal the ninth and tenth slot. :( */
  596. const int inrate = (int) (size_t) cvt->filters[SDL_AUDIOCVT_MAX_FILTERS-1];
  597. const int outrate = (int) (size_t) cvt->filters[SDL_AUDIOCVT_MAX_FILTERS];
  598. const float *src = (const float *) cvt->buf;
  599. const int srclen = cvt->len_cvt;
  600. /*float *dst = (float *) cvt->buf;
  601. const int dstlen = (cvt->len * cvt->len_mult);*/
  602. /* !!! FIXME: remove this if we can get the resampler to work in-place again. */
  603. float *dst = (float *) (cvt->buf + srclen);
  604. const int dstlen = (cvt->len * cvt->len_mult) - srclen;
  605. const int requestedpadding = ResamplerPadding(inrate, outrate);
  606. int paddingsamples;
  607. float *padding;
  608. if (requestedpadding < SDL_MAX_SINT32 / chans) {
  609. paddingsamples = requestedpadding * chans;
  610. } else {
  611. paddingsamples = 0;
  612. }
  613. SDL_assert(format == AUDIO_F32SYS);
  614. /* we keep no streaming state here, so pad with silence on both ends. */
  615. padding = (float *) SDL_calloc(paddingsamples ? paddingsamples : 1, sizeof (float));
  616. if (!padding) {
  617. SDL_OutOfMemory();
  618. return;
  619. }
  620. cvt->len_cvt = SDL_ResampleAudio(chans, inrate, outrate, padding, padding, src, srclen, dst, dstlen);
  621. SDL_free(padding);
  622. SDL_memmove(cvt->buf, dst, cvt->len_cvt); /* !!! FIXME: remove this if we can get the resampler to work in-place again. */
  623. if (cvt->filters[++cvt->filter_index]) {
  624. cvt->filters[cvt->filter_index](cvt, format);
  625. }
  626. }
  627. /* !!! FIXME: We only have this macro salsa because SDL_AudioCVT doesn't
  628. !!! FIXME: store channel info, so we have to have function entry
  629. !!! FIXME: points for each supported channel count and multiple
  630. !!! FIXME: vs arbitrary. When we rev the ABI, clean this up. */
  631. #define RESAMPLER_FUNCS(chans) \
  632. static void SDLCALL \
  633. SDL_ResampleCVT_c##chans(SDL_AudioCVT *cvt, SDL_AudioFormat format) { \
  634. SDL_ResampleCVT(cvt, chans, format); \
  635. }
  636. RESAMPLER_FUNCS(1)
  637. RESAMPLER_FUNCS(2)
  638. RESAMPLER_FUNCS(4)
  639. RESAMPLER_FUNCS(6)
  640. RESAMPLER_FUNCS(8)
  641. #undef RESAMPLER_FUNCS
  642. static SDL_AudioFilter
  643. ChooseCVTResampler(const int dst_channels)
  644. {
  645. switch (dst_channels) {
  646. case 1: return SDL_ResampleCVT_c1;
  647. case 2: return SDL_ResampleCVT_c2;
  648. case 4: return SDL_ResampleCVT_c4;
  649. case 6: return SDL_ResampleCVT_c6;
  650. case 8: return SDL_ResampleCVT_c8;
  651. default: break;
  652. }
  653. return NULL;
  654. }
  655. static int
  656. SDL_BuildAudioResampleCVT(SDL_AudioCVT * cvt, const int dst_channels,
  657. const int src_rate, const int dst_rate)
  658. {
  659. SDL_AudioFilter filter;
  660. if (src_rate == dst_rate) {
  661. return 0; /* no conversion necessary. */
  662. }
  663. filter = ChooseCVTResampler(dst_channels);
  664. if (filter == NULL) {
  665. return SDL_SetError("No conversion available for these rates");
  666. }
  667. if (SDL_PrepareResampleFilter() < 0) {
  668. return -1;
  669. }
  670. /* Update (cvt) with filter details... */
  671. if (SDL_AddAudioCVTFilter(cvt, filter) < 0) {
  672. return -1;
  673. }
  674. /* !!! FIXME in 2.1: there are ten slots in the filter list, and the theoretical maximum we use is six (seven with NULL terminator).
  675. !!! FIXME in 2.1: We need to store data for this resampler, because the cvt structure doesn't store the original sample rates,
  676. !!! FIXME in 2.1: so we steal the ninth and tenth slot. :( */
  677. if (cvt->filter_index >= (SDL_AUDIOCVT_MAX_FILTERS-2)) {
  678. return SDL_SetError("Too many filters needed for conversion, exceeded maximum of %d", SDL_AUDIOCVT_MAX_FILTERS-2);
  679. }
  680. cvt->filters[SDL_AUDIOCVT_MAX_FILTERS-1] = (SDL_AudioFilter) (size_t) src_rate;
  681. cvt->filters[SDL_AUDIOCVT_MAX_FILTERS] = (SDL_AudioFilter) (size_t) dst_rate;
  682. if (src_rate < dst_rate) {
  683. const double mult = ((double) dst_rate) / ((double) src_rate);
  684. cvt->len_mult *= (int) SDL_ceil(mult);
  685. cvt->len_ratio *= mult;
  686. } else {
  687. cvt->len_ratio /= ((double) src_rate) / ((double) dst_rate);
  688. }
  689. /* !!! FIXME: remove this if we can get the resampler to work in-place again. */
  690. /* the buffer is big enough to hold the destination now, but
  691. we need it large enough to hold a separate scratch buffer. */
  692. cvt->len_mult *= 2;
  693. return 1; /* added a converter. */
  694. }
  695. static SDL_bool
  696. SDL_SupportedAudioFormat(const SDL_AudioFormat fmt)
  697. {
  698. switch (fmt) {
  699. case AUDIO_U8:
  700. case AUDIO_S8:
  701. case AUDIO_U16LSB:
  702. case AUDIO_S16LSB:
  703. case AUDIO_U16MSB:
  704. case AUDIO_S16MSB:
  705. case AUDIO_S32LSB:
  706. case AUDIO_S32MSB:
  707. case AUDIO_F32LSB:
  708. case AUDIO_F32MSB:
  709. return SDL_TRUE; /* supported. */
  710. default:
  711. break;
  712. }
  713. return SDL_FALSE; /* unsupported. */
  714. }
  715. static SDL_bool
  716. SDL_SupportedChannelCount(const int channels)
  717. {
  718. switch (channels) {
  719. case 1: /* mono */
  720. case 2: /* stereo */
  721. case 4: /* quad */
  722. case 6: /* 5.1 */
  723. case 8: /* 7.1 */
  724. return SDL_TRUE; /* supported. */
  725. default:
  726. break;
  727. }
  728. return SDL_FALSE; /* unsupported. */
  729. }
  730. /* Creates a set of audio filters to convert from one format to another.
  731. Returns 0 if no conversion is needed, 1 if the audio filter is set up,
  732. or -1 if an error like invalid parameter, unsupported format, etc. occurred.
  733. */
  734. int
  735. SDL_BuildAudioCVT(SDL_AudioCVT * cvt,
  736. SDL_AudioFormat src_fmt, Uint8 src_channels, int src_rate,
  737. SDL_AudioFormat dst_fmt, Uint8 dst_channels, int dst_rate)
  738. {
  739. /* Sanity check target pointer */
  740. if (cvt == NULL) {
  741. return SDL_InvalidParamError("cvt");
  742. }
  743. /* Make sure we zero out the audio conversion before error checking */
  744. SDL_zerop(cvt);
  745. if (!SDL_SupportedAudioFormat(src_fmt)) {
  746. return SDL_SetError("Invalid source format");
  747. } else if (!SDL_SupportedAudioFormat(dst_fmt)) {
  748. return SDL_SetError("Invalid destination format");
  749. } else if (!SDL_SupportedChannelCount(src_channels)) {
  750. return SDL_SetError("Invalid source channels");
  751. } else if (!SDL_SupportedChannelCount(dst_channels)) {
  752. return SDL_SetError("Invalid destination channels");
  753. } else if (src_rate <= 0) {
  754. return SDL_SetError("Source rate is equal to or less than zero");
  755. } else if (dst_rate <= 0) {
  756. return SDL_SetError("Destination rate is equal to or less than zero");
  757. } else if (src_rate >= SDL_MAX_SINT32 / RESAMPLER_SAMPLES_PER_ZERO_CROSSING) {
  758. return SDL_SetError("Source rate is too high");
  759. } else if (dst_rate >= SDL_MAX_SINT32 / RESAMPLER_SAMPLES_PER_ZERO_CROSSING) {
  760. return SDL_SetError("Destination rate is too high");
  761. }
  762. #if DEBUG_CONVERT
  763. printf("Build format %04x->%04x, channels %u->%u, rate %d->%d\n",
  764. src_fmt, dst_fmt, src_channels, dst_channels, src_rate, dst_rate);
  765. #endif
  766. /* Start off with no conversion necessary */
  767. cvt->src_format = src_fmt;
  768. cvt->dst_format = dst_fmt;
  769. cvt->needed = 0;
  770. cvt->filter_index = 0;
  771. SDL_zeroa(cvt->filters);
  772. cvt->len_mult = 1;
  773. cvt->len_ratio = 1.0;
  774. cvt->rate_incr = ((double) dst_rate) / ((double) src_rate);
  775. /* Make sure we've chosen audio conversion functions (MMX, scalar, etc.) */
  776. SDL_ChooseAudioConverters();
  777. /* Type conversion goes like this now:
  778. - byteswap to CPU native format first if necessary.
  779. - convert to native Float32 if necessary.
  780. - resample and change channel count if necessary.
  781. - convert back to native format.
  782. - byteswap back to foreign format if necessary.
  783. The expectation is we can process data faster in float32
  784. (possibly with SIMD), and making several passes over the same
  785. buffer is likely to be CPU cache-friendly, avoiding the
  786. biggest performance hit in modern times. Previously we had
  787. (script-generated) custom converters for every data type and
  788. it was a bloat on SDL compile times and final library size. */
  789. /* see if we can skip float conversion entirely. */
  790. if (src_rate == dst_rate && src_channels == dst_channels) {
  791. if (src_fmt == dst_fmt) {
  792. return 0;
  793. }
  794. /* just a byteswap needed? */
  795. if ((src_fmt & ~SDL_AUDIO_MASK_ENDIAN) == (dst_fmt & ~SDL_AUDIO_MASK_ENDIAN)) {
  796. if (SDL_AddAudioCVTFilter(cvt, SDL_Convert_Byteswap) < 0) {
  797. return -1;
  798. }
  799. cvt->needed = 1;
  800. return 1;
  801. }
  802. }
  803. /* Convert data types, if necessary. Updates (cvt). */
  804. if (SDL_BuildAudioTypeCVTToFloat(cvt, src_fmt) < 0) {
  805. return -1; /* shouldn't happen, but just in case... */
  806. }
  807. /* Channel conversion */
  808. if (src_channels < dst_channels) {
  809. /* Upmixing */
  810. /* Mono -> Stereo [-> ...] */
  811. if ((src_channels == 1) && (dst_channels > 1)) {
  812. if (SDL_AddAudioCVTFilter(cvt, SDL_ConvertMonoToStereo) < 0) {
  813. return -1;
  814. }
  815. cvt->len_mult *= 2;
  816. src_channels = 2;
  817. cvt->len_ratio *= 2;
  818. }
  819. /* [Mono ->] Stereo -> 5.1 [-> 7.1] */
  820. if ((src_channels == 2) && (dst_channels >= 6)) {
  821. if (SDL_AddAudioCVTFilter(cvt, SDL_ConvertStereoTo51) < 0) {
  822. return -1;
  823. }
  824. src_channels = 6;
  825. cvt->len_mult *= 3;
  826. cvt->len_ratio *= 3;
  827. }
  828. /* Quad -> 5.1 [-> 7.1] */
  829. if ((src_channels == 4) && (dst_channels >= 6)) {
  830. if (SDL_AddAudioCVTFilter(cvt, SDL_ConvertQuadTo51) < 0) {
  831. return -1;
  832. }
  833. src_channels = 6;
  834. cvt->len_mult = (cvt->len_mult * 3 + 1) / 2;
  835. cvt->len_ratio *= 1.5;
  836. }
  837. /* [[Mono ->] Stereo ->] 5.1 -> 7.1 */
  838. if ((src_channels == 6) && (dst_channels == 8)) {
  839. if (SDL_AddAudioCVTFilter(cvt, SDL_Convert51To71) < 0) {
  840. return -1;
  841. }
  842. src_channels = 8;
  843. cvt->len_mult = (cvt->len_mult * 4 + 2) / 3;
  844. /* Should be numerically exact with every valid input to this
  845. function */
  846. cvt->len_ratio = cvt->len_ratio * 4 / 3;
  847. }
  848. /* [Mono ->] Stereo -> Quad */
  849. if ((src_channels == 2) && (dst_channels == 4)) {
  850. if (SDL_AddAudioCVTFilter(cvt, SDL_ConvertStereoToQuad) < 0) {
  851. return -1;
  852. }
  853. src_channels = 4;
  854. cvt->len_mult *= 2;
  855. cvt->len_ratio *= 2;
  856. }
  857. } else if (src_channels > dst_channels) {
  858. /* Downmixing */
  859. /* 7.1 -> 5.1 [-> Stereo [-> Mono]] */
  860. /* 7.1 -> 5.1 [-> Quad] */
  861. if ((src_channels == 8) && (dst_channels <= 6)) {
  862. if (SDL_AddAudioCVTFilter(cvt, SDL_Convert71To51) < 0) {
  863. return -1;
  864. }
  865. src_channels = 6;
  866. cvt->len_ratio *= 0.75;
  867. }
  868. /* [7.1 ->] 5.1 -> Stereo [-> Mono] */
  869. if ((src_channels == 6) && (dst_channels <= 2)) {
  870. if (SDL_AddAudioCVTFilter(cvt, SDL_Convert51ToStereo) < 0) {
  871. return -1;
  872. }
  873. src_channels = 2;
  874. cvt->len_ratio /= 3;
  875. }
  876. /* 5.1 -> Quad */
  877. if ((src_channels == 6) && (dst_channels == 4)) {
  878. if (SDL_AddAudioCVTFilter(cvt, SDL_Convert51ToQuad) < 0) {
  879. return -1;
  880. }
  881. src_channels = 4;
  882. cvt->len_ratio = cvt->len_ratio * 2 / 3;
  883. }
  884. /* Quad -> Stereo [-> Mono] */
  885. if ((src_channels == 4) && (dst_channels <= 2)) {
  886. if (SDL_AddAudioCVTFilter(cvt, SDL_ConvertQuadToStereo) < 0) {
  887. return -1;
  888. }
  889. src_channels = 2;
  890. cvt->len_ratio /= 2;
  891. }
  892. /* [... ->] Stereo -> Mono */
  893. if ((src_channels == 2) && (dst_channels == 1)) {
  894. SDL_AudioFilter filter = NULL;
  895. #if HAVE_SSE3_INTRINSICS
  896. if (SDL_HasSSE3()) {
  897. filter = SDL_ConvertStereoToMono_SSE3;
  898. }
  899. #endif
  900. if (!filter) {
  901. filter = SDL_ConvertStereoToMono;
  902. }
  903. if (SDL_AddAudioCVTFilter(cvt, filter) < 0) {
  904. return -1;
  905. }
  906. src_channels = 1;
  907. cvt->len_ratio /= 2;
  908. }
  909. }
  910. if (src_channels != dst_channels) {
  911. /* All combinations of supported channel counts should have been
  912. handled by now, but let's be defensive */
  913. return SDL_SetError("Invalid channel combination");
  914. }
  915. /* Do rate conversion, if necessary. Updates (cvt). */
  916. if (SDL_BuildAudioResampleCVT(cvt, dst_channels, src_rate, dst_rate) < 0) {
  917. return -1; /* shouldn't happen, but just in case... */
  918. }
  919. /* Move to final data type. */
  920. if (SDL_BuildAudioTypeCVTFromFloat(cvt, dst_fmt) < 0) {
  921. return -1; /* shouldn't happen, but just in case... */
  922. }
  923. cvt->needed = (cvt->filter_index != 0);
  924. return (cvt->needed);
  925. }
  926. typedef int (*SDL_ResampleAudioStreamFunc)(SDL_AudioStream *stream, const void *inbuf, const int inbuflen, void *outbuf, const int outbuflen);
  927. typedef void (*SDL_ResetAudioStreamResamplerFunc)(SDL_AudioStream *stream);
  928. typedef void (*SDL_CleanupAudioStreamResamplerFunc)(SDL_AudioStream *stream);
  929. struct _SDL_AudioStream
  930. {
  931. SDL_AudioCVT cvt_before_resampling;
  932. SDL_AudioCVT cvt_after_resampling;
  933. SDL_DataQueue *queue;
  934. SDL_bool first_run;
  935. Uint8 *staging_buffer;
  936. int staging_buffer_size;
  937. int staging_buffer_filled;
  938. Uint8 *work_buffer_base; /* maybe unaligned pointer from SDL_realloc(). */
  939. int work_buffer_len;
  940. int src_sample_frame_size;
  941. SDL_AudioFormat src_format;
  942. Uint8 src_channels;
  943. int src_rate;
  944. int dst_sample_frame_size;
  945. SDL_AudioFormat dst_format;
  946. Uint8 dst_channels;
  947. int dst_rate;
  948. double rate_incr;
  949. Uint8 pre_resample_channels;
  950. int packetlen;
  951. int resampler_padding_samples;
  952. float *resampler_padding;
  953. void *resampler_state;
  954. SDL_ResampleAudioStreamFunc resampler_func;
  955. SDL_ResetAudioStreamResamplerFunc reset_resampler_func;
  956. SDL_CleanupAudioStreamResamplerFunc cleanup_resampler_func;
  957. };
  958. static Uint8 *
  959. EnsureStreamBufferSize(SDL_AudioStream *stream, const int newlen)
  960. {
  961. Uint8 *ptr;
  962. size_t offset;
  963. if (stream->work_buffer_len >= newlen) {
  964. ptr = stream->work_buffer_base;
  965. } else {
  966. ptr = (Uint8 *) SDL_realloc(stream->work_buffer_base, newlen + 32);
  967. if (!ptr) {
  968. SDL_OutOfMemory();
  969. return NULL;
  970. }
  971. /* Make sure we're aligned to 16 bytes for SIMD code. */
  972. stream->work_buffer_base = ptr;
  973. stream->work_buffer_len = newlen;
  974. }
  975. offset = ((size_t) ptr) & 15;
  976. return offset ? ptr + (16 - offset) : ptr;
  977. }
  978. #ifdef HAVE_LIBSAMPLERATE_H
  979. static int
  980. SDL_ResampleAudioStream_SRC(SDL_AudioStream *stream, const void *_inbuf, const int inbuflen, void *_outbuf, const int outbuflen)
  981. {
  982. const float *inbuf = (const float *) _inbuf;
  983. float *outbuf = (float *) _outbuf;
  984. const int framelen = sizeof(float) * stream->pre_resample_channels;
  985. SRC_STATE *state = (SRC_STATE *)stream->resampler_state;
  986. SRC_DATA data;
  987. int result;
  988. SDL_assert(inbuf != ((const float *) outbuf)); /* SDL_AudioStreamPut() shouldn't allow in-place resamples. */
  989. data.data_in = (float *)inbuf; /* Older versions of libsamplerate had a non-const pointer, but didn't write to it */
  990. data.input_frames = inbuflen / framelen;
  991. data.input_frames_used = 0;
  992. data.data_out = outbuf;
  993. data.output_frames = outbuflen / framelen;
  994. data.end_of_input = 0;
  995. data.src_ratio = stream->rate_incr;
  996. result = SRC_src_process(state, &data);
  997. if (result != 0) {
  998. SDL_SetError("src_process() failed: %s", SRC_src_strerror(result));
  999. return 0;
  1000. }
  1001. /* If this fails, we need to store them off somewhere */
  1002. SDL_assert(data.input_frames_used == data.input_frames);
  1003. return data.output_frames_gen * (sizeof(float) * stream->pre_resample_channels);
  1004. }
  1005. static void
  1006. SDL_ResetAudioStreamResampler_SRC(SDL_AudioStream *stream)
  1007. {
  1008. SRC_src_reset((SRC_STATE *)stream->resampler_state);
  1009. }
  1010. static void
  1011. SDL_CleanupAudioStreamResampler_SRC(SDL_AudioStream *stream)
  1012. {
  1013. SRC_STATE *state = (SRC_STATE *)stream->resampler_state;
  1014. if (state) {
  1015. SRC_src_delete(state);
  1016. }
  1017. stream->resampler_state = NULL;
  1018. stream->resampler_func = NULL;
  1019. stream->reset_resampler_func = NULL;
  1020. stream->cleanup_resampler_func = NULL;
  1021. }
  1022. static SDL_bool
  1023. SetupLibSampleRateResampling(SDL_AudioStream *stream)
  1024. {
  1025. int result = 0;
  1026. SRC_STATE *state = NULL;
  1027. if (SRC_available) {
  1028. state = SRC_src_new(SRC_converter, stream->pre_resample_channels, &result);
  1029. if (!state) {
  1030. SDL_SetError("src_new() failed: %s", SRC_src_strerror(result));
  1031. }
  1032. }
  1033. if (!state) {
  1034. SDL_CleanupAudioStreamResampler_SRC(stream);
  1035. return SDL_FALSE;
  1036. }
  1037. stream->resampler_state = state;
  1038. stream->resampler_func = SDL_ResampleAudioStream_SRC;
  1039. stream->reset_resampler_func = SDL_ResetAudioStreamResampler_SRC;
  1040. stream->cleanup_resampler_func = SDL_CleanupAudioStreamResampler_SRC;
  1041. return SDL_TRUE;
  1042. }
  1043. #endif /* HAVE_LIBSAMPLERATE_H */
  1044. static int
  1045. SDL_ResampleAudioStream(SDL_AudioStream *stream, const void *_inbuf, const int inbuflen, void *_outbuf, const int outbuflen)
  1046. {
  1047. const Uint8 *inbufend = ((const Uint8 *) _inbuf) + inbuflen;
  1048. const float *inbuf = (const float *) _inbuf;
  1049. float *outbuf = (float *) _outbuf;
  1050. const int chans = (int) stream->pre_resample_channels;
  1051. const int inrate = stream->src_rate;
  1052. const int outrate = stream->dst_rate;
  1053. const int paddingsamples = stream->resampler_padding_samples;
  1054. const int paddingbytes = paddingsamples * sizeof (float);
  1055. float *lpadding = (float *) stream->resampler_state;
  1056. const float *rpadding = (const float *) inbufend; /* we set this up so there are valid padding samples at the end of the input buffer. */
  1057. const int cpy = SDL_min(inbuflen, paddingbytes);
  1058. int retval;
  1059. SDL_assert(inbuf != ((const float *) outbuf)); /* SDL_AudioStreamPut() shouldn't allow in-place resamples. */
  1060. retval = SDL_ResampleAudio(chans, inrate, outrate, lpadding, rpadding, inbuf, inbuflen, outbuf, outbuflen);
  1061. /* update our left padding with end of current input, for next run. */
  1062. SDL_memcpy((lpadding + paddingsamples) - (cpy / sizeof (float)), inbufend - cpy, cpy);
  1063. return retval;
  1064. }
  1065. static void
  1066. SDL_ResetAudioStreamResampler(SDL_AudioStream *stream)
  1067. {
  1068. /* set all the padding to silence. */
  1069. const int len = stream->resampler_padding_samples;
  1070. SDL_memset(stream->resampler_state, '\0', len * sizeof (float));
  1071. }
  1072. static void
  1073. SDL_CleanupAudioStreamResampler(SDL_AudioStream *stream)
  1074. {
  1075. SDL_free(stream->resampler_state);
  1076. }
  1077. SDL_AudioStream *
  1078. SDL_NewAudioStream(const SDL_AudioFormat src_format,
  1079. const Uint8 src_channels,
  1080. const int src_rate,
  1081. const SDL_AudioFormat dst_format,
  1082. const Uint8 dst_channels,
  1083. const int dst_rate)
  1084. {
  1085. const int packetlen = 4096; /* !!! FIXME: good enough for now. */
  1086. Uint8 pre_resample_channels;
  1087. SDL_AudioStream *retval;
  1088. retval = (SDL_AudioStream *) SDL_calloc(1, sizeof (SDL_AudioStream));
  1089. if (!retval) {
  1090. return NULL;
  1091. }
  1092. /* If increasing channels, do it after resampling, since we'd just
  1093. do more work to resample duplicate channels. If we're decreasing, do
  1094. it first so we resample the interpolated data instead of interpolating
  1095. the resampled data (!!! FIXME: decide if that works in practice, though!). */
  1096. pre_resample_channels = SDL_min(src_channels, dst_channels);
  1097. retval->first_run = SDL_TRUE;
  1098. retval->src_sample_frame_size = (SDL_AUDIO_BITSIZE(src_format) / 8) * src_channels;
  1099. retval->src_format = src_format;
  1100. retval->src_channels = src_channels;
  1101. retval->src_rate = src_rate;
  1102. retval->dst_sample_frame_size = (SDL_AUDIO_BITSIZE(dst_format) / 8) * dst_channels;
  1103. retval->dst_format = dst_format;
  1104. retval->dst_channels = dst_channels;
  1105. retval->dst_rate = dst_rate;
  1106. retval->pre_resample_channels = pre_resample_channels;
  1107. retval->packetlen = packetlen;
  1108. retval->rate_incr = ((double) dst_rate) / ((double) src_rate);
  1109. retval->resampler_padding_samples = ResamplerPadding(retval->src_rate, retval->dst_rate) * pre_resample_channels;
  1110. retval->resampler_padding = (float *) SDL_calloc(retval->resampler_padding_samples ? retval->resampler_padding_samples : 1, sizeof (float));
  1111. if (retval->resampler_padding == NULL) {
  1112. SDL_FreeAudioStream(retval);
  1113. SDL_OutOfMemory();
  1114. return NULL;
  1115. }
  1116. retval->staging_buffer_size = ((retval->resampler_padding_samples / retval->pre_resample_channels) * retval->src_sample_frame_size);
  1117. if (retval->staging_buffer_size > 0) {
  1118. retval->staging_buffer = (Uint8 *) SDL_malloc(retval->staging_buffer_size);
  1119. if (retval->staging_buffer == NULL) {
  1120. SDL_FreeAudioStream(retval);
  1121. SDL_OutOfMemory();
  1122. return NULL;
  1123. }
  1124. }
  1125. /* Not resampling? It's an easy conversion (and maybe not even that!) */
  1126. if (src_rate == dst_rate) {
  1127. retval->cvt_before_resampling.needed = SDL_FALSE;
  1128. if (SDL_BuildAudioCVT(&retval->cvt_after_resampling, src_format, src_channels, dst_rate, dst_format, dst_channels, dst_rate) < 0) {
  1129. SDL_FreeAudioStream(retval);
  1130. return NULL; /* SDL_BuildAudioCVT should have called SDL_SetError. */
  1131. }
  1132. } else {
  1133. /* Don't resample at first. Just get us to Float32 format. */
  1134. /* !!! FIXME: convert to int32 on devices without hardware float. */
  1135. if (SDL_BuildAudioCVT(&retval->cvt_before_resampling, src_format, src_channels, src_rate, AUDIO_F32SYS, pre_resample_channels, src_rate) < 0) {
  1136. SDL_FreeAudioStream(retval);
  1137. return NULL; /* SDL_BuildAudioCVT should have called SDL_SetError. */
  1138. }
  1139. #ifdef HAVE_LIBSAMPLERATE_H
  1140. SetupLibSampleRateResampling(retval);
  1141. #endif
  1142. if (!retval->resampler_func) {
  1143. retval->resampler_state = SDL_calloc(retval->resampler_padding_samples, sizeof (float));
  1144. if (!retval->resampler_state) {
  1145. SDL_FreeAudioStream(retval);
  1146. SDL_OutOfMemory();
  1147. return NULL;
  1148. }
  1149. if (SDL_PrepareResampleFilter() < 0) {
  1150. SDL_free(retval->resampler_state);
  1151. retval->resampler_state = NULL;
  1152. SDL_FreeAudioStream(retval);
  1153. return NULL;
  1154. }
  1155. retval->resampler_func = SDL_ResampleAudioStream;
  1156. retval->reset_resampler_func = SDL_ResetAudioStreamResampler;
  1157. retval->cleanup_resampler_func = SDL_CleanupAudioStreamResampler;
  1158. }
  1159. /* Convert us to the final format after resampling. */
  1160. if (SDL_BuildAudioCVT(&retval->cvt_after_resampling, AUDIO_F32SYS, pre_resample_channels, dst_rate, dst_format, dst_channels, dst_rate) < 0) {
  1161. SDL_FreeAudioStream(retval);
  1162. return NULL; /* SDL_BuildAudioCVT should have called SDL_SetError. */
  1163. }
  1164. }
  1165. retval->queue = SDL_NewDataQueue(packetlen, packetlen * 2);
  1166. if (!retval->queue) {
  1167. SDL_FreeAudioStream(retval);
  1168. return NULL; /* SDL_NewDataQueue should have called SDL_SetError. */
  1169. }
  1170. return retval;
  1171. }
  1172. static int
  1173. SDL_AudioStreamPutInternal(SDL_AudioStream *stream, const void *buf, int len, int *maxputbytes)
  1174. {
  1175. int buflen = len;
  1176. int workbuflen;
  1177. Uint8 *workbuf;
  1178. Uint8 *resamplebuf = NULL;
  1179. int resamplebuflen = 0;
  1180. int neededpaddingbytes;
  1181. int paddingbytes;
  1182. /* !!! FIXME: several converters can take advantage of SIMD, but only
  1183. !!! FIXME: if the data is aligned to 16 bytes. EnsureStreamBufferSize()
  1184. !!! FIXME: guarantees the buffer will align, but the
  1185. !!! FIXME: converters will iterate over the data backwards if
  1186. !!! FIXME: the output grows, and this means we won't align if buflen
  1187. !!! FIXME: isn't a multiple of 16. In these cases, we should chop off
  1188. !!! FIXME: a few samples at the end and convert them separately. */
  1189. /* no padding prepended on first run. */
  1190. neededpaddingbytes = stream->resampler_padding_samples * sizeof (float);
  1191. paddingbytes = stream->first_run ? 0 : neededpaddingbytes;
  1192. stream->first_run = SDL_FALSE;
  1193. /* Make sure the work buffer can hold all the data we need at once... */
  1194. workbuflen = buflen;
  1195. if (stream->cvt_before_resampling.needed) {
  1196. workbuflen *= stream->cvt_before_resampling.len_mult;
  1197. }
  1198. if (stream->dst_rate != stream->src_rate) {
  1199. /* resamples can't happen in place, so make space for second buf. */
  1200. const int framesize = stream->pre_resample_channels * sizeof (float);
  1201. const int frames = workbuflen / framesize;
  1202. resamplebuflen = ((int) SDL_ceil(frames * stream->rate_incr)) * framesize;
  1203. #if DEBUG_AUDIOSTREAM
  1204. printf("AUDIOSTREAM: will resample %d bytes to %d (ratio=%.6f)\n", workbuflen, resamplebuflen, stream->rate_incr);
  1205. #endif
  1206. workbuflen += resamplebuflen;
  1207. }
  1208. if (stream->cvt_after_resampling.needed) {
  1209. /* !!! FIXME: buffer might be big enough already? */
  1210. workbuflen *= stream->cvt_after_resampling.len_mult;
  1211. }
  1212. workbuflen += neededpaddingbytes;
  1213. #if DEBUG_AUDIOSTREAM
  1214. printf("AUDIOSTREAM: Putting %d bytes of preconverted audio, need %d byte work buffer\n", buflen, workbuflen);
  1215. #endif
  1216. workbuf = EnsureStreamBufferSize(stream, workbuflen);
  1217. if (!workbuf) {
  1218. return -1; /* probably out of memory. */
  1219. }
  1220. resamplebuf = workbuf; /* default if not resampling. */
  1221. SDL_memcpy(workbuf + paddingbytes, buf, buflen);
  1222. if (stream->cvt_before_resampling.needed) {
  1223. stream->cvt_before_resampling.buf = workbuf + paddingbytes;
  1224. stream->cvt_before_resampling.len = buflen;
  1225. if (SDL_ConvertAudio(&stream->cvt_before_resampling) == -1) {
  1226. return -1; /* uhoh! */
  1227. }
  1228. buflen = stream->cvt_before_resampling.len_cvt;
  1229. #if DEBUG_AUDIOSTREAM
  1230. printf("AUDIOSTREAM: After initial conversion we have %d bytes\n", buflen);
  1231. #endif
  1232. }
  1233. if (stream->dst_rate != stream->src_rate) {
  1234. /* save off some samples at the end; they are used for padding now so
  1235. the resampler is coherent and then used at the start of the next
  1236. put operation. Prepend last put operation's padding, too. */
  1237. /* prepend prior put's padding. :P */
  1238. if (paddingbytes) {
  1239. SDL_memcpy(workbuf, stream->resampler_padding, paddingbytes);
  1240. buflen += paddingbytes;
  1241. }
  1242. /* save off the data at the end for the next run. */
  1243. SDL_memcpy(stream->resampler_padding, workbuf + (buflen - neededpaddingbytes), neededpaddingbytes);
  1244. resamplebuf = workbuf + buflen; /* skip to second piece of workbuf. */
  1245. SDL_assert(buflen >= neededpaddingbytes);
  1246. if (buflen > neededpaddingbytes) {
  1247. buflen = stream->resampler_func(stream, workbuf, buflen - neededpaddingbytes, resamplebuf, resamplebuflen);
  1248. } else {
  1249. buflen = 0;
  1250. }
  1251. #if DEBUG_AUDIOSTREAM
  1252. printf("AUDIOSTREAM: After resampling we have %d bytes\n", buflen);
  1253. #endif
  1254. }
  1255. if (stream->cvt_after_resampling.needed && (buflen > 0)) {
  1256. stream->cvt_after_resampling.buf = resamplebuf;
  1257. stream->cvt_after_resampling.len = buflen;
  1258. if (SDL_ConvertAudio(&stream->cvt_after_resampling) == -1) {
  1259. return -1; /* uhoh! */
  1260. }
  1261. buflen = stream->cvt_after_resampling.len_cvt;
  1262. #if DEBUG_AUDIOSTREAM
  1263. printf("AUDIOSTREAM: After final conversion we have %d bytes\n", buflen);
  1264. #endif
  1265. }
  1266. #if DEBUG_AUDIOSTREAM
  1267. printf("AUDIOSTREAM: Final output is %d bytes\n", buflen);
  1268. #endif
  1269. if (maxputbytes) {
  1270. const int maxbytes = *maxputbytes;
  1271. if (buflen > maxbytes)
  1272. buflen = maxbytes;
  1273. *maxputbytes -= buflen;
  1274. }
  1275. /* resamplebuf holds the final output, even if we didn't resample. */
  1276. return buflen ? SDL_WriteToDataQueue(stream->queue, resamplebuf, buflen) : 0;
  1277. }
  1278. int
  1279. SDL_AudioStreamPut(SDL_AudioStream *stream, const void *buf, int len)
  1280. {
  1281. /* !!! FIXME: several converters can take advantage of SIMD, but only
  1282. !!! FIXME: if the data is aligned to 16 bytes. EnsureStreamBufferSize()
  1283. !!! FIXME: guarantees the buffer will align, but the
  1284. !!! FIXME: converters will iterate over the data backwards if
  1285. !!! FIXME: the output grows, and this means we won't align if buflen
  1286. !!! FIXME: isn't a multiple of 16. In these cases, we should chop off
  1287. !!! FIXME: a few samples at the end and convert them separately. */
  1288. #if DEBUG_AUDIOSTREAM
  1289. printf("AUDIOSTREAM: wants to put %d preconverted bytes\n", buflen);
  1290. #endif
  1291. if (!stream) {
  1292. return SDL_InvalidParamError("stream");
  1293. } else if (!buf) {
  1294. return SDL_InvalidParamError("buf");
  1295. } else if (len == 0) {
  1296. return 0; /* nothing to do. */
  1297. } else if ((len % stream->src_sample_frame_size) != 0) {
  1298. return SDL_SetError("Can't add partial sample frames");
  1299. }
  1300. if (!stream->cvt_before_resampling.needed &&
  1301. (stream->dst_rate == stream->src_rate) &&
  1302. !stream->cvt_after_resampling.needed) {
  1303. #if DEBUG_AUDIOSTREAM
  1304. printf("AUDIOSTREAM: no conversion needed at all, queueing %d bytes.\n", len);
  1305. #endif
  1306. return SDL_WriteToDataQueue(stream->queue, buf, len);
  1307. }
  1308. while (len > 0) {
  1309. int amount;
  1310. /* If we don't have a staging buffer or we're given enough data that
  1311. we don't need to store it for later, skip the staging process.
  1312. */
  1313. if (!stream->staging_buffer_filled && len >= stream->staging_buffer_size) {
  1314. return SDL_AudioStreamPutInternal(stream, buf, len, NULL);
  1315. }
  1316. /* If there's not enough data to fill the staging buffer, just save it */
  1317. if ((stream->staging_buffer_filled + len) < stream->staging_buffer_size) {
  1318. SDL_memcpy(stream->staging_buffer + stream->staging_buffer_filled, buf, len);
  1319. stream->staging_buffer_filled += len;
  1320. return 0;
  1321. }
  1322. /* Fill the staging buffer, process it, and continue */
  1323. amount = (stream->staging_buffer_size - stream->staging_buffer_filled);
  1324. SDL_assert(amount > 0);
  1325. SDL_memcpy(stream->staging_buffer + stream->staging_buffer_filled, buf, amount);
  1326. stream->staging_buffer_filled = 0;
  1327. if (SDL_AudioStreamPutInternal(stream, stream->staging_buffer, stream->staging_buffer_size, NULL) < 0) {
  1328. return -1;
  1329. }
  1330. buf = (void *)((Uint8 *)buf + amount);
  1331. len -= amount;
  1332. }
  1333. return 0;
  1334. }
  1335. int SDL_AudioStreamFlush(SDL_AudioStream *stream)
  1336. {
  1337. if (!stream) {
  1338. return SDL_InvalidParamError("stream");
  1339. }
  1340. #if DEBUG_AUDIOSTREAM
  1341. printf("AUDIOSTREAM: flushing! staging_buffer_filled=%d bytes\n", stream->staging_buffer_filled);
  1342. #endif
  1343. /* shouldn't use a staging buffer if we're not resampling. */
  1344. SDL_assert((stream->dst_rate != stream->src_rate) || (stream->staging_buffer_filled == 0));
  1345. if (stream->staging_buffer_filled > 0) {
  1346. /* push the staging buffer + silence. We need to flush out not just
  1347. the staging buffer, but the piece that the stream was saving off
  1348. for right-side resampler padding. */
  1349. const SDL_bool first_run = stream->first_run;
  1350. const int filled = stream->staging_buffer_filled;
  1351. int actual_input_frames = filled / stream->src_sample_frame_size;
  1352. if (!first_run)
  1353. actual_input_frames += stream->resampler_padding_samples / stream->pre_resample_channels;
  1354. if (actual_input_frames > 0) { /* don't bother if nothing to flush. */
  1355. /* This is how many bytes we're expecting without silence appended. */
  1356. int flush_remaining = ((int) SDL_ceil(actual_input_frames * stream->rate_incr)) * stream->dst_sample_frame_size;
  1357. #if DEBUG_AUDIOSTREAM
  1358. printf("AUDIOSTREAM: flushing with padding to get max %d bytes!\n", flush_remaining);
  1359. #endif
  1360. SDL_memset(stream->staging_buffer + filled, '\0', stream->staging_buffer_size - filled);
  1361. if (SDL_AudioStreamPutInternal(stream, stream->staging_buffer, stream->staging_buffer_size, &flush_remaining) < 0) {
  1362. return -1;
  1363. }
  1364. /* we have flushed out (or initially filled) the pending right-side
  1365. resampler padding, but we need to push more silence to guarantee
  1366. the staging buffer is fully flushed out, too. */
  1367. SDL_memset(stream->staging_buffer, '\0', filled);
  1368. if (SDL_AudioStreamPutInternal(stream, stream->staging_buffer, stream->staging_buffer_size, &flush_remaining) < 0) {
  1369. return -1;
  1370. }
  1371. }
  1372. }
  1373. stream->staging_buffer_filled = 0;
  1374. stream->first_run = SDL_TRUE;
  1375. return 0;
  1376. }
  1377. /* get converted/resampled data from the stream */
  1378. int
  1379. SDL_AudioStreamGet(SDL_AudioStream *stream, void *buf, int len)
  1380. {
  1381. #if DEBUG_AUDIOSTREAM
  1382. printf("AUDIOSTREAM: want to get %d converted bytes\n", len);
  1383. #endif
  1384. if (!stream) {
  1385. return SDL_InvalidParamError("stream");
  1386. } else if (!buf) {
  1387. return SDL_InvalidParamError("buf");
  1388. } else if (len <= 0) {
  1389. return 0; /* nothing to do. */
  1390. } else if ((len % stream->dst_sample_frame_size) != 0) {
  1391. return SDL_SetError("Can't request partial sample frames");
  1392. }
  1393. return (int) SDL_ReadFromDataQueue(stream->queue, buf, len);
  1394. }
  1395. /* number of converted/resampled bytes available */
  1396. int
  1397. SDL_AudioStreamAvailable(SDL_AudioStream *stream)
  1398. {
  1399. return stream ? (int) SDL_CountDataQueue(stream->queue) : 0;
  1400. }
  1401. void
  1402. SDL_AudioStreamClear(SDL_AudioStream *stream)
  1403. {
  1404. if (!stream) {
  1405. SDL_InvalidParamError("stream");
  1406. } else {
  1407. SDL_ClearDataQueue(stream->queue, stream->packetlen * 2);
  1408. if (stream->reset_resampler_func) {
  1409. stream->reset_resampler_func(stream);
  1410. }
  1411. stream->first_run = SDL_TRUE;
  1412. stream->staging_buffer_filled = 0;
  1413. }
  1414. }
  1415. /* dispose of a stream */
  1416. void
  1417. SDL_FreeAudioStream(SDL_AudioStream *stream)
  1418. {
  1419. if (stream) {
  1420. if (stream->cleanup_resampler_func) {
  1421. stream->cleanup_resampler_func(stream);
  1422. }
  1423. SDL_FreeDataQueue(stream->queue);
  1424. SDL_free(stream->staging_buffer);
  1425. SDL_free(stream->work_buffer_base);
  1426. SDL_free(stream->resampler_padding);
  1427. SDL_free(stream);
  1428. }
  1429. }
  1430. /* vi: set ts=4 sw=4 expandtab: */