testautomation_audio.c 49 KB

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