SDL_audiocvt.c 44 KB

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