testautomation_audio.c 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459
  1. /**
  2. * Original code: automated SDL audio test written by Edgar Simo "bobbens"
  3. * New/updated tests: aschiffler at ferzkopp dot net
  4. */
  5. /* quiet windows compiler warnings */
  6. #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
  7. #define _CRT_SECURE_NO_WARNINGS
  8. #endif
  9. #include <math.h>
  10. #include <stdio.h>
  11. #include <SDL3/SDL.h>
  12. #include <SDL3/SDL_test.h>
  13. #include "testautomation_suites.h"
  14. /* ================= Test Case Implementation ================== */
  15. /* Fixture */
  16. static void audioSetUp(void *arg)
  17. {
  18. /* Start SDL audio subsystem */
  19. int ret = SDL_InitSubSystem(SDL_INIT_AUDIO);
  20. SDLTest_AssertPass("Call to SDL_InitSubSystem(SDL_INIT_AUDIO)");
  21. SDLTest_AssertCheck(ret == 0, "Check result from SDL_InitSubSystem(SDL_INIT_AUDIO)");
  22. if (ret != 0) {
  23. SDLTest_LogError("%s", SDL_GetError());
  24. }
  25. }
  26. static void audioTearDown(void *arg)
  27. {
  28. /* Remove a possibly created file from SDL disk writer audio driver; ignore errors */
  29. (void)remove("sdlaudio.raw");
  30. SDLTest_AssertPass("Cleanup of test files completed");
  31. }
  32. #if 0 /* !!! FIXME: maybe update this? */
  33. /* Global counter for callback invocation */
  34. static int g_audio_testCallbackCounter;
  35. /* Global accumulator for total callback length */
  36. static int g_audio_testCallbackLength;
  37. /* Test callback function */
  38. static void SDLCALL audio_testCallback(void *userdata, Uint8 *stream, int len)
  39. {
  40. /* track that callback was called */
  41. g_audio_testCallbackCounter++;
  42. g_audio_testCallbackLength += len;
  43. }
  44. #endif
  45. static SDL_AudioDeviceID g_audio_id = 0;
  46. /* Test case functions */
  47. /**
  48. * Stop and restart audio subsystem
  49. *
  50. * \sa SDL_QuitSubSystem
  51. * \sa SDL_InitSubSystem
  52. */
  53. static int audio_quitInitAudioSubSystem(void *arg)
  54. {
  55. /* Stop SDL audio subsystem */
  56. SDL_QuitSubSystem(SDL_INIT_AUDIO);
  57. SDLTest_AssertPass("Call to SDL_QuitSubSystem(SDL_INIT_AUDIO)");
  58. /* Restart audio again */
  59. audioSetUp(NULL);
  60. return TEST_COMPLETED;
  61. }
  62. /**
  63. * Start and stop audio directly
  64. *
  65. * \sa SDL_InitAudio
  66. * \sa SDL_QuitAudio
  67. */
  68. static int audio_initQuitAudio(void *arg)
  69. {
  70. int result;
  71. int i, iMax;
  72. const char *audioDriver;
  73. const char *hint = SDL_GetHint(SDL_HINT_AUDIO_DRIVER);
  74. /* Stop SDL audio subsystem */
  75. SDL_QuitSubSystem(SDL_INIT_AUDIO);
  76. SDLTest_AssertPass("Call to SDL_QuitSubSystem(SDL_INIT_AUDIO)");
  77. /* Loop over all available audio drivers */
  78. iMax = SDL_GetNumAudioDrivers();
  79. SDLTest_AssertPass("Call to SDL_GetNumAudioDrivers()");
  80. SDLTest_AssertCheck(iMax > 0, "Validate number of audio drivers; expected: >0 got: %d", iMax);
  81. for (i = 0; i < iMax; i++) {
  82. audioDriver = SDL_GetAudioDriver(i);
  83. SDLTest_AssertPass("Call to SDL_GetAudioDriver(%d)", i);
  84. SDLTest_Assert(audioDriver != NULL, "Audio driver name is not NULL");
  85. SDLTest_AssertCheck(audioDriver[0] != '\0', "Audio driver name is not empty; got: %s", audioDriver); /* NOLINT(clang-analyzer-core.NullDereference): Checked for NULL above */
  86. if (hint && SDL_strcmp(audioDriver, hint) != 0) {
  87. continue;
  88. }
  89. /* Call Init */
  90. SDL_SetHint("SDL_AUDIO_DRIVER", audioDriver);
  91. result = SDL_InitSubSystem(SDL_INIT_AUDIO);
  92. SDLTest_AssertPass("Call to SDL_InitSubSystem(SDL_INIT_AUDIO) with driver='%s'", audioDriver);
  93. SDLTest_AssertCheck(result == 0, "Validate result value; expected: 0 got: %d", result);
  94. /* Call Quit */
  95. SDL_QuitSubSystem(SDL_INIT_AUDIO);
  96. SDLTest_AssertPass("Call to SDL_QuitSubSystem(SDL_INIT_AUDIO)");
  97. }
  98. /* NULL driver specification */
  99. audioDriver = NULL;
  100. /* Call Init */
  101. SDL_SetHint("SDL_AUDIO_DRIVER", audioDriver);
  102. result = SDL_InitSubSystem(SDL_INIT_AUDIO);
  103. SDLTest_AssertPass("Call to SDL_AudioInit(NULL)");
  104. SDLTest_AssertCheck(result == 0, "Validate result value; expected: 0 got: %d", result);
  105. /* Call Quit */
  106. SDL_QuitSubSystem(SDL_INIT_AUDIO);
  107. SDLTest_AssertPass("Call to SDL_QuitSubSystem(SDL_INIT_AUDIO)");
  108. /* Restart audio again */
  109. audioSetUp(NULL);
  110. return TEST_COMPLETED;
  111. }
  112. /**
  113. * Start, open, close and stop audio
  114. *
  115. * \sa SDL_InitAudio
  116. * \sa SDL_OpenAudioDevice
  117. * \sa SDL_CloseAudioDevice
  118. * \sa SDL_QuitAudio
  119. */
  120. static int audio_initOpenCloseQuitAudio(void *arg)
  121. {
  122. int result;
  123. int i, iMax, j, k;
  124. const char *audioDriver;
  125. SDL_AudioSpec desired;
  126. const char *hint = SDL_GetHint(SDL_HINT_AUDIO_DRIVER);
  127. /* Stop SDL audio subsystem */
  128. SDL_QuitSubSystem(SDL_INIT_AUDIO);
  129. SDLTest_AssertPass("Call to SDL_QuitSubSystem(SDL_INIT_AUDIO)");
  130. /* Loop over all available audio drivers */
  131. iMax = SDL_GetNumAudioDrivers();
  132. SDLTest_AssertPass("Call to SDL_GetNumAudioDrivers()");
  133. SDLTest_AssertCheck(iMax > 0, "Validate number of audio drivers; expected: >0 got: %d", iMax);
  134. for (i = 0; i < iMax; i++) {
  135. audioDriver = SDL_GetAudioDriver(i);
  136. SDLTest_AssertPass("Call to SDL_GetAudioDriver(%d)", i);
  137. SDLTest_Assert(audioDriver != NULL, "Audio driver name is not NULL");
  138. SDLTest_AssertCheck(audioDriver[0] != '\0', "Audio driver name is not empty; got: %s", audioDriver); /* NOLINT(clang-analyzer-core.NullDereference): Checked for NULL above */
  139. if (hint && SDL_strcmp(audioDriver, hint) != 0) {
  140. continue;
  141. }
  142. /* Change specs */
  143. for (j = 0; j < 2; j++) {
  144. /* Call Init */
  145. SDL_SetHint("SDL_AUDIO_DRIVER", audioDriver);
  146. result = SDL_InitSubSystem(SDL_INIT_AUDIO);
  147. SDLTest_AssertPass("Call to SDL_InitSubSystem(SDL_INIT_AUDIO) with driver='%s'", audioDriver);
  148. SDLTest_AssertCheck(result == 0, "Validate result value; expected: 0 got: %d", result);
  149. /* Set spec */
  150. SDL_memset(&desired, 0, sizeof(desired));
  151. switch (j) {
  152. case 0:
  153. /* Set standard desired spec */
  154. desired.freq = 22050;
  155. desired.format = SDL_AUDIO_S16;
  156. desired.channels = 2;
  157. break;
  158. case 1:
  159. /* Set custom desired spec */
  160. desired.freq = 48000;
  161. desired.format = SDL_AUDIO_F32;
  162. desired.channels = 2;
  163. break;
  164. }
  165. /* Call Open (maybe multiple times) */
  166. for (k = 0; k <= j; k++) {
  167. result = SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &desired);
  168. if (k == 0) {
  169. g_audio_id = result;
  170. }
  171. SDLTest_AssertPass("Call to SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, desired_spec_%d), call %d", j, k + 1);
  172. SDLTest_AssertCheck(result > 0, "Verify return value; expected: > 0, got: %d", result);
  173. }
  174. /* Call Close (maybe multiple times) */
  175. for (k = 0; k <= j; k++) {
  176. SDL_CloseAudioDevice(g_audio_id);
  177. SDLTest_AssertPass("Call to SDL_CloseAudioDevice(), call %d", k + 1);
  178. }
  179. /* Call Quit (maybe multiple times) */
  180. for (k = 0; k <= j; k++) {
  181. SDL_QuitSubSystem(SDL_INIT_AUDIO);
  182. SDLTest_AssertPass("Call to SDL_QuitSubSystem(SDL_INIT_AUDIO), call %d", k + 1);
  183. }
  184. } /* spec loop */
  185. } /* driver loop */
  186. /* Restart audio again */
  187. audioSetUp(NULL);
  188. return TEST_COMPLETED;
  189. }
  190. /**
  191. * Pause and unpause audio
  192. *
  193. * \sa SDL_PauseAudioDevice
  194. * \sa SDL_PlayAudioDevice
  195. */
  196. static int audio_pauseUnpauseAudio(void *arg)
  197. {
  198. int iMax;
  199. int i, j /*, k, l*/;
  200. int result;
  201. const char *audioDriver;
  202. SDL_AudioSpec desired;
  203. const char *hint = SDL_GetHint(SDL_HINT_AUDIO_DRIVER);
  204. /* Stop SDL audio subsystem */
  205. SDL_QuitSubSystem(SDL_INIT_AUDIO);
  206. SDLTest_AssertPass("Call to SDL_QuitSubSystem(SDL_INIT_AUDIO)");
  207. /* Loop over all available audio drivers */
  208. iMax = SDL_GetNumAudioDrivers();
  209. SDLTest_AssertPass("Call to SDL_GetNumAudioDrivers()");
  210. SDLTest_AssertCheck(iMax > 0, "Validate number of audio drivers; expected: >0 got: %d", iMax);
  211. for (i = 0; i < iMax; i++) {
  212. audioDriver = SDL_GetAudioDriver(i);
  213. SDLTest_AssertPass("Call to SDL_GetAudioDriver(%d)", i);
  214. SDLTest_Assert(audioDriver != NULL, "Audio driver name is not NULL");
  215. SDLTest_AssertCheck(audioDriver[0] != '\0', "Audio driver name is not empty; got: %s", audioDriver); /* NOLINT(clang-analyzer-core.NullDereference): Checked for NULL above */
  216. if (hint && SDL_strcmp(audioDriver, hint) != 0) {
  217. continue;
  218. }
  219. /* Change specs */
  220. for (j = 0; j < 2; j++) {
  221. /* Call Init */
  222. SDL_SetHint("SDL_AUDIO_DRIVER", audioDriver);
  223. result = SDL_InitSubSystem(SDL_INIT_AUDIO);
  224. SDLTest_AssertPass("Call to SDL_InitSubSystem(SDL_INIT_AUDIO) with driver='%s'", audioDriver);
  225. SDLTest_AssertCheck(result == 0, "Validate result value; expected: 0 got: %d", result);
  226. /* Set spec */
  227. SDL_memset(&desired, 0, sizeof(desired));
  228. switch (j) {
  229. case 0:
  230. /* Set standard desired spec */
  231. desired.freq = 22050;
  232. desired.format = SDL_AUDIO_S16;
  233. desired.channels = 2;
  234. break;
  235. case 1:
  236. /* Set custom desired spec */
  237. desired.freq = 48000;
  238. desired.format = SDL_AUDIO_F32;
  239. desired.channels = 2;
  240. break;
  241. }
  242. /* Call Open */
  243. g_audio_id = SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &desired);
  244. result = g_audio_id;
  245. SDLTest_AssertPass("Call to SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, desired_spec_%d)", j);
  246. SDLTest_AssertCheck(result > 0, "Verify return value; expected > 0 got: %d", result);
  247. #if 0 /* !!! FIXME: maybe update this? */
  248. /* Start and stop audio multiple times */
  249. for (l = 0; l < 3; l++) {
  250. SDLTest_Log("Pause/Unpause iteration: %d", l + 1);
  251. /* Reset callback counters */
  252. g_audio_testCallbackCounter = 0;
  253. g_audio_testCallbackLength = 0;
  254. /* Un-pause audio to start playing (maybe multiple times) */
  255. for (k = 0; k <= j; k++) {
  256. SDL_PlayAudioDevice(g_audio_id);
  257. SDLTest_AssertPass("Call to SDL_PlayAudioDevice(g_audio_id), call %d", k + 1);
  258. }
  259. /* Wait for callback */
  260. int totalDelay = 0;
  261. do {
  262. SDL_Delay(10);
  263. totalDelay += 10;
  264. } while (g_audio_testCallbackCounter == 0 && totalDelay < 1000);
  265. SDLTest_AssertCheck(g_audio_testCallbackCounter > 0, "Verify callback counter; expected: >0 got: %d", g_audio_testCallbackCounter);
  266. SDLTest_AssertCheck(g_audio_testCallbackLength > 0, "Verify callback length; expected: >0 got: %d", g_audio_testCallbackLength);
  267. /* Pause audio to stop playing (maybe multiple times) */
  268. for (k = 0; k <= j; k++) {
  269. const int pause_on = (k == 0) ? 1 : SDLTest_RandomIntegerInRange(99, 9999);
  270. if (pause_on) {
  271. SDL_PauseAudioDevice(g_audio_id);
  272. SDLTest_AssertPass("Call to SDL_PauseAudioDevice(g_audio_id), call %d", k + 1);
  273. } else {
  274. SDL_PlayAudioDevice(g_audio_id);
  275. SDLTest_AssertPass("Call to SDL_PlayAudioDevice(g_audio_id), call %d", k + 1);
  276. }
  277. }
  278. /* Ensure callback is not called again */
  279. const int originalCounter = g_audio_testCallbackCounter;
  280. SDL_Delay(totalDelay + 10);
  281. SDLTest_AssertCheck(originalCounter == g_audio_testCallbackCounter, "Verify callback counter; expected: %d, got: %d", originalCounter, g_audio_testCallbackCounter);
  282. }
  283. #endif
  284. /* Call Close */
  285. SDL_CloseAudioDevice(g_audio_id);
  286. SDLTest_AssertPass("Call to SDL_CloseAudioDevice()");
  287. /* Call Quit */
  288. SDL_QuitSubSystem(SDL_INIT_AUDIO);
  289. SDLTest_AssertPass("Call to SDL_QuitSubSystem(SDL_INIT_AUDIO)");
  290. } /* spec loop */
  291. } /* driver loop */
  292. /* Restart audio again */
  293. audioSetUp(NULL);
  294. return TEST_COMPLETED;
  295. }
  296. /**
  297. * Enumerate and name available audio devices (playback and recording).
  298. *
  299. * \sa SDL_GetNumAudioDevices
  300. * \sa SDL_GetAudioDeviceName
  301. */
  302. static int audio_enumerateAndNameAudioDevices(void *arg)
  303. {
  304. int t;
  305. int i, n;
  306. const char *name;
  307. SDL_AudioDeviceID *devices = NULL;
  308. /* Iterate over types: t=0 playback device, t=1 recording device */
  309. for (t = 0; t < 2; t++) {
  310. /* Get number of devices. */
  311. devices = (t) ? SDL_GetAudioRecordingDevices(&n) : SDL_GetAudioPlaybackDevices(&n);
  312. SDLTest_AssertPass("Call to SDL_GetAudio%sDevices(%i)", (t) ? "Recording" : "Playback", t);
  313. SDLTest_Log("Number of %s devices < 0, reported as %i", (t) ? "recording" : "playback", n);
  314. SDLTest_AssertCheck(n >= 0, "Validate result is >= 0, got: %i", n);
  315. /* List devices. */
  316. if (n > 0) {
  317. SDLTest_AssertCheck(devices != NULL, "Validate devices is not NULL if n > 0");
  318. for (i = 0; i < n; i++) {
  319. name = SDL_GetAudioDeviceName(devices[i]);
  320. SDLTest_AssertPass("Call to SDL_GetAudioDeviceName(%i)", i);
  321. SDLTest_AssertCheck(name != NULL, "Verify result from SDL_GetAudioDeviceName(%i) is not NULL", i);
  322. if (name != NULL) {
  323. SDLTest_AssertCheck(name[0] != '\0', "verify result from SDL_GetAudioDeviceName(%i) is not empty, got: '%s'", i, name);
  324. }
  325. }
  326. }
  327. SDL_free(devices);
  328. }
  329. return TEST_COMPLETED;
  330. }
  331. /**
  332. * Negative tests around enumeration and naming of audio devices.
  333. *
  334. * \sa SDL_GetNumAudioDevices
  335. * \sa SDL_GetAudioDeviceName
  336. */
  337. static int audio_enumerateAndNameAudioDevicesNegativeTests(void *arg)
  338. {
  339. return TEST_COMPLETED; /* nothing in here atm since these interfaces changed in SDL3. */
  340. }
  341. /**
  342. * Checks available audio driver names.
  343. *
  344. * \sa SDL_GetNumAudioDrivers
  345. * \sa SDL_GetAudioDriver
  346. */
  347. static int audio_printAudioDrivers(void *arg)
  348. {
  349. int i, n;
  350. const char *name;
  351. /* Get number of drivers */
  352. n = SDL_GetNumAudioDrivers();
  353. SDLTest_AssertPass("Call to SDL_GetNumAudioDrivers()");
  354. SDLTest_AssertCheck(n >= 0, "Verify number of audio drivers >= 0, got: %i", n);
  355. /* List drivers. */
  356. if (n > 0) {
  357. for (i = 0; i < n; i++) {
  358. name = SDL_GetAudioDriver(i);
  359. SDLTest_AssertPass("Call to SDL_GetAudioDriver(%i)", i);
  360. SDLTest_AssertCheck(name != NULL, "Verify returned name is not NULL");
  361. if (name != NULL) {
  362. SDLTest_AssertCheck(name[0] != '\0', "Verify returned name is not empty, got: '%s'", name);
  363. }
  364. }
  365. }
  366. return TEST_COMPLETED;
  367. }
  368. /**
  369. * Checks current audio driver name with initialized audio.
  370. *
  371. * \sa SDL_GetCurrentAudioDriver
  372. */
  373. static int audio_printCurrentAudioDriver(void *arg)
  374. {
  375. /* Check current audio driver */
  376. const char *name = SDL_GetCurrentAudioDriver();
  377. SDLTest_AssertPass("Call to SDL_GetCurrentAudioDriver()");
  378. SDLTest_AssertCheck(name != NULL, "Verify returned name is not NULL");
  379. if (name != NULL) {
  380. SDLTest_AssertCheck(name[0] != '\0', "Verify returned name is not empty, got: '%s'", name);
  381. }
  382. return TEST_COMPLETED;
  383. }
  384. /* Definition of all formats, channels, and frequencies used to test audio conversions */
  385. static SDL_AudioFormat g_audioFormats[] = {
  386. SDL_AUDIO_S8, SDL_AUDIO_U8,
  387. SDL_AUDIO_S16LE, SDL_AUDIO_S16BE,
  388. SDL_AUDIO_S32LE, SDL_AUDIO_S32BE,
  389. SDL_AUDIO_F32LE, SDL_AUDIO_F32BE
  390. };
  391. static const char *g_audioFormatsVerbose[] = {
  392. "SDL_AUDIO_S8", "SDL_AUDIO_U8",
  393. "SDL_AUDIO_S16LE", "SDL_AUDIO_S16BE",
  394. "SDL_AUDIO_S32LE", "SDL_AUDIO_S32BE",
  395. "SDL_AUDIO_F32LE", "SDL_AUDIO_F32BE"
  396. };
  397. static const int g_numAudioFormats = SDL_arraysize(g_audioFormats);
  398. static Uint8 g_audioChannels[] = { 1, 2, 4, 6 };
  399. static const int g_numAudioChannels = SDL_arraysize(g_audioChannels);
  400. static int g_audioFrequencies[] = { 11025, 22050, 44100, 48000 };
  401. static const int g_numAudioFrequencies = SDL_arraysize(g_audioFrequencies);
  402. /* Verify the audio formats are laid out as expected */
  403. SDL_COMPILE_TIME_ASSERT(SDL_AUDIO_U8_FORMAT, SDL_AUDIO_U8 == SDL_AUDIO_BITSIZE(8));
  404. SDL_COMPILE_TIME_ASSERT(SDL_AUDIO_S8_FORMAT, SDL_AUDIO_S8 == (SDL_AUDIO_BITSIZE(8) | SDL_AUDIO_MASK_SIGNED));
  405. SDL_COMPILE_TIME_ASSERT(SDL_AUDIO_S16LE_FORMAT, SDL_AUDIO_S16LE == (SDL_AUDIO_BITSIZE(16) | SDL_AUDIO_MASK_SIGNED));
  406. SDL_COMPILE_TIME_ASSERT(SDL_AUDIO_S16BE_FORMAT, SDL_AUDIO_S16BE == (SDL_AUDIO_S16LE | SDL_AUDIO_MASK_BIG_ENDIAN));
  407. SDL_COMPILE_TIME_ASSERT(SDL_AUDIO_S32LE_FORMAT, SDL_AUDIO_S32LE == (SDL_AUDIO_BITSIZE(32) | SDL_AUDIO_MASK_SIGNED));
  408. SDL_COMPILE_TIME_ASSERT(SDL_AUDIO_S32BE_FORMAT, SDL_AUDIO_S32BE == (SDL_AUDIO_S32LE | SDL_AUDIO_MASK_BIG_ENDIAN));
  409. SDL_COMPILE_TIME_ASSERT(SDL_AUDIO_F32LE_FORMAT, SDL_AUDIO_F32LE == (SDL_AUDIO_BITSIZE(32) | SDL_AUDIO_MASK_FLOAT | SDL_AUDIO_MASK_SIGNED));
  410. SDL_COMPILE_TIME_ASSERT(SDL_AUDIO_F32BE_FORMAT, SDL_AUDIO_F32BE == (SDL_AUDIO_F32LE | SDL_AUDIO_MASK_BIG_ENDIAN));
  411. /**
  412. * Builds various audio conversion structures
  413. *
  414. * \sa SDL_CreateAudioStream
  415. */
  416. static int audio_buildAudioStream(void *arg)
  417. {
  418. SDL_AudioStream *stream;
  419. SDL_AudioSpec spec1;
  420. SDL_AudioSpec spec2;
  421. int i, ii, j, jj, k, kk;
  422. /* Call Quit */
  423. SDL_QuitSubSystem(SDL_INIT_AUDIO);
  424. SDLTest_AssertPass("Call to SDL_QuitSubSystem(SDL_INIT_AUDIO)");
  425. /* No conversion needed */
  426. spec1.format = SDL_AUDIO_S16LE;
  427. spec1.channels = 2;
  428. spec1.freq = 22050;
  429. stream = SDL_CreateAudioStream(&spec1, &spec1);
  430. SDLTest_AssertPass("Call to SDL_CreateAudioStream(spec1 ==> spec1)");
  431. SDLTest_AssertCheck(stream != NULL, "Verify stream value; expected: != NULL, got: %p", (void *)stream);
  432. SDL_DestroyAudioStream(stream);
  433. /* Typical conversion */
  434. spec1.format = SDL_AUDIO_S8;
  435. spec1.channels = 1;
  436. spec1.freq = 22050;
  437. spec2.format = SDL_AUDIO_S16LE;
  438. spec2.channels = 2;
  439. spec2.freq = 44100;
  440. stream = SDL_CreateAudioStream(&spec1, &spec2);
  441. SDLTest_AssertPass("Call to SDL_CreateAudioStream(spec1 ==> spec2)");
  442. SDLTest_AssertCheck(stream != NULL, "Verify stream value; expected: != NULL, got: %p", (void *)stream);
  443. SDL_DestroyAudioStream(stream);
  444. /* All source conversions with random conversion targets, allow 'null' conversions */
  445. for (i = 0; i < g_numAudioFormats; i++) {
  446. for (j = 0; j < g_numAudioChannels; j++) {
  447. for (k = 0; k < g_numAudioFrequencies; k++) {
  448. spec1.format = g_audioFormats[i];
  449. spec1.channels = g_audioChannels[j];
  450. spec1.freq = g_audioFrequencies[k];
  451. ii = SDLTest_RandomIntegerInRange(0, g_numAudioFormats - 1);
  452. jj = SDLTest_RandomIntegerInRange(0, g_numAudioChannels - 1);
  453. kk = SDLTest_RandomIntegerInRange(0, g_numAudioFrequencies - 1);
  454. spec2.format = g_audioFormats[ii];
  455. spec2.channels = g_audioChannels[jj];
  456. spec2.freq = g_audioFrequencies[kk];
  457. stream = SDL_CreateAudioStream(&spec1, &spec2);
  458. SDLTest_AssertPass("Call to SDL_CreateAudioStream(format[%i]=%s(%i),channels[%i]=%i,freq[%i]=%i ==> format[%i]=%s(%i),channels[%i]=%i,freq[%i]=%i)",
  459. i, g_audioFormatsVerbose[i], spec1.format, j, spec1.channels, k, spec1.freq, ii, g_audioFormatsVerbose[ii], spec2.format, jj, spec2.channels, kk, spec2.freq);
  460. SDLTest_AssertCheck(stream != NULL, "Verify stream value; expected: != NULL, got: %p", (void *)stream);
  461. if (stream == NULL) {
  462. SDLTest_LogError("%s", SDL_GetError());
  463. }
  464. SDL_DestroyAudioStream(stream);
  465. }
  466. }
  467. }
  468. /* Restart audio again */
  469. audioSetUp(NULL);
  470. return TEST_COMPLETED;
  471. }
  472. /**
  473. * Checks calls with invalid input to SDL_CreateAudioStream
  474. *
  475. * \sa SDL_CreateAudioStream
  476. */
  477. static int audio_buildAudioStreamNegative(void *arg)
  478. {
  479. const char *error;
  480. SDL_AudioStream *stream;
  481. SDL_AudioSpec spec1;
  482. SDL_AudioSpec spec2;
  483. int i;
  484. char message[256];
  485. /* Valid format */
  486. spec1.format = SDL_AUDIO_S8;
  487. spec1.channels = 1;
  488. spec1.freq = 22050;
  489. spec2.format = SDL_AUDIO_S16LE;
  490. spec2.channels = 2;
  491. spec2.freq = 44100;
  492. SDL_ClearError();
  493. SDLTest_AssertPass("Call to SDL_ClearError()");
  494. /* Invalid conversions */
  495. for (i = 1; i < 64; i++) {
  496. /* Valid format to start with */
  497. spec1.format = SDL_AUDIO_S8;
  498. spec1.channels = 1;
  499. spec1.freq = 22050;
  500. spec2.format = SDL_AUDIO_S16LE;
  501. spec2.channels = 2;
  502. spec2.freq = 44100;
  503. SDL_ClearError();
  504. SDLTest_AssertPass("Call to SDL_ClearError()");
  505. /* Set various invalid format inputs */
  506. SDL_strlcpy(message, "Invalid: ", 256);
  507. if (i & 1) {
  508. SDL_strlcat(message, " spec1.format", 256);
  509. spec1.format = 0;
  510. }
  511. if (i & 2) {
  512. SDL_strlcat(message, " spec1.channels", 256);
  513. spec1.channels = 0;
  514. }
  515. if (i & 4) {
  516. SDL_strlcat(message, " spec1.freq", 256);
  517. spec1.freq = 0;
  518. }
  519. if (i & 8) {
  520. SDL_strlcat(message, " spec2.format", 256);
  521. spec2.format = 0;
  522. }
  523. if (i & 16) {
  524. SDL_strlcat(message, " spec2.channels", 256);
  525. spec2.channels = 0;
  526. }
  527. if (i & 32) {
  528. SDL_strlcat(message, " spec2.freq", 256);
  529. spec2.freq = 0;
  530. }
  531. SDLTest_Log("%s", message);
  532. stream = SDL_CreateAudioStream(&spec1, &spec2);
  533. SDLTest_AssertPass("Call to SDL_CreateAudioStream(spec1 ==> spec2)");
  534. SDLTest_AssertCheck(stream == NULL, "Verify stream value; expected: NULL, got: %p", (void *)stream);
  535. error = SDL_GetError();
  536. SDLTest_AssertPass("Call to SDL_GetError()");
  537. SDLTest_AssertCheck(error != NULL && error[0] != '\0', "Validate that error message was not NULL or empty");
  538. SDL_DestroyAudioStream(stream);
  539. }
  540. SDL_ClearError();
  541. SDLTest_AssertPass("Call to SDL_ClearError()");
  542. return TEST_COMPLETED;
  543. }
  544. /**
  545. * Checks current audio status.
  546. *
  547. * \sa SDL_GetAudioDeviceStatus
  548. */
  549. static int audio_getAudioStatus(void *arg)
  550. {
  551. return TEST_COMPLETED; /* no longer a thing in SDL3. */
  552. }
  553. /**
  554. * Opens, checks current audio status, and closes a device.
  555. *
  556. * \sa SDL_GetAudioStatus
  557. */
  558. static int audio_openCloseAndGetAudioStatus(void *arg)
  559. {
  560. return TEST_COMPLETED; /* not a thing in SDL3. */
  561. }
  562. /**
  563. * Locks and unlocks open audio device.
  564. *
  565. * \sa SDL_LockAudioDevice
  566. * \sa SDL_UnlockAudioDevice
  567. */
  568. static int audio_lockUnlockOpenAudioDevice(void *arg)
  569. {
  570. return TEST_COMPLETED; /* not a thing in SDL3 */
  571. }
  572. /**
  573. * Convert audio using various conversion structures
  574. *
  575. * \sa SDL_CreateAudioStream
  576. */
  577. static int audio_convertAudio(void *arg)
  578. {
  579. SDL_AudioStream *stream;
  580. SDL_AudioSpec spec1;
  581. SDL_AudioSpec spec2;
  582. int c;
  583. char message[128];
  584. int i, ii, j, jj, k, kk;
  585. /* Iterate over bitmask that determines which parameters are modified in the conversion */
  586. for (c = 1; c < 8; c++) {
  587. SDL_strlcpy(message, "Changing:", 128);
  588. if (c & 1) {
  589. SDL_strlcat(message, " Format", 128);
  590. }
  591. if (c & 2) {
  592. SDL_strlcat(message, " Channels", 128);
  593. }
  594. if (c & 4) {
  595. SDL_strlcat(message, " Frequencies", 128);
  596. }
  597. SDLTest_Log("%s", message);
  598. /* All source conversions with random conversion targets */
  599. for (i = 0; i < g_numAudioFormats; i++) {
  600. for (j = 0; j < g_numAudioChannels; j++) {
  601. for (k = 0; k < g_numAudioFrequencies; k++) {
  602. spec1.format = g_audioFormats[i];
  603. spec1.channels = g_audioChannels[j];
  604. spec1.freq = g_audioFrequencies[k];
  605. /* Ensure we have a different target format */
  606. do {
  607. if (c & 1) {
  608. ii = SDLTest_RandomIntegerInRange(0, g_numAudioFormats - 1);
  609. } else {
  610. ii = 1;
  611. }
  612. if (c & 2) {
  613. jj = SDLTest_RandomIntegerInRange(0, g_numAudioChannels - 1);
  614. } else {
  615. jj = j;
  616. }
  617. if (c & 4) {
  618. kk = SDLTest_RandomIntegerInRange(0, g_numAudioFrequencies - 1);
  619. } else {
  620. kk = k;
  621. }
  622. } while ((i == ii) && (j == jj) && (k == kk));
  623. spec2.format = g_audioFormats[ii];
  624. spec2.channels = g_audioChannels[jj];
  625. spec2.freq = g_audioFrequencies[kk];
  626. stream = SDL_CreateAudioStream(&spec1, &spec2);
  627. SDLTest_AssertPass("Call to SDL_CreateAudioStream(format[%i]=%s(%i),channels[%i]=%i,freq[%i]=%i ==> format[%i]=%s(%i),channels[%i]=%i,freq[%i]=%i)",
  628. i, g_audioFormatsVerbose[i], spec1.format, j, spec1.channels, k, spec1.freq, ii, g_audioFormatsVerbose[ii], spec2.format, jj, spec2.channels, kk, spec2.freq);
  629. SDLTest_AssertCheck(stream != NULL, "Verify stream value; expected: != NULL, got: %p", (void *)stream);
  630. if (stream == NULL) {
  631. SDLTest_LogError("%s", SDL_GetError());
  632. } else {
  633. Uint8 *dst_buf = NULL, *src_buf = NULL;
  634. int dst_len = 0, src_len = 0, real_dst_len = 0;
  635. int l = 64, m;
  636. int src_framesize, dst_framesize;
  637. int src_silence, dst_silence;
  638. src_framesize = SDL_AUDIO_FRAMESIZE(spec1);
  639. dst_framesize = SDL_AUDIO_FRAMESIZE(spec2);
  640. src_len = l * src_framesize;
  641. SDLTest_Log("Creating dummy sample buffer of %i length (%i bytes)", l, src_len);
  642. src_buf = (Uint8 *)SDL_malloc(src_len);
  643. SDLTest_AssertCheck(src_buf != NULL, "Check src data buffer to convert is not NULL");
  644. if (src_buf == NULL) {
  645. return TEST_ABORTED;
  646. }
  647. src_silence = SDL_GetSilenceValueForFormat(spec1.format);
  648. SDL_memset(src_buf, src_silence, src_len);
  649. dst_len = ((int)((((Sint64)l * spec2.freq) - 1) / spec1.freq) + 1) * dst_framesize;
  650. dst_buf = (Uint8 *)SDL_malloc(dst_len);
  651. SDLTest_AssertCheck(dst_buf != NULL, "Check dst data buffer to convert is not NULL");
  652. if (dst_buf == NULL) {
  653. return TEST_ABORTED;
  654. }
  655. real_dst_len = SDL_GetAudioStreamAvailable(stream);
  656. SDLTest_AssertCheck(0 == real_dst_len, "Verify available (pre-put); expected: %i; got: %i", 0, real_dst_len);
  657. /* Run the audio converter */
  658. if (SDL_PutAudioStreamData(stream, src_buf, src_len) < 0 ||
  659. SDL_FlushAudioStream(stream) < 0) {
  660. return TEST_ABORTED;
  661. }
  662. real_dst_len = SDL_GetAudioStreamAvailable(stream);
  663. SDLTest_AssertCheck(dst_len == real_dst_len, "Verify available (post-put); expected: %i; got: %i", dst_len, real_dst_len);
  664. real_dst_len = SDL_GetAudioStreamData(stream, dst_buf, dst_len);
  665. SDLTest_AssertCheck(dst_len == real_dst_len, "Verify result value; expected: %i; got: %i", dst_len, real_dst_len);
  666. if (dst_len != real_dst_len) {
  667. return TEST_ABORTED;
  668. }
  669. real_dst_len = SDL_GetAudioStreamAvailable(stream);
  670. SDLTest_AssertCheck(0 == real_dst_len, "Verify available (post-get); expected: %i; got: %i", 0, real_dst_len);
  671. dst_silence = SDL_GetSilenceValueForFormat(spec2.format);
  672. for (m = 0; m < dst_len; ++m) {
  673. if (dst_buf[m] != dst_silence) {
  674. SDLTest_LogError("Output buffer is not silent");
  675. return TEST_ABORTED;
  676. }
  677. }
  678. SDL_DestroyAudioStream(stream);
  679. /* Free converted buffer */
  680. SDL_free(src_buf);
  681. SDL_free(dst_buf);
  682. }
  683. }
  684. }
  685. }
  686. }
  687. return TEST_COMPLETED;
  688. }
  689. /**
  690. * Opens, checks current connected status, and closes a device.
  691. *
  692. * \sa SDL_AudioDeviceConnected
  693. */
  694. static int audio_openCloseAudioDeviceConnected(void *arg)
  695. {
  696. return TEST_COMPLETED; /* not a thing in SDL3. */
  697. }
  698. static double sine_wave_sample(const Sint64 idx, const Sint64 rate, const Sint64 freq, const double phase)
  699. {
  700. /* Using integer modulo to avoid precision loss caused by large floating
  701. * point numbers. Sint64 is needed for the large integer multiplication.
  702. * The integers are assumed to be non-negative so that modulo is always
  703. * non-negative.
  704. * sin(i / rate * freq * 2 * PI + phase)
  705. * = sin(mod(i / rate * freq, 1) * 2 * PI + phase)
  706. * = sin(mod(i * freq, rate) / rate * 2 * PI + phase) */
  707. return SDL_sin(((double)(idx * freq % rate)) / ((double)rate) * (SDL_PI_D * 2) + phase);
  708. }
  709. /* Split the data into randomly sized chunks */
  710. static int put_audio_data_split(SDL_AudioStream* stream, const void* buf, int len)
  711. {
  712. SDL_AudioSpec spec;
  713. int frame_size;
  714. int ret = SDL_GetAudioStreamFormat(stream, &spec, NULL);
  715. if (ret != 0) {
  716. return ret;
  717. }
  718. frame_size = SDL_AUDIO_FRAMESIZE(spec);
  719. while (len > 0) {
  720. int n = SDLTest_RandomIntegerInRange(1, 10000) * frame_size;
  721. n = SDL_min(n, len);
  722. ret = SDL_PutAudioStreamData(stream, buf, n);
  723. if (ret != 0) {
  724. return ret;
  725. }
  726. buf = ((const Uint8*) buf) + n;
  727. len -= n;
  728. }
  729. return 0;
  730. }
  731. /* Read the data in randomly sized chunks */
  732. static int get_audio_data_split(SDL_AudioStream* stream, void* buf, int len) {
  733. SDL_AudioSpec spec;
  734. int frame_size;
  735. int ret = SDL_GetAudioStreamFormat(stream, NULL, &spec);
  736. int total = 0;
  737. if (ret != 0) {
  738. return ret;
  739. }
  740. frame_size = SDL_AUDIO_FRAMESIZE(spec);
  741. while (len > 0) {
  742. int n = SDLTest_RandomIntegerInRange(1, 10000) * frame_size;
  743. n = SDL_min(n, len);
  744. ret = SDL_GetAudioStreamData(stream, buf, n);
  745. if (ret <= 0) {
  746. return total ? total : ret;
  747. }
  748. buf = ((Uint8*) buf) + ret;
  749. total += ret;
  750. len -= ret;
  751. }
  752. return total;
  753. }
  754. /* Convert the data in chunks, putting/getting randomly sized chunks until finished */
  755. static int convert_audio_chunks(SDL_AudioStream* stream, const void* src, int srclen, void* dst, int dstlen)
  756. {
  757. SDL_AudioSpec src_spec, dst_spec;
  758. int src_frame_size, dst_frame_size;
  759. int total_in = 0, total_out = 0;
  760. int ret = SDL_GetAudioStreamFormat(stream, &src_spec, &dst_spec);
  761. if (ret) {
  762. return ret;
  763. }
  764. src_frame_size = SDL_AUDIO_FRAMESIZE(src_spec);
  765. dst_frame_size = SDL_AUDIO_FRAMESIZE(dst_spec);
  766. while ((total_in < srclen) || (total_out < dstlen)) {
  767. int to_put = SDLTest_RandomIntegerInRange(1, 40000) * src_frame_size;
  768. int to_get = SDLTest_RandomIntegerInRange(1, (int)((40000.0f * dst_spec.freq) / src_spec.freq)) * dst_frame_size;
  769. to_put = SDL_min(to_put, srclen - total_in);
  770. to_get = SDL_min(to_get, dstlen - total_out);
  771. if (to_put)
  772. {
  773. ret = put_audio_data_split(stream, (const Uint8*)(src) + total_in, to_put);
  774. if (ret) {
  775. return total_out ? total_out : ret;
  776. }
  777. total_in += to_put;
  778. if (total_in == srclen) {
  779. ret = SDL_FlushAudioStream(stream);
  780. if (ret) {
  781. return total_out ? total_out : ret;
  782. }
  783. }
  784. }
  785. if (to_get)
  786. {
  787. ret = get_audio_data_split(stream, (Uint8*)(dst) + total_out, to_get);
  788. if ((ret == 0) && (total_in == srclen)) {
  789. ret = -1;
  790. }
  791. if (ret < 0) {
  792. return total_out ? total_out : ret;
  793. }
  794. total_out += ret;
  795. }
  796. }
  797. return total_out;
  798. }
  799. /**
  800. * Check signal-to-noise ratio and maximum error of audio resampling.
  801. *
  802. * \sa https://wiki.libsdl.org/SDL_CreateAudioStream
  803. * \sa https://wiki.libsdl.org/SDL_DestroyAudioStream
  804. * \sa https://wiki.libsdl.org/SDL_PutAudioStreamData
  805. * \sa https://wiki.libsdl.org/SDL_FlushAudioStream
  806. * \sa https://wiki.libsdl.org/SDL_GetAudioStreamData
  807. */
  808. static int audio_resampleLoss(void *arg)
  809. {
  810. /* Note: always test long input time (>= 5s from experience) in some test
  811. * cases because an improper implementation may suffer from low resampling
  812. * precision with long input due to e.g. doing subtraction with large floats. */
  813. struct test_spec_t {
  814. int time;
  815. int freq;
  816. double phase;
  817. int rate_in;
  818. int rate_out;
  819. double signal_to_noise;
  820. double max_error;
  821. } test_specs[] = {
  822. { 50, 440, 0, 44100, 48000, 80, 0.0010 },
  823. { 50, 5000, SDL_PI_D / 2, 20000, 10000, 999, 0.0001 },
  824. { 50, 440, 0, 22050, 96000, 79, 0.0120 },
  825. { 50, 440, 0, 96000, 22050, 80, 0.0002 },
  826. { 0 }
  827. };
  828. int spec_idx = 0;
  829. int min_channels = 1;
  830. int max_channels = 1 /*8*/;
  831. int num_channels = min_channels;
  832. for (spec_idx = 0; test_specs[spec_idx].time > 0;) {
  833. const struct test_spec_t *spec = &test_specs[spec_idx];
  834. const int frames_in = spec->time * spec->rate_in;
  835. const int frames_target = spec->time * spec->rate_out;
  836. const int len_in = (frames_in * num_channels) * (int)sizeof(float);
  837. const int len_target = (frames_target * num_channels) * (int)sizeof(float);
  838. SDL_AudioSpec tmpspec1, tmpspec2;
  839. Uint64 tick_beg = 0;
  840. Uint64 tick_end = 0;
  841. int i = 0;
  842. int j = 0;
  843. SDL_AudioStream *stream = NULL;
  844. float *buf_in = NULL;
  845. float *buf_out = NULL;
  846. int len_out = 0;
  847. double max_error = 0;
  848. double sum_squared_error = 0;
  849. double sum_squared_value = 0;
  850. double signal_to_noise = 0;
  851. SDLTest_AssertPass("Test resampling of %i s %i Hz %f phase sine wave from sampling rate of %i Hz to %i Hz",
  852. spec->time, spec->freq, spec->phase, spec->rate_in, spec->rate_out);
  853. tmpspec1.format = SDL_AUDIO_F32;
  854. tmpspec1.channels = num_channels;
  855. tmpspec1.freq = spec->rate_in;
  856. tmpspec2.format = SDL_AUDIO_F32;
  857. tmpspec2.channels = num_channels;
  858. tmpspec2.freq = spec->rate_out;
  859. stream = SDL_CreateAudioStream(&tmpspec1, &tmpspec2);
  860. SDLTest_AssertPass("Call to SDL_CreateAudioStream(SDL_AUDIO_F32, %i, %i, SDL_AUDIO_F32, %i, %i)", num_channels, spec->rate_in, num_channels, spec->rate_out);
  861. SDLTest_AssertCheck(stream != NULL, "Expected SDL_CreateAudioStream to succeed.");
  862. if (stream == NULL) {
  863. return TEST_ABORTED;
  864. }
  865. buf_in = (float *)SDL_malloc(len_in);
  866. SDLTest_AssertCheck(buf_in != NULL, "Expected input buffer to be created.");
  867. if (buf_in == NULL) {
  868. SDL_DestroyAudioStream(stream);
  869. return TEST_ABORTED;
  870. }
  871. for (i = 0; i < frames_in; ++i) {
  872. float f = (float)sine_wave_sample(i, spec->rate_in, spec->freq, spec->phase);
  873. for (j = 0; j < num_channels; ++j) {
  874. *(buf_in + (i * num_channels) + j) = f;
  875. }
  876. }
  877. tick_beg = SDL_GetPerformanceCounter();
  878. buf_out = (float *)SDL_malloc(len_target);
  879. SDLTest_AssertCheck(buf_out != NULL, "Expected output buffer to be created.");
  880. if (buf_out == NULL) {
  881. SDL_DestroyAudioStream(stream);
  882. return TEST_ABORTED;
  883. }
  884. len_out = convert_audio_chunks(stream, buf_in, len_in, buf_out, len_target);
  885. SDLTest_AssertPass("Call to convert_audio_chunks(stream, buf_in, %i, buf_out, %i)", len_in, len_target);
  886. SDLTest_AssertCheck(len_out == len_target, "Expected output length to be %i, got %i.",
  887. len_target, len_out);
  888. SDL_free(buf_in);
  889. if (len_out != len_target) {
  890. SDL_DestroyAudioStream(stream);
  891. return TEST_ABORTED;
  892. }
  893. tick_end = SDL_GetPerformanceCounter();
  894. SDLTest_Log("Resampling used %f seconds.", ((double)(tick_end - tick_beg)) / SDL_GetPerformanceFrequency());
  895. for (i = 0; i < frames_target; ++i) {
  896. const double target = sine_wave_sample(i, spec->rate_out, spec->freq, spec->phase);
  897. for (j = 0; j < num_channels; ++j) {
  898. const float output = *(buf_out + (i * num_channels) + j);
  899. const double error = SDL_fabs(target - output);
  900. max_error = SDL_max(max_error, error);
  901. sum_squared_error += error * error;
  902. sum_squared_value += target * target;
  903. }
  904. }
  905. SDL_free(buf_out);
  906. signal_to_noise = 10 * SDL_log10(sum_squared_value / sum_squared_error); /* decibel */
  907. SDLTest_AssertCheck(ISFINITE(sum_squared_value), "Sum of squared target should be finite.");
  908. SDLTest_AssertCheck(ISFINITE(sum_squared_error), "Sum of squared error should be finite.");
  909. /* Infinity is theoretically possible when there is very little to no noise */
  910. SDLTest_AssertCheck(!ISNAN(signal_to_noise), "Signal-to-noise ratio should not be NaN.");
  911. SDLTest_AssertCheck(ISFINITE(max_error), "Maximum conversion error should be finite.");
  912. SDLTest_AssertCheck(signal_to_noise >= spec->signal_to_noise, "Conversion signal-to-noise ratio %f dB should be no less than %f dB.",
  913. signal_to_noise, spec->signal_to_noise);
  914. SDLTest_AssertCheck(max_error <= spec->max_error, "Maximum conversion error %f should be no more than %f.",
  915. max_error, spec->max_error);
  916. if (++num_channels > max_channels) {
  917. num_channels = min_channels;
  918. ++spec_idx;
  919. }
  920. }
  921. return TEST_COMPLETED;
  922. }
  923. /**
  924. * Check accuracy converting between audio formats.
  925. *
  926. * \sa SDL_ConvertAudioSamples
  927. */
  928. static int audio_convertAccuracy(void *arg)
  929. {
  930. static SDL_AudioFormat formats[] = { SDL_AUDIO_S8, SDL_AUDIO_U8, SDL_AUDIO_S16, SDL_AUDIO_S32 };
  931. static const char* format_names[] = { "S8", "U8", "S16", "S32" };
  932. int src_num = 65537 + 2048 + 48 + 256 + 100000;
  933. int src_len = src_num * sizeof(float);
  934. float* src_data = SDL_malloc(src_len);
  935. int i, j;
  936. SDLTest_AssertCheck(src_data != NULL, "Expected source buffer to be created.");
  937. if (src_data == NULL) {
  938. return TEST_ABORTED;
  939. }
  940. j = 0;
  941. /* Generate a uniform range of floats between [-1.0, 1.0] */
  942. for (i = 0; i < 65537; ++i) {
  943. src_data[j++] = ((float)i - 32768.0f) / 32768.0f;
  944. }
  945. /* Generate floats close to 1.0 */
  946. const float max_val = 16777216.0f;
  947. for (i = 0; i < 1024; ++i) {
  948. float f = (max_val + (float)(512 - i)) / max_val;
  949. src_data[j++] = f;
  950. src_data[j++] = -f;
  951. }
  952. for (i = 0; i < 24; ++i) {
  953. float f = (max_val + (float)(3u << i)) / max_val;
  954. src_data[j++] = f;
  955. src_data[j++] = -f;
  956. }
  957. /* Generate floats far outside the [-1.0, 1.0] range */
  958. for (i = 0; i < 128; ++i) {
  959. float f = 2.0f + (float) i;
  960. src_data[j++] = f;
  961. src_data[j++] = -f;
  962. }
  963. /* Fill the rest with random floats between [-1.0, 1.0] */
  964. for (i = 0; i < 100000; ++i) {
  965. src_data[j++] = SDLTest_RandomSint32() / 2147483648.0f;
  966. }
  967. /* Shuffle the data for good measure */
  968. for (i = src_num - 1; i > 0; --i) {
  969. float f = src_data[i];
  970. j = SDLTest_RandomIntegerInRange(0, i);
  971. src_data[i] = src_data[j];
  972. src_data[j] = f;
  973. }
  974. for (i = 0; i < SDL_arraysize(formats); ++i) {
  975. SDL_AudioSpec src_spec, tmp_spec;
  976. Uint64 convert_begin, convert_end;
  977. Uint8 *tmp_data, *dst_data;
  978. int tmp_len, dst_len;
  979. int ret;
  980. SDL_AudioFormat format = formats[i];
  981. const char* format_name = format_names[i];
  982. /* Formats with > 23 bits can represent every value exactly */
  983. float min_delta = 1.0f;
  984. float max_delta = -1.0f;
  985. /* Subtract 1 bit to account for sign */
  986. int bits = SDL_AUDIO_BITSIZE(format) - 1;
  987. float target_max_delta = (bits > 23) ? 0.0f : (1.0f / (float)(1 << bits));
  988. float target_min_delta = -target_max_delta;
  989. src_spec.format = SDL_AUDIO_F32;
  990. src_spec.channels = 1;
  991. src_spec.freq = 44100;
  992. tmp_spec.format = format;
  993. tmp_spec.channels = 1;
  994. tmp_spec.freq = 44100;
  995. convert_begin = SDL_GetPerformanceCounter();
  996. tmp_data = NULL;
  997. tmp_len = 0;
  998. ret = SDL_ConvertAudioSamples(&src_spec, (const Uint8*) src_data, src_len, &tmp_spec, &tmp_data, &tmp_len);
  999. SDLTest_AssertCheck(ret == 0, "Expected SDL_ConvertAudioSamples(F32->%s) to succeed", format_name);
  1000. if (ret != 0) {
  1001. SDL_free(src_data);
  1002. return TEST_ABORTED;
  1003. }
  1004. dst_data = NULL;
  1005. dst_len = 0;
  1006. ret = SDL_ConvertAudioSamples(&tmp_spec, tmp_data, tmp_len, &src_spec, &dst_data, &dst_len);
  1007. SDLTest_AssertCheck(ret == 0, "Expected SDL_ConvertAudioSamples(%s->F32) to succeed", format_name);
  1008. if (ret != 0) {
  1009. SDL_free(tmp_data);
  1010. SDL_free(src_data);
  1011. return TEST_ABORTED;
  1012. }
  1013. convert_end = SDL_GetPerformanceCounter();
  1014. SDLTest_Log("Conversion via %s took %f seconds.", format_name, ((double)(convert_end - convert_begin)) / SDL_GetPerformanceFrequency());
  1015. SDL_free(tmp_data);
  1016. for (j = 0; j < src_num; ++j) {
  1017. float x = src_data[j];
  1018. float y = ((float*)dst_data)[j];
  1019. float d = SDL_clamp(x, -1.0f, 1.0f) - y;
  1020. min_delta = SDL_min(min_delta, d);
  1021. max_delta = SDL_max(max_delta, d);
  1022. }
  1023. SDLTest_AssertCheck(min_delta >= target_min_delta, "%s has min delta of %+f, should be >= %+f", format_name, min_delta, target_min_delta);
  1024. SDLTest_AssertCheck(max_delta <= target_max_delta, "%s has max delta of %+f, should be <= %+f", format_name, max_delta, target_max_delta);
  1025. SDL_free(dst_data);
  1026. }
  1027. SDL_free(src_data);
  1028. return TEST_COMPLETED;
  1029. }
  1030. /**
  1031. * Check accuracy when switching between formats
  1032. *
  1033. * \sa SDL_SetAudioStreamFormat
  1034. */
  1035. static int audio_formatChange(void *arg)
  1036. {
  1037. int i;
  1038. SDL_AudioSpec spec1, spec2, spec3;
  1039. int frames_1, frames_2, frames_3;
  1040. int length_1, length_2, length_3;
  1041. int retval = 0;
  1042. int status = TEST_ABORTED;
  1043. float* buffer_1 = NULL;
  1044. float* buffer_2 = NULL;
  1045. float* buffer_3 = NULL;
  1046. SDL_AudioStream* stream = NULL;
  1047. double max_error = 0;
  1048. double sum_squared_error = 0;
  1049. double sum_squared_value = 0;
  1050. double signal_to_noise = 0;
  1051. double target_max_error = 0.02;
  1052. double target_signal_to_noise = 75.0;
  1053. int sine_freq = 500;
  1054. spec1.format = SDL_AUDIO_F32;
  1055. spec1.channels = 1;
  1056. spec1.freq = 20000;
  1057. spec2.format = SDL_AUDIO_F32;
  1058. spec2.channels = 1;
  1059. spec2.freq = 40000;
  1060. spec3.format = SDL_AUDIO_F32;
  1061. spec3.channels = 1;
  1062. spec3.freq = 80000;
  1063. frames_1 = spec1.freq;
  1064. frames_2 = spec2.freq;
  1065. frames_3 = spec3.freq * 2;
  1066. length_1 = (int)(frames_1 * sizeof(*buffer_1));
  1067. buffer_1 = (float*) SDL_malloc(length_1);
  1068. if (!SDLTest_AssertCheck(buffer_1 != NULL, "Expected buffer_1 to be created.")) {
  1069. goto cleanup;
  1070. }
  1071. length_2 = (int)(frames_2 * sizeof(*buffer_2));
  1072. buffer_2 = (float*) SDL_malloc(length_2);
  1073. if (!SDLTest_AssertCheck(buffer_2 != NULL, "Expected buffer_2 to be created.")) {
  1074. goto cleanup;
  1075. }
  1076. length_3 = (int)(frames_3 * sizeof(*buffer_3));
  1077. buffer_3 = (float*) SDL_malloc(length_3);
  1078. if (!SDLTest_AssertCheck(buffer_3 != NULL, "Expected buffer_3 to be created.")) {
  1079. goto cleanup;
  1080. }
  1081. for (i = 0; i < frames_1; ++i) {
  1082. buffer_1[i] = (float) sine_wave_sample(i, spec1.freq, sine_freq, 0.0f);
  1083. }
  1084. for (i = 0; i < frames_2; ++i) {
  1085. buffer_2[i] = (float) sine_wave_sample(i, spec2.freq, sine_freq, 0.0f);
  1086. }
  1087. stream = SDL_CreateAudioStream(NULL, NULL);
  1088. if (!SDLTest_AssertCheck(stream != NULL, "Expected SDL_CreateAudioStream to succeed")) {
  1089. goto cleanup;
  1090. }
  1091. retval = SDL_SetAudioStreamFormat(stream, &spec1, &spec3);
  1092. if (!SDLTest_AssertCheck(retval == 0, "Expected SDL_SetAudioStreamFormat(spec1, spec3) to succeed")) {
  1093. goto cleanup;
  1094. }
  1095. retval = SDL_GetAudioStreamAvailable(stream);
  1096. if (!SDLTest_AssertCheck(retval == 0, "Expected SDL_GetAudioStreamAvailable return 0")) {
  1097. goto cleanup;
  1098. }
  1099. retval = SDL_PutAudioStreamData(stream, buffer_1, length_1);
  1100. if (!SDLTest_AssertCheck(retval == 0, "Expected SDL_PutAudioStreamData(buffer_1) to succeed")) {
  1101. goto cleanup;
  1102. }
  1103. retval = SDL_FlushAudioStream(stream);
  1104. if (!SDLTest_AssertCheck(retval == 0, "Expected SDL_FlushAudioStream to succeed")) {
  1105. goto cleanup;
  1106. }
  1107. retval = SDL_SetAudioStreamFormat(stream, &spec2, &spec3);
  1108. if (!SDLTest_AssertCheck(retval == 0, "Expected SDL_SetAudioStreamFormat(spec2, spec3) to succeed")) {
  1109. goto cleanup;
  1110. }
  1111. retval = SDL_PutAudioStreamData(stream, buffer_2, length_2);
  1112. if (!SDLTest_AssertCheck(retval == 0, "Expected SDL_PutAudioStreamData(buffer_1) to succeed")) {
  1113. goto cleanup;
  1114. }
  1115. retval = SDL_FlushAudioStream(stream);
  1116. if (!SDLTest_AssertCheck(retval == 0, "Expected SDL_FlushAudioStream to succeed")) {
  1117. goto cleanup;
  1118. }
  1119. retval = SDL_GetAudioStreamAvailable(stream);
  1120. if (!SDLTest_AssertCheck(retval == length_3, "Expected SDL_GetAudioStreamAvailable to return %i, got %i", length_3, retval)) {
  1121. goto cleanup;
  1122. }
  1123. retval = SDL_GetAudioStreamData(stream, buffer_3, length_3);
  1124. if (!SDLTest_AssertCheck(retval == length_3, "Expected SDL_GetAudioStreamData to return %i, got %i", length_3, retval)) {
  1125. goto cleanup;
  1126. }
  1127. retval = SDL_GetAudioStreamAvailable(stream);
  1128. if (!SDLTest_AssertCheck(retval == 0, "Expected SDL_GetAudioStreamAvailable to return 0")) {
  1129. goto cleanup;
  1130. }
  1131. for (i = 0; i < frames_3; ++i) {
  1132. const float output = buffer_3[i];
  1133. const float target = (float) sine_wave_sample(i, spec3.freq, sine_freq, 0.0f);
  1134. const double error = SDL_fabs(target - output);
  1135. max_error = SDL_max(max_error, error);
  1136. sum_squared_error += error * error;
  1137. sum_squared_value += target * target;
  1138. }
  1139. signal_to_noise = 10 * SDL_log10(sum_squared_value / sum_squared_error); /* decibel */
  1140. SDLTest_AssertCheck(ISFINITE(sum_squared_value), "Sum of squared target should be finite.");
  1141. SDLTest_AssertCheck(ISFINITE(sum_squared_error), "Sum of squared error should be finite.");
  1142. /* Infinity is theoretically possible when there is very little to no noise */
  1143. SDLTest_AssertCheck(!ISNAN(signal_to_noise), "Signal-to-noise ratio should not be NaN.");
  1144. SDLTest_AssertCheck(ISFINITE(max_error), "Maximum conversion error should be finite.");
  1145. SDLTest_AssertCheck(signal_to_noise >= target_signal_to_noise, "Conversion signal-to-noise ratio %f dB should be no less than %f dB.",
  1146. signal_to_noise, target_signal_to_noise);
  1147. SDLTest_AssertCheck(max_error <= target_max_error, "Maximum conversion error %f should be no more than %f.",
  1148. max_error, target_max_error);
  1149. status = TEST_COMPLETED;
  1150. cleanup:
  1151. SDL_free(buffer_1);
  1152. SDL_free(buffer_2);
  1153. SDL_free(buffer_3);
  1154. SDL_DestroyAudioStream(stream);
  1155. return status;
  1156. }
  1157. /* ================= Test Case References ================== */
  1158. /* Audio test cases */
  1159. static const SDLTest_TestCaseReference audioTest1 = {
  1160. audio_enumerateAndNameAudioDevices, "audio_enumerateAndNameAudioDevices", "Enumerate and name available audio devices (playback and recording)", TEST_ENABLED
  1161. };
  1162. static const SDLTest_TestCaseReference audioTest2 = {
  1163. audio_enumerateAndNameAudioDevicesNegativeTests, "audio_enumerateAndNameAudioDevicesNegativeTests", "Negative tests around enumeration and naming of audio devices.", TEST_ENABLED
  1164. };
  1165. static const SDLTest_TestCaseReference audioTest3 = {
  1166. audio_printAudioDrivers, "audio_printAudioDrivers", "Checks available audio driver names.", TEST_ENABLED
  1167. };
  1168. static const SDLTest_TestCaseReference audioTest4 = {
  1169. audio_printCurrentAudioDriver, "audio_printCurrentAudioDriver", "Checks current audio driver name with initialized audio.", TEST_ENABLED
  1170. };
  1171. static const SDLTest_TestCaseReference audioTest5 = {
  1172. audio_buildAudioStream, "audio_buildAudioStream", "Builds various audio conversion structures.", TEST_ENABLED
  1173. };
  1174. static const SDLTest_TestCaseReference audioTest6 = {
  1175. audio_buildAudioStreamNegative, "audio_buildAudioStreamNegative", "Checks calls with invalid input to SDL_CreateAudioStream", TEST_ENABLED
  1176. };
  1177. static const SDLTest_TestCaseReference audioTest7 = {
  1178. audio_getAudioStatus, "audio_getAudioStatus", "Checks current audio status.", TEST_ENABLED
  1179. };
  1180. static const SDLTest_TestCaseReference audioTest8 = {
  1181. audio_openCloseAndGetAudioStatus, "audio_openCloseAndGetAudioStatus", "Opens and closes audio device and get audio status.", TEST_ENABLED
  1182. };
  1183. static const SDLTest_TestCaseReference audioTest9 = {
  1184. audio_lockUnlockOpenAudioDevice, "audio_lockUnlockOpenAudioDevice", "Locks and unlocks an open audio device.", TEST_ENABLED
  1185. };
  1186. static const SDLTest_TestCaseReference audioTest10 = {
  1187. audio_convertAudio, "audio_convertAudio", "Convert audio using available formats.", TEST_ENABLED
  1188. };
  1189. /* TODO: enable test when SDL_AudioDeviceConnected has been implemented. */
  1190. static const SDLTest_TestCaseReference audioTest11 = {
  1191. audio_openCloseAudioDeviceConnected, "audio_openCloseAudioDeviceConnected", "Opens and closes audio device and get connected status.", TEST_DISABLED
  1192. };
  1193. static const SDLTest_TestCaseReference audioTest12 = {
  1194. audio_quitInitAudioSubSystem, "audio_quitInitAudioSubSystem", "Quit and re-init audio subsystem.", TEST_ENABLED
  1195. };
  1196. static const SDLTest_TestCaseReference audioTest13 = {
  1197. audio_initQuitAudio, "audio_initQuitAudio", "Init and quit audio drivers directly.", TEST_ENABLED
  1198. };
  1199. static const SDLTest_TestCaseReference audioTest14 = {
  1200. audio_initOpenCloseQuitAudio, "audio_initOpenCloseQuitAudio", "Cycle through init, open, close and quit with various audio specs.", TEST_ENABLED
  1201. };
  1202. static const SDLTest_TestCaseReference audioTest15 = {
  1203. audio_pauseUnpauseAudio, "audio_pauseUnpauseAudio", "Pause and Unpause audio for various audio specs while testing callback.", TEST_ENABLED
  1204. };
  1205. static const SDLTest_TestCaseReference audioTest16 = {
  1206. audio_resampleLoss, "audio_resampleLoss", "Check signal-to-noise ratio and maximum error of audio resampling.", TEST_ENABLED
  1207. };
  1208. static const SDLTest_TestCaseReference audioTest17 = {
  1209. audio_convertAccuracy, "audio_convertAccuracy", "Check accuracy converting between audio formats.", TEST_ENABLED
  1210. };
  1211. static const SDLTest_TestCaseReference audioTest18 = {
  1212. audio_formatChange, "audio_formatChange", "Check handling of format changes.", TEST_ENABLED
  1213. };
  1214. /* Sequence of Audio test cases */
  1215. static const SDLTest_TestCaseReference *audioTests[] = {
  1216. &audioTest1, &audioTest2, &audioTest3, &audioTest4, &audioTest5, &audioTest6,
  1217. &audioTest7, &audioTest8, &audioTest9, &audioTest10, &audioTest11,
  1218. &audioTest12, &audioTest13, &audioTest14, &audioTest15, &audioTest16,
  1219. &audioTest17, &audioTest18, NULL
  1220. };
  1221. /* Audio test suite (global) */
  1222. SDLTest_TestSuiteReference audioTestSuite = {
  1223. "Audio",
  1224. audioSetUp,
  1225. audioTests,
  1226. audioTearDown
  1227. };