testautomation_audio.c 52 KB

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