JA
apps/winzik / src / Cloud / PlaySync.php · commit 6576d6f
<?phpnamespace App\Cloud;use App\Audio\Player;use App\Core\WinZik;use App\Model\Playlist;use App\Model\Text;/** * « Lecture synchronisée avec mes appareils »: the devices of the account play the same thing (the song, playing / * paused / stopped, the position, WinZik's own volume), through the account's room (CloudLink, sealed type 40 JSON). * * The last device where the user acted leads: each frame its player is compared with the frame before (whatever * interface changed it: desktop, phone, original, the TV's remote); a change goes out at once as `play` {why: act} with * the next sequence number; the leader also sends its position every BEAT s while it plays (`why: beat`). The others * apply it without sending anything back (their player is compared again after it: no echo), and seek when they are more * than DRIFT s off (the age of the message counted). Acting on a follower makes it the leader. What WinZik does by itself * (the end of a song, the resume of the last time; WinZik::$autoChanges) never takes the lead. * * Messages: play {seq, leader, why: act | beat | state, song: {entry, sha256, artist, title, duration, name} | null, * state, pos, vol, sent}, playAsk {} (a device that comes into the room: the others answer with `play` {why: state} * to it alone), sync {on: false} (this device became independent). A newer seq wins; the same seq: the same leader * (its beats), or the bigger device id (two devices that acted at the same moment end on the same one). * * The song is found on a follower by its cloud entry (its file here, else its cloud line: playing it starts its copy, * then it plays where the others are), else its SHA-256 among the cloud entries copied here, else the file's name or * artist + title + length in the play lists; not found: a notice, and this device stays as it is. */final class PlaySync{    public const BEAT = 2.0;    public const DRIFT = 1.5;    /** an order (act / state): followed to this close */    public const NEAR = 0.5;    /** a follower that went to the next song by itself waits this long for the leader's next one */    public const AUTO_WAIT = 5.0;    private const RETRY = 1.0;    /** "Synchronisé" (true) or "Indépendant" (false); Cloud::setPlaySync() saves it */    public bool $enabled = true;    /** the clock (seconds; tests give theirs) */    public \Closure $now;    public int $seq = 0;    /** the device that leads ('' none known) */    public string $leader = '';    /** @var array<string, mixed>|null the leader's last state, with `at` (its arrival here) and `age` */    public ?array $remote = null;    /** @var array<string, bool> device id => synced (it said so by a message) */    private array $synced = [];    /** @var array<string, list<float>> device id => last arrival - sent differences (the smallest = its clock's offset) */    private array $deltas = [];    // what the player was after the last look    private ?string $file = null;    private string $state = Player::STOPPED;    private int $volume = -1;    private int $seeks = 0;    private int $autos = 0;    private bool $looked = false;    private bool $inRoom = false;    private float $beatAt = 0.0;    private bool $pending = false;    private float $sentAt = -99.0;    private float $retryAt = -99.0;    /** the remote song this device plays (its key) and its file here */    private string $appliedKey = '';    private ?string $appliedFile = null;    /** the remote song whose cloud line was played (its copy started), the song said missing */    private string $fetchedKey = '';    private string $missingKey = '';    private float $autoAt = -99.0;    private int $autoSeq = -1;    public function __construct(private WinZik $wz, private Cloud $cloud, private CloudLink $link)    {        $this->now = static fn (): float => microtime(true);    }    private function now(): float    {        return ($this->now)();    }    private function me(): string    {        return $this->cloud->deviceId();    }    // --- what the interfaces show ------------------------------------------------------------------------------------    /** the devices playing together now: this one + the synced ones in the room (0: independent or not in the room) */    public function count(): int    {        if (!$this->enabled || !$this->link->inRoom()) {            return 0;        }        $room = $this->link->devices();        return 1 + count(array_filter(array_keys($this->synced), fn (string $d) => isset($room[$d])));    }    /** the leader is another device of the room */    public function following(): bool    {        return $this->enabled && $this->leader !== '' && $this->leader !== $this->me() && $this->link->has($this->leader);    }    // --- each frame --------------------------------------------------------------------------------------------------    /** Before the room's messages: what the user did since the last frame goes out. */    public function observe(): void    {        $p = $this->wz->player;        $in = $this->link->inRoom();        if (!$this->enabled) {            $this->inRoom = false;            $this->snapshot();            return;        }        if ($in && !$this->inRoom) {            $this->inRoom = true;            $this->synced = [];            $this->seq = 0;         // what this device did alone counts for nothing: it joins the others            $this->leader = '';            $this->link->send(['t' => 'playAsk']);     // the state of the others: this device joins it        } elseif (!$in) {            $this->inRoom = false;        }        if ($this->leader !== '' && $this->leader !== $this->me() && $in && !$this->link->has($this->leader)) {            $this->leader = '';     // the leader left: whoever acts next leads (this one's own next songs too)        }        if (!$this->looked) {            $this->snapshot();            return;        }        $song = $p->file !== $this->file && !($p->state === Player::STOPPED && $this->state === Player::STOPPED);        $changed = $song || $p->state !== $this->state || $this->wz->seeks !== $this->seeks || $p->volume !== $this->volume;        $auto = $this->wz->autoChanges !== $this->autos;        $this->snapshot();        if (!$changed) {            if ($this->pending && $this->now() - $this->sentAt >= 0.15) {                $this->act();            }            return;        }        if ($auto && $this->following()) {            // the end of the song here: the leader's next one comes (Hasard: not the same one), not this one's            $this->autoAt = $this->now();            $this->autoSeq = $this->seq;            $this->appliedKey = '';            return;        }        // the user acted here (or WinZik went on by itself while leading): this device leads        $this->seq++;        $this->leader = $this->me();        $this->remote = null;        $this->appliedKey = $this->fetchedKey = '';        if ($this->now() - $this->sentAt < 0.15 && !$song && $p->state === $this->state) {            $this->pending = true;      // the volume slider dragged: one message every 0.15 s            return;        }        $this->act();    }    /** After the room's messages: the leader's beat, a follower trying its song again (its copy came, its tag is read). */    public function tick(): void    {        if (!$this->enabled || !$this->link->inRoom()) {            return;        }        $now = $this->now();        if ($this->leader === $this->me() && $this->wz->player->state === Player::PLAYING && $now - $this->beatAt >= self::BEAT && $this->count() > 1) {            $this->send('beat');        }        $r = $this->remote;        if ($r !== null && $this->following() && $now - $this->retryAt >= self::RETRY && ($r['state'] ?? '') !== Player::STOPPED            && !$this->sameSong($r)) {            $this->retryAt = $now;            $this->apply($r, true);        }    }    private function snapshot(): void    {        $p = $this->wz->player;        $this->file = $p->file;        $this->state = $p->state;        $this->volume = $p->volume;        $this->seeks = $this->wz->seeks;        $this->autos = $this->wz->autoChanges;        $this->looked = true;    }    private function act(): void    {        $this->pending = false;        $this->send('act');    }    // --- the messages ----------------------------------------------------------------------------------------------    /** @return array<string, mixed> this device's player as a message */    private function message(string $why): array    {        $p = $this->wz->player;        return ['t' => 'play', 'seq' => $this->seq, 'leader' => $this->leader, 'why' => $why, 'song' => $this->song(),            'state' => $p->state, 'pos' => round($p->position, 3), 'vol' => $p->volume, 'sent' => $this->now()];    }    private function send(string $why, ?string $to = null): void    {        if ($why !== 'state') {            $this->beatAt = $this->sentAt = $this->now();        }        $this->link->send($this->message($why), $to);    }    /** @return array<string, mixed>|null the song playing here, as another device can find it */    private function song(): ?array    {        $file = $this->wz->player->file;        if ($file === null) {            return null;        }        $e = $this->cloud->entryOfItem($this->wz->relative($file));        [$tag] = $this->wz->describe($file);        return ['entry' => (string)($e['id'] ?? ''), 'sha256' => (string)($e['sha256'] ?? ''),            'artist' => $tag->artist !== '' ? $tag->artist : (string)($e['artist'] ?? ''),            'title' => $tag->title !== '' ? $tag->title : (string)($e['title'] ?? ''),            'duration' => round($this->wz->player->duration(), 1), 'name' => Text::baseName($file)];    }    /** @param array<string, mixed> $m a message of the room (Cloud routes play, playAsk, sync here) */    public function received(string $from, array $m): void    {        if (!$this->enabled) {            return;        }        switch ($m['t'] ?? '') {            case 'sync':                if (empty($m['on'])) {                    unset($this->synced[$from]);                    if ($this->leader === $from) {                        $this->leader = '';                    }                }                return;            case 'playAsk':                $this->synced[$from] = true;                $this->send('state', $from);                return;            case 'play':                $this->synced[$from] = true;                $this->played($from, $m);                return;        }    }    /** @param array<string, mixed> $m */    private function played(string $from, array $m): void    {        $seq = (int)($m['seq'] ?? 0);        $leader = (string)($m['leader'] ?? '');        if ($seq <= 0 || $leader === '' || $leader === $this->me()) {            return;     // no state yet over there, or this device's own state told back        }        $accept = $seq > $this->seq || ($seq === $this->seq && ($leader === $this->leader || strcmp($leader, $this->leader) > 0));        if (!$accept) {            return;        }        $now = $this->now();        // the age of the message: its delay over the smallest one seen from that device (the clocks of two devices differ)        $d = $now - (float)($m['sent'] ?? $now);        $list = $this->deltas[$from] ?? [];        $list[] = $d;        $this->deltas[$from] = $list = array_slice($list, -20);        $age = max(0.0, min(3.0, $d - min($list)));        $changed = $leader !== $this->leader;        $this->seq = $seq;        $this->leader = $leader;        $this->pending = false;        $m['at'] = $now;        $m['age'] = $age;        $this->remote = $m;        if ($changed && $leader !== $this->me() && ($m['why'] ?? '') !== 'beat') {            $this->wz->notice('Synchro : ' . $this->cloud->deviceLabel($leader) . ' mène la lecture', 3);        }        $this->apply($this->remote, false);    }    // --- following ---------------------------------------------------------------------------------------------------    /** the key of a remote song: its entry, else its SHA-256, else artist + title, else its name */    private static function key(?array $song): string    {        if ($song === null) {            return '';        }        if (($song['entry'] ?? '') !== '') {            return 'e:' . $song['entry'];        }        if (($song['sha256'] ?? '') !== '') {            return 's:' . $song['sha256'];        }        if (($song['title'] ?? '') !== '') {            return 't:' . mb_strtolower($song['artist'] . '|' . $song['title']);        }        return 'n:' . mb_strtolower((string)($song['name'] ?? ''));    }    /** @param array<string, mixed> $r */    private function sameSong(array $r): bool    {        $p = $this->wz->player;        return $p->file !== null && $this->appliedKey !== '' && $this->appliedKey === self::key($r['song'] ?? null) && $p->file === $this->appliedFile;    }    /** @param array<string, mixed> $r the leader's state, applied here without sending anything */    private function apply(array $r, bool $retry): void    {        $wz = $this->wz;        $p = $wz->player;        $wz->cancelResume();        $vol = (int)($r['vol'] ?? -1);        if ($vol >= 0 && $vol !== $p->volume) {            $wz->setVolume($vol);        }        $state = (string)($r['state'] ?? Player::STOPPED);        $song = is_array($r['song'] ?? null) ? $r['song'] : null;        $now = $this->now();        $expected = (float)($r['pos'] ?? 0) + ($state === Player::PLAYING ? (float)$r['age'] + $now - (float)$r['at'] : 0.0);        if ($state === Player::STOPPED) {            if ($p->state !== Player::STOPPED) {                $wz->stop();            }            $this->snapshot();            return;        }        $fresh = false;        if ($song !== null && !$this->sameSong($r)) {            if ($this->autoSeq === $this->seq && $now - $this->autoAt < self::AUTO_WAIT) {                $this->snapshot();                return;     // this device just went to its next song: the leader's comes            }            $key = self::key($song);            $at = $this->locate($song);            if ($at === null) {                if ($this->missingKey !== $key) {                    $this->missingKey = $key;                    $name = trim(($song['artist'] ?? '') . ' - ' . ($song['title'] ?? ''), ' -') ?: (string)($song['name'] ?? '');                    $wz->notice('Synchro : « ' . $name . ' » n\'est pas sur cet appareil', 5);                }                $this->snapshot();                return;            }            [$view, $index] = $at;            if ($view !== $this->cloud->view()) {                $this->cloud->useView($view);            }            $item = $wz->playlist->items[$index] ?? '';            if (Cloud::isPseudo($item)) {                if ($this->fetchedKey !== $key) {                    $this->fetchedKey = $key;                    $wz->playIndex($index);     // its copy starts: it plays once here (tick() tries again)                }                $this->snapshot();                return;            }            $wz->playIndex($index);            if ($p->file === null || $p->error) {                $this->snapshot();                return;            }            $this->appliedKey = $key;            $this->appliedFile = $p->file;            $this->missingKey = $this->fetchedKey = '';            $fresh = true;        }        if ($p->file === null) {            $this->snapshot();            return;        }        if ($state === Player::PLAYING && $p->state !== Player::PLAYING) {            $wz->play();        } elseif ($state === Player::PAUSED && $p->state !== Player::PAUSED) {            if ($p->state === Player::STOPPED) {                $wz->play();            }            $wz->pause();        }        $near = ($r['why'] ?? '') === 'beat' && !$fresh && !$retry ? self::DRIFT : self::NEAR;        if (abs($p->position - $expected) > $near) {            $wz->seek($expected);        }        $this->snapshot();    }    /**     * Where the remote song is here: [view, index] of a play list (the one shown, else the other one), null: not here.     * @param array<string, mixed> $song     * @return array{0: string, 1: int}|null     */    private function locate(array $song): ?array    {        $cloud = $this->cloud;        $paths = [];        $pseudo = [];        $ids = [];        $entry = (string)($song['entry'] ?? '');        if ($entry !== '' && $cloud->playlist->entry($entry) !== null) {            $ids[] = $entry;        }        $sha = (string)($song['sha256'] ?? '');        if ($sha !== '') {            foreach ($cloud->playlist->entries as $e) {                if (($e['sha256'] ?? '') === $sha) {                    $ids[] = (string)$e['id'];                }            }        }        foreach (array_unique($ids) as $id) {            $f = $cloud->playlist->fileOf($id);            if ($f !== null) {                $paths[$this->wz->path($f)] = true;            }            $pseudo[Cloud::PSEUDO . $id . '.mp3'] = true;        }        $view = $cloud->view();        $other = $view === 'cloud' ? 'local' : 'cloud';        $shown = $this->find($this->wz->playlist, $song, $paths, $pseudo);        if ($shown !== null) {            return [$view, $shown];        }        if ($view === 'cloud') {            $local = $cloud->localPlaylist();            $i = $local !== null ? $this->find($local, $song, $paths, []) : null;            return $i !== null ? ['local', $i] : null;        }        if ($ids !== [] && $cloud->signedIn()) {            // in the cloud playlist: shown, then its line (its file here, or its cloud line)            $cloud->useView('cloud');            $i = $this->find($this->wz->playlist, $song, $paths, $pseudo);            if ($i !== null) {                return [$other, $i];            }            $cloud->useView('local');        }        return null;    }    /**     * @param array<string, mixed> $song     * @param array<string, bool> $paths     * @param array<string, bool> $pseudo     */    private function find(Playlist $list, array $song, array $paths, array $pseudo): ?int    {        $wz = $this->wz;        foreach ($list->items as $i => $item) {            if (isset($pseudo[$item]) || ($paths !== [] && !Cloud::isPseudo($item) && isset($paths[$wz->path($item)]))) {                return $i;            }        }        $name = mb_strtolower((string)($song['name'] ?? ''));        if ($name !== '') {            foreach ($list->items as $i => $item) {                if (!Cloud::isPseudo($item) && mb_strtolower(Text::baseName($item)) === $name) {                    return $i;                }            }        }        $title = mb_strtolower(trim((string)($song['title'] ?? '')));        if ($title === '') {            return null;        }        $artist = mb_strtolower(trim((string)($song['artist'] ?? '')));        $duration = (float)($song['duration'] ?? 0);        foreach (array_slice($list->items, 0, 3000, true) as $i => $item) {            if (Cloud::isPseudo($item)) {                continue;            }            [$tag, $info] = $wz->describeLater($item);      // not read yet: the next try (tick) has it            if (mb_strtolower(trim($tag->title)) === $title && mb_strtolower(trim($tag->artist)) === $artist                && ($duration <= 0 || $info->duration <= 0 || abs($info->duration - $duration) <= 3.0)) {                return $i;            }        }        return null;    }    // --- the choice of this device -------------------------------------------------------------------------------------    /** Synchronisé / Indépendant: the others are told; back to synchronised, this device joins their state. */    public function setEnabled(bool $on): void    {        if ($on === $this->enabled) {            return;        }        if (!$on) {            $this->link->send(['t' => 'sync', 'on' => false]);        }        $this->enabled = $on;        $this->inRoom = false;      // the next look asks the others' state again        $this->leader = '';        $this->remote = null;        $this->pending = false;        $this->synced = [];        $this->appliedKey = $this->fetchedKey = $this->missingKey = '';        $this->snapshot();    }}