SDL_audiocvt.c 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2023 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. #include "SDL_audio_c.h"
  20. #include "SDL_audioqueue.h"
  21. #include "SDL_audioresample.h"
  22. #ifndef SDL_INT_MAX
  23. #define SDL_INT_MAX ((int)(~0u>>1))
  24. #endif
  25. /*
  26. * CHANNEL LAYOUTS AS SDL EXPECTS THEM:
  27. *
  28. * (Even if the platform expects something else later, that
  29. * SDL will swizzle between the app and the platform).
  30. *
  31. * Abbreviations:
  32. * - FRONT=single mono speaker
  33. * - FL=front left speaker
  34. * - FR=front right speaker
  35. * - FC=front center speaker
  36. * - BL=back left speaker
  37. * - BR=back right speaker
  38. * - SR=surround right speaker
  39. * - SL=surround left speaker
  40. * - BC=back center speaker
  41. * - LFE=low-frequency speaker
  42. *
  43. * These are listed in the order they are laid out in
  44. * memory, so "FL+FR" means "the front left speaker is
  45. * layed out in memory first, then the front right, then
  46. * it repeats for the next audio frame".
  47. *
  48. * 1 channel (mono) layout: FRONT
  49. * 2 channels (stereo) layout: FL+FR
  50. * 3 channels (2.1) layout: FL+FR+LFE
  51. * 4 channels (quad) layout: FL+FR+BL+BR
  52. * 5 channels (4.1) layout: FL+FR+LFE+BL+BR
  53. * 6 channels (5.1) layout: FL+FR+FC+LFE+BL+BR
  54. * 7 channels (6.1) layout: FL+FR+FC+LFE+BC+SL+SR
  55. * 8 channels (7.1) layout: FL+FR+FC+LFE+BL+BR+SL+SR
  56. */
  57. #ifdef SDL_SSE3_INTRINSICS
  58. // Convert from stereo to mono. Average left and right.
  59. static void SDL_TARGETING("sse3") SDL_ConvertStereoToMono_SSE3(float *dst, const float *src, int num_frames)
  60. {
  61. LOG_DEBUG_AUDIO_CONVERT("stereo", "mono (using SSE3)");
  62. const __m128 divby2 = _mm_set1_ps(0.5f);
  63. int i = num_frames;
  64. /* Do SSE blocks as long as we have 16 bytes available.
  65. Just use unaligned load/stores, if the memory at runtime is
  66. aligned it'll be just as fast on modern processors */
  67. while (i >= 4) { // 4 * float32
  68. _mm_storeu_ps(dst, _mm_mul_ps(_mm_hadd_ps(_mm_loadu_ps(src), _mm_loadu_ps(src + 4)), divby2));
  69. i -= 4;
  70. src += 8;
  71. dst += 4;
  72. }
  73. // Finish off any leftovers with scalar operations.
  74. while (i) {
  75. *dst = (src[0] + src[1]) * 0.5f;
  76. dst++;
  77. i--;
  78. src += 2;
  79. }
  80. }
  81. #endif
  82. #ifdef SDL_SSE_INTRINSICS
  83. // Convert from mono to stereo. Duplicate to stereo left and right.
  84. static void SDL_TARGETING("sse") SDL_ConvertMonoToStereo_SSE(float *dst, const float *src, int num_frames)
  85. {
  86. LOG_DEBUG_AUDIO_CONVERT("mono", "stereo (using SSE)");
  87. // convert backwards, since output is growing in-place.
  88. src += (num_frames-4) * 1;
  89. dst += (num_frames-4) * 2;
  90. /* Do SSE blocks as long as we have 16 bytes available.
  91. Just use unaligned load/stores, if the memory at runtime is
  92. aligned it'll be just as fast on modern processors */
  93. // convert backwards, since output is growing in-place.
  94. int i = num_frames;
  95. while (i >= 4) { // 4 * float32
  96. const __m128 input = _mm_loadu_ps(src); // A B C D
  97. _mm_storeu_ps(dst, _mm_unpacklo_ps(input, input)); // A A B B
  98. _mm_storeu_ps(dst + 4, _mm_unpackhi_ps(input, input)); // C C D D
  99. i -= 4;
  100. src -= 4;
  101. dst -= 8;
  102. }
  103. // Finish off any leftovers with scalar operations.
  104. src += 3;
  105. dst += 6; // adjust for smaller buffers.
  106. while (i) { // convert backwards, since output is growing in-place.
  107. const float srcFC = src[0];
  108. dst[1] /* FR */ = srcFC;
  109. dst[0] /* FL */ = srcFC;
  110. i--;
  111. src--;
  112. dst -= 2;
  113. }
  114. }
  115. #endif
  116. // Include the autogenerated channel converters...
  117. #include "SDL_audio_channel_converters.h"
  118. static void AudioConvertByteswap(void *dst, const void *src, int num_samples, int bitsize)
  119. {
  120. #if DEBUG_AUDIO_CONVERT
  121. SDL_Log("SDL_AUDIO_CONVERT: Converting %d-bit byte order", bitsize);
  122. #endif
  123. switch (bitsize) {
  124. #define CASESWAP(b) \
  125. case b: { \
  126. const Uint##b *tsrc = (const Uint##b *)src; \
  127. Uint##b *tdst = (Uint##b *)dst; \
  128. for (int i = 0; i < num_samples; i++) { \
  129. tdst[i] = SDL_Swap##b(tsrc[i]); \
  130. } \
  131. break; \
  132. }
  133. CASESWAP(16);
  134. CASESWAP(32);
  135. #undef CASESWAP
  136. default:
  137. SDL_assert(!"unhandled byteswap datatype!");
  138. break;
  139. }
  140. }
  141. static void AudioConvertToFloat(float *dst, const void *src, int num_samples, SDL_AudioFormat src_fmt)
  142. {
  143. // Endian conversion is handled separately
  144. switch (src_fmt & ~SDL_AUDIO_MASK_BIG_ENDIAN) {
  145. case SDL_AUDIO_S8: SDL_Convert_S8_to_F32(dst, (const Sint8 *) src, num_samples); break;
  146. case SDL_AUDIO_U8: SDL_Convert_U8_to_F32(dst, (const Uint8 *) src, num_samples); break;
  147. case SDL_AUDIO_S16LE: SDL_Convert_S16_to_F32(dst, (const Sint16 *) src, num_samples); break;
  148. case SDL_AUDIO_S32LE: SDL_Convert_S32_to_F32(dst, (const Sint32 *) src, num_samples); break;
  149. default: SDL_assert(!"Unexpected audio format!"); break;
  150. }
  151. }
  152. static void AudioConvertFromFloat(void *dst, const float *src, int num_samples, SDL_AudioFormat dst_fmt)
  153. {
  154. // Endian conversion is handled separately
  155. switch (dst_fmt & ~SDL_AUDIO_MASK_BIG_ENDIAN) {
  156. case SDL_AUDIO_S8: SDL_Convert_F32_to_S8((Sint8 *) dst, src, num_samples); break;
  157. case SDL_AUDIO_U8: SDL_Convert_F32_to_U8((Uint8 *) dst, src, num_samples); break;
  158. case SDL_AUDIO_S16LE: SDL_Convert_F32_to_S16((Sint16 *) dst, src, num_samples); break;
  159. case SDL_AUDIO_S32LE: SDL_Convert_F32_to_S32((Sint32 *) dst, src, num_samples); break;
  160. default: SDL_assert(!"Unexpected audio format!"); break;
  161. }
  162. }
  163. static SDL_bool SDL_IsSupportedAudioFormat(const SDL_AudioFormat fmt)
  164. {
  165. switch (fmt) {
  166. case SDL_AUDIO_U8:
  167. case SDL_AUDIO_S8:
  168. case SDL_AUDIO_S16LE:
  169. case SDL_AUDIO_S16BE:
  170. case SDL_AUDIO_S32LE:
  171. case SDL_AUDIO_S32BE:
  172. case SDL_AUDIO_F32LE:
  173. case SDL_AUDIO_F32BE:
  174. return SDL_TRUE; // supported.
  175. default:
  176. break;
  177. }
  178. return SDL_FALSE; // unsupported.
  179. }
  180. static SDL_bool SDL_IsSupportedChannelCount(const int channels)
  181. {
  182. return ((channels >= 1) && (channels <= 8)) ? SDL_TRUE : SDL_FALSE;
  183. }
  184. // This does type and channel conversions _but not resampling_ (resampling happens in SDL_AudioStream).
  185. // This does not check parameter validity, (beyond asserts), it expects you did that already!
  186. // All of this has to function as if src==dst==scratch (conversion in-place), but as a convenience
  187. // if you're just going to copy the final output elsewhere, you can specify a different output pointer.
  188. //
  189. // The scratch buffer must be able to store `num_frames * CalculateMaxSampleFrameSize(src_format, src_channels, dst_format, dst_channels)` bytes.
  190. // If the scratch buffer is NULL, this restriction applies to the output buffer instead.
  191. void ConvertAudio(int num_frames, const void *src, SDL_AudioFormat src_format, int src_channels,
  192. void *dst, SDL_AudioFormat dst_format, int dst_channels, void* scratch)
  193. {
  194. SDL_assert(src != NULL);
  195. SDL_assert(dst != NULL);
  196. SDL_assert(SDL_IsSupportedAudioFormat(src_format));
  197. SDL_assert(SDL_IsSupportedAudioFormat(dst_format));
  198. SDL_assert(SDL_IsSupportedChannelCount(src_channels));
  199. SDL_assert(SDL_IsSupportedChannelCount(dst_channels));
  200. if (!num_frames) {
  201. return; // no data to convert, quit.
  202. }
  203. #if DEBUG_AUDIO_CONVERT
  204. SDL_Log("SDL_AUDIO_CONVERT: Convert format %04x->%04x, channels %u->%u", src_format, dst_format, src_channels, dst_channels);
  205. #endif
  206. const int src_bitsize = (int) SDL_AUDIO_BITSIZE(src_format);
  207. const int dst_bitsize = (int) SDL_AUDIO_BITSIZE(dst_format);
  208. const int dst_sample_frame_size = (dst_bitsize / 8) * dst_channels;
  209. /* Type conversion goes like this now:
  210. - byteswap to CPU native format first if necessary.
  211. - convert to native Float32 if necessary.
  212. - change channel count if necessary.
  213. - convert to final data format.
  214. - byteswap back to foreign format if necessary.
  215. The expectation is we can process data faster in float32
  216. (possibly with SIMD), and making several passes over the same
  217. buffer is likely to be CPU cache-friendly, avoiding the
  218. biggest performance hit in modern times. Previously we had
  219. (script-generated) custom converters for every data type and
  220. it was a bloat on SDL compile times and final library size. */
  221. // see if we can skip float conversion entirely.
  222. if (src_channels == dst_channels) {
  223. if (src_format == dst_format) {
  224. // nothing to do, we're already in the right format, just copy it over if necessary.
  225. if (src != dst) {
  226. SDL_memcpy(dst, src, num_frames * dst_sample_frame_size);
  227. }
  228. return;
  229. }
  230. // just a byteswap needed?
  231. if ((src_format & ~SDL_AUDIO_MASK_BIG_ENDIAN) == (dst_format & ~SDL_AUDIO_MASK_BIG_ENDIAN)) {
  232. if (src_bitsize == 8) {
  233. if (src != dst) {
  234. SDL_memcpy(dst, src, num_frames * dst_sample_frame_size);
  235. }
  236. return; // nothing to do, it's a 1-byte format.
  237. }
  238. AudioConvertByteswap(dst, src, num_frames * src_channels, src_bitsize);
  239. return; // all done.
  240. }
  241. }
  242. if (scratch == NULL) {
  243. scratch = dst;
  244. }
  245. const SDL_bool srcbyteswap = (SDL_AUDIO_ISBIGENDIAN(src_format) != 0) == (SDL_BYTEORDER == SDL_LIL_ENDIAN) && (src_bitsize > 8);
  246. const SDL_bool srcconvert = !SDL_AUDIO_ISFLOAT(src_format);
  247. const SDL_bool channelconvert = src_channels != dst_channels;
  248. const SDL_bool dstconvert = !SDL_AUDIO_ISFLOAT(dst_format);
  249. const SDL_bool dstbyteswap = (SDL_AUDIO_ISBIGENDIAN(dst_format) != 0) == (SDL_BYTEORDER == SDL_LIL_ENDIAN) && (dst_bitsize > 8);
  250. // make sure we're in native byte order.
  251. if (srcbyteswap) {
  252. // No point writing straight to dst. If we only need a byteswap, we wouldn't be bere.
  253. AudioConvertByteswap(scratch, src, num_frames * src_channels, src_bitsize);
  254. src = scratch;
  255. }
  256. // get us to float format.
  257. if (srcconvert) {
  258. void* buf = (channelconvert || dstconvert || dstbyteswap) ? scratch : dst;
  259. AudioConvertToFloat((float *) buf, src, num_frames * src_channels, src_format);
  260. src = buf;
  261. }
  262. // Channel conversion
  263. if (channelconvert) {
  264. SDL_AudioChannelConverter channel_converter;
  265. SDL_AudioChannelConverter override = NULL;
  266. // SDL_IsSupportedChannelCount should have caught these asserts, or we added a new format and forgot to update the table.
  267. SDL_assert(src_channels <= SDL_arraysize(channel_converters));
  268. SDL_assert(dst_channels <= SDL_arraysize(channel_converters[0]));
  269. channel_converter = channel_converters[src_channels - 1][dst_channels - 1];
  270. SDL_assert(channel_converter != NULL);
  271. // swap in some SIMD versions for a few of these.
  272. if (channel_converter == SDL_ConvertStereoToMono) {
  273. #ifdef SDL_SSE3_INTRINSICS
  274. if (!override && SDL_HasSSE3()) { override = SDL_ConvertStereoToMono_SSE3; }
  275. #endif
  276. } else if (channel_converter == SDL_ConvertMonoToStereo) {
  277. #ifdef SDL_SSE_INTRINSICS
  278. if (!override && SDL_HasSSE()) { override = SDL_ConvertMonoToStereo_SSE; }
  279. #endif
  280. }
  281. if (override) {
  282. channel_converter = override;
  283. }
  284. void* buf = (dstconvert || dstbyteswap) ? scratch : dst;
  285. channel_converter((float *) buf, (const float *) src, num_frames);
  286. src = buf;
  287. }
  288. // Resampling is not done in here. SDL_AudioStream handles that.
  289. // Move to final data type.
  290. if (dstconvert) {
  291. AudioConvertFromFloat(dst, (const float *) src, num_frames * dst_channels, dst_format);
  292. src = dst;
  293. }
  294. // make sure we're in final byte order.
  295. if (dstbyteswap) {
  296. AudioConvertByteswap(dst, src, num_frames * dst_channels, dst_bitsize);
  297. src = dst; // we've written to dst, future work will convert in-place.
  298. }
  299. SDL_assert(src == dst); // if we got here, we _had_ to have done _something_. Otherwise, we should have memcpy'd!
  300. }
  301. // Calculate the largest frame size needed to convert between the two formats.
  302. static int CalculateMaxFrameSize(SDL_AudioFormat src_format, int src_channels, SDL_AudioFormat dst_format, int dst_channels)
  303. {
  304. const int src_format_size = SDL_AUDIO_BYTESIZE(src_format);
  305. const int dst_format_size = SDL_AUDIO_BYTESIZE(dst_format);
  306. const int max_app_format_size = SDL_max(src_format_size, dst_format_size);
  307. const int max_format_size = SDL_max(max_app_format_size, sizeof (float)); // ConvertAudio and ResampleAudio use floats.
  308. const int max_channels = SDL_max(src_channels, dst_channels);
  309. return max_format_size * max_channels;
  310. }
  311. static Sint64 GetAudioStreamResampleRate(SDL_AudioStream* stream, int src_freq, Sint64 resample_offset)
  312. {
  313. src_freq = (int)((float)src_freq * stream->freq_ratio);
  314. Sint64 resample_rate = SDL_GetResampleRate(src_freq, stream->dst_spec.freq);
  315. // If src_freq == dst_freq, and we aren't between frames, don't resample
  316. if ((resample_rate == 0x100000000) && (resample_offset == 0)) {
  317. resample_rate = 0;
  318. }
  319. return resample_rate;
  320. }
  321. static int UpdateAudioStreamInputSpec(SDL_AudioStream *stream, const SDL_AudioSpec *spec)
  322. {
  323. if (AUDIO_SPECS_EQUAL(stream->input_spec, *spec)) {
  324. return 0;
  325. }
  326. const size_t history_buffer_allocation = SDL_GetResamplerHistoryFrames() * SDL_AUDIO_FRAMESIZE(*spec);
  327. Uint8 *history_buffer = stream->history_buffer;
  328. if (stream->history_buffer_allocation < history_buffer_allocation) {
  329. history_buffer = (Uint8 *) SDL_aligned_alloc(SDL_SIMDGetAlignment(), history_buffer_allocation);
  330. if (!history_buffer) {
  331. return SDL_OutOfMemory();
  332. }
  333. SDL_aligned_free(stream->history_buffer);
  334. stream->history_buffer = history_buffer;
  335. stream->history_buffer_allocation = history_buffer_allocation;
  336. }
  337. SDL_memset(history_buffer, SDL_GetSilenceValueForFormat(spec->format), history_buffer_allocation);
  338. SDL_copyp(&stream->input_spec, spec);
  339. return 0;
  340. }
  341. SDL_AudioStream *SDL_CreateAudioStream(const SDL_AudioSpec *src_spec, const SDL_AudioSpec *dst_spec)
  342. {
  343. if (!SDL_WasInit(SDL_INIT_AUDIO)) {
  344. SDL_SetError("Audio subsystem is not initialized");
  345. return NULL;
  346. }
  347. SDL_AudioStream *retval = (SDL_AudioStream *)SDL_calloc(1, sizeof(SDL_AudioStream));
  348. if (retval == NULL) {
  349. SDL_OutOfMemory();
  350. return NULL;
  351. }
  352. retval->freq_ratio = 1.0f;
  353. retval->queue = SDL_CreateAudioQueue(4096);
  354. if (retval->queue == NULL) {
  355. SDL_free(retval);
  356. return NULL;
  357. }
  358. retval->lock = SDL_CreateMutex();
  359. if (retval->lock == NULL) {
  360. SDL_free(retval->queue);
  361. SDL_free(retval);
  362. return NULL;
  363. }
  364. OnAudioStreamCreated(retval);
  365. if (SDL_SetAudioStreamFormat(retval, src_spec, dst_spec) == -1) {
  366. SDL_DestroyAudioStream(retval);
  367. return NULL;
  368. }
  369. return retval;
  370. }
  371. int SDL_SetAudioStreamGetCallback(SDL_AudioStream *stream, SDL_AudioStreamCallback callback, void *userdata)
  372. {
  373. if (!stream) {
  374. return SDL_InvalidParamError("stream");
  375. }
  376. SDL_LockMutex(stream->lock);
  377. stream->get_callback = callback;
  378. stream->get_callback_userdata = userdata;
  379. SDL_UnlockMutex(stream->lock);
  380. return 0;
  381. }
  382. int SDL_SetAudioStreamPutCallback(SDL_AudioStream *stream, SDL_AudioStreamCallback callback, void *userdata)
  383. {
  384. if (!stream) {
  385. return SDL_InvalidParamError("stream");
  386. }
  387. SDL_LockMutex(stream->lock);
  388. stream->put_callback = callback;
  389. stream->put_callback_userdata = userdata;
  390. SDL_UnlockMutex(stream->lock);
  391. return 0;
  392. }
  393. int SDL_LockAudioStream(SDL_AudioStream *stream)
  394. {
  395. return stream ? SDL_LockMutex(stream->lock) : SDL_InvalidParamError("stream");
  396. }
  397. int SDL_UnlockAudioStream(SDL_AudioStream *stream)
  398. {
  399. return stream ? SDL_UnlockMutex(stream->lock) : SDL_InvalidParamError("stream");
  400. }
  401. int SDL_GetAudioStreamFormat(SDL_AudioStream *stream, SDL_AudioSpec *src_spec, SDL_AudioSpec *dst_spec)
  402. {
  403. if (!stream) {
  404. return SDL_InvalidParamError("stream");
  405. }
  406. SDL_LockMutex(stream->lock);
  407. if (src_spec) {
  408. SDL_copyp(src_spec, &stream->src_spec);
  409. }
  410. if (dst_spec) {
  411. SDL_copyp(dst_spec, &stream->dst_spec);
  412. }
  413. SDL_UnlockMutex(stream->lock);
  414. if (src_spec && src_spec->format == 0) {
  415. return SDL_SetError("Stream has no source format");
  416. } else if (dst_spec && dst_spec->format == 0) {
  417. return SDL_SetError("Stream has no destination format");
  418. }
  419. return 0;
  420. }
  421. int SDL_SetAudioStreamFormat(SDL_AudioStream *stream, const SDL_AudioSpec *src_spec, const SDL_AudioSpec *dst_spec)
  422. {
  423. if (!stream) {
  424. return SDL_InvalidParamError("stream");
  425. }
  426. // Picked mostly arbitrarily.
  427. static const int min_freq = 4000;
  428. static const int max_freq = 384000;
  429. if (src_spec) {
  430. if (!SDL_IsSupportedAudioFormat(src_spec->format)) {
  431. return SDL_InvalidParamError("src_spec->format");
  432. } else if (!SDL_IsSupportedChannelCount(src_spec->channels)) {
  433. return SDL_InvalidParamError("src_spec->channels");
  434. } else if (src_spec->freq <= 0) {
  435. return SDL_InvalidParamError("src_spec->freq");
  436. } else if (src_spec->freq < min_freq) {
  437. return SDL_SetError("Source rate is too low");
  438. } else if (src_spec->freq > max_freq) {
  439. return SDL_SetError("Source rate is too high");
  440. }
  441. }
  442. if (dst_spec) {
  443. if (!SDL_IsSupportedAudioFormat(dst_spec->format)) {
  444. return SDL_InvalidParamError("dst_spec->format");
  445. } else if (!SDL_IsSupportedChannelCount(dst_spec->channels)) {
  446. return SDL_InvalidParamError("dst_spec->channels");
  447. } else if (dst_spec->freq <= 0) {
  448. return SDL_InvalidParamError("dst_spec->freq");
  449. } else if (dst_spec->freq < min_freq) {
  450. return SDL_SetError("Destination rate is too low");
  451. } else if (dst_spec->freq > max_freq) {
  452. return SDL_SetError("Destination rate is too high");
  453. }
  454. }
  455. SDL_LockMutex(stream->lock);
  456. // quietly refuse to change the format of the end currently bound to a device.
  457. if (stream->bound_device) {
  458. if (stream->bound_device->physical_device->iscapture) {
  459. dst_spec = NULL;
  460. } else {
  461. src_spec = NULL;
  462. }
  463. }
  464. if (src_spec) {
  465. SDL_copyp(&stream->src_spec, src_spec);
  466. }
  467. if (dst_spec) {
  468. SDL_copyp(&stream->dst_spec, dst_spec);
  469. }
  470. SDL_UnlockMutex(stream->lock);
  471. return 0;
  472. }
  473. float SDL_GetAudioStreamFrequencyRatio(SDL_AudioStream *stream)
  474. {
  475. if (!stream) {
  476. SDL_InvalidParamError("stream");
  477. return 0.0f;
  478. }
  479. SDL_LockMutex(stream->lock);
  480. float freq_ratio = stream->freq_ratio;
  481. SDL_UnlockMutex(stream->lock);
  482. return freq_ratio;
  483. }
  484. int SDL_SetAudioStreamFrequencyRatio(SDL_AudioStream *stream, float freq_ratio)
  485. {
  486. if (!stream) {
  487. return SDL_InvalidParamError("stream");
  488. }
  489. // Picked mostly arbitrarily.
  490. static const float min_freq_ratio = 0.01f;
  491. static const float max_freq_ratio = 100.0f;
  492. if (freq_ratio < min_freq_ratio) {
  493. return SDL_SetError("Frequency ratio is too low");
  494. } else if (freq_ratio > max_freq_ratio) {
  495. return SDL_SetError("Frequency ratio is too high");
  496. }
  497. SDL_LockMutex(stream->lock);
  498. stream->freq_ratio = freq_ratio;
  499. SDL_UnlockMutex(stream->lock);
  500. return 0;
  501. }
  502. static int CheckAudioStreamIsFullySetup(SDL_AudioStream *stream)
  503. {
  504. if (stream->src_spec.format == 0) {
  505. return SDL_SetError("Stream has no source format");
  506. } else if (stream->dst_spec.format == 0) {
  507. return SDL_SetError("Stream has no destination format");
  508. }
  509. return 0;
  510. }
  511. int SDL_PutAudioStreamData(SDL_AudioStream *stream, const void *buf, int len)
  512. {
  513. #if DEBUG_AUDIOSTREAM
  514. SDL_Log("AUDIOSTREAM: wants to put %d bytes", len);
  515. #endif
  516. if (stream == NULL) {
  517. return SDL_InvalidParamError("stream");
  518. } else if (buf == NULL) {
  519. return SDL_InvalidParamError("buf");
  520. } else if (len < 0) {
  521. return SDL_InvalidParamError("len");
  522. } else if (len == 0) {
  523. return 0; // nothing to do.
  524. }
  525. SDL_LockMutex(stream->lock);
  526. if (CheckAudioStreamIsFullySetup(stream) != 0) {
  527. SDL_UnlockMutex(stream->lock);
  528. return -1;
  529. }
  530. if ((len % SDL_AUDIO_FRAMESIZE(stream->src_spec)) != 0) {
  531. SDL_UnlockMutex(stream->lock);
  532. return SDL_SetError("Can't add partial sample frames");
  533. }
  534. SDL_AudioTrack* track = NULL;
  535. // When copying in large amounts of data, try and do as much work as possible
  536. // outside of the stream lock, otherwise the output device is likely to be starved.
  537. const int large_input_thresh = 1024 * 1024;
  538. if (len >= large_input_thresh) {
  539. SDL_AudioSpec src_spec;
  540. SDL_copyp(&src_spec, &stream->src_spec);
  541. SDL_UnlockMutex(stream->lock);
  542. size_t chunk_size = SDL_GetAudioQueueChunkSize(stream->queue);
  543. track = SDL_CreateChunkedAudioTrack(&src_spec, buf, len, chunk_size);
  544. if (track == NULL) {
  545. return -1;
  546. }
  547. SDL_LockMutex(stream->lock);
  548. }
  549. const int prev_available = stream->put_callback ? SDL_GetAudioStreamAvailable(stream) : 0;
  550. int retval = 0;
  551. if (track != NULL) {
  552. SDL_AddTrackToAudioQueue(stream->queue, track);
  553. } else {
  554. retval = SDL_WriteToAudioQueue(stream->queue, &stream->src_spec, buf, len);
  555. }
  556. if (retval == 0) {
  557. stream->total_bytes_queued += len;
  558. if (stream->put_callback) {
  559. const int newavail = SDL_GetAudioStreamAvailable(stream) - prev_available;
  560. stream->put_callback(stream->put_callback_userdata, stream, newavail, newavail);
  561. }
  562. }
  563. SDL_UnlockMutex(stream->lock);
  564. return retval;
  565. }
  566. int SDL_FlushAudioStream(SDL_AudioStream *stream)
  567. {
  568. if (stream == NULL) {
  569. return SDL_InvalidParamError("stream");
  570. }
  571. SDL_LockMutex(stream->lock);
  572. SDL_FlushAudioQueue(stream->queue);
  573. SDL_UnlockMutex(stream->lock);
  574. return 0;
  575. }
  576. /* this does not save the previous contents of stream->work_buffer. It's a work buffer!!
  577. The returned buffer is aligned/padded for use with SIMD instructions. */
  578. static Uint8 *EnsureAudioStreamWorkBufferSize(SDL_AudioStream *stream, size_t newlen)
  579. {
  580. if (stream->work_buffer_allocation >= newlen) {
  581. return stream->work_buffer;
  582. }
  583. Uint8 *ptr = (Uint8 *) SDL_aligned_alloc(SDL_SIMDGetAlignment(), newlen);
  584. if (ptr == NULL) {
  585. SDL_OutOfMemory();
  586. return NULL; // previous work buffer is still valid!
  587. }
  588. SDL_aligned_free(stream->work_buffer);
  589. stream->work_buffer = ptr;
  590. stream->work_buffer_allocation = newlen;
  591. return ptr;
  592. }
  593. static void UpdateAudioStreamHistoryBuffer(SDL_AudioStream* stream,
  594. Uint8* input_buffer, int input_bytes, Uint8* left_padding, int padding_bytes)
  595. {
  596. const int history_buffer_frames = SDL_GetResamplerHistoryFrames();
  597. // Even if we aren't currently resampling, we always need to update the history buffer
  598. Uint8 *history_buffer = stream->history_buffer;
  599. int history_bytes = history_buffer_frames * SDL_AUDIO_FRAMESIZE(stream->input_spec);
  600. if (left_padding != NULL) {
  601. // Fill in the left padding using the history buffer
  602. SDL_assert(padding_bytes <= history_bytes);
  603. SDL_memcpy(left_padding, history_buffer + history_bytes - padding_bytes, padding_bytes);
  604. }
  605. // Update the history buffer using the new input data
  606. if (input_bytes >= history_bytes) {
  607. SDL_memcpy(history_buffer, input_buffer + (input_bytes - history_bytes), history_bytes);
  608. } else {
  609. int preserve_bytes = history_bytes - input_bytes;
  610. SDL_memmove(history_buffer, history_buffer + input_bytes, preserve_bytes);
  611. SDL_memcpy(history_buffer + preserve_bytes, input_buffer, input_bytes);
  612. }
  613. }
  614. static Sint64 NextAudioStreamIter(SDL_AudioStream* stream, void** inout_iter,
  615. Sint64* inout_resample_offset, SDL_AudioSpec* out_spec, SDL_bool* out_flushed)
  616. {
  617. SDL_AudioSpec spec;
  618. SDL_bool flushed;
  619. size_t queued_bytes = SDL_NextAudioQueueIter(stream->queue, inout_iter, &spec, &flushed);
  620. if (out_spec) {
  621. SDL_copyp(out_spec, &spec);
  622. }
  623. // There is infinite audio available, whether or not we are resampling
  624. if (queued_bytes == SDL_SIZE_MAX) {
  625. *inout_resample_offset = 0;
  626. if (out_flushed) {
  627. *out_flushed = SDL_FALSE;
  628. }
  629. return SDL_MAX_SINT32;
  630. }
  631. Sint64 resample_offset = *inout_resample_offset;
  632. Sint64 resample_rate = GetAudioStreamResampleRate(stream, spec.freq, resample_offset);
  633. Sint64 output_frames = (Sint64)(queued_bytes / SDL_AUDIO_FRAMESIZE(spec));
  634. if (resample_rate) {
  635. // Resampling requires padding frames to the left and right of the current position.
  636. // Past the end of the track, the right padding is filled with silence.
  637. // But we only want to do that if the track is actually finished (flushed).
  638. if (!flushed) {
  639. output_frames -= SDL_GetResamplerPaddingFrames(resample_rate);
  640. }
  641. output_frames = SDL_GetResamplerOutputFrames(output_frames, resample_rate, &resample_offset);
  642. }
  643. if (flushed) {
  644. resample_offset = 0;
  645. }
  646. *inout_resample_offset = resample_offset;
  647. if (out_flushed) {
  648. *out_flushed = flushed;
  649. }
  650. return output_frames;
  651. }
  652. static Sint64 GetAudioStreamAvailableFrames(SDL_AudioStream* stream, Sint64* out_resample_offset)
  653. {
  654. void* iter = SDL_BeginAudioQueueIter(stream->queue);
  655. Sint64 resample_offset = stream->resample_offset;
  656. Sint64 output_frames = 0;
  657. while (iter) {
  658. output_frames += NextAudioStreamIter(stream, &iter, &resample_offset, NULL, NULL);
  659. // Already got loads of frames. Just clamp it to something reasonable
  660. if (output_frames >= SDL_MAX_SINT32) {
  661. output_frames = SDL_MAX_SINT32;
  662. break;
  663. }
  664. }
  665. if (out_resample_offset) {
  666. *out_resample_offset = resample_offset;
  667. }
  668. return output_frames;
  669. }
  670. static Sint64 GetAudioStreamHead(SDL_AudioStream* stream, SDL_AudioSpec* out_spec, SDL_bool* out_flushed)
  671. {
  672. void* iter = SDL_BeginAudioQueueIter(stream->queue);
  673. if (iter == NULL) {
  674. SDL_zerop(out_spec);
  675. *out_flushed = SDL_FALSE;
  676. return 0;
  677. }
  678. Sint64 resample_offset = stream->resample_offset;
  679. return NextAudioStreamIter(stream, &iter, &resample_offset, out_spec, out_flushed);
  680. }
  681. // You must hold stream->lock and validate your parameters before calling this!
  682. // Enough input data MUST be available!
  683. static int GetAudioStreamDataInternal(SDL_AudioStream *stream, void *buf, int output_frames)
  684. {
  685. const SDL_AudioSpec* src_spec = &stream->input_spec;
  686. const SDL_AudioSpec* dst_spec = &stream->dst_spec;
  687. const SDL_AudioFormat src_format = src_spec->format;
  688. const int src_channels = src_spec->channels;
  689. const int src_frame_size = SDL_AUDIO_FRAMESIZE(*src_spec);
  690. const SDL_AudioFormat dst_format = dst_spec->format;
  691. const int dst_channels = dst_spec->channels;
  692. const int max_frame_size = CalculateMaxFrameSize(src_format, src_channels, dst_format, dst_channels);
  693. const Sint64 resample_rate = GetAudioStreamResampleRate(stream, src_spec->freq, stream->resample_offset);
  694. #if DEBUG_AUDIOSTREAM
  695. SDL_Log("AUDIOSTREAM: asking for %d frames.", output_frames);
  696. #endif
  697. SDL_assert(output_frames > 0);
  698. // Not resampling? It's an easy conversion (and maybe not even that!)
  699. if (resample_rate == 0) {
  700. Uint8* input_buffer = NULL;
  701. // If no conversion is happening, read straight into the output buffer.
  702. // Note, this is just to avoid extra copies.
  703. // Some other formats may fit directly into the output buffer, but i'd rather process data in a SIMD-aligned buffer.
  704. if ((src_format == dst_format) && (src_channels == dst_channels)) {
  705. input_buffer = buf;
  706. } else {
  707. input_buffer = EnsureAudioStreamWorkBufferSize(stream, output_frames * max_frame_size);
  708. if (!input_buffer) {
  709. return -1;
  710. }
  711. }
  712. const int input_bytes = output_frames * src_frame_size;
  713. if (SDL_ReadFromAudioQueue(stream->queue, input_buffer, input_bytes) != 0) {
  714. SDL_assert(!"Not enough data in queue (read)");
  715. }
  716. stream->total_bytes_queued -= input_bytes;
  717. // Even if we aren't currently resampling, we always need to update the history buffer
  718. UpdateAudioStreamHistoryBuffer(stream, input_buffer, input_bytes, NULL, 0);
  719. // Convert the data, if necessary
  720. if (buf != input_buffer) {
  721. ConvertAudio(output_frames, input_buffer, src_format, src_channels, buf, dst_format, dst_channels, input_buffer);
  722. }
  723. return 0;
  724. }
  725. // Time to do some resampling!
  726. // Calculate the number of input frames necessary for this request.
  727. // Because resampling happens "between" frames, The same number of output_frames
  728. // can require a different number of input_frames, depending on the resample_offset.
  729. // Infact, input_frames can sometimes even be zero when upsampling.
  730. const int input_frames = (int) SDL_GetResamplerInputFrames(output_frames, resample_rate, stream->resample_offset);
  731. const int input_bytes = input_frames * src_frame_size;
  732. const int resampler_padding_frames = SDL_GetResamplerPaddingFrames(resample_rate);
  733. // If increasing channels, do it after resampling, since we'd just
  734. // do more work to resample duplicate channels. If we're decreasing, do
  735. // it first so we resample the interpolated data instead of interpolating
  736. // the resampled data.
  737. const int resample_channels = SDL_min(src_channels, dst_channels);
  738. // The size of the frame used when resampling
  739. const int resample_frame_size = resample_channels * sizeof(float);
  740. // The main portion of the work_buffer can be used to store 3 things:
  741. // src_sample_frame_size * (left_padding+input_buffer+right_padding)
  742. // resample_frame_size * (left_padding+input_buffer+right_padding)
  743. // dst_sample_frame_size * output_frames
  744. //
  745. // ResampleAudio also requires an additional buffer if it can't write straight to the output:
  746. // resample_frame_size * output_frames
  747. //
  748. // Note, ConvertAudio requires (num_frames * max_sample_frame_size) of scratch space
  749. const int work_buffer_frames = input_frames + (resampler_padding_frames * 2);
  750. int work_buffer_capacity = work_buffer_frames * max_frame_size;
  751. int resample_buffer_offset = -1;
  752. // Check if we can resample directly into the output buffer.
  753. // Note, this is just to avoid extra copies.
  754. // Some other formats may fit directly into the output buffer, but i'd rather process data in a SIMD-aligned buffer.
  755. if ((dst_format != SDL_AUDIO_F32) || (dst_channels != resample_channels)) {
  756. // Allocate space for converting the resampled output to the destination format
  757. int resample_convert_bytes = output_frames * max_frame_size;
  758. work_buffer_capacity = SDL_max(work_buffer_capacity, resample_convert_bytes);
  759. // SIMD-align the buffer
  760. int simd_alignment = (int) SDL_SIMDGetAlignment();
  761. work_buffer_capacity += simd_alignment - 1;
  762. work_buffer_capacity -= work_buffer_capacity % simd_alignment;
  763. // Allocate space for the resampled output
  764. int resample_bytes = output_frames * resample_frame_size;
  765. resample_buffer_offset = work_buffer_capacity;
  766. work_buffer_capacity += resample_bytes;
  767. }
  768. Uint8* work_buffer = EnsureAudioStreamWorkBufferSize(stream, work_buffer_capacity);
  769. if (!work_buffer) {
  770. return -1;
  771. }
  772. const int padding_bytes = resampler_padding_frames * src_frame_size;
  773. Uint8* work_buffer_tail = work_buffer;
  774. // Split the work_buffer into [left_padding][input_buffer][right_padding]
  775. Uint8* left_padding = work_buffer_tail;
  776. work_buffer_tail += padding_bytes;
  777. Uint8* input_buffer = work_buffer_tail;
  778. work_buffer_tail += input_bytes;
  779. Uint8* right_padding = work_buffer_tail;
  780. work_buffer_tail += padding_bytes;
  781. SDL_assert((work_buffer_tail - work_buffer) <= work_buffer_capacity);
  782. // Now read unconverted data from the queue into the work buffer to fulfill the request.
  783. if (SDL_ReadFromAudioQueue(stream->queue, input_buffer, input_bytes) != 0) {
  784. SDL_assert(!"Not enough data in queue (resample read)");
  785. }
  786. stream->total_bytes_queued -= input_bytes;
  787. // Update the history buffer and fill in the left padding
  788. UpdateAudioStreamHistoryBuffer(stream, input_buffer, input_bytes, left_padding, padding_bytes);
  789. // Fill in the right padding by peeking into the input queue (missing data is filled with silence)
  790. if (SDL_PeekIntoAudioQueue(stream->queue, right_padding, padding_bytes) != 0) {
  791. SDL_assert(!"Not enough data in queue (resample peek)");
  792. }
  793. SDL_assert(work_buffer_frames == input_frames + (resampler_padding_frames * 2));
  794. // Resampling! get the work buffer to float32 format, etc, in-place.
  795. ConvertAudio(work_buffer_frames, work_buffer, src_format, src_channels, work_buffer, SDL_AUDIO_F32, resample_channels, NULL);
  796. // Update the work_buffer pointers based on the new frame size
  797. input_buffer = work_buffer + ((input_buffer - work_buffer) / src_frame_size * resample_frame_size);
  798. work_buffer_tail = work_buffer + ((work_buffer_tail - work_buffer) / src_frame_size * resample_frame_size);
  799. SDL_assert((work_buffer_tail - work_buffer) <= work_buffer_capacity);
  800. // Decide where the resampled output goes
  801. void* resample_buffer = (resample_buffer_offset != -1) ? (work_buffer + resample_buffer_offset) : buf;
  802. SDL_ResampleAudio(resample_channels,
  803. (const float *) input_buffer, input_frames,
  804. (float*) resample_buffer, output_frames,
  805. resample_rate, &stream->resample_offset);
  806. // Convert to the final format, if necessary
  807. if (buf != resample_buffer) {
  808. ConvertAudio(output_frames, resample_buffer, SDL_AUDIO_F32, resample_channels, buf, dst_format, dst_channels, work_buffer);
  809. }
  810. return 0;
  811. }
  812. // get converted/resampled data from the stream
  813. int SDL_GetAudioStreamData(SDL_AudioStream *stream, void *voidbuf, int len)
  814. {
  815. Uint8 *buf = (Uint8 *) voidbuf;
  816. #if DEBUG_AUDIOSTREAM
  817. SDL_Log("AUDIOSTREAM: want to get %d converted bytes", len);
  818. #endif
  819. if (stream == NULL) {
  820. return SDL_InvalidParamError("stream");
  821. } else if (buf == NULL) {
  822. return SDL_InvalidParamError("buf");
  823. } else if (len < 0) {
  824. return SDL_InvalidParamError("len");
  825. } else if (len == 0) {
  826. return 0; // nothing to do.
  827. }
  828. SDL_LockMutex(stream->lock);
  829. if (CheckAudioStreamIsFullySetup(stream) != 0) {
  830. SDL_UnlockMutex(stream->lock);
  831. return -1;
  832. }
  833. const int dst_frame_size = SDL_AUDIO_FRAMESIZE(stream->dst_spec);
  834. len -= len % dst_frame_size; // chop off any fractional sample frame.
  835. // give the callback a chance to fill in more stream data if it wants.
  836. if (stream->get_callback) {
  837. Sint64 total_request = len / dst_frame_size; // start with sample frames desired
  838. Sint64 additional_request = total_request;
  839. Sint64 resample_offset = 0;
  840. Sint64 available_frames = GetAudioStreamAvailableFrames(stream, &resample_offset);
  841. additional_request -= SDL_min(additional_request, available_frames);
  842. Sint64 resample_rate = GetAudioStreamResampleRate(stream, stream->src_spec.freq, resample_offset);
  843. if (resample_rate) {
  844. total_request = SDL_GetResamplerInputFrames(total_request, resample_rate, resample_offset);
  845. additional_request = SDL_GetResamplerInputFrames(additional_request, resample_rate, resample_offset);
  846. }
  847. total_request *= SDL_AUDIO_FRAMESIZE(stream->src_spec); // convert sample frames to bytes.
  848. additional_request *= SDL_AUDIO_FRAMESIZE(stream->src_spec); // convert sample frames to bytes.
  849. stream->get_callback(stream->get_callback_userdata, stream, (int) SDL_min(additional_request, SDL_INT_MAX), (int) SDL_min(total_request, SDL_INT_MAX));
  850. }
  851. // Process the data in chunks to avoid allocating too much memory (and potential integer overflows)
  852. const int chunk_size = 4096;
  853. int total = 0;
  854. while (total < len) {
  855. // Audio is processed a track at a time.
  856. SDL_AudioSpec input_spec;
  857. SDL_bool flushed;
  858. const Sint64 available_frames = GetAudioStreamHead(stream, &input_spec, &flushed);
  859. if (available_frames == 0) {
  860. if (flushed) {
  861. SDL_PopAudioQueueHead(stream->queue);
  862. SDL_zero(stream->input_spec);
  863. stream->resample_offset = 0;
  864. continue;
  865. }
  866. // There are no frames available, but the track hasn't been flushed, so more might be added later.
  867. break;
  868. }
  869. if (UpdateAudioStreamInputSpec(stream, &input_spec) != 0) {
  870. total = total ? total : -1;
  871. break;
  872. }
  873. // Clamp the output length to the maximum currently available.
  874. // GetAudioStreamDataInternal requires enough input data is available.
  875. int output_frames = (len - total) / dst_frame_size;
  876. output_frames = SDL_min(output_frames, chunk_size);
  877. output_frames = (int) SDL_min(output_frames, available_frames);
  878. if (GetAudioStreamDataInternal(stream, &buf[total], output_frames) != 0) {
  879. total = total ? total : -1;
  880. break;
  881. }
  882. total += output_frames * dst_frame_size;
  883. }
  884. SDL_UnlockMutex(stream->lock);
  885. #if DEBUG_AUDIOSTREAM
  886. SDL_Log("AUDIOSTREAM: Final result was %d", total);
  887. #endif
  888. return total;
  889. }
  890. // number of converted/resampled bytes available for output
  891. int SDL_GetAudioStreamAvailable(SDL_AudioStream *stream)
  892. {
  893. if (!stream) {
  894. return SDL_InvalidParamError("stream");
  895. }
  896. SDL_LockMutex(stream->lock);
  897. if (CheckAudioStreamIsFullySetup(stream) != 0) {
  898. SDL_UnlockMutex(stream->lock);
  899. return 0;
  900. }
  901. Sint64 count = GetAudioStreamAvailableFrames(stream, NULL);
  902. // convert from sample frames to bytes in destination format.
  903. count *= SDL_AUDIO_FRAMESIZE(stream->dst_spec);
  904. SDL_UnlockMutex(stream->lock);
  905. // if this overflows an int, just clamp it to a maximum.
  906. return (int) SDL_min(count, SDL_INT_MAX);
  907. }
  908. // number of sample frames that are currently queued as input.
  909. int SDL_GetAudioStreamQueued(SDL_AudioStream *stream)
  910. {
  911. if (!stream) {
  912. return SDL_InvalidParamError("stream");
  913. }
  914. SDL_LockMutex(stream->lock);
  915. const Uint64 total = stream->total_bytes_queued;
  916. SDL_UnlockMutex(stream->lock);
  917. // if this overflows an int, just clamp it to a maximum.
  918. return (int) SDL_min(total, SDL_INT_MAX);
  919. }
  920. int SDL_ClearAudioStream(SDL_AudioStream *stream)
  921. {
  922. if (stream == NULL) {
  923. return SDL_InvalidParamError("stream");
  924. }
  925. SDL_LockMutex(stream->lock);
  926. SDL_ClearAudioQueue(stream->queue);
  927. SDL_zero(stream->input_spec);
  928. stream->resample_offset = 0;
  929. stream->total_bytes_queued = 0;
  930. SDL_UnlockMutex(stream->lock);
  931. return 0;
  932. }
  933. void SDL_DestroyAudioStream(SDL_AudioStream *stream)
  934. {
  935. if (stream == NULL) {
  936. return;
  937. }
  938. OnAudioStreamDestroy(stream);
  939. const SDL_bool simplified = stream->simplified;
  940. if (simplified) {
  941. SDL_assert(stream->bound_device->simplified);
  942. SDL_CloseAudioDevice(stream->bound_device->instance_id); // this will unbind the stream.
  943. } else {
  944. SDL_UnbindAudioStream(stream);
  945. }
  946. SDL_aligned_free(stream->history_buffer);
  947. SDL_aligned_free(stream->work_buffer);
  948. SDL_DestroyAudioQueue(stream->queue);
  949. SDL_DestroyMutex(stream->lock);
  950. SDL_free(stream);
  951. }
  952. int SDL_ConvertAudioSamples(const SDL_AudioSpec *src_spec, const Uint8 *src_data, int src_len,
  953. const SDL_AudioSpec *dst_spec, Uint8 **dst_data, int *dst_len)
  954. {
  955. if (dst_data) {
  956. *dst_data = NULL;
  957. }
  958. if (dst_len) {
  959. *dst_len = 0;
  960. }
  961. if (src_data == NULL) {
  962. return SDL_InvalidParamError("src_data");
  963. } else if (src_len < 0) {
  964. return SDL_InvalidParamError("src_len");
  965. } else if (dst_data == NULL) {
  966. return SDL_InvalidParamError("dst_data");
  967. } else if (dst_len == NULL) {
  968. return SDL_InvalidParamError("dst_len");
  969. }
  970. int retval = -1;
  971. Uint8 *dst = NULL;
  972. int dstlen = 0;
  973. SDL_AudioStream *stream = SDL_CreateAudioStream(src_spec, dst_spec);
  974. if (stream != NULL) {
  975. if ((SDL_PutAudioStreamData(stream, src_data, src_len) == 0) && (SDL_FlushAudioStream(stream) == 0)) {
  976. dstlen = SDL_GetAudioStreamAvailable(stream);
  977. if (dstlen >= 0) {
  978. dst = (Uint8 *)SDL_malloc(dstlen);
  979. if (!dst) {
  980. SDL_OutOfMemory();
  981. } else {
  982. retval = (SDL_GetAudioStreamData(stream, dst, dstlen) >= 0) ? 0 : -1;
  983. }
  984. }
  985. }
  986. }
  987. if (retval == -1) {
  988. SDL_free(dst);
  989. } else {
  990. *dst_data = dst;
  991. *dst_len = dstlen;
  992. }
  993. SDL_DestroyAudioStream(stream);
  994. return retval;
  995. }