<?phpnamespace Tests;use App\Audio\Player;use App\Cloud\Cloud;use App\Cloud\CloudAccount;use App\Core\WinZik;use PHPUnit\Framework\TestCase;use Tests\Cloud\FakeCloudServer;use Tests\Cloud\FakeRelay;/** * « Lecture synchronisée avec mes appareils » (App\Cloud\PlaySync): two or three WinZik of the same account, each with * its own folder and its own copies of the songs, through the fake server and the fake relay (tests/Cloud). The players * play silently (no sound device): their clocks really move with the frames. */final class PlaySyncTest extends TestCase{ private string $tmp; private FakeCloudServer $server; private FakeRelay $relay; /** the clock of every device (seconds) */ private float $clock = 1000.0; /** @var list<WinZik> */ private array $all = []; protected function setUp(): void { $this->tmp = sys_get_temp_dir() . '/winzik-playsync-' . bin2hex(random_bytes(4)); @mkdir($this->tmp, 0777, true); $this->server = new FakeCloudServer(); $this->relay = new FakeRelay(); $this->server->accounts['ada'] = ['password' => 'motdepasse1', 'recovery' => 'X', 'version' => 0, 'entries' => [], 'lyrics' => []]; } protected function tearDown(): void { foreach ($this->all as $wz) { $wz->cloud()?->stop(); } exec('rm -rf ' . escapeshellarg($this->tmp)); } /** * A device of the account, signed in, with its own copies of the songs in its play list. * @param list<string> $songs names of assets/music files copied as <name>.<ext>: 'alpha.mp3' => winzik.mp3 * @return array{0: WinZik, 1: Cloud} */ private function device(string $name, string $kind, array $songs = ['alpha' => 'winzik.mp3', 'beta' => 'chaine-hifi.wav']): array { $wz = new WinZik(); $account = new CloudAccount(fn (string $m, string $u, string|array|null $b, array $h) => $this->server->request($m, $u, $b, $h), FakeCloudServer::BASE, "$this->tmp/$name/cloud.json", $kind); $cloud = new Cloud($wz, $account, "$this->tmp/$name/cloud", fn () => $this->relay->session(), null, "$this->tmp/$name/received"); self::assertNotNull($cloud->playSync); $cloud->playSync->now = fn (): float => $this->clock; $wz->useCloud($cloud); $files = []; foreach ($songs as $song => $asset) { $file = "$this->tmp/$name/music/$song." . pathinfo($asset, PATHINFO_EXTENSION); @mkdir(dirname($file), 0777, true); copy(__DIR__ . '/../assets/music/' . $asset, $file); $files[] = $file; } $wz->playlist = new \App\Model\Playlist(); $wz->addFiles($files); $wz->open(0); $wz->playlist->shuffle = false; $cloud->signIn('ada', 'motdepasse1', ucfirst($name))->then(fn () => null, fn (\Throwable $e) => self::fail($e->getMessage())); $this->all[] = $wz; return [$wz, $cloud]; } /** every device a frame of 50 ms, until $until says yes */ private function frames(\Closure $until, int $max = 400): void { for ($i = 0; $i < $max; $i++) { $this->frame(); if ($until()) { return; } } self::fail('not reached after ' . $max . ' frames'); } private function frame(int $n = 1): void { for ($k = 0; $k < $n; $k++) { $this->clock += 0.05; foreach ($this->all as $wz) { $wz->tick(0.05); } } } /** both in the room, each seeing the other synced */ private function together(Cloud ...$clouds): void { $this->frames(function () use ($clouds): bool { foreach ($clouds as $c) { if ($c->syncCount() !== count($clouds)) { return false; } } return true; }); } private static function song(WinZik $wz): string { return basename((string)$wz->player->file); } public function testASongChangedOnOneDevicePlaysOnTheOtherWhereItIs(): void { [$pc, $pcCloud] = $this->device('pc', 'desktop'); [$phone, $phoneCloud] = $this->device('phone', 'phone'); $this->together($pcCloud, $phoneCloud); self::assertSame('Synchro · 2 appareils', $phoneCloud->syncLabel()); $pc->playIndex(1); // beta, on the PC $this->frames(fn () => self::song($phone) === 'beta.wav' && $phone->player->state === Player::PLAYING); self::assertNotSame($pc->player->file, $phone->player->file, 'its own copy, on the phone'); self::assertSame($pcCloud->deviceId(), $phoneCloud->playSync?->leader); self::assertTrue($phoneCloud->playSync->following()); self::assertStringContainsString('Pc mène la lecture', $phoneCloud->syncText()); $this->frame(40); self::assertEqualsWithDelta($pc->player->position, $phone->player->position, 0.2, 'the same moment of the song'); } public function testPausePlaySeekAndVolumeFollowWithoutAnEcho(): void { [$pc, $pcCloud] = $this->device('pc', 'desktop'); [$phone, $phoneCloud] = $this->device('phone', 'phone'); $this->together($pcCloud, $phoneCloud); $pc->playIndex(0); $this->frames(fn () => $phone->player->state === Player::PLAYING && self::song($phone) === 'alpha.mp3'); $sent = count($this->relay->traffic); $pc->pause(); $this->frames(fn () => $phone->player->state === Player::PAUSED, 5); $pc->seek(42.0); $this->frames(fn () => abs($phone->player->position - 42.0) < 0.01, 5); $pc->play(); $this->frames(fn () => $phone->player->state === Player::PLAYING, 5); $pc->setVolume(23); $this->frames(fn () => $phone->player->volume === 23, 10); $pc->stop(); $this->frames(fn () => $phone->player->state === Player::STOPPED, 5); // nothing came back from the phone: five orders, five messages (and no beat: paused or just played) $this->frame(10); self::assertSame($sent + 5, count($this->relay->traffic), 'no echo'); self::assertSame($pcCloud->deviceId(), $phoneCloud->playSync?->leader); self::assertSame($pcCloud->deviceId(), $pcCloud->playSync?->leader, 'the PC still leads'); } public function testTheLeaderSendsItsPositionAndAFollowerThatDriftsCatchesUp(): void { [$pc, $pcCloud] = $this->device('pc', 'desktop'); [$phone, $phoneCloud] = $this->device('phone', 'phone'); $this->together($pcCloud, $phoneCloud); $pc->playIndex(0); $this->frames(fn () => $phone->player->state === Player::PLAYING); $before = count($this->relay->traffic); $this->frame(50); // 2.5 s: a beat self::assertGreaterThan($before, count($this->relay->traffic), 'a beat while it plays'); // the phone's clock went off by 3 s (a busy phone): the next beat puts it back $phone->player->position -= 3.0; $this->frame(45); self::assertEqualsWithDelta($pc->player->position, $phone->player->position, 0.2); // a second off: left alone (no seek for less than 1.5 s) $phone->player->position -= 1.0; $this->frame(45); self::assertEqualsWithDelta($pc->player->position - 1.0, $phone->player->position, 0.2); self::assertSame($pcCloud->deviceId(), $phoneCloud->playSync?->leader, 'its own corrections never take the lead'); // a beat that took 2 s to come (the relay was slow): its age is counted $sync = $phoneCloud->playSync; $phone->player->position = $pc->player->position - 2.5; $sync->received($pcCloud->deviceId(), ['t' => 'play', 'seq' => $sync->seq, 'leader' => $pcCloud->deviceId(), 'why' => 'beat', 'song' => $sync->remote['song'] ?? null, 'state' => 'playing', 'pos' => $pc->player->position - 2.0, 'vol' => $pc->player->volume, 'sent' => $this->clock - 2.0]); self::assertEqualsWithDelta($pc->player->position, $phone->player->position, 0.2, 'where the PC is now, not where it was'); } public function testActingOnTheFollowerMakesItTheLeader(): void { [$pc, $pcCloud] = $this->device('pc', 'desktop'); [$phone, $phoneCloud] = $this->device('phone', 'phone'); $this->together($pcCloud, $phoneCloud); $pc->playIndex(0); $this->frames(fn () => $phone->player->state === Player::PLAYING); $phone->playIndex(1); // the user, on the phone $this->frames(fn () => self::song($pc) === 'beta.wav' && $pc->player->state === Player::PLAYING); self::assertSame($phoneCloud->deviceId(), $pcCloud->playSync?->leader); self::assertSame($phoneCloud->deviceId(), $phoneCloud->playSync?->leader); $phone->pause(); $this->frames(fn () => $pc->player->state === Player::PAUSED, 5); self::assertStringContainsString('mène la lecture', $pc->notice); // both at the same moment: they end on the same one (the bigger device id) $pc->setVolume(10); $phone->setVolume(90); $this->frame(5); self::assertSame($pc->player->volume, $phone->player->volume); self::assertSame($pcCloud->playSync?->leader, $phoneCloud->playSync?->leader); } public function testAnIndependentDeviceNeitherSendsNorFollows(): void { [$pc, $pcCloud] = $this->device('pc', 'desktop'); [$phone, $phoneCloud] = $this->device('phone', 'phone'); $this->together($pcCloud, $phoneCloud); $phoneCloud->setPlaySync(false); self::assertFalse(json_decode((string)file_get_contents("$this->tmp/phone/cloud/settings.json"), true)['playSync'], 'kept on this device'); $this->frame(3); self::assertSame(1, $pcCloud->syncCount(), 'the PC knows the phone went its own way'); self::assertSame('', $pcCloud->syncLabel()); self::assertStringStartsWith('Indépendant', $phoneCloud->syncText()); $pc->playIndex(1); $this->frame(20); self::assertNull($phone->player->file === null ? null : ($phone->player->state === Player::PLAYING ? 'playing' : null), 'the phone does not follow'); $sent = count($this->relay->traffic); $phone->playIndex(0); $phone->setVolume(12); $this->frame(20); self::assertSame('beta.wav', self::song($pc), 'the PC does not follow the phone'); $mine = 0; foreach (array_slice($this->relay->traffic, $sent) as $_) { $mine++; } self::assertSame(0, $mine - $this->beatsBetween($sent), 'the phone sent nothing'); // back to synchronised: it joins what the PC plays $phoneCloud->setPlaySync(true); $this->frames(fn () => self::song($phone) === 'beta.wav' && $phone->player->state === Player::PLAYING); $independent = new Cloud($phone, new CloudAccount(fn () => null, FakeCloudServer::BASE, "$this->tmp/phone/cloud.json", 'phone'), "$this->tmp/phone/cloud"); self::assertTrue($independent->playSynced(), 'saved again'); } /** the PC's beats since $from (it plays alone): every message after $from is one of them */ private function beatsBetween(int $from): int { return count($this->relay->traffic) - $from; } public function testADeviceThatComesLaterJoinsWhatTheOthersPlay(): void { [$pc, $pcCloud] = $this->device('pc', 'desktop'); [$phone, $phoneCloud] = $this->device('phone', 'phone'); $this->together($pcCloud, $phoneCloud); $phone->playIndex(1); $this->frames(fn () => $pc->player->state === Player::PLAYING); $phone->seek(10.0); $this->frame(40); // a tablet signs in: it asks, the others answer, it plays the same song at the same moment [$tablet, $tabletCloud] = $this->device('tablet', 'phone'); $this->frames(fn () => $tablet->player->state === Player::PLAYING && self::song($tablet) === 'beta.wav'); $this->frame(10); self::assertEqualsWithDelta($phone->player->position, $tablet->player->position, 0.3); self::assertSame($phoneCloud->deviceId(), $tabletCloud->playSync?->leader); $this->together($pcCloud, $phoneCloud, $tabletCloud); self::assertSame('Synchro · 3 appareils', $pcCloud->syncLabel()); } public function testASongMissingOnTheFollowerSaysSoAndItStaysAsItIs(): void { [$pc, $pcCloud] = $this->device('pc', 'desktop', ['alpha' => 'winzik.mp3', 'gamma' => 'partage.mp3']); [$phone, $phoneCloud] = $this->device('phone', 'phone', ['alpha' => 'winzik.mp3']); $this->together($pcCloud, $phoneCloud); $pc->playIndex(0); $this->frames(fn () => $phone->player->state === Player::PLAYING); $pc->playIndex(1); // gamma: not on the phone $this->frame(3); self::assertSame('alpha.mp3', self::song($phone), 'it stays as it is'); self::assertStringContainsString('n\'est pas sur cet appareil', $phone->notice); $notice = $phone->notice; $phone->notice = ''; $this->frame(60); self::assertSame('', $phone->notice, 'said once'); self::assertNotSame('', $notice); } public function testACloudSongNotOnTheFollowerStartsItsCopyThenPlaysWhereTheOthersAre(): void { [$pc, $pcCloud] = $this->device('pc', 'desktop', ['alpha' => 'winzik.mp3', 'gamma' => 'partage.mp3']); [$phone, $phoneCloud] = $this->device('phone', 'phone', ['alpha' => 'winzik.mp3']); $phoneCloud->wifiOnly = false; // the relay on its own (no LAN here) $phoneCloud->autoCopy = false; $this->together($pcCloud, $phoneCloud); $gamma = (string)$pc->playlist->items[1]; self::assertSame(1, $pcCloud->putFromPc([$pc->path($gamma)])); $this->frames(fn () => count($phoneCloud->entries()) === 1, 800); $id = (string)$phoneCloud->entries()[0]['id']; $pc->playIndex(1); $this->frames(fn () => $phoneCloud->rowState($id)['state'] !== 'absent', 20); self::assertSame('cloud', $phoneCloud->view(), 'the cloud playlist, where its line is'); $this->frames(fn () => $phoneCloud->rowState($id)['state'] === 'here', 2000); $this->frames(fn () => $phone->player->state === Player::PLAYING && $phone->player->file === $phoneCloud->playlist->fileOf($id), 40); $this->frame(5); self::assertEqualsWithDelta($pc->player->position, $phone->player->position, 0.3, 'where the PC is'); } public function testTheEndOfASongOnAFollowerWaitsForTheLeadersNextOne(): void { [$pc, $pcCloud] = $this->device('pc', 'desktop', ['alpha' => 'winzik.mp3', 'beta' => 'chaine-hifi.wav', 'delta' => 'partage.mp3']); [$phone, $phoneCloud] = $this->device('phone', 'phone', ['alpha' => 'winzik.mp3', 'delta' => 'partage.mp3', 'beta' => 'chaine-hifi.wav']); $this->together($pcCloud, $phoneCloud); $pc->playIndex(0); $this->frames(fn () => $phone->player->state === Player::PLAYING); $end = $pc->player->duration(); self::assertGreaterThan(1.0, $end); $pc->seek($end - 0.5); $this->frames(fn () => abs($phone->player->position - ($end - 0.5)) < 0.3, 5); // the phone's list goes on with delta, the PC's with beta: the PC leads, the phone plays beta $this->frames(fn () => self::song($pc) === 'beta.wav', 60); $this->frames(fn () => self::song($phone) === 'beta.wav', 60); self::assertSame($pcCloud->deviceId(), $phoneCloud->playSync?->leader, 'the phone\'s own next song did not take the lead'); $this->frame(60); self::assertSame('beta.wav', self::song($phone)); }}