testautomation_audio.c 48 KB

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