<?php

declare(strict_types=1);

namespace Blax\WebRtc\Support;

/**
 * Small audio helpers for the realtime bridge. Providers speak raw PCM16; browsers
 * play containers — {@see wav()} wraps PCM as a WAV so it plays in an <audio> tag or
 * a data: URL with no client-side decoding.
 */
final class Audio
{
    /** Wrap raw PCM16 little-endian as a WAV container (default 24kHz mono, the realtime format). */
    public static function wav(string $pcm, int $sampleRate = 24000, int $channels = 1, int $bits = 16): string
    {
        $byteRate = $sampleRate * $channels * intdiv($bits, 8);
        $blockAlign = $channels * intdiv($bits, 8);

        return 'RIFF'.pack('V', 36 + strlen($pcm)).'WAVE'
            .'fmt '.pack('V', 16).pack('v', 1).pack('v', $channels)
            .pack('V', $sampleRate).pack('V', $byteRate).pack('v', $blockAlign).pack('v', $bits)
            .'data'.pack('V', strlen($pcm)).$pcm;
    }

    /** A `data:audio/wav;base64,…` URL for raw PCM16, ready to hand a browser <audio> element. */
    public static function wavDataUri(string $pcm, int $sampleRate = 24000, int $channels = 1, int $bits = 16): string
    {
        return 'data:audio/wav;base64,'.base64_encode(self::wav($pcm, $sampleRate, $channels, $bits));
    }
}
