SDL_audio.c 51 KB

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