testautomation_audio.c 49 KB

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