client/tests/browser_audio.c (2998B)
1 #include "browser_audio.h" 2 #include <assert.h> 3 #include <emscripten.h> 4 #include <emscripten/threading.h> 5 #include <stdatomic.h> 6 #include <stdio.h> 7 #include <unistd.h> 8 9 static atomic_uint callbacks; 10 11 static void render(void *argument, Uint8 *buffer, int length) 12 { 13 SDL_AudioSpec *format = argument; 14 assert(!emscripten_is_main_browser_thread()); 15 for (int frame = 0; frame < format->samples; ++frame) { 16 int value = frame % 128 < 64 ? 1 : -1; 17 if (format->format == AUDIO_U8) buffer[frame] = 128 + value * 4; 18 else { 19 ((int16_t *)buffer)[frame * 2] = value * 1024; 20 ((int16_t *)buffer)[frame * 2 + 1] = -value * 1024; 21 } 22 } 23 assert(length == format->samples * format->channels * (SDL_AUDIO_BITSIZE(format->format) / 8)); 24 atomic_fetch_add(&callbacks, 1); 25 } 26 27 int main(void) 28 { 29 for (unsigned stereo = 0; stereo < 2; ++stereo) { 30 SDL_AudioSpec desired = {0}, obtained; 31 desired.freq = 44100; 32 desired.channels = stereo ? 2 : 1; 33 desired.format = stereo ? AUDIO_S16LSB : AUDIO_U8; 34 desired.samples = 512; 35 desired.callback = render; 36 desired.userdata = &desired; 37 atomic_store(&callbacks, 0); 38 SDL_AudioDeviceID device = audio_output_open(&desired, &obtained); 39 assert(obtained.freq == MAIN_THREAD_EM_ASM_INT({ return Module.audioContext.sampleRate; })); 40 assert(obtained.channels == desired.channels); 41 assert(obtained.format == desired.format && obtained.samples == 512); 42 43 audio_output_pause(device, 0); 44 for (unsigned attempt = 0; attempt < 500 && atomic_load(&callbacks) < 32; ++attempt) usleep(10000); 45 assert(MAIN_THREAD_EM_ASM_INT({ return Module.verifyPlaybackWithStall(); })); 46 audio_output_lock(device); 47 unsigned locked_count = atomic_load(&callbacks); 48 usleep(50000); 49 50 assert(locked_count >= 32 && atomic_load(&callbacks) == locked_count); 51 audio_output_unlock(device); 52 audio_output_pause(device, 1); 53 unsigned paused_count = atomic_load(&callbacks); 54 usleep(50000); 55 assert(atomic_load(&callbacks) == paused_count); 56 audio_output_pause(device, 0); 57 for (unsigned attempt = 0; attempt < 500 && atomic_load(&callbacks) == paused_count; ++attempt) usleep(10000); 58 assert(atomic_load(&callbacks) > paused_count); 59 audio_output_close(device); 60 unsigned closed_count = atomic_load(&callbacks); 61 usleep(50000); 62 assert(atomic_load(&callbacks) == closed_count); 63 } 64 for (unsigned attempt = 0; attempt < 500 && 65 !MAIN_THREAD_EM_ASM_INT({ return Module.outputs.every(output => output.closed); }); ++attempt) 66 usleep(10000); 67 assert(MAIN_THREAD_EM_ASM_INT({ return Module.outputs.length === 2 && Module.outputs.every(output => output.closed); })); 68 puts("PASS: worker mixing, PCM conversion, uninterrupted playback during UI stalls, locking, pause/resume and acknowledged close"); 69 }