SDL_audio.c 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2026 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. /* Allow access to a raw mixing buffer */
  20. #include "SDL.h"
  21. #include "SDL_audio.h"
  22. #include "SDL_audio_c.h"
  23. #include "SDL_sysaudio.h"
  24. #include "../thread/SDL_systhread.h"
  25. #include "../SDL_utils_c.h"
  26. #define _THIS SDL_AudioDevice *_this
  27. typedef struct AudioThreadStartupData
  28. {
  29. SDL_AudioDevice *device;
  30. SDL_sem *startup_semaphore;
  31. } AudioThreadStartupData;
  32. static SDL_AudioDriver current_audio;
  33. static SDL_AudioDevice *open_devices[16];
  34. /* Available audio drivers */
  35. static const AudioBootStrap *const bootstrap[] = {
  36. #ifdef SDL_AUDIO_DRIVER_PULSEAUDIO
  37. &PULSEAUDIO_bootstrap,
  38. #endif
  39. #ifdef SDL_AUDIO_DRIVER_ALSA
  40. &ALSA_bootstrap,
  41. #endif
  42. #ifdef SDL_AUDIO_DRIVER_SNDIO
  43. &SNDIO_bootstrap,
  44. #endif
  45. #ifdef SDL_AUDIO_DRIVER_NETBSD
  46. &NETBSDAUDIO_bootstrap,
  47. #endif
  48. #ifdef SDL_AUDIO_DRIVER_QSA
  49. &QSAAUDIO_bootstrap,
  50. #endif
  51. #ifdef SDL_AUDIO_DRIVER_SUNAUDIO
  52. &SUNAUDIO_bootstrap,
  53. #endif
  54. #ifdef SDL_AUDIO_DRIVER_ARTS
  55. &ARTS_bootstrap,
  56. #endif
  57. #ifdef SDL_AUDIO_DRIVER_ESD
  58. &ESD_bootstrap,
  59. #endif
  60. #ifdef SDL_AUDIO_DRIVER_NACL
  61. &NACLAUDIO_bootstrap,
  62. #endif
  63. #ifdef SDL_AUDIO_DRIVER_NAS
  64. &NAS_bootstrap,
  65. #endif
  66. #ifdef SDL_AUDIO_DRIVER_WASAPI
  67. &WASAPI_bootstrap,
  68. #endif
  69. #ifdef SDL_AUDIO_DRIVER_DSOUND
  70. &DSOUND_bootstrap,
  71. #endif
  72. #ifdef SDL_AUDIO_DRIVER_WINMM
  73. &WINMM_bootstrap,
  74. #endif
  75. #ifdef SDL_AUDIO_DRIVER_PAUDIO
  76. &PAUDIO_bootstrap,
  77. #endif
  78. #ifdef SDL_AUDIO_DRIVER_HAIKU
  79. &HAIKUAUDIO_bootstrap,
  80. #endif
  81. #ifdef SDL_AUDIO_DRIVER_COREAUDIO
  82. &COREAUDIO_bootstrap,
  83. #endif
  84. #ifdef SDL_AUDIO_DRIVER_FUSIONSOUND
  85. &FUSIONSOUND_bootstrap,
  86. #endif
  87. #ifdef SDL_AUDIO_DRIVER_OPENSLES
  88. &openslES_bootstrap,
  89. #endif
  90. #ifdef SDL_AUDIO_DRIVER_AAUDIO
  91. &aaudio_bootstrap,
  92. #endif
  93. #ifdef SDL_AUDIO_DRIVER_ANDROID
  94. &ANDROIDAUDIO_bootstrap,
  95. #endif
  96. #ifdef SDL_AUDIO_DRIVER_PS2
  97. &PS2AUDIO_bootstrap,
  98. #endif
  99. #ifdef SDL_AUDIO_DRIVER_PSP
  100. &PSPAUDIO_bootstrap,
  101. #endif
  102. #ifdef SDL_AUDIO_DRIVER_VITA
  103. &VITAAUD_bootstrap,
  104. #endif
  105. #ifdef SDL_AUDIO_DRIVER_N3DS
  106. &N3DSAUDIO_bootstrap,
  107. #endif
  108. #ifdef SDL_AUDIO_DRIVER_EMSCRIPTEN
  109. &EMSCRIPTENAUDIO_bootstrap,
  110. #endif
  111. #ifdef SDL_AUDIO_DRIVER_JACK
  112. &JACK_bootstrap,
  113. #endif
  114. #ifdef SDL_AUDIO_DRIVER_PIPEWIRE
  115. &PIPEWIRE_bootstrap,
  116. #endif
  117. #ifdef SDL_AUDIO_DRIVER_OSS
  118. &DSP_bootstrap,
  119. #endif
  120. #ifdef SDL_AUDIO_DRIVER_OS2
  121. &OS2AUDIO_bootstrap,
  122. #endif
  123. #ifdef SDL_AUDIO_DRIVER_DISK
  124. &DISKAUDIO_bootstrap,
  125. #endif
  126. #ifdef SDL_AUDIO_DRIVER_DUMMY
  127. &DUMMYAUDIO_bootstrap,
  128. #endif
  129. NULL
  130. };
  131. #ifdef HAVE_LIBSAMPLERATE_H
  132. #ifdef SDL_LIBSAMPLERATE_DYNAMIC
  133. static void *SRC_lib = NULL;
  134. #endif
  135. SDL_bool SRC_available = SDL_FALSE;
  136. int SRC_converter = 0;
  137. SRC_STATE *(*SRC_src_new)(int converter_type, int channels, int *error) = NULL;
  138. int (*SRC_src_process)(SRC_STATE *state, SRC_DATA *data) = NULL;
  139. int (*SRC_src_reset)(SRC_STATE *state) = NULL;
  140. SRC_STATE *(*SRC_src_delete)(SRC_STATE *state) = NULL;
  141. const char *(*SRC_src_strerror)(int error) = NULL;
  142. int (*SRC_src_simple)(SRC_DATA *data, int converter_type, int channels) = NULL;
  143. static SDL_bool LoadLibSampleRate(void)
  144. {
  145. const char *hint = SDL_GetHint(SDL_HINT_AUDIO_RESAMPLING_MODE);
  146. SRC_available = SDL_FALSE;
  147. SRC_converter = 0;
  148. if (!hint || *hint == '0' || SDL_strcasecmp(hint, "default") == 0) {
  149. return SDL_FALSE; /* don't load anything. */
  150. } else if (*hint == '1' || SDL_strcasecmp(hint, "fast") == 0) {
  151. SRC_converter = SRC_SINC_FASTEST;
  152. } else if (*hint == '2' || SDL_strcasecmp(hint, "medium") == 0) {
  153. SRC_converter = SRC_SINC_MEDIUM_QUALITY;
  154. } else if (*hint == '3' || SDL_strcasecmp(hint, "best") == 0) {
  155. SRC_converter = SRC_SINC_BEST_QUALITY;
  156. } else if (*hint == '4' || SDL_strcasecmp(hint, "linear") == 0) {
  157. SRC_converter = SRC_LINEAR;
  158. } else {
  159. return SDL_FALSE; /* treat it like "default", don't load anything. */
  160. }
  161. #ifdef SDL_LIBSAMPLERATE_DYNAMIC
  162. SDL_assert(SRC_lib == NULL);
  163. SRC_lib = SDL_LoadObject(SDL_LIBSAMPLERATE_DYNAMIC);
  164. if (!SRC_lib) {
  165. SDL_ClearError();
  166. return SDL_FALSE;
  167. }
  168. /* *INDENT-OFF* */ /* clang-format off */
  169. SRC_src_new = (SRC_STATE* (*)(int converter_type, int channels, int *error))SDL_LoadFunction(SRC_lib, "src_new");
  170. SRC_src_process = (int (*)(SRC_STATE *state, SRC_DATA *data))SDL_LoadFunction(SRC_lib, "src_process");
  171. SRC_src_reset = (int(*)(SRC_STATE *state))SDL_LoadFunction(SRC_lib, "src_reset");
  172. SRC_src_delete = (SRC_STATE* (*)(SRC_STATE *state))SDL_LoadFunction(SRC_lib, "src_delete");
  173. SRC_src_strerror = (const char* (*)(int error))SDL_LoadFunction(SRC_lib, "src_strerror");
  174. SRC_src_simple = (int(*)(SRC_DATA *data, int converter_type, int channels))SDL_LoadFunction(SRC_lib, "src_simple");
  175. /* *INDENT-ON* */ /* clang-format on */
  176. if (!SRC_src_new || !SRC_src_process || !SRC_src_reset || !SRC_src_delete || !SRC_src_strerror || !SRC_src_simple) {
  177. SDL_UnloadObject(SRC_lib);
  178. SRC_lib = NULL;
  179. return SDL_FALSE;
  180. }
  181. #else
  182. SRC_src_new = src_new;
  183. SRC_src_process = src_process;
  184. SRC_src_reset = src_reset;
  185. SRC_src_delete = src_delete;
  186. SRC_src_strerror = src_strerror;
  187. SRC_src_simple = src_simple;
  188. #endif
  189. SRC_available = SDL_TRUE;
  190. return SDL_TRUE;
  191. }
  192. static void UnloadLibSampleRate(void)
  193. {
  194. #ifdef SDL_LIBSAMPLERATE_DYNAMIC
  195. if (SRC_lib != NULL) {
  196. SDL_UnloadObject(SRC_lib);
  197. }
  198. SRC_lib = NULL;
  199. #endif
  200. SRC_available = SDL_FALSE;
  201. SRC_src_new = NULL;
  202. SRC_src_process = NULL;
  203. SRC_src_reset = NULL;
  204. SRC_src_delete = NULL;
  205. SRC_src_strerror = NULL;
  206. }
  207. #endif
  208. static SDL_AudioDevice *get_audio_device(SDL_AudioDeviceID id)
  209. {
  210. id--;
  211. if ((id >= SDL_arraysize(open_devices)) || (open_devices[id] == NULL)) {
  212. SDL_SetError("Invalid audio device ID");
  213. return NULL;
  214. }
  215. return open_devices[id];
  216. }
  217. /* stubs for audio drivers that don't need a specific entry point... */
  218. static void SDL_AudioDetectDevices_Default(void)
  219. {
  220. /* you have to write your own implementation if these assertions fail. */
  221. SDL_assert(current_audio.impl.OnlyHasDefaultOutputDevice);
  222. SDL_assert(current_audio.impl.OnlyHasDefaultCaptureDevice || !current_audio.impl.HasCaptureSupport);
  223. SDL_AddAudioDevice(SDL_FALSE, DEFAULT_OUTPUT_DEVNAME, NULL, (void *)((size_t)0x1));
  224. if (current_audio.impl.HasCaptureSupport) {
  225. SDL_AddAudioDevice(SDL_TRUE, DEFAULT_INPUT_DEVNAME, NULL, (void *)((size_t)0x2));
  226. }
  227. }
  228. static void SDL_AudioThreadInit_Default(_THIS)
  229. { /* no-op. */
  230. }
  231. static void SDL_AudioThreadDeinit_Default(_THIS)
  232. { /* no-op. */
  233. }
  234. static void SDL_AudioWaitDevice_Default(_THIS)
  235. { /* no-op. */
  236. }
  237. static void SDL_AudioPlayDevice_Default(_THIS)
  238. { /* no-op. */
  239. }
  240. static Uint8 *SDL_AudioGetDeviceBuf_Default(_THIS)
  241. {
  242. return NULL;
  243. }
  244. static int SDL_AudioCaptureFromDevice_Default(_THIS, void *buffer, int buflen)
  245. {
  246. return -1; /* just fail immediately. */
  247. }
  248. static void SDL_AudioFlushCapture_Default(_THIS)
  249. { /* no-op. */
  250. }
  251. static void SDL_AudioCloseDevice_Default(_THIS)
  252. { /* no-op. */
  253. }
  254. static void SDL_AudioDeinitialize_Default(void)
  255. { /* no-op. */
  256. }
  257. static void SDL_AudioFreeDeviceHandle_Default(void *handle)
  258. { /* no-op. */
  259. }
  260. static int SDL_AudioOpenDevice_Default(_THIS, const char *devname)
  261. {
  262. return SDL_Unsupported();
  263. }
  264. static SDL_INLINE SDL_bool is_in_audio_device_thread(SDL_AudioDevice *device)
  265. {
  266. /* The device thread locks the same mutex, but not through the public API.
  267. This check is in case the application, in the audio callback,
  268. tries to lock the thread that we've already locked from the
  269. device thread...just in case we only have non-recursive mutexes. */
  270. if (device->thread && (SDL_ThreadID() == device->threadid)) {
  271. return SDL_TRUE;
  272. }
  273. return SDL_FALSE;
  274. }
  275. static void SDL_AudioLockDevice_Default(SDL_AudioDevice *device) SDL_NO_THREAD_SAFETY_ANALYSIS /* clang assumes recursive locks */
  276. {
  277. if (!is_in_audio_device_thread(device)) {
  278. SDL_LockMutex(device->mixer_lock);
  279. }
  280. }
  281. static void SDL_AudioUnlockDevice_Default(SDL_AudioDevice *device) SDL_NO_THREAD_SAFETY_ANALYSIS /* clang assumes recursive locks */
  282. {
  283. if (!is_in_audio_device_thread(device)) {
  284. SDL_UnlockMutex(device->mixer_lock);
  285. }
  286. }
  287. static void finish_audio_entry_points_init(void)
  288. {
  289. /*
  290. * Fill in stub functions for unused driver entry points. This lets us
  291. * blindly call them without having to check for validity first.
  292. */
  293. #define FILL_STUB(x) \
  294. if (current_audio.impl.x == NULL) { \
  295. current_audio.impl.x = SDL_Audio##x##_Default; \
  296. }
  297. FILL_STUB(DetectDevices);
  298. FILL_STUB(OpenDevice);
  299. FILL_STUB(ThreadInit);
  300. FILL_STUB(ThreadDeinit);
  301. FILL_STUB(WaitDevice);
  302. FILL_STUB(PlayDevice);
  303. FILL_STUB(GetDeviceBuf);
  304. FILL_STUB(CaptureFromDevice);
  305. FILL_STUB(FlushCapture);
  306. FILL_STUB(CloseDevice);
  307. FILL_STUB(LockDevice);
  308. FILL_STUB(UnlockDevice);
  309. FILL_STUB(FreeDeviceHandle);
  310. FILL_STUB(Deinitialize);
  311. #undef FILL_STUB
  312. }
  313. /* device hotplug support... */
  314. static int add_audio_device(const char *name, SDL_AudioSpec *spec, void *handle, SDL_AudioDeviceItem **devices, int *devCount)
  315. {
  316. int retval = -1;
  317. SDL_AudioDeviceItem *item;
  318. const SDL_AudioDeviceItem *i;
  319. int dupenum = 0;
  320. SDL_assert(handle != NULL); /* we reserve NULL, audio backends can't use it. */
  321. SDL_assert(name != NULL);
  322. item = (SDL_AudioDeviceItem *)SDL_malloc(sizeof(SDL_AudioDeviceItem));
  323. if (!item) {
  324. return SDL_OutOfMemory();
  325. }
  326. item->original_name = SDL_strdup(name);
  327. if (!item->original_name) {
  328. SDL_free(item);
  329. return SDL_OutOfMemory();
  330. }
  331. item->dupenum = 0;
  332. item->name = item->original_name;
  333. if (spec != NULL) {
  334. SDL_copyp(&item->spec, spec);
  335. } else {
  336. SDL_zero(item->spec);
  337. }
  338. item->handle = handle;
  339. SDL_LockMutex(current_audio.detectionLock);
  340. for (i = *devices; i != NULL; i = i->next) {
  341. if (SDL_strcmp(name, i->original_name) == 0) {
  342. dupenum = i->dupenum + 1;
  343. break; /* stop at the highest-numbered dupe. */
  344. }
  345. }
  346. if (dupenum) {
  347. const size_t len = SDL_strlen(name) + 16;
  348. char *replacement = (char *)SDL_malloc(len);
  349. if (!replacement) {
  350. SDL_UnlockMutex(current_audio.detectionLock);
  351. SDL_free(item->original_name);
  352. SDL_free(item);
  353. return SDL_OutOfMemory();
  354. }
  355. (void)SDL_snprintf(replacement, len, "%s (%d)", name, dupenum + 1);
  356. item->dupenum = dupenum;
  357. item->name = replacement;
  358. }
  359. item->next = *devices;
  360. *devices = item;
  361. retval = (*devCount)++; /* !!! FIXME: this should be an atomic increment */
  362. SDL_UnlockMutex(current_audio.detectionLock);
  363. return retval;
  364. }
  365. static SDL_INLINE int add_capture_device(const char *name, SDL_AudioSpec *spec, void *handle)
  366. {
  367. SDL_assert(current_audio.impl.HasCaptureSupport);
  368. return add_audio_device(name, spec, handle, &current_audio.inputDevices, &current_audio.inputDeviceCount);
  369. }
  370. static SDL_INLINE int add_output_device(const char *name, SDL_AudioSpec *spec, void *handle)
  371. {
  372. return add_audio_device(name, spec, handle, &current_audio.outputDevices, &current_audio.outputDeviceCount);
  373. }
  374. static void free_device_list(SDL_AudioDeviceItem **devices, int *devCount)
  375. {
  376. SDL_AudioDeviceItem *item, *next;
  377. for (item = *devices; item != NULL; item = next) {
  378. next = item->next;
  379. if (item->handle != NULL) {
  380. current_audio.impl.FreeDeviceHandle(item->handle);
  381. }
  382. /* these two pointers are the same if not a duplicate devname */
  383. if (item->name != item->original_name) {
  384. SDL_free(item->name);
  385. }
  386. SDL_free(item->original_name);
  387. SDL_free(item);
  388. }
  389. *devices = NULL;
  390. *devCount = 0;
  391. }
  392. /* The audio backends call this when a new device is plugged in. */
  393. void SDL_AddAudioDevice(const SDL_bool iscapture, const char *name, SDL_AudioSpec *spec, void *handle)
  394. {
  395. const int device_index = iscapture ? add_capture_device(name, spec, handle) : add_output_device(name, spec, handle);
  396. if (device_index != -1) {
  397. /* Post the event, if desired */
  398. if (SDL_GetEventState(SDL_AUDIODEVICEADDED) == SDL_ENABLE) {
  399. SDL_Event event;
  400. SDL_zero(event);
  401. event.adevice.type = SDL_AUDIODEVICEADDED;
  402. event.adevice.which = device_index;
  403. event.adevice.iscapture = iscapture;
  404. SDL_PushEvent(&event);
  405. }
  406. }
  407. }
  408. /* The audio backends call this when a currently-opened device is lost. */
  409. void SDL_OpenedAudioDeviceDisconnected(SDL_AudioDevice *device)
  410. {
  411. SDL_assert(get_audio_device(device->id) == device);
  412. if (!SDL_AtomicGet(&device->enabled)) {
  413. return; /* don't report disconnects more than once. */
  414. }
  415. if (SDL_AtomicGet(&device->shutdown)) {
  416. return; /* don't report disconnect if we're trying to close device. */
  417. }
  418. /* Ends the audio callback and mark the device as STOPPED, but the
  419. app still needs to close the device to free resources. */
  420. current_audio.impl.LockDevice(device);
  421. SDL_AtomicSet(&device->enabled, 0);
  422. current_audio.impl.UnlockDevice(device);
  423. /* Post the event, if desired */
  424. if (SDL_GetEventState(SDL_AUDIODEVICEREMOVED) == SDL_ENABLE) {
  425. SDL_Event event;
  426. SDL_zero(event);
  427. event.adevice.type = SDL_AUDIODEVICEREMOVED;
  428. event.adevice.which = device->id;
  429. event.adevice.iscapture = device->iscapture ? 1 : 0;
  430. SDL_PushEvent(&event);
  431. }
  432. }
  433. static void mark_device_removed(void *handle, SDL_AudioDeviceItem *devices, SDL_bool *removedFlag)
  434. {
  435. SDL_AudioDeviceItem *item;
  436. SDL_assert(handle != NULL);
  437. for (item = devices; item != NULL; item = item->next) {
  438. if (item->handle == handle) {
  439. item->handle = NULL;
  440. *removedFlag = SDL_TRUE;
  441. return;
  442. }
  443. }
  444. }
  445. /* The audio backends call this when a device is removed from the system. */
  446. void SDL_RemoveAudioDevice(const SDL_bool iscapture, void *handle)
  447. {
  448. int device_index;
  449. SDL_AudioDevice *device = NULL;
  450. SDL_bool device_was_opened = SDL_FALSE;
  451. SDL_LockMutex(current_audio.detectionLock);
  452. if (iscapture) {
  453. mark_device_removed(handle, current_audio.inputDevices, &current_audio.captureDevicesRemoved);
  454. } else {
  455. mark_device_removed(handle, current_audio.outputDevices, &current_audio.outputDevicesRemoved);
  456. }
  457. for (device_index = 0; device_index < SDL_arraysize(open_devices); device_index++) {
  458. device = open_devices[device_index];
  459. if (device != NULL && device->handle == handle) {
  460. device_was_opened = SDL_TRUE;
  461. SDL_OpenedAudioDeviceDisconnected(device);
  462. break;
  463. }
  464. }
  465. /* Devices that aren't opened, as of 2.24.0, will post an
  466. SDL_AUDIODEVICEREMOVED event with the `which` field set to zero.
  467. Apps can use this to decide if they need to refresh a list of
  468. available devices instead of closing an opened one.
  469. Note that opened devices will send the non-zero event in
  470. SDL_OpenedAudioDeviceDisconnected(). */
  471. if (!device_was_opened) {
  472. if (SDL_GetEventState(SDL_AUDIODEVICEREMOVED) == SDL_ENABLE) {
  473. SDL_Event event;
  474. SDL_zero(event);
  475. event.adevice.type = SDL_AUDIODEVICEREMOVED;
  476. event.adevice.which = 0;
  477. event.adevice.iscapture = iscapture ? 1 : 0;
  478. SDL_PushEvent(&event);
  479. }
  480. }
  481. SDL_UnlockMutex(current_audio.detectionLock);
  482. current_audio.impl.FreeDeviceHandle(handle);
  483. }
  484. /* buffer queueing support... */
  485. static void SDLCALL SDL_BufferQueueDrainCallback(void *userdata, Uint8 *stream, int len)
  486. {
  487. /* this function always holds the mixer lock before being called. */
  488. SDL_AudioDevice *device = (SDL_AudioDevice *)userdata;
  489. size_t dequeued;
  490. SDL_assert(device != NULL); /* this shouldn't ever happen, right?! */
  491. SDL_assert(!device->iscapture); /* this shouldn't ever happen, right?! */
  492. SDL_assert(len >= 0); /* this shouldn't ever happen, right?! */
  493. dequeued = SDL_ReadFromDataQueue(device->buffer_queue, stream, len);
  494. stream += dequeued;
  495. len -= (int)dequeued;
  496. if (len > 0) { /* fill any remaining space in the stream with silence. */
  497. SDL_assert(SDL_CountDataQueue(device->buffer_queue) == 0);
  498. SDL_memset(stream, device->callbackspec.silence, len);
  499. }
  500. }
  501. static void SDLCALL SDL_BufferQueueFillCallback(void *userdata, Uint8 *stream, int len)
  502. {
  503. /* this function always holds the mixer lock before being called. */
  504. SDL_AudioDevice *device = (SDL_AudioDevice *)userdata;
  505. SDL_assert(device != NULL); /* this shouldn't ever happen, right?! */
  506. SDL_assert(device->iscapture); /* this shouldn't ever happen, right?! */
  507. SDL_assert(len >= 0); /* this shouldn't ever happen, right?! */
  508. /* note that if this needs to allocate more space and run out of memory,
  509. we have no choice but to quietly drop the data and hope it works out
  510. later, but you probably have bigger problems in this case anyhow. */
  511. SDL_WriteToDataQueue(device->buffer_queue, stream, len);
  512. }
  513. int SDL_QueueAudio(SDL_AudioDeviceID devid, const void *data, Uint32 len)
  514. {
  515. SDL_AudioDevice *device = get_audio_device(devid);
  516. int rc = 0;
  517. if (!device) {
  518. return -1; /* get_audio_device() will have set the error state */
  519. } else if (device->iscapture) {
  520. return SDL_SetError("This is a capture device, queueing not allowed");
  521. } else if (device->callbackspec.callback != SDL_BufferQueueDrainCallback) {
  522. return SDL_SetError("Audio device has a callback, queueing not allowed");
  523. }
  524. if (len > 0) {
  525. current_audio.impl.LockDevice(device);
  526. rc = SDL_WriteToDataQueue(device->buffer_queue, data, len);
  527. current_audio.impl.UnlockDevice(device);
  528. }
  529. return rc;
  530. }
  531. Uint32 SDL_DequeueAudio(SDL_AudioDeviceID devid, void *data, Uint32 len)
  532. {
  533. SDL_AudioDevice *device = get_audio_device(devid);
  534. Uint32 rc;
  535. if ((len == 0) || /* nothing to do? */
  536. (!device) || /* called with bogus device id */
  537. (!device->iscapture) || /* playback devices can't dequeue */
  538. (device->callbackspec.callback != SDL_BufferQueueFillCallback)) { /* not set for queueing */
  539. return 0; /* just report zero bytes dequeued. */
  540. }
  541. current_audio.impl.LockDevice(device);
  542. rc = (Uint32)SDL_ReadFromDataQueue(device->buffer_queue, data, len);
  543. current_audio.impl.UnlockDevice(device);
  544. return rc;
  545. }
  546. Uint32 SDL_GetQueuedAudioSize(SDL_AudioDeviceID devid)
  547. {
  548. Uint32 retval = 0;
  549. SDL_AudioDevice *device = get_audio_device(devid);
  550. if (!device) {
  551. return 0;
  552. }
  553. /* Nothing to do unless we're set up for queueing. */
  554. if (device->callbackspec.callback == SDL_BufferQueueDrainCallback ||
  555. device->callbackspec.callback == SDL_BufferQueueFillCallback) {
  556. current_audio.impl.LockDevice(device);
  557. retval = (Uint32)SDL_CountDataQueue(device->buffer_queue);
  558. current_audio.impl.UnlockDevice(device);
  559. }
  560. return retval;
  561. }
  562. void SDL_ClearQueuedAudio(SDL_AudioDeviceID devid)
  563. {
  564. SDL_AudioDevice *device = get_audio_device(devid);
  565. if (!device) {
  566. return; /* nothing to do. */
  567. }
  568. /* Blank out the device and release the mutex. Free it afterwards. */
  569. current_audio.impl.LockDevice(device);
  570. /* Keep up to two packets in the pool to reduce future memory allocation pressure. */
  571. SDL_ClearDataQueue(device->buffer_queue, SDL_AUDIOBUFFERQUEUE_PACKETLEN * 2);
  572. current_audio.impl.UnlockDevice(device);
  573. }
  574. #ifdef SDL_AUDIO_DRIVER_ANDROID
  575. extern void Android_JNI_AudioSetThreadPriority(int, int);
  576. #endif
  577. /* The general mixing thread function */
  578. static int SDLCALL SDL_RunAudio(void *userdata)
  579. {
  580. const AudioThreadStartupData *startup_data = (const AudioThreadStartupData *) userdata;
  581. SDL_AudioDevice *device = startup_data->device;
  582. void *udata = device->callbackspec.userdata;
  583. SDL_AudioCallback callback = device->callbackspec.callback;
  584. int data_len = 0;
  585. Uint8 *data;
  586. Uint8 *device_buf_keepsafe = NULL;
  587. Uint32 delay;
  588. SDL_assert(!device->iscapture);
  589. #ifdef SDL_AUDIO_DRIVER_ANDROID
  590. {
  591. /* Set thread priority to THREAD_PRIORITY_AUDIO */
  592. Android_JNI_AudioSetThreadPriority(device->iscapture, device->id);
  593. }
  594. #else
  595. /* The audio mixing is always a high priority thread */
  596. SDL_SetThreadPriority(SDL_THREAD_PRIORITY_TIME_CRITICAL);
  597. #endif
  598. /* Perform any thread setup */
  599. device->threadid = SDL_ThreadID();
  600. SDL_SemPost(startup_data->startup_semaphore); /* SDL_OpenAudioDevice may now continue. */
  601. current_audio.impl.ThreadInit(device);
  602. /* Loop, filling the audio buffers */
  603. while (!SDL_AtomicGet(&device->shutdown)) {
  604. /* Fill the current buffer with sound */
  605. if (!device->stream && SDL_AtomicGet(&device->enabled)) {
  606. data = current_audio.impl.GetDeviceBuf(device);
  607. if (device->stream && SDL_AtomicGet(&device->enabled)) {
  608. /* Oops. Audio device reset and now we suddenly use a stream, */
  609. /* so save this devicebuf for later, to prevent de-sync */
  610. if (data != NULL) {
  611. device_buf_keepsafe = data;
  612. }
  613. data = NULL;
  614. }
  615. } else {
  616. /* if the device isn't enabled, we still write to the
  617. work_buffer, so the app's callback will fire with
  618. a regular frequency, in case they depend on that
  619. for timing or progress. They can use hotplug
  620. now to know if the device failed.
  621. Streaming playback uses work_buffer, too. */
  622. data = NULL;
  623. }
  624. if (data == NULL) {
  625. data = device->work_buffer;
  626. }
  627. data_len = device->callbackspec.size;
  628. /* !!! FIXME: this should be LockDevice. */
  629. SDL_LockMutex(device->mixer_lock);
  630. if (SDL_AtomicGet(&device->paused)) {
  631. SDL_memset(data, device->callbackspec.silence, data_len);
  632. } else {
  633. callback(udata, data, data_len);
  634. }
  635. SDL_UnlockMutex(device->mixer_lock);
  636. if (device->stream) {
  637. /* Stream available audio to device, converting/resampling. */
  638. /* if this fails...oh well. We'll play silence here. */
  639. SDL_AudioStreamPut(device->stream, data, data_len);
  640. while (SDL_AudioStreamAvailable(device->stream) >= ((int)device->spec.size)) {
  641. int got;
  642. if (SDL_AtomicGet(&device->enabled)) {
  643. /* if device reset occured - a switch from direct output to streaming */
  644. /* use the already aquired device buffer */
  645. if (device_buf_keepsafe) {
  646. data = device_buf_keepsafe;
  647. device_buf_keepsafe = NULL;
  648. } else {
  649. /* else - normal flow, just acquire the device buffer here */
  650. data = current_audio.impl.GetDeviceBuf(device);
  651. }
  652. } else {
  653. data = NULL;
  654. }
  655. got = SDL_AudioStreamGet(device->stream, data ? data : device->work_buffer, device->spec.size);
  656. SDL_assert((got <= 0) || (got == device->spec.size));
  657. if (data == NULL) { /* device is having issues... */
  658. delay = ((device->spec.samples * 1000) / device->spec.freq);
  659. SDL_Delay(delay); /* wait for as long as this buffer would have played. Maybe device recovers later? */
  660. } else {
  661. if (got != device->spec.size) {
  662. SDL_memset(data, device->spec.silence, device->spec.size);
  663. }
  664. current_audio.impl.PlayDevice(device);
  665. current_audio.impl.WaitDevice(device);
  666. }
  667. }
  668. /* it seems resampling was not fast enough, device_buf_keepsafe was not released yet, so play silence here */
  669. if (device_buf_keepsafe) {
  670. SDL_memset(device_buf_keepsafe, device->spec.silence, device->spec.size);
  671. current_audio.impl.PlayDevice(device);
  672. current_audio.impl.WaitDevice(device);
  673. device_buf_keepsafe = NULL;
  674. }
  675. } else if (data == device->work_buffer) {
  676. /* nothing to do; pause like we queued a buffer to play. */
  677. delay = ((device->spec.samples * 1000) / device->spec.freq);
  678. SDL_Delay(delay);
  679. } else { /* writing directly to the device. */
  680. /* queue this buffer and wait for it to finish playing. */
  681. current_audio.impl.PlayDevice(device);
  682. current_audio.impl.WaitDevice(device);
  683. }
  684. }
  685. /* Wait for the audio to drain. */
  686. delay = ((device->spec.samples * 1000) / device->spec.freq) * 2;
  687. if (delay > 100) {
  688. delay = 100;
  689. }
  690. SDL_Delay(delay);
  691. current_audio.impl.ThreadDeinit(device);
  692. return 0;
  693. }
  694. /* !!! FIXME: this needs to deal with device spec changes. */
  695. /* The general capture thread function */
  696. static int SDLCALL SDL_CaptureAudio(void *userdata)
  697. {
  698. const AudioThreadStartupData *startup_data = (const AudioThreadStartupData *) userdata;
  699. SDL_AudioDevice *device = startup_data->device;
  700. const int silence = (int)device->spec.silence;
  701. const Uint32 delay = ((device->spec.samples * 1000) / device->spec.freq);
  702. const int data_len = device->spec.size;
  703. Uint8 *data;
  704. void *udata = device->callbackspec.userdata;
  705. SDL_AudioCallback callback = device->callbackspec.callback;
  706. SDL_assert(device->iscapture);
  707. #ifdef SDL_AUDIO_DRIVER_ANDROID
  708. {
  709. /* Set thread priority to THREAD_PRIORITY_AUDIO */
  710. Android_JNI_AudioSetThreadPriority(device->iscapture, device->id);
  711. }
  712. #else
  713. /* The audio mixing is always a high priority thread */
  714. SDL_SetThreadPriority(SDL_THREAD_PRIORITY_HIGH);
  715. #endif
  716. /* Perform any thread setup */
  717. device->threadid = SDL_ThreadID();
  718. SDL_SemPost(startup_data->startup_semaphore); /* SDL_OpenAudioDevice may now continue. */
  719. current_audio.impl.ThreadInit(device);
  720. /* Loop, filling the audio buffers */
  721. while (!SDL_AtomicGet(&device->shutdown)) {
  722. int still_need;
  723. Uint8 *ptr;
  724. if (SDL_AtomicGet(&device->paused)) {
  725. SDL_Delay(delay); /* just so we don't cook the CPU. */
  726. if (device->stream) {
  727. SDL_AudioStreamClear(device->stream);
  728. }
  729. current_audio.impl.FlushCapture(device); /* dump anything pending. */
  730. continue;
  731. }
  732. /* Fill the current buffer with sound */
  733. still_need = data_len;
  734. /* Use the work_buffer to hold data read from the device. */
  735. data = device->work_buffer;
  736. SDL_assert(data != NULL);
  737. ptr = data;
  738. /* We still read from the device when "paused" to keep the state sane,
  739. and block when there isn't data so this thread isn't eating CPU.
  740. But we don't process it further or call the app's callback. */
  741. if (!SDL_AtomicGet(&device->enabled)) {
  742. SDL_Delay(delay); /* try to keep callback firing at normal pace. */
  743. } else {
  744. while (still_need > 0) {
  745. const int rc = current_audio.impl.CaptureFromDevice(device, ptr, still_need);
  746. SDL_assert(rc <= still_need); /* device should not overflow buffer. :) */
  747. if (rc > 0) {
  748. still_need -= rc;
  749. ptr += rc;
  750. } else { /* uhoh, device failed for some reason! */
  751. SDL_OpenedAudioDeviceDisconnected(device);
  752. break;
  753. }
  754. }
  755. }
  756. if (still_need > 0) {
  757. /* Keep any data we already read, silence the rest. */
  758. SDL_memset(ptr, silence, still_need);
  759. }
  760. if (device->stream) {
  761. /* if this fails...oh well. */
  762. SDL_AudioStreamPut(device->stream, data, data_len);
  763. while (SDL_AudioStreamAvailable(device->stream) >= ((int)device->callbackspec.size)) {
  764. const int got = SDL_AudioStreamGet(device->stream, device->work_buffer, device->callbackspec.size);
  765. SDL_assert((got < 0) || (got == device->callbackspec.size));
  766. if (got != device->callbackspec.size) {
  767. SDL_memset(device->work_buffer, device->spec.silence, device->callbackspec.size);
  768. }
  769. /* !!! FIXME: this should be LockDevice. */
  770. SDL_LockMutex(device->mixer_lock);
  771. if (!SDL_AtomicGet(&device->paused)) {
  772. callback(udata, device->work_buffer, device->callbackspec.size);
  773. }
  774. SDL_UnlockMutex(device->mixer_lock);
  775. }
  776. } else { /* feeding user callback directly without streaming. */
  777. /* !!! FIXME: this should be LockDevice. */
  778. SDL_LockMutex(device->mixer_lock);
  779. if (!SDL_AtomicGet(&device->paused)) {
  780. callback(udata, data, device->callbackspec.size);
  781. }
  782. SDL_UnlockMutex(device->mixer_lock);
  783. }
  784. }
  785. current_audio.impl.FlushCapture(device);
  786. current_audio.impl.ThreadDeinit(device);
  787. return 0;
  788. }
  789. static SDL_AudioFormat SDL_ParseAudioFormat(const char *string)
  790. {
  791. #define CHECK_FMT_STRING(x) \
  792. if (SDL_strcmp(string, #x) == 0) \
  793. return AUDIO_##x
  794. CHECK_FMT_STRING(U8);
  795. CHECK_FMT_STRING(S8);
  796. CHECK_FMT_STRING(U16LSB);
  797. CHECK_FMT_STRING(S16LSB);
  798. CHECK_FMT_STRING(U16MSB);
  799. CHECK_FMT_STRING(S16MSB);
  800. CHECK_FMT_STRING(U16SYS);
  801. CHECK_FMT_STRING(S16SYS);
  802. CHECK_FMT_STRING(U16);
  803. CHECK_FMT_STRING(S16);
  804. CHECK_FMT_STRING(S32LSB);
  805. CHECK_FMT_STRING(S32MSB);
  806. CHECK_FMT_STRING(S32SYS);
  807. CHECK_FMT_STRING(S32);
  808. CHECK_FMT_STRING(F32LSB);
  809. CHECK_FMT_STRING(F32MSB);
  810. CHECK_FMT_STRING(F32SYS);
  811. CHECK_FMT_STRING(F32);
  812. #undef CHECK_FMT_STRING
  813. return 0;
  814. }
  815. int SDL_GetNumAudioDrivers(void)
  816. {
  817. return SDL_arraysize(bootstrap) - 1;
  818. }
  819. const char *SDL_GetAudioDriver(int index)
  820. {
  821. if (index >= 0 && index < SDL_GetNumAudioDrivers()) {
  822. return bootstrap[index]->name;
  823. }
  824. return NULL;
  825. }
  826. int SDL_AudioInit(const char *driver_name)
  827. {
  828. int i;
  829. SDL_bool initialized = SDL_FALSE, tried_to_init = SDL_FALSE;
  830. if (SDL_GetCurrentAudioDriver()) {
  831. SDL_AudioQuit(); /* shutdown driver if already running. */
  832. }
  833. SDL_zeroa(open_devices);
  834. /* Select the proper audio driver */
  835. if (driver_name == NULL) {
  836. driver_name = SDL_GetHint(SDL_HINT_AUDIODRIVER);
  837. }
  838. if (driver_name != NULL && *driver_name != 0) {
  839. const char *driver_attempt = driver_name;
  840. while (driver_attempt != NULL && *driver_attempt != 0 && !initialized) {
  841. const char *driver_attempt_end = SDL_strchr(driver_attempt, ',');
  842. size_t driver_attempt_len = (driver_attempt_end != NULL) ? (driver_attempt_end - driver_attempt)
  843. : SDL_strlen(driver_attempt);
  844. #ifdef SDL_AUDIO_DRIVER_DSOUND
  845. /* SDL 1.2 uses the name "dsound", so we'll support both. */
  846. if (driver_attempt_len == SDL_strlen("dsound") &&
  847. (SDL_strncasecmp(driver_attempt, "dsound", driver_attempt_len) == 0)) {
  848. driver_attempt = "directsound";
  849. driver_attempt_len = SDL_strlen("directsound");
  850. }
  851. #endif
  852. #ifdef SDL_AUDIO_DRIVER_PULSEAUDIO
  853. /* SDL 1.2 uses the name "pulse", so we'll support both. */
  854. if (driver_attempt_len == SDL_strlen("pulse") &&
  855. (SDL_strncasecmp(driver_attempt, "pulse", driver_attempt_len) == 0)) {
  856. driver_attempt = "pulseaudio";
  857. driver_attempt_len = SDL_strlen("pulseaudio");
  858. }
  859. #endif
  860. for (i = 0; bootstrap[i]; ++i) {
  861. if ((driver_attempt_len == SDL_strlen(bootstrap[i]->name)) &&
  862. (SDL_strncasecmp(bootstrap[i]->name, driver_attempt, driver_attempt_len) == 0)) {
  863. tried_to_init = SDL_TRUE;
  864. SDL_zero(current_audio);
  865. current_audio.name = bootstrap[i]->name;
  866. current_audio.desc = bootstrap[i]->desc;
  867. initialized = bootstrap[i]->init(&current_audio.impl);
  868. break;
  869. }
  870. }
  871. driver_attempt = (driver_attempt_end) ? (driver_attempt_end + 1) : NULL;
  872. }
  873. } else {
  874. for (i = 0; (!initialized) && (bootstrap[i]); ++i) {
  875. if (bootstrap[i]->demand_only) {
  876. continue;
  877. }
  878. tried_to_init = SDL_TRUE;
  879. SDL_zero(current_audio);
  880. current_audio.name = bootstrap[i]->name;
  881. current_audio.desc = bootstrap[i]->desc;
  882. initialized = bootstrap[i]->init(&current_audio.impl);
  883. }
  884. }
  885. if (!initialized) {
  886. /* specific drivers will set the error message if they fail... */
  887. if (!tried_to_init) {
  888. if (driver_name) {
  889. SDL_SetError("Audio target '%s' not available", driver_name);
  890. } else {
  891. SDL_SetError("No available audio device");
  892. }
  893. }
  894. SDL_zero(current_audio);
  895. return -1; /* No driver was available, so fail. */
  896. }
  897. current_audio.detectionLock = SDL_CreateMutex();
  898. finish_audio_entry_points_init();
  899. /* Make sure we have a list of devices available at startup. */
  900. current_audio.impl.DetectDevices();
  901. #ifdef HAVE_LIBSAMPLERATE_H
  902. LoadLibSampleRate();
  903. #endif
  904. return 0;
  905. }
  906. /*
  907. * Get the current audio driver name
  908. */
  909. const char *SDL_GetCurrentAudioDriver(void)
  910. {
  911. return current_audio.name;
  912. }
  913. /* Clean out devices that we've removed but had to keep around for stability. */
  914. static void clean_out_device_list(SDL_AudioDeviceItem **devices, int *devCount, SDL_bool *removedFlag)
  915. {
  916. SDL_AudioDeviceItem *item = *devices;
  917. SDL_AudioDeviceItem *prev = NULL;
  918. int total = 0;
  919. while (item) {
  920. SDL_AudioDeviceItem *next = item->next;
  921. if (item->handle != NULL) {
  922. total++;
  923. prev = item;
  924. } else {
  925. if (prev) {
  926. prev->next = next;
  927. } else {
  928. *devices = next;
  929. }
  930. /* these two pointers are the same if not a duplicate devname */
  931. if (item->name != item->original_name) {
  932. SDL_free(item->name);
  933. }
  934. SDL_free(item->original_name);
  935. SDL_free(item);
  936. }
  937. item = next;
  938. }
  939. *devCount = total;
  940. *removedFlag = SDL_FALSE;
  941. }
  942. int SDL_GetNumAudioDevices(int iscapture)
  943. {
  944. int retval = 0;
  945. if (!SDL_GetCurrentAudioDriver()) {
  946. return -1;
  947. }
  948. SDL_LockMutex(current_audio.detectionLock);
  949. if (iscapture && current_audio.captureDevicesRemoved) {
  950. clean_out_device_list(&current_audio.inputDevices, &current_audio.inputDeviceCount, &current_audio.captureDevicesRemoved);
  951. }
  952. if (!iscapture && current_audio.outputDevicesRemoved) {
  953. clean_out_device_list(&current_audio.outputDevices, &current_audio.outputDeviceCount, &current_audio.outputDevicesRemoved);
  954. }
  955. retval = iscapture ? current_audio.inputDeviceCount : current_audio.outputDeviceCount;
  956. SDL_UnlockMutex(current_audio.detectionLock);
  957. return retval;
  958. }
  959. const char *SDL_GetAudioDeviceName(int index, int iscapture)
  960. {
  961. SDL_AudioDeviceItem *item;
  962. int i;
  963. const char *retval;
  964. if (!SDL_GetCurrentAudioDriver()) {
  965. SDL_SetError("Audio subsystem is not initialized");
  966. return NULL;
  967. }
  968. SDL_LockMutex(current_audio.detectionLock);
  969. item = iscapture ? current_audio.inputDevices : current_audio.outputDevices;
  970. i = iscapture ? current_audio.inputDeviceCount : current_audio.outputDeviceCount;
  971. if (index >= 0 && index < i) {
  972. for (i--; i > index; i--, item = item->next) {
  973. SDL_assert(item != NULL);
  974. }
  975. SDL_assert(item != NULL);
  976. retval = item->name;
  977. } else {
  978. SDL_InvalidParamError("index");
  979. retval = NULL;
  980. }
  981. SDL_UnlockMutex(current_audio.detectionLock);
  982. return retval;
  983. }
  984. int SDL_GetAudioDeviceSpec(int index, int iscapture, SDL_AudioSpec *spec)
  985. {
  986. SDL_AudioDeviceItem *item;
  987. int i, retval;
  988. if (spec == NULL) {
  989. return SDL_InvalidParamError("spec");
  990. }
  991. if (!SDL_GetCurrentAudioDriver()) {
  992. return SDL_SetError("Audio subsystem is not initialized");
  993. }
  994. SDL_LockMutex(current_audio.detectionLock);
  995. item = iscapture ? current_audio.inputDevices : current_audio.outputDevices;
  996. i = iscapture ? current_audio.inputDeviceCount : current_audio.outputDeviceCount;
  997. if (index >= 0 && index < i) {
  998. for (i--; i > index; i--, item = item->next) {
  999. SDL_assert(item != NULL);
  1000. }
  1001. SDL_assert(item != NULL);
  1002. SDL_copyp(spec, &item->spec);
  1003. retval = 0;
  1004. } else {
  1005. retval = SDL_InvalidParamError("index");
  1006. }
  1007. SDL_UnlockMutex(current_audio.detectionLock);
  1008. return retval;
  1009. }
  1010. int SDL_GetDefaultAudioInfo(char **name, SDL_AudioSpec *spec, int iscapture)
  1011. {
  1012. if (spec == NULL) {
  1013. return SDL_InvalidParamError("spec");
  1014. }
  1015. if (!SDL_GetCurrentAudioDriver()) {
  1016. return SDL_SetError("Audio subsystem is not initialized");
  1017. }
  1018. if (current_audio.impl.GetDefaultAudioInfo == NULL) {
  1019. return SDL_Unsupported();
  1020. }
  1021. return current_audio.impl.GetDefaultAudioInfo(name, spec, iscapture);
  1022. }
  1023. static void close_audio_device(SDL_AudioDevice *device)
  1024. {
  1025. if (!device) {
  1026. return;
  1027. }
  1028. /* make sure the device is paused before we do anything else, so the
  1029. audio callback definitely won't fire again. */
  1030. current_audio.impl.LockDevice(device);
  1031. SDL_AtomicSet(&device->paused, 1);
  1032. SDL_AtomicSet(&device->shutdown, 1);
  1033. SDL_AtomicSet(&device->enabled, 0);
  1034. current_audio.impl.UnlockDevice(device);
  1035. if (device->thread != NULL) {
  1036. SDL_WaitThread(device->thread, NULL);
  1037. }
  1038. if (device->mixer_lock != NULL) {
  1039. SDL_DestroyMutex(device->mixer_lock);
  1040. }
  1041. SDL_free(device->work_buffer);
  1042. SDL_FreeAudioStream(device->stream);
  1043. if (device->id > 0) {
  1044. SDL_AudioDevice *opendev = open_devices[device->id - 1];
  1045. SDL_assert((opendev == device) || (opendev == NULL));
  1046. if (opendev == device) {
  1047. open_devices[device->id - 1] = NULL;
  1048. }
  1049. }
  1050. if (device->hidden != NULL) {
  1051. current_audio.impl.CloseDevice(device);
  1052. }
  1053. SDL_FreeDataQueue(device->buffer_queue);
  1054. SDL_free(device);
  1055. }
  1056. static Uint16 GetDefaultSamplesFromFreq(int freq)
  1057. {
  1058. /* Pick a default of ~46 ms at desired frequency */
  1059. /* !!! FIXME: remove this when the non-Po2 resampling is in. */
  1060. const Uint16 max_sample = (freq / 1000) * 46;
  1061. Uint16 current_sample = 1;
  1062. while (current_sample < max_sample) {
  1063. current_sample *= 2;
  1064. }
  1065. return current_sample;
  1066. }
  1067. /*
  1068. * Sanity check desired AudioSpec for SDL_OpenAudio() in (orig).
  1069. * Fills in a sanitized copy in (prepared).
  1070. * Returns non-zero if okay, zero on fatal parameters in (orig).
  1071. */
  1072. static int prepare_audiospec(const SDL_AudioSpec *orig, SDL_AudioSpec *prepared)
  1073. {
  1074. SDL_copyp(prepared, orig);
  1075. if (orig->freq == 0) {
  1076. static const int DEFAULT_FREQ = 22050;
  1077. const char *env = SDL_getenv("SDL_AUDIO_FREQUENCY");
  1078. if (env != NULL) {
  1079. int freq = SDL_atoi(env);
  1080. prepared->freq = freq != 0 ? freq : DEFAULT_FREQ;
  1081. } else {
  1082. prepared->freq = DEFAULT_FREQ;
  1083. }
  1084. }
  1085. if (orig->format == 0) {
  1086. const char *env = SDL_getenv("SDL_AUDIO_FORMAT");
  1087. if (env != NULL) {
  1088. const SDL_AudioFormat format = SDL_ParseAudioFormat(env);
  1089. prepared->format = format != 0 ? format : AUDIO_S16;
  1090. } else {
  1091. prepared->format = AUDIO_S16;
  1092. }
  1093. }
  1094. if (orig->channels == 0) {
  1095. const char *env = SDL_getenv("SDL_AUDIO_CHANNELS");
  1096. if (env != NULL) {
  1097. Uint8 channels = (Uint8)SDL_atoi(env);
  1098. prepared->channels = channels != 0 ? channels : 2;
  1099. } else {
  1100. prepared->channels = 2;
  1101. }
  1102. } else if (orig->channels > 8) {
  1103. SDL_SetError("Unsupported number of audio channels.");
  1104. return 0;
  1105. }
  1106. if (orig->samples == 0) {
  1107. const char *env = SDL_getenv("SDL_AUDIO_SAMPLES");
  1108. if (env != NULL) {
  1109. Uint16 samples = (Uint16)SDL_atoi(env);
  1110. prepared->samples = samples != 0 ? samples : GetDefaultSamplesFromFreq(prepared->freq);
  1111. } else {
  1112. prepared->samples = GetDefaultSamplesFromFreq(prepared->freq);
  1113. }
  1114. }
  1115. /* Calculate the silence and size of the audio specification */
  1116. SDL_CalculateAudioSpec(prepared);
  1117. return 1;
  1118. }
  1119. static SDL_AudioDeviceID open_audio_device(const char *devname, int iscapture,
  1120. const SDL_AudioSpec *desired, SDL_AudioSpec *obtained,
  1121. int allowed_changes, int min_id)
  1122. {
  1123. SDL_AudioDeviceID id = 0;
  1124. SDL_AudioSpec _obtained;
  1125. SDL_AudioDevice *device;
  1126. SDL_bool build_stream;
  1127. void *handle = NULL;
  1128. int i = 0;
  1129. if (!SDL_GetCurrentAudioDriver()) {
  1130. SDL_SetError("Audio subsystem is not initialized");
  1131. return 0;
  1132. }
  1133. if (iscapture && !current_audio.impl.HasCaptureSupport) {
  1134. SDL_SetError("No capture support");
  1135. return 0;
  1136. }
  1137. if (!obtained) {
  1138. obtained = &_obtained;
  1139. }
  1140. if (!prepare_audiospec(desired, obtained)) {
  1141. return 0;
  1142. }
  1143. /* If app doesn't care about a specific device, let the user override. */
  1144. if (devname == NULL) {
  1145. devname = SDL_getenv("SDL_AUDIO_DEVICE_NAME");
  1146. }
  1147. /*
  1148. * Catch device names at the high level for the simple case...
  1149. * This lets us have a basic "device enumeration" for systems that
  1150. * don't have multiple devices, but makes sure the device name is
  1151. * always NULL when it hits the low level.
  1152. *
  1153. * Also make sure that the simple case prevents multiple simultaneous
  1154. * opens of the default system device.
  1155. */
  1156. if ((iscapture) && (current_audio.impl.OnlyHasDefaultCaptureDevice)) {
  1157. if ((devname) && (SDL_strcmp(devname, DEFAULT_INPUT_DEVNAME) != 0)) {
  1158. SDL_SetError("No such device");
  1159. return 0;
  1160. }
  1161. devname = NULL;
  1162. SDL_LockMutex(current_audio.detectionLock);
  1163. for (i = 0; i < SDL_arraysize(open_devices); i++) {
  1164. if ((open_devices[i]) && (open_devices[i]->iscapture)) {
  1165. SDL_SetError("Audio device already open");
  1166. SDL_UnlockMutex(current_audio.detectionLock);
  1167. return 0;
  1168. }
  1169. }
  1170. SDL_UnlockMutex(current_audio.detectionLock);
  1171. } else if ((!iscapture) && (current_audio.impl.OnlyHasDefaultOutputDevice)) {
  1172. if ((devname) && (SDL_strcmp(devname, DEFAULT_OUTPUT_DEVNAME) != 0)) {
  1173. SDL_SetError("No such device");
  1174. return 0;
  1175. }
  1176. devname = NULL;
  1177. SDL_LockMutex(current_audio.detectionLock);
  1178. for (i = 0; i < SDL_arraysize(open_devices); i++) {
  1179. if ((open_devices[i]) && (!open_devices[i]->iscapture)) {
  1180. SDL_UnlockMutex(current_audio.detectionLock);
  1181. SDL_SetError("Audio device already open");
  1182. return 0;
  1183. }
  1184. }
  1185. SDL_UnlockMutex(current_audio.detectionLock);
  1186. } else if (devname != NULL) {
  1187. /* if the app specifies an exact string, we can pass the backend
  1188. an actual device handle thingey, which saves them the effort of
  1189. figuring out what device this was (such as, reenumerating
  1190. everything again to find the matching human-readable name).
  1191. It might still need to open a device based on the string for,
  1192. say, a network audio server, but this optimizes some cases. */
  1193. SDL_AudioDeviceItem *item;
  1194. SDL_LockMutex(current_audio.detectionLock);
  1195. for (item = iscapture ? current_audio.inputDevices : current_audio.outputDevices; item; item = item->next) {
  1196. if ((item->handle != NULL) && (SDL_strcmp(item->name, devname) == 0)) {
  1197. handle = item->handle;
  1198. break;
  1199. }
  1200. }
  1201. SDL_UnlockMutex(current_audio.detectionLock);
  1202. }
  1203. if (!current_audio.impl.AllowsArbitraryDeviceNames) {
  1204. /* has to be in our device list, or the default device. */
  1205. if ((handle == NULL) && (devname != NULL)) {
  1206. SDL_SetError("No such device.");
  1207. return 0;
  1208. }
  1209. }
  1210. device = (SDL_AudioDevice *)SDL_calloc(1, sizeof(SDL_AudioDevice));
  1211. if (device == NULL) {
  1212. SDL_OutOfMemory();
  1213. return 0;
  1214. }
  1215. device->spec = *obtained;
  1216. device->iscapture = iscapture ? SDL_TRUE : SDL_FALSE;
  1217. device->handle = handle;
  1218. SDL_AtomicSet(&device->shutdown, 0); /* just in case. */
  1219. SDL_AtomicSet(&device->paused, 1);
  1220. SDL_AtomicSet(&device->enabled, 1);
  1221. /* Create a mutex for locking the sound buffers */
  1222. if (current_audio.impl.LockDevice == SDL_AudioLockDevice_Default) {
  1223. device->mixer_lock = SDL_CreateMutex();
  1224. if (device->mixer_lock == NULL) {
  1225. close_audio_device(device);
  1226. SDL_SetError("Couldn't create mixer lock");
  1227. return 0;
  1228. }
  1229. }
  1230. /* For backends that require a power-of-two value for spec.samples, take the
  1231. * value we got from 'desired' and round up to the nearest value
  1232. */
  1233. if (!current_audio.impl.SupportsNonPow2Samples && device->spec.samples > 0) {
  1234. device->spec.samples = SDL_powerof2(device->spec.samples);
  1235. }
  1236. if (current_audio.impl.OpenDevice(device, devname) < 0) {
  1237. close_audio_device(device);
  1238. return 0;
  1239. }
  1240. /* if your target really doesn't need it, set it to 0x1 or something. */
  1241. /* otherwise, close_audio_device() won't call impl.CloseDevice(). */
  1242. SDL_assert(device->hidden != NULL);
  1243. /* See if we need to do any conversion */
  1244. build_stream = SDL_FALSE;
  1245. if (obtained->freq != device->spec.freq) {
  1246. if (allowed_changes & SDL_AUDIO_ALLOW_FREQUENCY_CHANGE) {
  1247. obtained->freq = device->spec.freq;
  1248. } else {
  1249. build_stream = SDL_TRUE;
  1250. }
  1251. }
  1252. if (obtained->format != device->spec.format) {
  1253. if (allowed_changes & SDL_AUDIO_ALLOW_FORMAT_CHANGE) {
  1254. obtained->format = device->spec.format;
  1255. } else {
  1256. build_stream = SDL_TRUE;
  1257. }
  1258. }
  1259. if (obtained->channels != device->spec.channels) {
  1260. if (allowed_changes & SDL_AUDIO_ALLOW_CHANNELS_CHANGE) {
  1261. obtained->channels = device->spec.channels;
  1262. } else {
  1263. build_stream = SDL_TRUE;
  1264. }
  1265. }
  1266. if (device->spec.samples != obtained->samples) {
  1267. if (allowed_changes & SDL_AUDIO_ALLOW_SAMPLES_CHANGE) {
  1268. obtained->samples = device->spec.samples;
  1269. } else {
  1270. build_stream = SDL_TRUE;
  1271. }
  1272. }
  1273. SDL_CalculateAudioSpec(obtained); /* recalc after possible changes. */
  1274. device->callbackspec = *obtained;
  1275. if (build_stream) {
  1276. if (iscapture) {
  1277. device->stream = SDL_NewAudioStream(device->spec.format,
  1278. device->spec.channels, device->spec.freq,
  1279. obtained->format, obtained->channels, obtained->freq);
  1280. } else {
  1281. device->stream = SDL_NewAudioStream(obtained->format, obtained->channels,
  1282. obtained->freq, device->spec.format,
  1283. device->spec.channels, device->spec.freq);
  1284. }
  1285. if (!device->stream) {
  1286. close_audio_device(device);
  1287. return 0;
  1288. }
  1289. }
  1290. if (device->spec.callback == NULL) { /* use buffer queueing? */
  1291. /* pool a few packets to start. Enough for two callbacks. */
  1292. device->buffer_queue = SDL_NewDataQueue(SDL_AUDIOBUFFERQUEUE_PACKETLEN, obtained->size * 2);
  1293. if (!device->buffer_queue) {
  1294. close_audio_device(device);
  1295. SDL_SetError("Couldn't create audio buffer queue");
  1296. return 0;
  1297. }
  1298. device->callbackspec.callback = iscapture ? SDL_BufferQueueFillCallback : SDL_BufferQueueDrainCallback;
  1299. device->callbackspec.userdata = device;
  1300. }
  1301. /* Allocate a scratch audio buffer */
  1302. device->work_buffer_len = build_stream ? device->callbackspec.size : 0;
  1303. if (device->spec.size > device->work_buffer_len) {
  1304. device->work_buffer_len = device->spec.size;
  1305. }
  1306. SDL_assert(device->work_buffer_len > 0);
  1307. device->work_buffer = (Uint8 *)SDL_malloc(device->work_buffer_len);
  1308. if (device->work_buffer == NULL) {
  1309. close_audio_device(device);
  1310. SDL_OutOfMemory();
  1311. return 0;
  1312. }
  1313. /* Find an available device ID... */
  1314. SDL_LockMutex(current_audio.detectionLock);
  1315. for (id = min_id - 1; id < SDL_arraysize(open_devices); id++) {
  1316. if (open_devices[id] == NULL) {
  1317. break;
  1318. }
  1319. }
  1320. if (id == SDL_arraysize(open_devices)) {
  1321. close_audio_device(device);
  1322. SDL_SetError("Too many open audio devices");
  1323. SDL_UnlockMutex(current_audio.detectionLock);
  1324. return 0;
  1325. }
  1326. device->id = id + 1;
  1327. open_devices[id] = device; /* add it to our list of open devices. */
  1328. SDL_UnlockMutex(current_audio.detectionLock);
  1329. /* Start the audio thread if necessary */
  1330. if (!current_audio.impl.ProvidesOwnCallbackThread) {
  1331. /* Start the audio thread */
  1332. char threadname[64];
  1333. AudioThreadStartupData startup_data;
  1334. startup_data.device = device;
  1335. startup_data.startup_semaphore = SDL_CreateSemaphore(0);
  1336. if (!startup_data.startup_semaphore) {
  1337. close_audio_device(device);
  1338. SDL_SetError("Couldn't create audio thread startup semaphore");
  1339. return 0;
  1340. }
  1341. (void)SDL_snprintf(threadname, sizeof(threadname), "SDLAudio%c%" SDL_PRIu32, (iscapture) ? 'C' : 'P', device->id);
  1342. device->thread = SDL_CreateThreadInternal(iscapture ? SDL_CaptureAudio : SDL_RunAudio, threadname, 0, &startup_data);
  1343. if (device->thread == NULL) {
  1344. SDL_DestroySemaphore(startup_data.startup_semaphore);
  1345. close_audio_device(device);
  1346. SDL_SetError("Couldn't create audio thread");
  1347. return 0;
  1348. }
  1349. SDL_SemWait(startup_data.startup_semaphore);
  1350. SDL_DestroySemaphore(startup_data.startup_semaphore);
  1351. }
  1352. return device->id;
  1353. }
  1354. int SDL_OpenAudio(SDL_AudioSpec *desired, SDL_AudioSpec *obtained)
  1355. {
  1356. SDL_AudioDeviceID id = 0;
  1357. /* Start up the audio driver, if necessary. This is legacy behaviour! */
  1358. if (!SDL_WasInit(SDL_INIT_AUDIO)) {
  1359. if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) {
  1360. return -1;
  1361. }
  1362. }
  1363. /* SDL_OpenAudio() is legacy and can only act on Device ID #1. */
  1364. if (open_devices[0] != NULL) {
  1365. return SDL_SetError("Audio device is already opened");
  1366. }
  1367. if (obtained) {
  1368. id = open_audio_device(NULL, 0, desired, obtained,
  1369. SDL_AUDIO_ALLOW_ANY_CHANGE, 1);
  1370. } else {
  1371. SDL_AudioSpec _obtained;
  1372. SDL_zero(_obtained);
  1373. id = open_audio_device(NULL, 0, desired, &_obtained, 0, 1);
  1374. /* On successful open, copy calculated values into 'desired'. */
  1375. if (id > 0) {
  1376. desired->size = _obtained.size;
  1377. desired->silence = _obtained.silence;
  1378. }
  1379. }
  1380. SDL_assert((id == 0) || (id == 1));
  1381. return (id == 0) ? -1 : 0;
  1382. }
  1383. SDL_AudioDeviceID SDL_OpenAudioDevice(const char *device, int iscapture,
  1384. const SDL_AudioSpec *desired, SDL_AudioSpec *obtained,
  1385. int allowed_changes)
  1386. {
  1387. return open_audio_device(device, iscapture, desired, obtained,
  1388. allowed_changes, 2);
  1389. }
  1390. SDL_AudioStatus SDL_GetAudioDeviceStatus(SDL_AudioDeviceID devid)
  1391. {
  1392. SDL_AudioDevice *device = get_audio_device(devid);
  1393. SDL_AudioStatus status = SDL_AUDIO_STOPPED;
  1394. if (device && SDL_AtomicGet(&device->enabled)) {
  1395. if (SDL_AtomicGet(&device->paused)) {
  1396. status = SDL_AUDIO_PAUSED;
  1397. } else {
  1398. status = SDL_AUDIO_PLAYING;
  1399. }
  1400. }
  1401. return status;
  1402. }
  1403. SDL_AudioStatus SDL_GetAudioStatus(void)
  1404. {
  1405. return SDL_GetAudioDeviceStatus(1);
  1406. }
  1407. void SDL_PauseAudioDevice(SDL_AudioDeviceID devid, int pause_on)
  1408. {
  1409. SDL_AudioDevice *device = get_audio_device(devid);
  1410. if (device) {
  1411. current_audio.impl.LockDevice(device);
  1412. SDL_AtomicSet(&device->paused, pause_on ? 1 : 0);
  1413. current_audio.impl.UnlockDevice(device);
  1414. }
  1415. }
  1416. void SDL_PauseAudio(int pause_on)
  1417. {
  1418. SDL_PauseAudioDevice(1, pause_on);
  1419. }
  1420. void SDL_LockAudioDevice(SDL_AudioDeviceID devid)
  1421. {
  1422. /* Obtain a lock on the mixing buffers */
  1423. SDL_AudioDevice *device = get_audio_device(devid);
  1424. if (device) {
  1425. current_audio.impl.LockDevice(device);
  1426. }
  1427. }
  1428. void SDL_LockAudio(void)
  1429. {
  1430. SDL_LockAudioDevice(1);
  1431. }
  1432. void SDL_UnlockAudioDevice(SDL_AudioDeviceID devid)
  1433. {
  1434. /* Obtain a lock on the mixing buffers */
  1435. SDL_AudioDevice *device = get_audio_device(devid);
  1436. if (device) {
  1437. current_audio.impl.UnlockDevice(device);
  1438. }
  1439. }
  1440. void SDL_UnlockAudio(void)
  1441. {
  1442. SDL_UnlockAudioDevice(1);
  1443. }
  1444. void SDL_CloseAudioDevice(SDL_AudioDeviceID devid)
  1445. {
  1446. close_audio_device(get_audio_device(devid));
  1447. }
  1448. void SDL_CloseAudio(void)
  1449. {
  1450. SDL_CloseAudioDevice(1);
  1451. }
  1452. void SDL_AudioQuit(void)
  1453. {
  1454. SDL_AudioDeviceID i;
  1455. if (!current_audio.name) { /* not initialized?! */
  1456. return;
  1457. }
  1458. for (i = 0; i < SDL_arraysize(open_devices); i++) {
  1459. close_audio_device(open_devices[i]);
  1460. }
  1461. free_device_list(&current_audio.outputDevices, &current_audio.outputDeviceCount);
  1462. free_device_list(&current_audio.inputDevices, &current_audio.inputDeviceCount);
  1463. /* Free the driver data */
  1464. current_audio.impl.Deinitialize();
  1465. SDL_DestroyMutex(current_audio.detectionLock);
  1466. SDL_zero(current_audio);
  1467. SDL_zeroa(open_devices);
  1468. #ifdef HAVE_LIBSAMPLERATE_H
  1469. UnloadLibSampleRate();
  1470. #endif
  1471. }
  1472. #define NUM_FORMATS 10
  1473. static int format_idx;
  1474. static int format_idx_sub;
  1475. static SDL_AudioFormat format_list[NUM_FORMATS][NUM_FORMATS] = {
  1476. { AUDIO_U8, AUDIO_S8, AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_U16LSB,
  1477. AUDIO_U16MSB, AUDIO_S32LSB, AUDIO_S32MSB, AUDIO_F32LSB, AUDIO_F32MSB },
  1478. { AUDIO_S8, AUDIO_U8, AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_U16LSB,
  1479. AUDIO_U16MSB, AUDIO_S32LSB, AUDIO_S32MSB, AUDIO_F32LSB, AUDIO_F32MSB },
  1480. { AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_U16LSB, AUDIO_U16MSB, AUDIO_S32LSB,
  1481. AUDIO_S32MSB, AUDIO_F32LSB, AUDIO_F32MSB, AUDIO_U8, AUDIO_S8 },
  1482. { AUDIO_S16MSB, AUDIO_S16LSB, AUDIO_U16MSB, AUDIO_U16LSB, AUDIO_S32MSB,
  1483. AUDIO_S32LSB, AUDIO_F32MSB, AUDIO_F32LSB, AUDIO_U8, AUDIO_S8 },
  1484. { AUDIO_U16LSB, AUDIO_U16MSB, AUDIO_S16LSB, AUDIO_S16MSB, AUDIO_S32LSB,
  1485. AUDIO_S32MSB, AUDIO_F32LSB, AUDIO_F32MSB, AUDIO_U8, AUDIO_S8 },
  1486. { AUDIO_U16MSB, AUDIO_U16LSB, AUDIO_S16MSB, AUDIO_S16LSB, AUDIO_S32MSB,
  1487. AUDIO_S32LSB, AUDIO_F32MSB, AUDIO_F32LSB, AUDIO_U8, AUDIO_S8 },
  1488. { AUDIO_S32LSB, AUDIO_S32MSB, AUDIO_F32LSB, AUDIO_F32MSB, AUDIO_S16LSB,
  1489. AUDIO_S16MSB, AUDIO_U16LSB, AUDIO_U16MSB, AUDIO_U8, AUDIO_S8 },
  1490. { AUDIO_S32MSB, AUDIO_S32LSB, AUDIO_F32MSB, AUDIO_F32LSB, AUDIO_S16MSB,
  1491. AUDIO_S16LSB, AUDIO_U16MSB, AUDIO_U16LSB, AUDIO_U8, AUDIO_S8 },
  1492. { AUDIO_F32LSB, AUDIO_F32MSB, AUDIO_S32LSB, AUDIO_S32MSB, AUDIO_S16LSB,
  1493. AUDIO_S16MSB, AUDIO_U16LSB, AUDIO_U16MSB, AUDIO_U8, AUDIO_S8 },
  1494. { AUDIO_F32MSB, AUDIO_F32LSB, AUDIO_S32MSB, AUDIO_S32LSB, AUDIO_S16MSB,
  1495. AUDIO_S16LSB, AUDIO_U16MSB, AUDIO_U16LSB, AUDIO_U8, AUDIO_S8 },
  1496. };
  1497. SDL_AudioFormat SDL_FirstAudioFormat(SDL_AudioFormat format)
  1498. {
  1499. for (format_idx = 0; format_idx < NUM_FORMATS; ++format_idx) {
  1500. if (format_list[format_idx][0] == format) {
  1501. break;
  1502. }
  1503. }
  1504. format_idx_sub = 0;
  1505. return SDL_NextAudioFormat();
  1506. }
  1507. SDL_AudioFormat SDL_NextAudioFormat(void)
  1508. {
  1509. if ((format_idx == NUM_FORMATS) || (format_idx_sub == NUM_FORMATS)) {
  1510. return 0;
  1511. }
  1512. return format_list[format_idx][format_idx_sub++];
  1513. }
  1514. Uint8 SDL_SilenceValueForFormat(const SDL_AudioFormat format)
  1515. {
  1516. switch (format) {
  1517. /* !!! FIXME: 0x80 isn't perfect for U16, but we can't fit 0x8000 in a
  1518. !!! FIXME: byte for SDL_memset() use. This is actually 0.1953 percent
  1519. !!! FIXME: off from silence. Maybe just don't use U16. */
  1520. case AUDIO_U16LSB:
  1521. case AUDIO_U16MSB:
  1522. case AUDIO_U8:
  1523. return 0x80;
  1524. default:
  1525. break;
  1526. }
  1527. return 0x00;
  1528. }
  1529. void SDL_CalculateAudioSpec(SDL_AudioSpec *spec)
  1530. {
  1531. spec->silence = SDL_SilenceValueForFormat(spec->format);
  1532. spec->size = SDL_AUDIO_BITSIZE(spec->format) / 8;
  1533. spec->size *= spec->channels;
  1534. spec->size *= spec->samples;
  1535. }
  1536. /*
  1537. * Moved here from SDL_mixer.c, since it relies on internals of an opened
  1538. * audio device (and is deprecated, by the way!).
  1539. */
  1540. void SDL_MixAudio(Uint8 *dst, const Uint8 *src, Uint32 len, int volume)
  1541. {
  1542. /* Mix the user-level audio format */
  1543. SDL_AudioDevice *device = get_audio_device(1);
  1544. if (device != NULL) {
  1545. SDL_MixAudioFormat(dst, src, device->callbackspec.format, len, volume);
  1546. }
  1547. }
  1548. /* vi: set ts=4 sw=4 expandtab: */