SDL_audio.c 48 KB

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