JA
apps/winzik / src / Audio / Player.php · commit 6576d6f
<?phpnamespace App\Audio;use App\Model\AudioInfo;use JumPHP\Audio\SoundManager;/** * The player of WinZik (Form8.MediaPlayer1 of 2001), on SDL_mixer's music stream: play, pause, stop, seek, volume, * balance, the position and the end of a song. * * SDL_mixer plays and seeks but does not tell the position nor the length: the length comes from the file's headers * (AudioInfo), the position from a clock that runs while the song plays (set again by every seek). Without an audio * device (tests, a server, a browser before the first click) the same clock plays the song silently: the position * moves, the end comes, the next song starts, exactly as with sound. */final class Player{    public const STOPPED = 'stopped';    public const PLAYING = 'playing';    public const PAUSED = 'paused';    /** SDL_mixer's channel number of the final mix (MIX_CHANNEL_POST): the balance pans the whole output */    private const POST = -2;    public string $state = self::STOPPED;    public ?string $file = null;    public AudioInfo $info;    /** seconds */    public float $position = 0.0;    /** 0..100 (Label1 "Volume : 50 %") */    public int $volume = 50;    /** -100..100 (Label2 "Balance : 0 %") */    public int $balance = 0;    /** the preamp of the equalizer: a gain (1 = none) on the volume */    public float $gain = 1.0;    /** the last file could not be opened (MediaPlayer1_Error) */    public bool $error = false;    /** cast: the song is heard on the TV (App\Cast): the clock runs, nothing comes out here */    public bool $silent = false;    private mixed $music = null;    /** seconds since play() / seek(): SDL_mixer needs a moment before Mix_PlayingMusic() says yes */    private float $since = 0.0;    public function __construct(private ?SoundManager $sound = null)    {        $this->info = new AudioInfo();    }    /** Real sound (SDL_mixer opened an audio device) or the silent clock. */    public function hasSound(): bool    {        return $this->sound !== null && $this->sound->isEnabled() && function_exists('Mix_LoadMUS');    }    public function duration(): float    {        return $this->info->duration;    }    /** Opens a file (stops the one playing); false when it cannot be played. $sound: what is heard, when it is another file (a film's sound). */    public function load(string $file, ?string $sound = null): bool    {        $this->halt();        $this->free();        $this->file = $file;        $sound ??= $file;        $this->heard = $sound;        $this->position = 0.0;        $this->state = self::STOPPED;        $this->error = !is_file($sound);        $this->info = $this->error ? new AudioInfo() : AudioInfo::of($sound);        if (!$this->error && $this->hasSound()) {            $this->music = $this->open($sound);            $this->error = $this->music === null;        }        return !$this->error;    }    /** the file heard: the song, or its sound through the equalizer, or a film's sound */    public string $heard = '';    /**     * Another file for the same song, heard from where it is (the equalizer's sound, made by ffmpeg): the clock, the     * length and the state stay. false when it cannot be opened (the old one goes on).     */    public function swapSound(string $sound): bool    {        if ($sound === $this->heard || $this->file === null || !is_file($sound)) {            return false;        }        $music = $this->hasSound() ? $this->open($sound) : null;        if ($this->hasSound() && $music === null) {            return false;        }        $this->halt();        $this->free();        $this->music = $music;        $this->heard = $sound;        if ($this->state === self::PLAYING && $music !== null) {            \Mix_PlayMusic($music, 0);            @\Mix_SetMusicPosition($this->position);            $this->applyVolume();            $this->since = 0.0;        } elseif ($this->state === self::PAUSED && $music !== null) {            \Mix_PlayMusic($music, 0);            @\Mix_SetMusicPosition($this->position);            \Mix_PauseMusic();        }        return true;    }    /** A film whose sound is not made yet: nothing to hear, no error. */    public function wait(string $file): void    {        $this->halt();        $this->free();        $this->file = $file;        $this->position = 0.0;        $this->state = self::STOPPED;        $this->error = false;        $this->info = new AudioInfo();    }    public function play(): void    {        if ($this->file === null || $this->error) {            return;        }        if ($this->state === self::PAUSED) {            if ($this->music !== null) {                \Mix_ResumeMusic();            }            $this->state = self::PLAYING;            return;        }        if ($this->state === self::PLAYING) {            return;        }        if ($this->music !== null) {            \Mix_PlayMusic($this->music, 0);            if ($this->position > 0.05) {                @\Mix_SetMusicPosition($this->position);            }            $this->applyVolume();        }        $this->since = 0.0;        $this->state = self::PLAYING;    }    public function pause(): void    {        if ($this->state !== self::PLAYING) {            return;        }        if ($this->music !== null) {            \Mix_PauseMusic();        }        $this->state = self::PAUSED;    }    /** Pause when it plays, play when it does not (the joystick's Play/Pause, the compact mode). */    public function togglePause(): void    {        $this->state === self::PLAYING ? $this->pause() : $this->play();    }    public function stop(): void    {        $this->halt();        $this->position = 0.0;        $this->state = self::STOPPED;    }    /** Goes to a time (the position bar); keeps playing, paused or stopped. */    public function seek(float $seconds): void    {        $max = $this->duration() > 0 ? $this->duration() : $seconds;        $this->position = max(0.0, min($seconds, $max));        $this->since = 0.0;        if ($this->music !== null && $this->state !== self::STOPPED) {            if (@\Mix_SetMusicPosition($this->position) !== 0 && $this->state === self::PLAYING) {                // a format SDL_mixer cannot seek in (some WAV): it starts again from there as well as it can                \Mix_PlayMusic($this->music, 0);                @\Mix_SetMusicPosition($this->position);            }        }    }    public function setVolume(int $volume): void    {        $this->volume = max(0, min(100, $volume));        $this->applyVolume();    }    /** The preamp of the equalizer, in dB (-12..+12). */    public function setPreamp(float $db): void    {        $this->gain = 10 ** (max(-12.0, min(12.0, $db)) / 20);        $this->applyVolume();    }    public function setBalance(int $balance): void    {        $this->balance = max(-100, min(100, $balance));        if ($this->hasSound() && function_exists('Mix_SetPosition')) {            // the angle of the sound: 0 in front, 90 on the right, 270 on the left            $angle = (int)round($this->balance >= 0 ? $this->balance * 0.9 : 360 + $this->balance * 0.9) % 360;            @\Mix_SetPosition(self::POST, $angle, 0);        }    }    /**     * Once per frame: the clock moves, and the end of the song is seen.     * @return bool true when the song just ended by itself (the player goes to the next one)     */    public function update(float $dt): bool    {        if ($this->state !== self::PLAYING) {            return false;        }        $this->position += $dt;        $this->since += $dt;        $duration = $this->duration();        $ended = $this->music !== null            ? ($this->since > 0.5 && !\Mix_PlayingMusic()) || ($duration > 0 && $this->position >= $duration + 2.0)            : $duration > 0 && $this->position >= $duration;    // (the sound that never says its end: 2 s after its length, the next one)        if ($ended || ($this->music === null && $duration <= 0 && $this->position > 600)) {            $this->state = self::STOPPED;            $this->position = $duration;            return true;        }        if ($duration > 0 && $this->position > $duration) {            $this->position = $duration;    // the clock waits for SDL_mixer to say the end        }        return false;    }    /** SDL_mixer's music of a file, null when it cannot read it. */    private function open(string $file): mixed    {        try {            // the binding's stub says Mix_Music, the real one gives false for a file it cannot read            $music = call_user_func('Mix_LoadMUS', $file);        } catch (\Throwable) {            return null;        }        return is_object($music) ? $music : null; // @phpstan-ignore function.alreadyNarrowedType    }    private function applyVolume(): void    {        // through the engine's sound manager: its mute (hidden tab) and its music volume stay right        $this->sound?->setMusicVolume($this->silent ? 0.0 : min(1.0, $this->volume / 100 * $this->gain));     // cast: silent    }    private function halt(): void    {        if ($this->music !== null && function_exists('Mix_HaltMusic')) {            \Mix_HaltMusic();        }    }    private function free(): void    {        if ($this->music !== null && function_exists('Mix_FreeMusic')) {            \Mix_FreeMusic($this->music);        }        $this->music = null;    }}