SDL_audio.c 49 KB

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