SDL_audio.c 53 KB

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