winzik/engine/tests/Audio/PcmStreamTest.php
David Nurdin abe53600c5 Continuous music stream on SDL_mixer's output (no gaps between blocks)
Desktop: the music was played as one SDL_mixer chunk per block, each started
when the previous one ended, at frame precision: a gap of up to a frame at each
block (measured on the real Freedoom song: 8 gaps, 371 ms of silence in 5 s).

- php-sdl-mixer (docker/ext/php-sdl-mixer-stream.patch): a ring buffer fed by
  PHP (JumPHP_StreamOpen / Push / Buffered / Clear / Volume / Close), read by
  Mix_HookMusic on SDL's audio thread, mixed with the sound effects by SDL_mixer,
  silence when empty. Resampling to the device rate in C.
- Mix_VolumeMusic does not reach the hook: the stream volume is set by PHP.
- PcmStream (desktop): uses the stream when the binding has it, the old chunks
  otherwise. The browser path is unchanged.
- Same functions in the desktop image and in the WebAssembly engine.
- Measured in capture (SDL disk driver): 0 gaps, the right frequency, sound
  effects and music in the same output. Listening test not done yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-14 17:16:10 +01:00

52 lines
1.9 KiB
PHP

<?php
namespace JumPHP\Tests\Audio;
use JumPHP\Audio\PcmStream;
use JumPHP\Audio\SoundManager;
use JumPHP\Bridge\JsBridge;
use PHPUnit\Framework\TestCase;
final class PcmStreamTest extends TestCase
{
public function testWithoutDeviceNothingIsQueued(): void
{
$sound = new SoundManager(); // not initialised: no device (headless)
$pcm = new PcmStream($sound, new JsBridge());
self::assertFalse($pcm->isAvailable());
self::assertGreaterThan(60.0, $pcm->buffered());
$pcm->push(str_repeat("\0\0", 2048), 22050, 2); // does nothing, no error
$pcm->update();
$pcm->clear();
self::assertGreaterThan(60.0, $pcm->buffered());
}
public function testThePageReportsWhatIsQueued(): void
{
$bridge = new JsBridge();
$pcm = new PcmStream(new SoundManager(), $bridge);
$bridge->emit('pcm', [['buffered' => 0.25]]);
self::assertFalse($pcm->isAvailable()); // desktop test run: still "nothing to hear"
}
/** Desktop with an audio device: what is pushed is queued on SDL_mixer's output, and clear() drops it. */
public function testTheStreamIsBufferedAndCleared(): void
{
if (!function_exists('JumPHP_StreamOpen')) {
self::markTestSkipped('the SDL_mixer binding has no continuous music stream');
}
$sound = new SoundManager();
$sound->init();
if (!$sound->isEnabled()) {
self::markTestSkipped('no audio device');
}
$pcm = new PcmStream($sound, new JsBridge());
self::assertTrue($pcm->isAvailable());
$pcm->push(str_repeat("\0\0", 22050), 22050, 1); // one second, mono, 22050 Hz
self::assertGreaterThan(0.5, $pcm->buffered(), 'the second is queued');
self::assertLessThanOrEqual(1.05, $pcm->buffered());
$pcm->clear();
self::assertLessThan(0.1, $pcm->buffered(), 'clear() drops the queue');
$sound->close();
}
}