tomato/test/testautomation_audio.c
Green Sky 644725478f Squashed 'external/sdl/SDL/' changes from ec0042081..399bc709b
399bc709b build-scripts.pl: Added add-source-to-projects.pl
ac6827187 Visual-WinRT: dos2unix the project files to match other Visual Studio targets.
34719cba9 Fixed crash in hid_init() if the HIDDeviceManager isn't available
2e92e94eb Make sure we update device->sample_frames in SDL_AudioDeviceFormatChangedAlreadyLocked()
9964e5c5b wayland: Don't retrieve the drag offer strings with every pointer motion event
bac7eeaaa Added missing include
a541e2ac1 audio: Change a few SDL_memcpy calls to SDL_copyp.
54125c140 audio: Only update bound audiostreams' formats when necessary.
e0b0f9a36 testaudio: Fix mouseover testing.
2f3deec24 wayland: Don't process drag & drop events from surfaces not owned by SDL
42bdced05 events: Log file drop position events and print the pointer coordinates
c10d93d3a wayland: Replace magic constant with define
500852153 emscripten: Restore compatibility with existing emsdk releases.
953b55dd6 Use EM_ASM_PTR when the return value is a pointer
a4541a255 audio: SDL_GetAudioStreamQueued now returns bytes, not frames.
703aefbce Sync SDL3 wiki -> header
99421b64d linux: Add portal drag and drop
952c5059b Remove stray Â
eebd5d18a linux: Handle upower's UP_DEVICE_STATE_PENDING_CHARGE, PENDING_DISCHARGE
f8fdb20d8 audio: Destroy all existing SDL_AudioStreams on shutdown.
62d445997 audio: Removed declarations of functions that don't exist anymore.
b656720bc loopwave: Use SDL_GetAudioStreamQueued() for more accurate results.
34b931f7e audio: Added SDL_GetAudioStreamQueued
23206b9e3 audio: Added SDL_EVENT_AUDIO_DEVICE_FORMAT_CHANGED
c7e6d7a1f audio: Changed debug logging output.
87ec6acf2 audio: Added a FIXME
ac88ffb7e audio: don't allocate buffer in SDL_SetAudioPostmixCallback for NULL callback.
2a950f6ae audio: Replace some SDL_memcpy calls with SDL_copyp.
0dc0434a3 audio: Fixed race condition in subsystem shutdown.
23f60203a audio: precalculate if we can use simple copies instead of the full mixer.
36b0f1141 audio: Optimize setting device formats during audio thread iteration.
4c3e84897 testspriteminimal: make standalone by embedding icon.bmp
2a01f9dcb tests: plug leaks when running with --trackmem
f42bbeca2 SDL_test: track stack frames of allocations on Windows
12c0be028 SDL_test: clear text cache on exit event
b4bfb1831 SDL_test: free state before logging allocations
248b1edd3 SDL_test: destroy windows in SDL_CommonQuit
98da2dd30 SDL_test: don't warn about expected allocations when running with --trackmem
6a381567b Support audio rate conversion up to 384KHz
b2b548a1f Don't hang if IAudioRenderClient_GetBuffer() fails indefinitely
a3a5e1728 Fixed build warning '=': conversion from 'Uint32' to 'Uint16', possible loss of data
6d3e21c27 Fixed android build warnings
fca2f5318 Fixed warning: this function declaration is not a prototype
a72dfa6a5 Fixed sensor timestamp units for third-party PS5 controllers
f6756047a Fixed error: array subscript 2 is above array bounds of ‘const Uint8[2]’
7059a55cc Fixed sensor timestamp calculation for third-party PS5 controllers
c0443e5d1 Fixed crash in SDL_IMMDevice_FindByDevID()
fde8499f6 Use around 20ms for the audio buffer size
e5739d7d1 video: Remove SDL_GetFocusWindow()
39c2f9737 Fix NULL dereference in SDL_OpenAudio
9a23d0e3f Added new audio files to the Xcode project
a62e62f97 Refactored SDL_audiocvt.c
31229fd47 include: Added a note about SDL's iOS app delegate functions.
65aaf3a9a x11: Always update clipboard owner
f622f21e6 Fixed build
5774c9638 Prefer hidraw over libusb when libusb whitelisting is not enabled
9301f7ace hidapi/libusb: only enumerate each interface once
859dc14ad Replaced SDL_GetGamepadBindForAxis() and SDL_GetGamepadBindForButton() with SDL_GetGamepadBindings()
9e50048ab Revert "Removed SDL_GamepadBinding from the API"
9f17d1a9d Don't reference the same function in "see also"
86505ea63 fix SDL_AudioStreamCallback documentation
d885d5c31 Sync SDL3 wiki -> header
2f43f7bc5 audio: Allow querying of device buffer size.
cf9572113 audio: Added a hint to let apps force device buffer size.
47d8c77c6 audio: Choose better default sample frame counts.
8b26e95f9 audio: Change SDL_AudioStreamCallback
9da34e8fb docs: Updated README-emscripten.md.
fd1c54a00 detect fanatec steering wheels
cb4414608 docs: Whoops, this got added by the wiki bridge by accident!
cd633b9a8 Renamed SDL_IsAudioDevicePaused() to SDL_AudioDevicePaused()
c6cad07fa Sync SDL3 wiki -> header
a6e52f9e4 Sync SDL3 wiki -> header
2de2e9d03 Fix flickering of window when using desktop-fullscreen and borderless window on multiple monitors on Linux.  Closes #8186.
723835d16 Windows: fix for client rect resizing larger each time we came from exclusive fullscreen -> windowed on a monitor with HiDPI set.  The problem was we were using the monitor DPI rather than the window DPI so AdjustWindowRectExForDpi was giving us an incorrect size which would be too large for the client rect.  Closes #8237.
ce27363df wikiheaders: Sort undocumented functions.
e22282b09 Added README about transparent windows in Win32
1d1c6e630 Turn off COREAUDIO debug logging by default
52efefca0 wayland: Fix drag offer leak
3a992af44 audio: Added a postmix callback to logical devices.
7207bdce5 render: Enable clipping for zero-sized rectangles
22d81fb3e cmake: use MSVC_RUNTIME_LIBRARY to force MT
a2e17852d cmake: make sure SDL_GetPrefPath is run before testfilesystem
2fb266e0a ci: run tests in parallel
ad1313e75 testaudio: Patched to compile.
5747ddc01 testaudio: Clean up some messy memory management.
fafbea1ce audio: Move internal float32 mixing to a simplified function
116b0ec97 include: minor tweak to audio API documentation
fb1377035 include: Replaced old Bugzilla URL.
38c8fc05c audio: Remove ChooseMixStrategy.
b00cbd76a wikiheaders.pl: create Unsupported.md file with list of functions undocumented in either the headers or the wiki
37e1fc3b5 wayland: Ensure that the toplevel window is recreated when switching decoration modes
f2ca9a615 Added SDL_AUDIO_FRAMESIZE
53122593f Added SDL_AUDIO_BYTESIZE
544351c98 Sync SDL3 wiki -> header
2e7d2b94e Clarify that SDL_BlitSurface() ignores the width and height in dstrect
a2c1984d3 Detect Simagic wheel bases as wheels (#8198)
1d8dfbb22 avoid type redefinition errors after PR/8181
266b91d2f Detect Logitech G923 Playstation as wheel G923 have two different versions - Xbox version is already present in the wheel list, but not the PS version.
cde67ea49 Detect Logitech PRO Racing Wheel for Xbox (PC mode) as wheel Logitech PRO Racing Wheel have two different versions - for Playstation and Xbox. Vendor + Product ID for Playstation version already present in SDL sources, but not an Xbox version
3a932141e Restore audio format binary compatibility with SDL 2.0
e85206ffd wikiheaders.pl: add --rev= option to pass revision string
233789b0d Audio types have the same naming convention as other SDL endian types, e.g. [S|U][BITS][LE|BE]
36b5f3e35 Sync SDL3 wiki -> header
0e552761b Renamed AudioStreamSpeed to AudioStreamFrequencyRatio
47bcb078f Fixed some incorrect SDL_AUDIO_F32 uses
2833f2e7b Fixed OOB access in audio_convertAccuracy test
8387fae69 Sync SDL3 wiki -> header
832181345 docs: Add note about Wayland application icons
825d34475 Make sure that the same timestamp is used for all PS5 events from the same packet
9c1430324 Removed SDL_dataqueue
28b28bd8f Added audio_formatChange test
a59152688 Try and avoid overflow when handling very large audio streams
5394a805f Improved testaudiostreamdynamicresample
e55844274 Added SDL_(Get|Set)AudioStreamSpeed
43c3c5736 Track the formats of data in an SDL_AudioStream
337fed3df Tweaked ResampleFrame_SSE Use _mm_unpack(lo|hi)_ps instead of _mm_shuffle_ps
fd7cd91dc audio: Mix multiple streams in float32 to prevent clipping.
9097573e3 audio: Choose a mixing strategy on each iteration.
bbe2e012a Don't provide the SDL3 header path
c17a35f09 Fixed typo
4f72255eb Fixed README.md link
e0ab59754 Simplified SDL_main.h migration notes
d44bde61e Added SDL migration information to the top level README.md
6ff31e10c metal: Add hint to select low power device instead of the default one (#8182)
8a8aed477 Make sure that we process touch events that position the mouse
f84c87f20 Sync SDL3 wiki -> header
a7eea9997 macOS: Don't raise the parent top-level window when raising a child window, only raise the child window to the top of the parent
a5e721479 Add SDL_WINDOW_NOT_FOCUSABLE flag to set that the window should not be able to gain key focus
b385dc3b6 n3dsaudio: Patched to compile.
4e0c7c91f audio: PlayDevice() should return an error code.
a94d724f1 wayland: add SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_EGL
da5d93d3d wayland: don't define SDL_VIDEO_DRIVER_WAYLAND_DYNAMIC_* macro's
f002f7d12 ci: build emscripten with Debug buid type
3699b12ed audio: Fixed some "is_*" variables to be cleaner and/or more specific.
2471d8cc2 audio: Fixed logic error in SDL_OpenAudioDeviceStream.
1b03a2430 testsurround: fix order of arguments of callback
82db2b58f Renamed audio stream callback and moved the userdata parameter first
5bdad5210 Sync SDL3 wiki -> header
58c859f64 audio: Rename SDL_GetAudioStreamBinding to SDL_GetAudioStreamDevice.
efd2023a7 audio: Fixed documentation.
1e775e0ee audio: Replace SDL_CreateAndBindAudioStream with SDL_OpenAudioDeviceStream.
bd088c2f9 Revert "Clarify whether an audio function expects a physical or logical device ID"
82e481b52 Added --randmem test parameter
ea68bb802 Add some additional checks to audio_convertAudio
f8286df16 Fixed ResampleFrame_SSE doing unnecessary work
b1d63be53 Fixed audio_resampleLoss test
c191d6c30 Better Win32 transparent window support
923d612ca hidapi: sync macOS code with mainstream.
363f4fa9c avoid type redefinition errors after commit ee806597b9.
615824a80 Updated documentation now that SDL_GetAudioDevices() has been split into separate functions for output and capture devices
506a133d8 Clarify whether an audio function expects a physical or logical device ID
3b1d1e4e3 hidapi: sync the hidraw changes with mainstream
f617918e0 cmake: check linkage to libusb too, instead of libusb.h presence only.
041dbd6b5 Fixed GetResamplerAvailableOutputFrames Non-euclidean division is a pain
b49d0a607 x11: Avoid including full Vulkan headers.
4d2f9f3a3 yuv_rgb: Comment out unused code.
3c3486e2a wayland: Don't include full Vulkan headers when not necessary.
f066bbe98 x11: Don't include system headers twice.
d86d02bbb updated dynapi after SDL_GDKGetDefaultUser addition
4355f9cec Fixed warning C4389: '!=': signed/unsigned mismatch
5755de07a Fixed build warnings
0f80d47bb Fixed thread-safety warning
ee806597b Removed SDL_vulkan_internal.h from SDL_sysvideo.h
34860b932 Fixed testautomation --filter pixels_allocFreeFormat
6f8a6a31c gdk: GetBasePath should be a UTF8 version of Win32 GetBasePath
e30e5c77e Sync SDL3 wiki -> header
c0cd8c814 gdk: Add SDL_GDKGetDefaultUser, SDL_GetPrefPath implementation
106abce69 Refactored GetAudioStreamDataInternal buffer handling The final conversion step should now always go straight into the output buffer.
e44f54ec5 Avoid using hex-floats
5b696996c Added ResampleFrame_SSE
958b3cfae Tweaked and enabled audio_convertAudio test
7dbb9b65b audio_convertAccuracy: Shuffle the data in case of a bad SIMD implementation
f6a4080ff audio_resampleLoss: Add support for multiple channels
4f894e748 audio_resampleLoss: SDL_GetAudioStreamData now returns the correct length
ab83f75bb Make sure GetAudioStreamDataInternal is called with a valid length
6a73f74b6 Rebuild full ResamplerFilter (left wing + right wing) at runtime
0c15ce006 Add a missing int cast
b74ee86b1 Optimized ResampleAudio, with special cases for 1 and 2 channels This would also benefit from some SIMD, since it's just a bunch of multiply-adds
fba6e1e3d Removed ResamplerFilterDifference It takes 1 extra multiply to calculate the correct interpolation, but I think the improvement in cache locality (and binary size) outweighs that.
9f7a22fa4 Removed 64-bit handling from AudioConvertByteswap
1f5327a9f Removed future_buffer, left_padding, and right_padding from SDL_AudioStream
71ad52d6d Lowered SDL_GetAudioStreamData to 32 KB No particular reason for this number, but 1 MB was a bit silly
69aec8c91 Fixed the report format for the Razer Wolverine V2 Pro
7c2669c9d Accept key events from any source
1e9d31448 Updated to Android minSdkVersion 19 and targetSdkVersion 34
8924d0d92 Added missing function prototype for SDL_WriteS64BE()
845f3c745 Fixed mismatch between stdlib calloc() and SDL free()
fb7921173 emscriptenaudio: Fire the capture silence_callback at an interval.
5191b2054 emscriptenaudio: Don't bother undefining things about to be unreachable.
fd75a4ca0 emscriptenaudio: Deal with blocked audio devices better.
981b8a337 emscriptenaudio: Remove unnecessary functions.
c7588e426 Transparent window for Win32 + OpenGL (#8143)
f9581178d cmake: fixed a typo.
e6c878824 Fixed ResampleAudio interpolation factor calculation
498363863 Misc audio tweaks/cleanup
72d9d53de Invert the inner ResampleAudio loops to avoid doing unnecessary work
88123a510 The history buffer should always have the maximum possible padding frames
96e47f165 Clamp results of GetResampler(AvailableOutput|NeededInput)Frames
d2b9c8b80 Fixed maths in testaudiostreamdynamicresample (and just show the actual scale)
14e38b17d Removed assertions from inner ResampleAudio loop
9d413dfdc The history buffer doesn't need to be so large
2788e848f Allow resampling less than 1 frame of input
383084e0a Pre-calculate resampling rate, and use it instead of .freq in most places
40a6a445c Update resample_offset inside ResampleAudio
47fea7f06 Used fixed-point arithmetic in ResampleAudio
7bb4e806e Clear resample_offset in SDL_ClearAudioStream, not SetAudioStreamFormat Not entirely sure if ClearAudioStream is the right place, but SetAudioStreamFormat was the wrong place
b9541b9ea Improved ResampleAudio * filterindex2 was off-by-one * Generate ResamplerFilter using doubles * Transpose ResamplerFilter to improve access patterns
cdaa19869 Track offset within the current sample when resampling
d60ebb06d mouse: Ensure that the dummy default cursor is removed from the cursor list
e58c2731f mouse: Free the default cursor when destroyed
789ce17e1 audio: Don't resample in chunks for now.
cbab33482 audio: Don't call SDL_AudioStream callbacks for empty data sets.
3e1ae0c86 Clearified the libusb whitelist default logic
f4520821e Removed some unnecessary integer casts
0989b7e86 Avoid using designated initializers
c6c1e673c Optimized SDL_Convert_*_to_*_Scalar
f97b920b3 Optimized SDL_Convert_*_to_*_SSE2 Some of the SDL_Convert_F32_to_*_SSE2 do not explicitly clamp the input, but instead rely on saturating casts. Inputs very far outside the valid [-1.0, 1.0] range may produce an incorrect result, but I believe that is an acceptable trade-off.
300d1ec3e Added audio_convertAccuracy test
32cecc2ea Fixed assertion in audio_convertAudio
33f11e21e Removed assertions in AudioConvert(To|From)Float
c2f388fd8 cmake: add SDL_HIDAPI_LIBUSB_SHARED option + test on ci
371cc2d17 wayland: Remove unnecessary flag and state settings
fe85e6e75 cocoa: Send a maximized event instead of restored if a deminiaturized window is zoomed
ddddcb78c cocoa: Use the close method to hide a miniaturized window
be8c42cfd Clarify that a window being 'hidden' means that it is unmapped/ordered out
a44338cbc Fix typo in SDL_audiocvt.c
f464eb2c5 SDL_hidapi.c: change 'use_libusb_whitelist_default' into a macro.
6607a3cfa Disable cache in python http server
181d5d285 hidapi: Enable libusb support by default.
f0f15e365 hidapi: Use a whitelist for libusb when other backends are available
c3f7a7dc4 Convert audio using SDL_AUDIO_F32SYS format instead of SDL_AUDIO_F32
796713b9d xxd.py: always write \n line endings
723bcd0a8 SDL_TriggerBreakppoint for riscv arch (both 32/64) version.

git-subtree-dir: external/sdl/SDL
git-subtree-split: 399bc709b7485bab57880f8261f826f29dc0d7b2
2023-09-23 18:45:49 +02:00

1337 lines
49 KiB
C

/**
* Original code: automated SDL audio test written by Edgar Simo "bobbens"
* New/updated tests: aschiffler at ferzkopp dot net
*/
/* quiet windows compiler warnings */
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <math.h>
#include <stdio.h>
#include <SDL3/SDL.h>
#include <SDL3/SDL_test.h>
#include "testautomation_suites.h"
/* ================= Test Case Implementation ================== */
/* Fixture */
static void audioSetUp(void *arg)
{
/* Start SDL audio subsystem */
int ret = SDL_InitSubSystem(SDL_INIT_AUDIO);
SDLTest_AssertPass("Call to SDL_InitSubSystem(SDL_INIT_AUDIO)");
SDLTest_AssertCheck(ret == 0, "Check result from SDL_InitSubSystem(SDL_INIT_AUDIO)");
if (ret != 0) {
SDLTest_LogError("%s", SDL_GetError());
}
}
static void audioTearDown(void *arg)
{
/* Remove a possibly created file from SDL disk writer audio driver; ignore errors */
(void)remove("sdlaudio.raw");
SDLTest_AssertPass("Cleanup of test files completed");
}
#if 0 /* !!! FIXME: maybe update this? */
/* Global counter for callback invocation */
static int g_audio_testCallbackCounter;
/* Global accumulator for total callback length */
static int g_audio_testCallbackLength;
/* Test callback function */
static void SDLCALL audio_testCallback(void *userdata, Uint8 *stream, int len)
{
/* track that callback was called */
g_audio_testCallbackCounter++;
g_audio_testCallbackLength += len;
}
#endif
static SDL_AudioDeviceID g_audio_id = -1;
/* Test case functions */
/**
* \brief Stop and restart audio subsystem
*
* \sa SDL_QuitSubSystem
* \sa SDL_InitSubSystem
*/
static int audio_quitInitAudioSubSystem(void *arg)
{
/* Stop SDL audio subsystem */
SDL_QuitSubSystem(SDL_INIT_AUDIO);
SDLTest_AssertPass("Call to SDL_QuitSubSystem(SDL_INIT_AUDIO)");
/* Restart audio again */
audioSetUp(NULL);
return TEST_COMPLETED;
}
/**
* \brief Start and stop audio directly
*
* \sa SDL_InitAudio
* \sa SDL_QuitAudio
*/
static int audio_initQuitAudio(void *arg)
{
int result;
int i, iMax;
const char *audioDriver;
/* Stop SDL audio subsystem */
SDL_QuitSubSystem(SDL_INIT_AUDIO);
SDLTest_AssertPass("Call to SDL_QuitSubSystem(SDL_INIT_AUDIO)");
/* Loop over all available audio drivers */
iMax = SDL_GetNumAudioDrivers();
SDLTest_AssertPass("Call to SDL_GetNumAudioDrivers()");
SDLTest_AssertCheck(iMax > 0, "Validate number of audio drivers; expected: >0 got: %d", iMax);
for (i = 0; i < iMax; i++) {
audioDriver = SDL_GetAudioDriver(i);
SDLTest_AssertPass("Call to SDL_GetAudioDriver(%d)", i);
SDLTest_Assert(audioDriver != NULL, "Audio driver name is not NULL");
SDLTest_AssertCheck(audioDriver[0] != '\0', "Audio driver name is not empty; got: %s", audioDriver); /* NOLINT(clang-analyzer-core.NullDereference): Checked for NULL above */
/* Call Init */
SDL_SetHint("SDL_AUDIO_DRIVER", audioDriver);
result = SDL_InitSubSystem(SDL_INIT_AUDIO);
SDLTest_AssertPass("Call to SDL_InitSubSystem(SDL_INIT_AUDIO) with driver='%s'", audioDriver);
SDLTest_AssertCheck(result == 0, "Validate result value; expected: 0 got: %d", result);
/* Call Quit */
SDL_QuitSubSystem(SDL_INIT_AUDIO);
SDLTest_AssertPass("Call to SDL_QuitSubSystem(SDL_INIT_AUDIO)");
}
/* NULL driver specification */
audioDriver = NULL;
/* Call Init */
SDL_SetHint("SDL_AUDIO_DRIVER", audioDriver);
result = SDL_InitSubSystem(SDL_INIT_AUDIO);
SDLTest_AssertPass("Call to SDL_AudioInit(NULL)");
SDLTest_AssertCheck(result == 0, "Validate result value; expected: 0 got: %d", result);
/* Call Quit */
SDL_QuitSubSystem(SDL_INIT_AUDIO);
SDLTest_AssertPass("Call to SDL_QuitSubSystem(SDL_INIT_AUDIO)");
/* Restart audio again */
audioSetUp(NULL);
return TEST_COMPLETED;
}
/**
* \brief Start, open, close and stop audio
*
* \sa SDL_InitAudio
* \sa SDL_OpenAudioDevice
* \sa SDL_CloseAudioDevice
* \sa SDL_QuitAudio
*/
static int audio_initOpenCloseQuitAudio(void *arg)
{
int result;
int i, iMax, j, k;
const char *audioDriver;
SDL_AudioSpec desired;
/* Stop SDL audio subsystem */
SDL_QuitSubSystem(SDL_INIT_AUDIO);
SDLTest_AssertPass("Call to SDL_QuitSubSystem(SDL_INIT_AUDIO)");
/* Loop over all available audio drivers */
iMax = SDL_GetNumAudioDrivers();
SDLTest_AssertPass("Call to SDL_GetNumAudioDrivers()");
SDLTest_AssertCheck(iMax > 0, "Validate number of audio drivers; expected: >0 got: %d", iMax);
for (i = 0; i < iMax; i++) {
audioDriver = SDL_GetAudioDriver(i);
SDLTest_AssertPass("Call to SDL_GetAudioDriver(%d)", i);
SDLTest_Assert(audioDriver != NULL, "Audio driver name is not NULL");
SDLTest_AssertCheck(audioDriver[0] != '\0', "Audio driver name is not empty; got: %s", audioDriver); /* NOLINT(clang-analyzer-core.NullDereference): Checked for NULL above */
/* Change specs */
for (j = 0; j < 2; j++) {
/* Call Init */
SDL_SetHint("SDL_AUDIO_DRIVER", audioDriver);
result = SDL_InitSubSystem(SDL_INIT_AUDIO);
SDLTest_AssertPass("Call to SDL_InitSubSystem(SDL_INIT_AUDIO) with driver='%s'", audioDriver);
SDLTest_AssertCheck(result == 0, "Validate result value; expected: 0 got: %d", result);
/* Set spec */
SDL_memset(&desired, 0, sizeof(desired));
switch (j) {
case 0:
/* Set standard desired spec */
desired.freq = 22050;
desired.format = SDL_AUDIO_S16;
desired.channels = 2;
case 1:
/* Set custom desired spec */
desired.freq = 48000;
desired.format = SDL_AUDIO_F32;
desired.channels = 2;
break;
}
/* Call Open (maybe multiple times) */
for (k = 0; k <= j; k++) {
result = SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_OUTPUT, &desired);
if (k == 0) {
g_audio_id = result;
}
SDLTest_AssertPass("Call to SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_OUTPUT, desired_spec_%d), call %d", j, k + 1);
SDLTest_AssertCheck(result > 0, "Verify return value; expected: > 0, got: %d", result);
}
/* Call Close (maybe multiple times) */
for (k = 0; k <= j; k++) {
SDL_CloseAudioDevice(g_audio_id);
SDLTest_AssertPass("Call to SDL_CloseAudioDevice(), call %d", k + 1);
}
/* Call Quit (maybe multiple times) */
for (k = 0; k <= j; k++) {
SDL_QuitSubSystem(SDL_INIT_AUDIO);
SDLTest_AssertPass("Call to SDL_QuitSubSystem(SDL_INIT_AUDIO), call %d", k + 1);
}
} /* spec loop */
} /* driver loop */
/* Restart audio again */
audioSetUp(NULL);
return TEST_COMPLETED;
}
/**
* \brief Pause and unpause audio
*
* \sa SDL_PauseAudioDevice
* \sa SDL_PlayAudioDevice
*/
static int audio_pauseUnpauseAudio(void *arg)
{
int iMax;
int i, j /*, k, l*/;
int result;
const char *audioDriver;
SDL_AudioSpec desired;
/* Stop SDL audio subsystem */
SDL_QuitSubSystem(SDL_INIT_AUDIO);
SDLTest_AssertPass("Call to SDL_QuitSubSystem(SDL_INIT_AUDIO)");
/* Loop over all available audio drivers */
iMax = SDL_GetNumAudioDrivers();
SDLTest_AssertPass("Call to SDL_GetNumAudioDrivers()");
SDLTest_AssertCheck(iMax > 0, "Validate number of audio drivers; expected: >0 got: %d", iMax);
for (i = 0; i < iMax; i++) {
audioDriver = SDL_GetAudioDriver(i);
SDLTest_AssertPass("Call to SDL_GetAudioDriver(%d)", i);
SDLTest_Assert(audioDriver != NULL, "Audio driver name is not NULL");
SDLTest_AssertCheck(audioDriver[0] != '\0', "Audio driver name is not empty; got: %s", audioDriver); /* NOLINT(clang-analyzer-core.NullDereference): Checked for NULL above */
/* Change specs */
for (j = 0; j < 2; j++) {
/* Call Init */
SDL_SetHint("SDL_AUDIO_DRIVER", audioDriver);
result = SDL_InitSubSystem(SDL_INIT_AUDIO);
SDLTest_AssertPass("Call to SDL_InitSubSystem(SDL_INIT_AUDIO) with driver='%s'", audioDriver);
SDLTest_AssertCheck(result == 0, "Validate result value; expected: 0 got: %d", result);
/* Set spec */
SDL_memset(&desired, 0, sizeof(desired));
switch (j) {
case 0:
/* Set standard desired spec */
desired.freq = 22050;
desired.format = SDL_AUDIO_S16;
desired.channels = 2;
break;
case 1:
/* Set custom desired spec */
desired.freq = 48000;
desired.format = SDL_AUDIO_F32;
desired.channels = 2;
break;
}
/* Call Open */
g_audio_id = SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_OUTPUT, &desired);
result = g_audio_id;
SDLTest_AssertPass("Call to SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_OUTPUT, desired_spec_%d)", j);
SDLTest_AssertCheck(result > 0, "Verify return value; expected > 0 got: %d", result);
#if 0 /* !!! FIXME: maybe update this? */
/* Start and stop audio multiple times */
for (l = 0; l < 3; l++) {
SDLTest_Log("Pause/Unpause iteration: %d", l + 1);
/* Reset callback counters */
g_audio_testCallbackCounter = 0;
g_audio_testCallbackLength = 0;
/* Un-pause audio to start playing (maybe multiple times) */
for (k = 0; k <= j; k++) {
SDL_PlayAudioDevice(g_audio_id);
SDLTest_AssertPass("Call to SDL_PlayAudioDevice(g_audio_id), call %d", k + 1);
}
/* Wait for callback */
int totalDelay = 0;
do {
SDL_Delay(10);
totalDelay += 10;
} while (g_audio_testCallbackCounter == 0 && totalDelay < 1000);
SDLTest_AssertCheck(g_audio_testCallbackCounter > 0, "Verify callback counter; expected: >0 got: %d", g_audio_testCallbackCounter);
SDLTest_AssertCheck(g_audio_testCallbackLength > 0, "Verify callback length; expected: >0 got: %d", g_audio_testCallbackLength);
/* Pause audio to stop playing (maybe multiple times) */
for (k = 0; k <= j; k++) {
const int pause_on = (k == 0) ? 1 : SDLTest_RandomIntegerInRange(99, 9999);
if (pause_on) {
SDL_PauseAudioDevice(g_audio_id);
SDLTest_AssertPass("Call to SDL_PauseAudioDevice(g_audio_id), call %d", k + 1);
} else {
SDL_PlayAudioDevice(g_audio_id);
SDLTest_AssertPass("Call to SDL_PlayAudioDevice(g_audio_id), call %d", k + 1);
}
}
/* Ensure callback is not called again */
const int originalCounter = g_audio_testCallbackCounter;
SDL_Delay(totalDelay + 10);
SDLTest_AssertCheck(originalCounter == g_audio_testCallbackCounter, "Verify callback counter; expected: %d, got: %d", originalCounter, g_audio_testCallbackCounter);
}
#endif
/* Call Close */
SDL_CloseAudioDevice(g_audio_id);
SDLTest_AssertPass("Call to SDL_CloseAudioDevice()");
/* Call Quit */
SDL_QuitSubSystem(SDL_INIT_AUDIO);
SDLTest_AssertPass("Call to SDL_QuitSubSystem(SDL_INIT_AUDIO)");
} /* spec loop */
} /* driver loop */
/* Restart audio again */
audioSetUp(NULL);
return TEST_COMPLETED;
}
/**
* \brief Enumerate and name available audio devices (output and capture).
*
* \sa SDL_GetNumAudioDevices
* \sa SDL_GetAudioDeviceName
*/
static int audio_enumerateAndNameAudioDevices(void *arg)
{
int t;
int i, n;
char *name;
SDL_AudioDeviceID *devices = NULL;
/* Iterate over types: t=0 output device, t=1 input/capture device */
for (t = 0; t < 2; t++) {
/* Get number of devices. */
devices = (t) ? SDL_GetAudioCaptureDevices(&n) : SDL_GetAudioOutputDevices(&n);
SDLTest_AssertPass("Call to SDL_GetAudio%sDevices(%i)", (t) ? "Capture" : "Output", t);
SDLTest_Log("Number of %s devices < 0, reported as %i", (t) ? "capture" : "output", n);
SDLTest_AssertCheck(n >= 0, "Validate result is >= 0, got: %i", n);
/* List devices. */
if (n > 0) {
SDLTest_AssertCheck(devices != NULL, "Validate devices is not NULL if n > 0");
for (i = 0; i < n; i++) {
name = SDL_GetAudioDeviceName(devices[i]);
SDLTest_AssertPass("Call to SDL_GetAudioDeviceName(%i)", i);
SDLTest_AssertCheck(name != NULL, "Verify result from SDL_GetAudioDeviceName(%i) is not NULL", i);
if (name != NULL) {
SDLTest_AssertCheck(name[0] != '\0', "verify result from SDL_GetAudioDeviceName(%i) is not empty, got: '%s'", i, name);
SDL_free(name);
}
}
}
SDL_free(devices);
}
return TEST_COMPLETED;
}
/**
* \brief Negative tests around enumeration and naming of audio devices.
*
* \sa SDL_GetNumAudioDevices
* \sa SDL_GetAudioDeviceName
*/
static int audio_enumerateAndNameAudioDevicesNegativeTests(void *arg)
{
return TEST_COMPLETED; /* nothing in here atm since these interfaces changed in SDL3. */
}
/**
* \brief Checks available audio driver names.
*
* \sa SDL_GetNumAudioDrivers
* \sa SDL_GetAudioDriver
*/
static int audio_printAudioDrivers(void *arg)
{
int i, n;
const char *name;
/* Get number of drivers */
n = SDL_GetNumAudioDrivers();
SDLTest_AssertPass("Call to SDL_GetNumAudioDrivers()");
SDLTest_AssertCheck(n >= 0, "Verify number of audio drivers >= 0, got: %i", n);
/* List drivers. */
if (n > 0) {
for (i = 0; i < n; i++) {
name = SDL_GetAudioDriver(i);
SDLTest_AssertPass("Call to SDL_GetAudioDriver(%i)", i);
SDLTest_AssertCheck(name != NULL, "Verify returned name is not NULL");
if (name != NULL) {
SDLTest_AssertCheck(name[0] != '\0', "Verify returned name is not empty, got: '%s'", name);
}
}
}
return TEST_COMPLETED;
}
/**
* \brief Checks current audio driver name with initialized audio.
*
* \sa SDL_GetCurrentAudioDriver
*/
static int audio_printCurrentAudioDriver(void *arg)
{
/* Check current audio driver */
const char *name = SDL_GetCurrentAudioDriver();
SDLTest_AssertPass("Call to SDL_GetCurrentAudioDriver()");
SDLTest_AssertCheck(name != NULL, "Verify returned name is not NULL");
if (name != NULL) {
SDLTest_AssertCheck(name[0] != '\0', "Verify returned name is not empty, got: '%s'", name);
}
return TEST_COMPLETED;
}
/* Definition of all formats, channels, and frequencies used to test audio conversions */
static SDL_AudioFormat g_audioFormats[] = {
SDL_AUDIO_S8, SDL_AUDIO_U8,
SDL_AUDIO_S16LE, SDL_AUDIO_S16BE,
SDL_AUDIO_S32LE, SDL_AUDIO_S32BE,
SDL_AUDIO_F32LE, SDL_AUDIO_F32BE
};
static const char *g_audioFormatsVerbose[] = {
"SDL_AUDIO_S8", "SDL_AUDIO_U8",
"SDL_AUDIO_S16LE", "SDL_AUDIO_S16BE",
"SDL_AUDIO_S32LE", "SDL_AUDIO_S32BE",
"SDL_AUDIO_F32LE", "SDL_AUDIO_F32BE"
};
static const int g_numAudioFormats = SDL_arraysize(g_audioFormats);
static Uint8 g_audioChannels[] = { 1, 2, 4, 6 };
static const int g_numAudioChannels = SDL_arraysize(g_audioChannels);
static int g_audioFrequencies[] = { 11025, 22050, 44100, 48000 };
static const int g_numAudioFrequencies = SDL_arraysize(g_audioFrequencies);
/* Verify the audio formats are laid out as expected */
SDL_COMPILE_TIME_ASSERT(SDL_AUDIO_U8_FORMAT, SDL_AUDIO_U8 == SDL_AUDIO_BITSIZE(8));
SDL_COMPILE_TIME_ASSERT(SDL_AUDIO_S8_FORMAT, SDL_AUDIO_S8 == (SDL_AUDIO_BITSIZE(8) | SDL_AUDIO_MASK_SIGNED));
SDL_COMPILE_TIME_ASSERT(SDL_AUDIO_S16LE_FORMAT, SDL_AUDIO_S16LE == (SDL_AUDIO_BITSIZE(16) | SDL_AUDIO_MASK_SIGNED));
SDL_COMPILE_TIME_ASSERT(SDL_AUDIO_S16BE_FORMAT, SDL_AUDIO_S16BE == (SDL_AUDIO_S16LE | SDL_AUDIO_MASK_BIG_ENDIAN));
SDL_COMPILE_TIME_ASSERT(SDL_AUDIO_S32LE_FORMAT, SDL_AUDIO_S32LE == (SDL_AUDIO_BITSIZE(32) | SDL_AUDIO_MASK_SIGNED));
SDL_COMPILE_TIME_ASSERT(SDL_AUDIO_S32BE_FORMAT, SDL_AUDIO_S32BE == (SDL_AUDIO_S32LE | SDL_AUDIO_MASK_BIG_ENDIAN));
SDL_COMPILE_TIME_ASSERT(SDL_AUDIO_F32LE_FORMAT, SDL_AUDIO_F32LE == (SDL_AUDIO_BITSIZE(32) | SDL_AUDIO_MASK_FLOAT | SDL_AUDIO_MASK_SIGNED));
SDL_COMPILE_TIME_ASSERT(SDL_AUDIO_F32BE_FORMAT, SDL_AUDIO_F32BE == (SDL_AUDIO_F32LE | SDL_AUDIO_MASK_BIG_ENDIAN));
/**
* \brief Builds various audio conversion structures
*
* \sa SDL_CreateAudioStream
*/
static int audio_buildAudioStream(void *arg)
{
SDL_AudioStream *stream;
SDL_AudioSpec spec1;
SDL_AudioSpec spec2;
int i, ii, j, jj, k, kk;
/* No conversion needed */
spec1.format = SDL_AUDIO_S16LE;
spec1.channels = 2;
spec1.freq = 22050;
stream = SDL_CreateAudioStream(&spec1, &spec1);
SDLTest_AssertPass("Call to SDL_CreateAudioStream(spec1 ==> spec1)");
SDLTest_AssertCheck(stream != NULL, "Verify stream value; expected: != NULL, got: %p", (void *)stream);
SDL_DestroyAudioStream(stream);
/* Typical conversion */
spec1.format = SDL_AUDIO_S8;
spec1.channels = 1;
spec1.freq = 22050;
spec2.format = SDL_AUDIO_S16LE;
spec2.channels = 2;
spec2.freq = 44100;
stream = SDL_CreateAudioStream(&spec1, &spec2);
SDLTest_AssertPass("Call to SDL_CreateAudioStream(spec1 ==> spec2)");
SDLTest_AssertCheck(stream != NULL, "Verify stream value; expected: != NULL, got: %p", (void *)stream);
SDL_DestroyAudioStream(stream);
/* All source conversions with random conversion targets, allow 'null' conversions */
for (i = 0; i < g_numAudioFormats; i++) {
for (j = 0; j < g_numAudioChannels; j++) {
for (k = 0; k < g_numAudioFrequencies; k++) {
spec1.format = g_audioFormats[i];
spec1.channels = g_audioChannels[j];
spec1.freq = g_audioFrequencies[k];
ii = SDLTest_RandomIntegerInRange(0, g_numAudioFormats - 1);
jj = SDLTest_RandomIntegerInRange(0, g_numAudioChannels - 1);
kk = SDLTest_RandomIntegerInRange(0, g_numAudioFrequencies - 1);
spec2.format = g_audioFormats[ii];
spec2.channels = g_audioChannels[jj];
spec2.freq = g_audioFrequencies[kk];
stream = SDL_CreateAudioStream(&spec1, &spec2);
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)",
i, g_audioFormatsVerbose[i], spec1.format, j, spec1.channels, k, spec1.freq, ii, g_audioFormatsVerbose[ii], spec2.format, jj, spec2.channels, kk, spec2.freq);
SDLTest_AssertCheck(stream != NULL, "Verify stream value; expected: != NULL, got: %p", (void *)stream);
if (stream == NULL) {
SDLTest_LogError("%s", SDL_GetError());
}
SDL_DestroyAudioStream(stream);
}
}
}
return TEST_COMPLETED;
}
/**
* \brief Checks calls with invalid input to SDL_CreateAudioStream
*
* \sa SDL_CreateAudioStream
*/
static int audio_buildAudioStreamNegative(void *arg)
{
const char *error;
SDL_AudioStream *stream;
SDL_AudioSpec spec1;
SDL_AudioSpec spec2;
int i;
char message[256];
/* Valid format */
spec1.format = SDL_AUDIO_S8;
spec1.channels = 1;
spec1.freq = 22050;
spec2.format = SDL_AUDIO_S16LE;
spec2.channels = 2;
spec2.freq = 44100;
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
/* Invalid conversions */
for (i = 1; i < 64; i++) {
/* Valid format to start with */
spec1.format = SDL_AUDIO_S8;
spec1.channels = 1;
spec1.freq = 22050;
spec2.format = SDL_AUDIO_S16LE;
spec2.channels = 2;
spec2.freq = 44100;
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
/* Set various invalid format inputs */
SDL_strlcpy(message, "Invalid: ", 256);
if (i & 1) {
SDL_strlcat(message, " spec1.format", 256);
spec1.format = 0;
}
if (i & 2) {
SDL_strlcat(message, " spec1.channels", 256);
spec1.channels = 0;
}
if (i & 4) {
SDL_strlcat(message, " spec1.freq", 256);
spec1.freq = 0;
}
if (i & 8) {
SDL_strlcat(message, " spec2.format", 256);
spec2.format = 0;
}
if (i & 16) {
SDL_strlcat(message, " spec2.channels", 256);
spec2.channels = 0;
}
if (i & 32) {
SDL_strlcat(message, " spec2.freq", 256);
spec2.freq = 0;
}
SDLTest_Log("%s", message);
stream = SDL_CreateAudioStream(&spec1, &spec2);
SDLTest_AssertPass("Call to SDL_CreateAudioStream(spec1 ==> spec2)");
SDLTest_AssertCheck(stream == NULL, "Verify stream value; expected: NULL, got: %p", (void *)stream);
error = SDL_GetError();
SDLTest_AssertPass("Call to SDL_GetError()");
SDLTest_AssertCheck(error != NULL && error[0] != '\0', "Validate that error message was not NULL or empty");
SDL_DestroyAudioStream(stream);
}
SDL_ClearError();
SDLTest_AssertPass("Call to SDL_ClearError()");
return TEST_COMPLETED;
}
/**
* \brief Checks current audio status.
*
* \sa SDL_GetAudioDeviceStatus
*/
static int audio_getAudioStatus(void *arg)
{
return TEST_COMPLETED; /* no longer a thing in SDL3. */
}
/**
* \brief Opens, checks current audio status, and closes a device.
*
* \sa SDL_GetAudioStatus
*/
static int audio_openCloseAndGetAudioStatus(void *arg)
{
return TEST_COMPLETED; /* not a thing in SDL3. */
}
/**
* \brief Locks and unlocks open audio device.
*
* \sa SDL_LockAudioDevice
* \sa SDL_UnlockAudioDevice
*/
static int audio_lockUnlockOpenAudioDevice(void *arg)
{
return TEST_COMPLETED; /* not a thing in SDL3 */
}
/**
* \brief Convert audio using various conversion structures
*
* \sa SDL_CreateAudioStream
*/
static int audio_convertAudio(void *arg)
{
SDL_AudioStream *stream;
SDL_AudioSpec spec1;
SDL_AudioSpec spec2;
int c;
char message[128];
int i, ii, j, jj, k, kk;
/* Iterate over bitmask that determines which parameters are modified in the conversion */
for (c = 1; c < 8; c++) {
SDL_strlcpy(message, "Changing:", 128);
if (c & 1) {
SDL_strlcat(message, " Format", 128);
}
if (c & 2) {
SDL_strlcat(message, " Channels", 128);
}
if (c & 4) {
SDL_strlcat(message, " Frequencies", 128);
}
SDLTest_Log("%s", message);
/* All source conversions with random conversion targets */
for (i = 0; i < g_numAudioFormats; i++) {
for (j = 0; j < g_numAudioChannels; j++) {
for (k = 0; k < g_numAudioFrequencies; k++) {
spec1.format = g_audioFormats[i];
spec1.channels = g_audioChannels[j];
spec1.freq = g_audioFrequencies[k];
/* Ensure we have a different target format */
do {
if (c & 1) {
ii = SDLTest_RandomIntegerInRange(0, g_numAudioFormats - 1);
} else {
ii = 1;
}
if (c & 2) {
jj = SDLTest_RandomIntegerInRange(0, g_numAudioChannels - 1);
} else {
jj = j;
}
if (c & 4) {
kk = SDLTest_RandomIntegerInRange(0, g_numAudioFrequencies - 1);
} else {
kk = k;
}
} while ((i == ii) && (j == jj) && (k == kk));
spec2.format = g_audioFormats[ii];
spec2.channels = g_audioChannels[jj];
spec2.freq = g_audioFrequencies[kk];
stream = SDL_CreateAudioStream(&spec1, &spec2);
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)",
i, g_audioFormatsVerbose[i], spec1.format, j, spec1.channels, k, spec1.freq, ii, g_audioFormatsVerbose[ii], spec2.format, jj, spec2.channels, kk, spec2.freq);
SDLTest_AssertCheck(stream != NULL, "Verify stream value; expected: != NULL, got: %p", (void *)stream);
if (stream == NULL) {
SDLTest_LogError("%s", SDL_GetError());
} else {
Uint8 *dst_buf = NULL, *src_buf = NULL;
int dst_len = 0, src_len = 0, real_dst_len = 0;
int l = 64, m;
int src_framesize, dst_framesize;
int src_silence, dst_silence;
src_framesize = SDL_AUDIO_FRAMESIZE(spec1);
dst_framesize = SDL_AUDIO_FRAMESIZE(spec2);
src_len = l * src_framesize;
SDLTest_Log("Creating dummy sample buffer of %i length (%i bytes)", l, src_len);
src_buf = (Uint8 *)SDL_malloc(src_len);
SDLTest_AssertCheck(src_buf != NULL, "Check src data buffer to convert is not NULL");
if (src_buf == NULL) {
return TEST_ABORTED;
}
src_silence = SDL_GetSilenceValueForFormat(spec1.format);
SDL_memset(src_buf, src_silence, src_len);
dst_len = ((int)((((Sint64)l * spec2.freq) - 1) / spec1.freq) + 1) * dst_framesize;
dst_buf = (Uint8 *)SDL_malloc(dst_len);
SDLTest_AssertCheck(dst_buf != NULL, "Check dst data buffer to convert is not NULL");
if (dst_buf == NULL) {
return TEST_ABORTED;
}
real_dst_len = SDL_GetAudioStreamAvailable(stream);
SDLTest_AssertCheck(0 == real_dst_len, "Verify available (pre-put); expected: %i; got: %i", 0, real_dst_len);
/* Run the audio converter */
if (SDL_PutAudioStreamData(stream, src_buf, src_len) < 0 ||
SDL_FlushAudioStream(stream) < 0) {
return TEST_ABORTED;
}
real_dst_len = SDL_GetAudioStreamAvailable(stream);
SDLTest_AssertCheck(dst_len == real_dst_len, "Verify available (post-put); expected: %i; got: %i", dst_len, real_dst_len);
real_dst_len = SDL_GetAudioStreamData(stream, dst_buf, dst_len);
SDLTest_AssertCheck(dst_len == real_dst_len, "Verify result value; expected: %i; got: %i", dst_len, real_dst_len);
if (dst_len != real_dst_len) {
return TEST_ABORTED;
}
real_dst_len = SDL_GetAudioStreamAvailable(stream);
SDLTest_AssertCheck(0 == real_dst_len, "Verify available (post-get); expected: %i; got: %i", 0, real_dst_len);
dst_silence = SDL_GetSilenceValueForFormat(spec2.format);
for (m = 0; m < dst_len; ++m) {
if (dst_buf[m] != dst_silence) {
SDLTest_LogError("Output buffer is not silent");
return TEST_ABORTED;
}
}
SDL_DestroyAudioStream(stream);
/* Free converted buffer */
SDL_free(src_buf);
SDL_free(dst_buf);
}
}
}
}
}
return TEST_COMPLETED;
}
/**
* \brief Opens, checks current connected status, and closes a device.
*
* \sa SDL_AudioDeviceConnected
*/
static int audio_openCloseAudioDeviceConnected(void *arg)
{
return TEST_COMPLETED; /* not a thing in SDL3. */
}
static double sine_wave_sample(const Sint64 idx, const Sint64 rate, const Sint64 freq, const double phase)
{
/* Using integer modulo to avoid precision loss caused by large floating
* point numbers. Sint64 is needed for the large integer multiplication.
* The integers are assumed to be non-negative so that modulo is always
* non-negative.
* sin(i / rate * freq * 2 * PI + phase)
* = sin(mod(i / rate * freq, 1) * 2 * PI + phase)
* = sin(mod(i * freq, rate) / rate * 2 * PI + phase) */
return SDL_sin(((double)(idx * freq % rate)) / ((double)rate) * (SDL_PI_D * 2) + phase);
}
/**
* \brief Check signal-to-noise ratio and maximum error of audio resampling.
*
* \sa https://wiki.libsdl.org/SDL_CreateAudioStream
* \sa https://wiki.libsdl.org/SDL_DestroyAudioStream
* \sa https://wiki.libsdl.org/SDL_PutAudioStreamData
* \sa https://wiki.libsdl.org/SDL_FlushAudioStream
* \sa https://wiki.libsdl.org/SDL_GetAudioStreamData
*/
static int audio_resampleLoss(void *arg)
{
/* Note: always test long input time (>= 5s from experience) in some test
* cases because an improper implementation may suffer from low resampling
* precision with long input due to e.g. doing subtraction with large floats. */
struct test_spec_t {
int time;
int freq;
double phase;
int rate_in;
int rate_out;
double signal_to_noise;
double max_error;
} test_specs[] = {
{ 50, 440, 0, 44100, 48000, 80, 0.0009 },
{ 50, 5000, SDL_PI_D / 2, 20000, 10000, 999, 0.0001 },
{ 50, 440, 0, 22050, 96000, 79, 0.0120 },
{ 50, 440, 0, 96000, 22050, 80, 0.0002 },
{ 0 }
};
int spec_idx = 0;
int min_channels = 1;
int max_channels = 1 /*8*/;
int num_channels = min_channels;
for (spec_idx = 0; test_specs[spec_idx].time > 0;) {
const struct test_spec_t *spec = &test_specs[spec_idx];
const int frames_in = spec->time * spec->rate_in;
const int frames_target = spec->time * spec->rate_out;
const int len_in = (frames_in * num_channels) * (int)sizeof(float);
const int len_target = (frames_target * num_channels) * (int)sizeof(float);
SDL_AudioSpec tmpspec1, tmpspec2;
Uint64 tick_beg = 0;
Uint64 tick_end = 0;
int i = 0;
int j = 0;
int ret = 0;
SDL_AudioStream *stream = NULL;
float *buf_in = NULL;
float *buf_out = NULL;
int len_out = 0;
double max_error = 0;
double sum_squared_error = 0;
double sum_squared_value = 0;
double signal_to_noise = 0;
SDLTest_AssertPass("Test resampling of %i s %i Hz %f phase sine wave from sampling rate of %i Hz to %i Hz",
spec->time, spec->freq, spec->phase, spec->rate_in, spec->rate_out);
tmpspec1.format = SDL_AUDIO_F32;
tmpspec1.channels = num_channels;
tmpspec1.freq = spec->rate_in;
tmpspec2.format = SDL_AUDIO_F32;
tmpspec2.channels = num_channels;
tmpspec2.freq = spec->rate_out;
stream = SDL_CreateAudioStream(&tmpspec1, &tmpspec2);
SDLTest_AssertPass("Call to SDL_CreateAudioStream(SDL_AUDIO_F32, 1, %i, SDL_AUDIO_F32, 1, %i)", spec->rate_in, spec->rate_out);
SDLTest_AssertCheck(stream != NULL, "Expected SDL_CreateAudioStream to succeed.");
if (stream == NULL) {
return TEST_ABORTED;
}
buf_in = (float *)SDL_malloc(len_in);
SDLTest_AssertCheck(buf_in != NULL, "Expected input buffer to be created.");
if (buf_in == NULL) {
SDL_DestroyAudioStream(stream);
return TEST_ABORTED;
}
for (i = 0; i < frames_in; ++i) {
float f = (float)sine_wave_sample(i, spec->rate_in, spec->freq, spec->phase);
for (j = 0; j < num_channels; ++j) {
*(buf_in + (i * num_channels) + j) = f;
}
}
tick_beg = SDL_GetPerformanceCounter();
ret = SDL_PutAudioStreamData(stream, buf_in, len_in);
SDLTest_AssertPass("Call to SDL_PutAudioStreamData(stream, buf_in, %i)", len_in);
SDLTest_AssertCheck(ret == 0, "Expected SDL_PutAudioStreamData to succeed.");
SDL_free(buf_in);
if (ret != 0) {
SDL_DestroyAudioStream(stream);
return TEST_ABORTED;
}
ret = SDL_FlushAudioStream(stream);
SDLTest_AssertPass("Call to SDL_FlushAudioStream(stream)");
SDLTest_AssertCheck(ret == 0, "Expected SDL_FlushAudioStream to succeed");
if (ret != 0) {
SDL_DestroyAudioStream(stream);
return TEST_ABORTED;
}
buf_out = (float *)SDL_malloc(len_target);
SDLTest_AssertCheck(buf_out != NULL, "Expected output buffer to be created.");
if (buf_out == NULL) {
SDL_DestroyAudioStream(stream);
return TEST_ABORTED;
}
len_out = SDL_GetAudioStreamData(stream, buf_out, len_target);
SDLTest_AssertPass("Call to SDL_GetAudioStreamData(stream, buf_out, %i)", len_target);
SDLTest_AssertCheck(len_out == len_target, "Expected output length to be no larger than %i, got %i.",
len_target, len_out);
SDL_DestroyAudioStream(stream);
if (len_out > len_target) {
SDL_free(buf_out);
return TEST_ABORTED;
}
tick_end = SDL_GetPerformanceCounter();
SDLTest_Log("Resampling used %f seconds.", ((double)(tick_end - tick_beg)) / SDL_GetPerformanceFrequency());
for (i = 0; i < frames_target; ++i) {
const double target = sine_wave_sample(i, spec->rate_out, spec->freq, spec->phase);
for (j = 0; j < num_channels; ++j) {
const float output = *(buf_out + (i * num_channels) + j);
const double error = SDL_fabs(target - output);
max_error = SDL_max(max_error, error);
sum_squared_error += error * error;
sum_squared_value += target * target;
}
}
SDL_free(buf_out);
signal_to_noise = 10 * SDL_log10(sum_squared_value / sum_squared_error); /* decibel */
SDLTest_AssertCheck(isfinite(sum_squared_value), "Sum of squared target should be finite.");
SDLTest_AssertCheck(isfinite(sum_squared_error), "Sum of squared error should be finite.");
/* Infinity is theoretically possible when there is very little to no noise */
SDLTest_AssertCheck(!isnan(signal_to_noise), "Signal-to-noise ratio should not be NaN.");
SDLTest_AssertCheck(isfinite(max_error), "Maximum conversion error should be finite.");
SDLTest_AssertCheck(signal_to_noise >= spec->signal_to_noise, "Conversion signal-to-noise ratio %f dB should be no less than %f dB.",
signal_to_noise, spec->signal_to_noise);
SDLTest_AssertCheck(max_error <= spec->max_error, "Maximum conversion error %f should be no more than %f.",
max_error, spec->max_error);
if (++num_channels > max_channels) {
num_channels = min_channels;
++spec_idx;
}
}
return TEST_COMPLETED;
}
/**
* \brief Check accuracy converting between audio formats.
*
* \sa SDL_ConvertAudioSamples
*/
static int audio_convertAccuracy(void *arg)
{
static SDL_AudioFormat formats[] = { SDL_AUDIO_S8, SDL_AUDIO_U8, SDL_AUDIO_S16, SDL_AUDIO_S32 };
static const char* format_names[] = { "S8", "U8", "S16", "S32" };
int src_num = 65537 + 2048 + 48 + 256 + 100000;
int src_len = src_num * sizeof(float);
float* src_data = SDL_malloc(src_len);
int i, j;
SDLTest_AssertCheck(src_data != NULL, "Expected source buffer to be created.");
if (src_data == NULL) {
return TEST_ABORTED;
}
j = 0;
/* Generate a uniform range of floats between [-1.0, 1.0] */
for (i = 0; i < 65537; ++i) {
src_data[j++] = ((float)i - 32768.0f) / 32768.0f;
}
/* Generate floats close to 1.0 */
const float max_val = 16777216.0f;
for (i = 0; i < 1024; ++i) {
float f = (max_val + (float)(512 - i)) / max_val;
src_data[j++] = f;
src_data[j++] = -f;
}
for (i = 0; i < 24; ++i) {
float f = (max_val + (float)(3u << i)) / max_val;
src_data[j++] = f;
src_data[j++] = -f;
}
/* Generate floats far outside the [-1.0, 1.0] range */
for (i = 0; i < 128; ++i) {
float f = 2.0f + (float) i;
src_data[j++] = f;
src_data[j++] = -f;
}
/* Fill the rest with random floats between [-1.0, 1.0] */
for (i = 0; i < 100000; ++i) {
src_data[j++] = SDLTest_RandomSint32() / 2147483648.0f;
}
/* Shuffle the data for good measure */
for (i = src_num - 1; i > 0; --i) {
float f = src_data[i];
j = SDLTest_RandomIntegerInRange(0, i);
src_data[i] = src_data[j];
src_data[j] = f;
}
for (i = 0; i < SDL_arraysize(formats); ++i) {
SDL_AudioSpec src_spec, tmp_spec;
Uint64 convert_begin, convert_end;
Uint8 *tmp_data, *dst_data;
int tmp_len, dst_len;
int ret;
SDL_AudioFormat format = formats[i];
const char* format_name = format_names[i];
/* Formats with > 23 bits can represent every value exactly */
float min_delta = 1.0f;
float max_delta = -1.0f;
/* Subtract 1 bit to account for sign */
int bits = SDL_AUDIO_BITSIZE(format) - 1;
float target_max_delta = (bits > 23) ? 0.0f : (1.0f / (float)(1 << bits));
float target_min_delta = -target_max_delta;
src_spec.format = SDL_AUDIO_F32;
src_spec.channels = 1;
src_spec.freq = 44100;
tmp_spec.format = format;
tmp_spec.channels = 1;
tmp_spec.freq = 44100;
convert_begin = SDL_GetPerformanceCounter();
tmp_data = NULL;
tmp_len = 0;
ret = SDL_ConvertAudioSamples(&src_spec, (const Uint8*) src_data, src_len, &tmp_spec, &tmp_data, &tmp_len);
SDLTest_AssertCheck(ret == 0, "Expected SDL_ConvertAudioSamples(F32->%s) to succeed", format_name);
if (ret != 0) {
SDL_free(src_data);
return TEST_ABORTED;
}
dst_data = NULL;
dst_len = 0;
ret = SDL_ConvertAudioSamples(&tmp_spec, tmp_data, tmp_len, &src_spec, &dst_data, &dst_len);
SDLTest_AssertCheck(ret == 0, "Expected SDL_ConvertAudioSamples(%s->F32) to succeed", format_name);
if (ret != 0) {
SDL_free(tmp_data);
SDL_free(src_data);
return TEST_ABORTED;
}
convert_end = SDL_GetPerformanceCounter();
SDLTest_Log("Conversion via %s took %f seconds.", format_name, ((double)(convert_end - convert_begin)) / SDL_GetPerformanceFrequency());
SDL_free(tmp_data);
for (j = 0; j < src_num; ++j) {
float x = src_data[j];
float y = ((float*)dst_data)[j];
float d = SDL_clamp(x, -1.0f, 1.0f) - y;
min_delta = SDL_min(min_delta, d);
max_delta = SDL_max(max_delta, d);
}
SDLTest_AssertCheck(min_delta >= target_min_delta, "%s has min delta of %+f, should be >= %+f", format_name, min_delta, target_min_delta);
SDLTest_AssertCheck(max_delta <= target_max_delta, "%s has max delta of %+f, should be <= %+f", format_name, max_delta, target_max_delta);
SDL_free(dst_data);
}
SDL_free(src_data);
return TEST_COMPLETED;
}
/**
* \brief Check accuracy when switching between formats
*
* \sa SDL_SetAudioStreamFormat
*/
static int audio_formatChange(void *arg)
{
int i;
SDL_AudioSpec spec1, spec2, spec3;
int frames_1, frames_2, frames_3;
int length_1, length_2, length_3;
int retval = 0;
int status = TEST_ABORTED;
float* buffer_1 = NULL;
float* buffer_2 = NULL;
float* buffer_3 = NULL;
SDL_AudioStream* stream = NULL;
double max_error = 0;
double sum_squared_error = 0;
double sum_squared_value = 0;
double signal_to_noise = 0;
double target_max_error = 0.02;
double target_signal_to_noise = 75.0;
int sine_freq = 500;
spec1.format = SDL_AUDIO_F32;
spec1.channels = 1;
spec1.freq = 20000;
spec2.format = SDL_AUDIO_F32;
spec2.channels = 1;
spec2.freq = 40000;
spec3.format = SDL_AUDIO_F32;
spec3.channels = 1;
spec3.freq = 80000;
frames_1 = spec1.freq;
frames_2 = spec2.freq;
frames_3 = spec3.freq * 2;
length_1 = (int)(frames_1 * sizeof(*buffer_1));
buffer_1 = (float*) SDL_malloc(length_1);
if (!SDLTest_AssertCheck(buffer_1 != NULL, "Expected buffer_1 to be created.")) {
goto cleanup;
}
length_2 = (int)(frames_2 * sizeof(*buffer_2));
buffer_2 = (float*) SDL_malloc(length_2);
if (!SDLTest_AssertCheck(buffer_2 != NULL, "Expected buffer_2 to be created.")) {
goto cleanup;
}
length_3 = (int)(frames_3 * sizeof(*buffer_3));
buffer_3 = (float*) SDL_malloc(length_3);
if (!SDLTest_AssertCheck(buffer_3 != NULL, "Expected buffer_3 to be created.")) {
goto cleanup;
}
for (i = 0; i < frames_1; ++i) {
buffer_1[i] = (float) sine_wave_sample(i, spec1.freq, sine_freq, 0.0f);
}
for (i = 0; i < frames_2; ++i) {
buffer_2[i] = (float) sine_wave_sample(i, spec2.freq, sine_freq, 0.0f);
}
stream = SDL_CreateAudioStream(NULL, NULL);
if (!SDLTest_AssertCheck(stream != NULL, "Expected SDL_CreateAudioStream to succeed")) {
goto cleanup;
}
retval = SDL_SetAudioStreamFormat(stream, &spec1, &spec3);
if (!SDLTest_AssertCheck(retval == 0, "Expected SDL_SetAudioStreamFormat(spec1, spec3) to succeed")) {
goto cleanup;
}
retval = SDL_GetAudioStreamAvailable(stream);
if (!SDLTest_AssertCheck(retval == 0, "Expected SDL_GetAudioStreamAvailable return 0")) {
goto cleanup;
}
retval = SDL_PutAudioStreamData(stream, buffer_1, length_1);
if (!SDLTest_AssertCheck(retval == 0, "Expected SDL_PutAudioStreamData(buffer_1) to succeed")) {
goto cleanup;
}
retval = SDL_FlushAudioStream(stream);
if (!SDLTest_AssertCheck(retval == 0, "Expected SDL_FlushAudioStream to succeed")) {
goto cleanup;
}
retval = SDL_SetAudioStreamFormat(stream, &spec2, &spec3);
if (!SDLTest_AssertCheck(retval == 0, "Expected SDL_SetAudioStreamFormat(spec2, spec3) to succeed")) {
goto cleanup;
}
retval = SDL_PutAudioStreamData(stream, buffer_2, length_2);
if (!SDLTest_AssertCheck(retval == 0, "Expected SDL_PutAudioStreamData(buffer_1) to succeed")) {
goto cleanup;
}
retval = SDL_FlushAudioStream(stream);
if (!SDLTest_AssertCheck(retval == 0, "Expected SDL_FlushAudioStream to succeed")) {
goto cleanup;
}
retval = SDL_GetAudioStreamAvailable(stream);
if (!SDLTest_AssertCheck(retval == length_3, "Expected SDL_GetAudioStreamAvailable to return %i, got %i", length_3, retval)) {
goto cleanup;
}
retval = SDL_GetAudioStreamData(stream, buffer_3, length_3);
if (!SDLTest_AssertCheck(retval == length_3, "Expected SDL_GetAudioStreamData to return %i, got %i", length_3, retval)) {
goto cleanup;
}
retval = SDL_GetAudioStreamAvailable(stream);
if (!SDLTest_AssertCheck(retval == 0, "Expected SDL_GetAudioStreamAvailable to return 0")) {
goto cleanup;
}
for (i = 0; i < frames_3; ++i) {
const float output = buffer_3[i];
const float target = (float) sine_wave_sample(i, spec3.freq, sine_freq, 0.0f);
const double error = SDL_fabs(target - output);
max_error = SDL_max(max_error, error);
sum_squared_error += error * error;
sum_squared_value += target * target;
}
signal_to_noise = 10 * SDL_log10(sum_squared_value / sum_squared_error); /* decibel */
SDLTest_AssertCheck(isfinite(sum_squared_value), "Sum of squared target should be finite.");
SDLTest_AssertCheck(isfinite(sum_squared_error), "Sum of squared error should be finite.");
/* Infinity is theoretically possible when there is very little to no noise */
SDLTest_AssertCheck(!isnan(signal_to_noise), "Signal-to-noise ratio should not be NaN.");
SDLTest_AssertCheck(isfinite(max_error), "Maximum conversion error should be finite.");
SDLTest_AssertCheck(signal_to_noise >= target_signal_to_noise, "Conversion signal-to-noise ratio %f dB should be no less than %f dB.",
signal_to_noise, target_signal_to_noise);
SDLTest_AssertCheck(max_error <= target_max_error, "Maximum conversion error %f should be no more than %f.",
max_error, target_max_error);
status = TEST_COMPLETED;
cleanup:
SDL_free(buffer_1);
SDL_free(buffer_2);
SDL_free(buffer_3);
SDL_DestroyAudioStream(stream);
return status;
}
/* ================= Test Case References ================== */
/* Audio test cases */
static const SDLTest_TestCaseReference audioTest1 = {
audio_enumerateAndNameAudioDevices, "audio_enumerateAndNameAudioDevices", "Enumerate and name available audio devices (output and capture)", TEST_ENABLED
};
static const SDLTest_TestCaseReference audioTest2 = {
audio_enumerateAndNameAudioDevicesNegativeTests, "audio_enumerateAndNameAudioDevicesNegativeTests", "Negative tests around enumeration and naming of audio devices.", TEST_ENABLED
};
static const SDLTest_TestCaseReference audioTest3 = {
audio_printAudioDrivers, "audio_printAudioDrivers", "Checks available audio driver names.", TEST_ENABLED
};
static const SDLTest_TestCaseReference audioTest4 = {
audio_printCurrentAudioDriver, "audio_printCurrentAudioDriver", "Checks current audio driver name with initialized audio.", TEST_ENABLED
};
static const SDLTest_TestCaseReference audioTest5 = {
audio_buildAudioStream, "audio_buildAudioStream", "Builds various audio conversion structures.", TEST_ENABLED
};
static const SDLTest_TestCaseReference audioTest6 = {
audio_buildAudioStreamNegative, "audio_buildAudioStreamNegative", "Checks calls with invalid input to SDL_CreateAudioStream", TEST_ENABLED
};
static const SDLTest_TestCaseReference audioTest7 = {
audio_getAudioStatus, "audio_getAudioStatus", "Checks current audio status.", TEST_ENABLED
};
static const SDLTest_TestCaseReference audioTest8 = {
audio_openCloseAndGetAudioStatus, "audio_openCloseAndGetAudioStatus", "Opens and closes audio device and get audio status.", TEST_ENABLED
};
static const SDLTest_TestCaseReference audioTest9 = {
audio_lockUnlockOpenAudioDevice, "audio_lockUnlockOpenAudioDevice", "Locks and unlocks an open audio device.", TEST_ENABLED
};
static const SDLTest_TestCaseReference audioTest10 = {
audio_convertAudio, "audio_convertAudio", "Convert audio using available formats.", TEST_ENABLED
};
/* TODO: enable test when SDL_AudioDeviceConnected has been implemented. */
static const SDLTest_TestCaseReference audioTest11 = {
audio_openCloseAudioDeviceConnected, "audio_openCloseAudioDeviceConnected", "Opens and closes audio device and get connected status.", TEST_DISABLED
};
static const SDLTest_TestCaseReference audioTest12 = {
audio_quitInitAudioSubSystem, "audio_quitInitAudioSubSystem", "Quit and re-init audio subsystem.", TEST_ENABLED
};
static const SDLTest_TestCaseReference audioTest13 = {
audio_initQuitAudio, "audio_initQuitAudio", "Init and quit audio drivers directly.", TEST_ENABLED
};
static const SDLTest_TestCaseReference audioTest14 = {
audio_initOpenCloseQuitAudio, "audio_initOpenCloseQuitAudio", "Cycle through init, open, close and quit with various audio specs.", TEST_ENABLED
};
static const SDLTest_TestCaseReference audioTest15 = {
audio_pauseUnpauseAudio, "audio_pauseUnpauseAudio", "Pause and Unpause audio for various audio specs while testing callback.", TEST_ENABLED
};
static const SDLTest_TestCaseReference audioTest16 = {
audio_resampleLoss, "audio_resampleLoss", "Check signal-to-noise ratio and maximum error of audio resampling.", TEST_ENABLED
};
static const SDLTest_TestCaseReference audioTest17 = {
audio_convertAccuracy, "audio_convertAccuracy", "Check accuracy converting between audio formats.", TEST_ENABLED
};
static const SDLTest_TestCaseReference audioTest18 = {
audio_formatChange, "audio_formatChange", "Check handling of format changes.", TEST_ENABLED
};
/* Sequence of Audio test cases */
static const SDLTest_TestCaseReference *audioTests[] = {
&audioTest1, &audioTest2, &audioTest3, &audioTest4, &audioTest5, &audioTest6,
&audioTest7, &audioTest8, &audioTest9, &audioTest10, &audioTest11,
&audioTest12, &audioTest13, &audioTest14, &audioTest15, &audioTest16,
&audioTest17, &audioTest18, NULL
};
/* Audio test suite (global) */
SDLTest_TestSuiteReference audioTestSuite = {
"Audio",
audioSetUp,
audioTests,
audioTearDown
};