IT
apps/winzik / tests / MediaTest.php · commit 6576d6f
<?phpnamespace Tests;use App\Form\YouTubeForm;use App\Gui\PlaylistWindow;use App\Media\Process;use App\Media\Tools;/** YouTube (yt-dlp), the films, the zoom, the list made longer, the magnet, the wheel, whole folders. */final class MediaTest extends PlayerTestCase{    private string $music = '';    private string $videos = '';    /** WinZik with "yt-dlp" and "ffmpeg" that answer at once (no network in the tests): they write what the real ones would. */    private function startWithTools(): void    {        $this->startPlayer();        $this->music = $this->wz->storagePath('test/Musique/WinZik');        $this->videos = $this->wz->storagePath('test/Vidéos/WinZik');        $tools = new Tools($this->wz->storagePath('bin'), $this->wz->storagePath('tmp'));        $tools->state = ['yt-dlp' => 'ready', 'ffmpeg' => 'ready'];        $tools->path = ['yt-dlp' => '/fake/yt-dlp', 'ffmpeg' => '/fake/ffmpeg'];        $song = $this->wz->path('assets/music/partage.mp3');        $runner = function (array $cmd) use ($song): Process {            $line = implode(' ', $cmd);            if (in_array('-J', $cmd, true)) {                return Process::finished($cmd, [(string)json_encode(['entries' => [                    ['id' => 'aaa', 'title' => 'Partage (clip officiel)', 'channel' => 'WinZik Band', 'duration' => 199, 'url' => 'https://www.youtube.com/watch?v=aaa'],                    ['id' => 'bbb', 'title' => 'Partage (live)', 'channel' => 'WinZik Band', 'duration' => 3725],                ]])]);            }            if (str_contains($line, '--audio-format mp3')) {                $file = $this->music . '/Partage (clip officiel).mp3';                return Process::finished($cmd, ['[download]  42.0% of 3.10MiB', '[download] 100.0% of 3.10MiB', $file], 0, function () use ($song, $file): void {                    @mkdir(dirname($file), 0777, true);                    copy($song, $file);                });            }            if (str_contains($line, '--merge-output-format mp4')) {                $file = $this->videos . '/Partage (clip officiel).mp4';                return Process::finished($cmd, ['[download] 100.0% of 9MiB', $file], 0, function () use ($file): void {                    @mkdir(dirname($file), 0777, true);                    file_put_contents($file, 'film');                });            }            if (str_ends_with($line, 'audio.wav')) {                // ffmpeg: the film's sound (a real WAV: the visualizer reads it)                return Process::finished($cmd, [], 0, fn () => copy($this->wz->path('assets/music/chaine-hifi.wav'), (string)end($cmd)));            }            if (str_contains($line, 'equalizer=') && str_contains($line, 'pcm_s16le')) {                // ffmpeg: the song through the equalizer                return Process::finished($cmd, [], 0, fn () => copy($this->wz->path('assets/music/chaine-hifi.wav'), (string)end($cmd)));            }            if (str_contains($line, '-ar 16000')) {                // ffmpeg: the sound for Whisper                return Process::finished($cmd, [], 0, fn () => file_put_contents((string)end($cmd), 'wav'));            }            if (str_contains($line, 'winzik-whisper.py')) {                // faster-whisper: two sung lines (and a music one)                return Process::finished($cmd, [], 0, function () use ($cmd): void {                    file_put_contents($cmd[3], json_encode(['segments' => [['start' => 1.5, 'text' => ' on partaje la musik'],                        ['start' => 4.0, 'text' => ' [Musique]'], ['start' => 6.25, 'text' => ' des parolles qui tombe du ciel']]]));                });            }            if (($cmd[1] ?? '') === '-p') {                // "claude -p": the words put right, line for line                return Process::finished($cmd, ['1|On partage la musique', '2|Des paroles qui tombent du ciel']);            }            if (str_contains($line, '%06d.jpg')) {                // ffmpeg: the film's pictures (3 coloured ones; PNG data: SDL_image reads it whatever the name)                return Process::finished($cmd, [], 0, function () use ($cmd): void {                    foreach ([[200, 40, 40], [40, 200, 40], [40, 40, 200]] as $i => [$r, $g, $b]) {                        $im = imagecreatetruecolor(64, 36);                        imagefill($im, 0, 0, (int)imagecolorallocate($im, $r, $g, $b));                        imagepng($im, sprintf(dirname((string)end($cmd)) . '/%06d.jpg', $i + 1));                    }                });            }            return Process::finished($cmd, [], 1);        };        $this->wz->useMedia($tools, \Closure::fromCallable($runner), $this->music, $this->videos);    }    public function testASearchOnYoutubeThenAnMp3GoesIntoTheMusicFolderAndThePlayList(): void    {        $this->startWithTools();        $before = $this->wz->playlist->count();        $this->form->type('y');        $this->game->run(2);        $dialog = $this->game->scene();        self::assertInstanceOf(YouTubeForm::class, $dialog);        $dialog->query->text = 'partage winzik';        $dialog->click($dialog->find);        $this->game->run(20);        self::assertCount(2, $dialog->results->items);        self::assertStringContainsString('Partage (clip officiel)', $dialog->results->items[0]);        self::assertStringContainsString('1:02:05', $dialog->results->items[1], 'the length of a long one');        $dialog->format->selected = 0;        $dialog->click($dialog->get);        $this->game->run(20);        self::assertSame($before + 1, $this->wz->playlist->count(), 'added to the play list');        self::assertFileExists($this->music . '/Partage (clip officiel).mp3');        self::assertStringContainsString('ajouté', implode(' ', $dialog->queue->items));        self::assertSame(100.0, (float)$dialog->total->value, 'the whole queue done');        $this->game->shot('youtube');    }    public function testAnMp4IsPlayedWithItsPicturesInTheVideoWindow(): void    {        $this->startWithTools();        $this->form->type('y');        $this->game->run(2);        $dialog = $this->game->scene();        self::assertInstanceOf(YouTubeForm::class, $dialog);        $dialog->query->text = 'partage';        $dialog->click($dialog->find);        $this->game->run(20);        $dialog->format->selected = 1;        $dialog->click($dialog->get);        $this->game->run(20);        $dialog->click($dialog->quit);        $this->game->run(5);        $film = $this->videos . '/Partage (clip officiel).mp4';        $index = array_search($this->wz->relative($film), $this->wz->playlist->items, true);        self::assertIsInt($index, 'the film is in the list');        $this->wz->playIndex($index);        // its sound was made as soon as it was downloaded (else it is being made now)        $this->game->run(20);        self::assertSame('', $this->wz->waitVideo);        self::assertSame('playing', $this->wz->player->state);        self::assertNotNull($this->wz->videoFrame(), 'a picture of the film');        self::assertTrue($this->desk->video?->visible());        $this->game->wait(1);        $this->game->shot('video');        // x hides it, the sound goes on        $this->clickControl($this->desk->video, 'close');        self::assertFalse($this->desk->video->visible());        self::assertSame('playing', $this->wz->player->state);    }    public function testTheZoomMakesEveryWindowSmaller(): void    {        $this->startPlayer();        $base = $this->desk->baseScale;        self::assertContains('Zoom', $this->desk->menuLabels() ?: array_column($this->desk->menuItems(), 'label'));        $this->desk->setZoom(50);        self::assertEqualsWithDelta(\App\Gui\Desktop::effectiveScale($base, 50), $this->desk->scale, 0.001);        self::assertEqualsWithDelta(0.0, fmod($this->desk->scale * 2, 1.0), 0.001, 'on a half: crisp pixels');        $this->desk->zoomStep(1);        self::assertSame(75, $this->desk->zoomPct(), 'Ctrl + wheel: one step');        $this->game->run(2);        $this->game->shot('zoom-80');    }    public function testTheDotsOfTheListMakeItLonger(): void    {        $this->startPlayer();        $list = $this->desk->playlist;        self::assertNotNull($list);        $h = $list->height();        [$cx, $cy, $cw, $ch] = $list->controls()['gripR'];        [$x, $y] = $this->at($list, $cx + $cw / 2, $cy + $ch / 2);        $this->dragView($x, $y, $x, $y + 5 * PlaylistWindow::ROW_HEIGHT * $this->desk->scale);        self::assertSame(PlaylistWindow::ROWS + 5, $list->rows());        self::assertEqualsWithDelta($h + 5 * PlaylistWindow::ROW_HEIGHT, $list->height(), 0.1);    }    public function testTheListSticksUnderThePlayerWhenItComesNear(): void    {        $this->startPlayer();        $list = $this->desk->playlist;        $main = $this->desk->main;        self::assertNotNull($list);        self::assertTrue($this->wz->ui['playlist']['attached'], 'docked at the first start');        // docked: dragging the list moves the whole        $mainX = $main->x;        [$x, $y] = $this->at($list, 120, 330);        $this->dragView($x, $y, $x + 40 * $this->desk->scale, $y);        self::assertTrue($this->wz->ui['playlist']['attached']);        self::assertEqualsWithDelta($mainX + 40, $main->x, 1, 'the player moved with its list');        // undocked by the menu, pulled away, then brought back near the player        $this->wz->ui['playlist']['attached'] = false;        [$x, $y] = $this->at($list, 120, 330);        $this->dragView($x, $y, $x + 150 * $this->desk->scale, $y + 60 * $this->desk->scale);        self::assertFalse($this->wz->ui['playlist']['attached']);        // brought back near the player's bottom (6 pixels under it, 5 to the right): the magnet does the rest        $dx = $main->x + 5 - $list->x;        $dy = $main->y + $main->height() + 6 - $list->y;        [$x, $y] = $this->at($list, 120, 330);        $this->dragView($x, $y, $x + $dx * $this->desk->scale, $y + $dy * $this->desk->scale);        self::assertTrue($this->wz->ui['playlist']['attached'], 'the magnet');        self::assertEqualsWithDelta($main->y + $main->height(), $list->y, 0.01);        self::assertEqualsWithDelta($main->x, $list->x, 0.01);    }    public function testTheWheelOnTheBalanceMovesIt(): void    {        $this->startPlayer();        $main = $this->desk->main;        [$cx, $cy] = $main->controls()['balance'];        $main->hover($cx + 10, $cy + 5);        $main->wheel(1);        self::assertSame(5, $this->wz->player->balance);        $volume = $this->wz->player->volume;        $main->hover(200, 20);        $main->wheel(-1);        self::assertSame($volume - 5, $this->wz->player->volume, 'elsewhere: the volume');    }    public function testAWholeFolderAndItsSubFoldersGoIntoTheList(): void    {        $this->startPlayer();        $dir = $this->wz->storagePath('test/album');        @mkdir("$dir/cd2", 0777, true);        foreach (['01 a.mp3', 'cd2/02 b.mp3', 'notes.txt', 'cd2/clip.mp4'] as $f) {            file_put_contents("$dir/$f", 'x');        }        $before = $this->wz->playlist->count();        self::assertSame(3, $this->wz->addPaths([$dir]));        self::assertSame($before + 3, $this->wz->playlist->count());    }    public function testTheSecondButtonOfTheLyricsBarUnrollsItToTheWholeScreen(): void    {        $this->startPlayer(['demo' => true]);        $bar = $this->desk->lyrics;        self::assertNotNull($bar);        self::assertSame((float)\App\Gui\LyricsBar::HEIGHT, $bar->height());        $this->clickControl($bar, 'grow');        $this->game->wait(1);        self::assertTrue($bar->full());        self::assertEqualsWithDelta($this->desk->deskHeight(), $bar->height(), 1, 'the whole screen');        self::assertEqualsWithDelta(0, $bar->y, 1);        // K: the animations over the syllables go round        self::assertSame('ball', $bar->karaokeMode());        $this->clickControl($bar, 'kara');        self::assertSame('star', $bar->karaokeMode());        $this->wz->options['karaoke'] = 'ball';        $this->game->wait(3);        $this->game->shot('lyrics-full');        $escape = new \JumPHP\Gui\Pointer();        $escape->keys[] = \JumPHP\Gui\Pointer::ESCAPE;        $this->form->handle($escape);        $this->game->wait(1);        self::assertFalse($bar->full());        self::assertSame((float)\App\Gui\LyricsBar::HEIGHT, $bar->height());        // the F key too        $this->form->type('f');        $this->game->wait(1);        self::assertTrue($bar->full());        $this->form->type('f');        $this->game->wait(1);        self::assertFalse($bar->full());    }    public function testTheEqualizerChangesTheSoundHeardThroughFfmpeg(): void    {        $this->startWithTools();        $this->wz->playIndex(0);        $this->game->run(5);        $plain = $this->wz->player->heard;        $this->wz->eq->preset('Rock');        $this->wz->eqChanged();        $this->game->wait(1.2);        self::assertNotSame($plain, $this->wz->player->heard, 'the song through the equalizer is heard');        self::assertStringContainsString('cache/sound', $this->wz->player->heard);        self::assertSame('playing', $this->wz->player->state);        $this->wz->eq->on = false;        $this->wz->eqChanged();        $this->game->wait(0.3);        self::assertSame($plain, $this->wz->player->heard, 'off: the song as it is');    }    public function testTheVisualizerFollowsTheSamplesOfTheSong(): void    {        $this->startPlayer(['demo' => true]);        $wav = $this->wz->path('assets/music/chaine-hifi.wav');        $index = $this->wz->addFiles([$wav]) > 0 ? $this->wz->playlist->count() - 1 : 0;        $this->wz->playIndex($index);        $this->wz->seek(2);        $this->game->wait(1);        self::assertGreaterThan(0.2, max($this->wz->spectrum->bars), 'the bars stand up with the sound');        self::assertGreaterThanOrEqual(max($this->wz->spectrum->bars) - 0.001, max($this->wz->spectrum->peaks));        $this->game->shot('visualizer');        $this->wz->pause();        $this->game->wait(2);        self::assertLessThan(0.05, max($this->wz->spectrum->bars), 'they fall back when it stops');    }    public function testWhisperThenClaudeMakeTheLyricsOfTheSong(): void    {        $this->startWithTools();        $t = $this->wz->transcriber;        self::assertNotNull($t);        // WinZik's faster-whisper, installed        $bin = $this->wz->storagePath('whisper/bin');        @mkdir($bin, 0777, true);        file_put_contents("$bin/python", '');        touch($this->wz->storagePath('whisper/faster-whisper.ok'));        $this->wz->playIndex(3);        $this->game->run(2);        self::assertTrue($this->wz->transcribe());        $this->game->run(30);        self::assertSame('done', $t->state, $t->error);        self::assertFileExists($t->result);        self::assertSame($this->wz->lyricsCachePath($t->song), $t->result, 'the song\'s own copy, never var/lyr/<name>.lyr');        $lyrics = \App\Model\Lyrics::load($t->result);        self::assertNotNull($lyrics);        if (\App\Media\Transcriber::claude() !== null) {            self::assertSame([[1.5, 'On partage la musique'], [6.25, 'Des paroles qui tombent du ciel']], $lyrics->lines);        } else {            self::assertSame([[1.5, 'on partaje la musik'], [6.25, 'des parolles qui tombe du ciel']], $lyrics->lines, 'the music line is left out');        }        self::assertTrue($this->wz->ui['lyrics']['visible']);    }    public function testClaudesAnswerIsKeptOnlyWhenItHasEveryLine(): void    {        self::assertSame(['A', 'B'], \App\Media\Transcriber::correctedLines("1|A\n2|B\n", 2));        self::assertNull(\App\Media\Transcriber::correctedLines("Voici :\n1|A", 2));        self::assertSame([[0.5, 'x']], \App\Media\Transcriber::parse((string)json_encode(['transcription' => [['offsets' => ['from' => 500], 'text' => ' x'], ['offsets' => ['from' => 900], 'text' => '♪']]])));    }    public function testTheDownloadsWaitTheirTurnInTheQueue(): void    {        $this->startWithTools();        $yt = $this->wz->youtube;        self::assertNotNull($yt);        $yt->download(['id' => 'a', 'title' => 'Un', 'url' => 'https://www.youtube.com/watch?v=a'], 'mp3');        $yt->download(['id' => 'b', 'title' => 'Deux', 'url' => 'https://www.youtube.com/watch?v=b'], 'mp3');        self::assertSame(['download', 'queued'], array_column($yt->jobs, 'state'), 'one at a time');        self::assertSame([0, 2], array_slice($yt->total(), 0, 2));        $this->game->run(30);        self::assertSame(['done', 'done'], array_column($yt->jobs, 'state'));        self::assertSame([2, 2, 1.0], $yt->total());        $yt->clearFinished();        self::assertSame([], $yt->jobs);    }    public function testSynchronisedLyricsOfLrclibBecomeALyr(): void    {        $lyrics = \App\Media\Lrclib::fromLrc("[00:03.56] Quand je n'aurai plus rien à chanter\n[01:06.22][02:10.00] Le refrain\n[ar:Artiste]\n");        self::assertNotNull($lyrics);        self::assertSame([[3.56, "Quand je n'aurai plus rien à chanter"], [66.22, 'Le refrain'], [130.0, 'Le refrain']], $lyrics->lines);        self::assertNull(\App\Media\Lrclib::fromLrc('des paroles sans les temps'));    }    public function testAFilmPreparedByAnOlderWinzikHasItsSoundMadeAgain(): void    {        $this->startWithTools();        $film = $this->videos . '/ancien.mp4';        @mkdir($this->videos, 0777, true);        file_put_contents($film, 'film');        $cache = $this->wz->video;        self::assertNotNull($cache);        // what 0.9.88 left: an MP3 sound marked ready, its pictures        $dir = $cache->folder($film);        @mkdir($dir, 0777, true);        file_put_contents("$dir/audio.mp3", 'x');        touch("$dir/audio.ok");        touch("$dir/frames.ok");        self::assertNull($cache->audio($film), 'not the old sound: made again');        $this->game->run(5);        self::assertSame("$dir/audio.wav", $cache->audio($film));    }    public function testALineIsMovedInTheListByDragAndDrop(): void    {        $this->startPlayer();        $list = $this->desk->playlist;        self::assertNotNull($list);        $items = $this->wz->playlist->items;        $this->wz->playIndex(0);        [$cx, $cy] = $list->controls()['list'];        [$x, $y] = $this->at($list, 120, $cy + 6);                        // the first line        $this->dragView($x, $y, $x, $y + 2 * PlaylistWindow::ROW_HEIGHT * $this->desk->scale);        self::assertSame([$items[1], $items[2], $items[0], $items[3]], $this->wz->playlist->items, 'the first line is now the third');        self::assertSame(2, $this->wz->playlist->active, 'the song playing is still the active one');        self::assertSame($items[0], $this->wz->playlist->current());    }    public function testTheRightDotMakesTheListWiderAndTheLinesSayArtistAndTitle(): void    {        $this->startPlayer();        $list = $this->desk->playlist;        self::assertNotNull($list);        [$cx, $cy, $cw, $ch] = $list->controls()['gripR'];        [$x, $y] = $this->at($list, $cx + $cw / 2, $cy + $ch / 2);        $this->dragView($x, $y, $x + 100 * $this->desk->scale, $y);        self::assertEqualsWithDelta(358, $list->width(), 2);        self::assertSame($list->width() - 26, $list->controls()['remove'][0], 'the buttons of the right follow');        $this->clickControl($list, 'showPaths');        self::assertTrue($this->wz->ui['playlist']['paths']);        $this->clickControl($list, 'showTags');        self::assertFalse($this->wz->ui['playlist']['paths']);        $this->game->run(2);        $this->game->shot('playlist-wide');    }    public function testTheSearchGoesPageByPageAndToOtherServices(): void    {        $this->startWithTools();        $yt = $this->wz->youtube;        self::assertNotNull($yt);        $asked = [];        $tools = new Tools($this->wz->storagePath('bin'), $this->wz->storagePath('tmp'));        $tools->state = ['yt-dlp' => 'ready', 'ffmpeg' => 'ready'];        $tools->path = ['yt-dlp' => '/fake/yt-dlp', 'ffmpeg' => '/fake/ffmpeg'];        $this->wz->useMedia($tools, function (array $cmd) use (&$asked): Process {            if (($cmd[0] ?? '') === '/fake/yt-dlp') {                $asked[] = implode(' ', $cmd);     // the searches (not the sounds ffmpeg makes meanwhile)            }            return Process::finished($cmd, [(string)json_encode(['entries' => array_map(fn ($i) => ['id' => "v$i", 'title' => "T$i", 'url' => "https://soundcloud.com/a/t$i"], range(1, 15))])]);        });        $yt = $this->wz->youtube;        self::assertTrue($yt->search('partage', 1, 'soundcloud'));        $this->game->run(3);        self::assertStringContainsString('--playlist-items 1-15 scsearch15:partage', $asked[0]);        self::assertSame('https://soundcloud.com/a/t1', $yt->results[0]['url'], 'the address of the service');        self::assertTrue($yt->nextPage());        $this->game->run(3);        self::assertStringContainsString('--playlist-items 16-30 scsearch30:partage', $asked[1]);        self::assertSame(2, $yt->page);        $yt->search('partage', 1, 'dailymotion');        self::assertStringContainsString('https://www.dailymotion.com/search/partage/videos', $asked[2]);    }    public function testClaudeSaysWhereTheLyricsAreAndAnId3v2TagIsReadWhole(): void    {        self::assertSame(['lrclib:16558947', 'url:https://example.org/a.lrc'], \App\Media\Transcriber::sources("LRCLIB:16558947\nURL:https://example.org/a.lrc\nLRCLIB:16558947"));        self::assertSame([], \App\Media\Transcriber::sources('INTROUVABLE'));        // an ID3v2.4 tag as yt-dlp / ffmpeg write it: the description in TXXX        // ID3v2.4: the sizes are "syncsafe" (7 bits a byte)        $safe = fn (int $n): string => chr(($n >> 21) & 0x7f) . chr(($n >> 14) & 0x7f) . chr(($n >> 7) & 0x7f) . chr($n & 0x7f);        $frame = fn (string $id, string $data): string => $id . $safe(strlen($data)) . "\0\0" . $data;        $body = $frame('TIT2', "\x03Mistral gagnant") . $frame('TPE1', "\x03Renaud")            . $frame('TXXX', "\x03description\0" . str_repeat('Une longue description. ', 5)) . $frame('TXXX', "\x03comment\0https://www.youtube.com/watch?v=x");        $tag = \App\Model\Id3Tag::parseV2(4, 0, $body);        self::assertSame('Mistral gagnant', $tag->title);        self::assertSame('Renaud', $tag->artist);        self::assertGreaterThan(100, mb_strlen($tag->comment), 'the whole description, not 30 characters');    }    public function testTheCardOfALineShowsAfterTwoSecondsStillAndGoesWhenThePointerMoves(): void    {        $this->startPlayer();        $list = $this->desk->playlist;        $card = $this->desk->card;        self::assertNotNull($list);        self::assertNotNull($card);        $mouse = $this->form->engineOrNull()?->input->getMouse();        self::assertNotNull($mouse);        [$x, $y] = $this->at($list, 120, PlaylistWindow::LIST_TOP + 6);        $mouse->move($x, $y);        $this->game->wait(1);        self::assertFalse($card->visible(), 'not before 2 seconds');        $this->game->wait(1.5);        self::assertTrue($card->visible());        self::assertSame(0, $card->index);        $this->game->shot('card');        $mouse->move($x + 10, $y);        $this->game->run(2);        self::assertFalse($card->visible(), 'the pointer moved: it goes');    }    public function testTheListByFoldersOpensAnArtistAndPlaysASong(): void    {        $this->startPlayer();        $list = $this->desk->playlist;        self::assertNotNull($list);        $this->clickControl($list, 'showGroups');        self::assertTrue($list->grouped());        $tree = $list->tree();        self::assertSame('artist', $tree[0]['kind']);        $artists = count($tree);        // the first artist opened: its songs under it        $this->clickIn($list, 120, PlaylistWindow::LIST_TOP + 6);        self::assertGreaterThan($artists, $list->lineCount());        $song = $list->tree()[1];        self::assertSame('song', $song['kind']);        $this->clickIn($list, 120, PlaylistWindow::LIST_TOP + PlaylistWindow::ROW_HEIGHT + 6);        self::assertSame($song['index'], $this->wz->playlist->active, 'a song of the folder plays');        $this->game->shot('playlist-folders');        $this->clickControl($list, 'showGroups');        self::assertFalse($list->grouped(), 'the usual list again');    }    public function testAHelperProcessReadsTheTagAndTheLengthOfASong(): void    {        $this->startPlayer();        $file = $this->wz->path((string)$this->wz->playlist->items[0]);        $command = \App\Work\WorkerPool::command();        self::assertNotNull($command, 'this PHP can start the helper script');        $pool = new \App\Work\WorkerPool($command[0], $command[1], 2);        $answer = null;        $pool->submit('describe', ['path' => $file, 'covers' => sys_get_temp_dir() . '/wz-covers'])->then(function (mixed $v) use (&$answer): void {            $answer = $v;        }, function (\Throwable $e) use (&$answer): void {            $answer = $e->getMessage();        });        $until = microtime(true) + 20;        while ($answer === null && microtime(true) < $until) {            $pool->poll();            usleep(10000);        }        $pool->close();        self::assertIsArray($answer, 'an answer from the other process: ' . var_export($answer, true));        [$tag, $info] = $this->wz->describe($file);        self::assertSame($tag->title, $answer['tag']['title']);        self::assertSame($tag->artist, $answer['tag']['artist']);        self::assertEqualsWithDelta($info->duration, $answer['info']['duration'], 0.01);        self::assertGreaterThan(0, $answer['info']['duration']);    }    public function testADownloadFollowsItsRedirectionAndShowsItsProgress(): void    {        $port = 18000 + random_int(0, 999);        $server = proc_open([PHP_BINARY, '-S', "127.0.0.1:$port", __DIR__ . '/fixtures/download-server.php'], [1 => ['file', '/dev/null', 'w'], 2 => ['file', '/dev/null', 'w']], $pipes);        self::assertIsResource($server);        try {            usleep(400000);            $target = sys_get_temp_dir() . '/wz-download-' . getmypid() . '.bin';            $d = new \App\Media\FileDownload("http://127.0.0.1:$port/redir", $target);            $seen = [];            $until = microtime(true) + 20;            while (!$d->poll() && microtime(true) < $until) {                $seen[] = $d->progress;                usleep(5000);            }            self::assertTrue($d->ok(), 'downloaded: ' . $d->error);            self::assertSame(1.0, $d->progress);            self::assertSame(1000000, filesize($target));            self::assertSame(str_repeat('T', 50000), substr((string)file_get_contents($target), -50000));            $between = array_filter($seen, fn (float $p) => $p > 0.1 && $p < 0.9);            self::assertNotEmpty($between, 'the progress went up while it came (not 0 % until the end)');            @unlink($target);            // a missing file: an error, not a file            $d = new \App\Media\FileDownload("http://127.0.0.1:$port/nothing", $target);            $until = microtime(true) + 10;            while (!$d->poll() && microtime(true) < $until) {                usleep(5000);            }            self::assertFalse($d->ok());            self::assertStringContainsString('404', $d->error);            self::assertFileDoesNotExist($target);        } finally {            proc_terminate($server);            proc_close($server);        }    }    public function testASongHeardPastHalfCountsAListenAndTheStarsSortTheListByPreference(): void    {        $this->startPlayer();        $stats = $this->wz->stats();        $first = (string)$this->wz->playlist->items[0];        $second = (string)$this->wz->playlist->items[1];        // heard past half: one listen        $this->wz->playIndex(0);        $this->wz->seek($this->wz->player->duration() * 0.6);        $this->game->run(3);        self::assertSame(1, $stats->plays($this->wz->path($first)));        // the second one changed at once (past 2 s, before a quarter): skipped        $this->wz->playIndex(1);        $this->game->wait(3);        $this->wz->playIndex(2);        self::assertSame(1, $stats->skips($this->wz->path($second)));        self::assertGreaterThan($stats->score($this->wz->path($second)), $stats->score($this->wz->path($first)));        // stars, then the list by preference (the starred one first), then back        $before = $this->wz->playlist->items;        $fourth = (string)$before[3];        $this->wz->rate($fourth, 5);        self::assertSame(5, $stats->rating($this->wz->path($fourth)));        $list = $this->desk->playlist;        self::assertNotNull($list);        $this->clickControl($list, 'showPrefs');        self::assertSame($fourth, $this->wz->playlist->items[0], 'the 5 stars first');        self::assertSame($first, $this->wz->playlist->items[1], 'then the one listened to');        $this->game->shot('playlist-preference');        $this->clickControl($list, 'showPrefs');        self::assertSame($before, $this->wz->playlist->items, 'the order before');        // the same stars again: none        $this->wz->rate($fourth, 5);        self::assertSame(0, $stats->rating($this->wz->path($fourth)));    }    public function testTheQueueOfDownloadsComesBackAfterARestartAndCanBeEmptied(): void    {        $this->startWithTools();        $yt = $this->wz->youtube;        self::assertNotNull($yt);        $yt->download(['id' => 'u1', 'title' => 'Un', 'url' => 'https://www.youtube.com/watch?v=u1'], 'mp3');        $yt->download(['id' => 'u2', 'title' => 'Deux', 'url' => 'https://www.youtube.com/watch?v=u2'], 'mp3', 'Renaud - Deux');        self::assertContains('ffmpeg:-threads 1', $yt->jobs[0]['args'], 'the conversion on one core: the sound keeps the computer');        // WinZik ends in the middle (what quit() does): the one downloading stops, both stay in the queue file        $yt->stopAll();        $this->wz->saveQueue();        $saved = json_decode((string)file_get_contents($this->wz->storagePath('youtube-queue.json')), true);        self::assertSame(['Un', 'Deux'], array_column($saved, 'title'));        // the next start (the media made again): the queue back, the import's name kept        $tools = $this->wz->tools;        self::assertNotNull($tools);        $this->wz->useMedia($tools, fn (array $cmd): Process => Process::finished($cmd, [], 1), $this->music, $this->videos);        $yt = $this->wz->youtube;        self::assertNotNull($yt);        self::assertSame(['Un', 'Deux'], array_column($yt->jobs, 'title'));        self::assertSame('Renaud - Deux', $yt->jobs[1]['key']);        // one removed, then all        $yt->remove(0);        self::assertSame(['Deux'], array_column($yt->jobs, 'title'));        $yt->clearQueue();        $this->wz->saveQueue();        self::assertSame([], $yt->jobs);        self::assertSame('[]', file_get_contents($this->wz->storagePath('youtube-queue.json')));    }    public function testASongAlreadyHereIsNotDownloadedAgainByAnImport(): void    {        $this->startWithTools();        $yt = $this->wz->youtube;        self::assertNotNull($yt);        @mkdir($this->music, 0777, true);        $here = $this->music . '/Renaud - Mistral gagnant (Clip officiel).mp3';        file_put_contents($here, 'mp3');        $yt->forgetFiles();        self::assertSame($here, $yt->alreadyHave('Renaud - Mistral gagnant', 'ytsearch1:Renaud Mistral gagnant'), 'its artist and title in the name of a file');        self::assertNull($yt->alreadyHave('Renaud - Laisse béton', 'ytsearch1:Renaud Laisse béton'));        self::assertNull($yt->alreadyHave('Mylène Farmer - Mistral gagnant', 'ytsearch1:x'), 'another artist: another song');        // downloaded before by an import under another name: its file kept with the import's name        $other = $this->music . '/GiedRé - La bande à Jacky (live).mp3';        file_put_contents($other, 'mp3');        file_put_contents($yt->importsFile, json_encode([\App\Media\YouTube::normalize('Giedré - Jacky') => $other]));        self::assertSame($other, $yt->alreadyHave('Giedré - Jacky', 'ytsearch1:Giedre Jacky'));        // waiting in the queue already        $yt->download(['id' => 'q', 'title' => 'Renaud - Laisse béton', 'url' => 'ytsearch1:Renaud Laisse béton'], 'mp3', 'Renaud - Laisse béton');        self::assertSame('en attente', $yt->alreadyHave('Renaud - Laisse béton', 'ytsearch1:Renaud Laisse béton'));        @unlink($here);        @unlink($other);        @unlink($yt->importsFile);    }    public function testTheMagnifierShowsOnlyTheSongsWithTheLettersTyped(): void    {        $this->startPlayer();        $list = $this->desk->playlist;        self::assertNotNull($list);        $this->clickControl($list, 'search');        self::assertTrue($list->searching);        $this->form->type('ARCHÉTT');       // "archettes-city": no accent, no case        $this->game->run(1);        self::assertSame('ARCHÉTT', $list->filter);        self::assertSame(1, $list->lineCount(), 'only the song that has it');        self::assertStringContainsString('archettes-city', (string)$this->wz->playlist->items[$list->indexAt(0)]);        $this->game->shot('playlist-search');        // Return: it plays; Escape: the search goes, every song again        $enter = new \JumPHP\Gui\Pointer();        $enter->keys[] = \JumPHP\Gui\Pointer::RETURN;        $this->form->handle($enter);        self::assertSame($list->indexAt(0), $this->wz->playlist->active);        $escape = new \JumPHP\Gui\Pointer();        $escape->keys[] = \JumPHP\Gui\Pointer::ESCAPE;        $this->form->handle($escape);        self::assertFalse($list->searching);        self::assertSame($this->wz->playlist->count(), $list->lineCount());    }    public function testInEditModeADragChoosesTheLinesGoneOver(): void    {        $this->startPlayer();        $list = $this->desk->playlist;        self::assertNotNull($list);        $this->clickControl($list, 'edit');        self::assertTrue($list->editing());        [$x, $y0] = $this->at($list, 120, PlaylistWindow::LIST_TOP + 4);        [, $y2] = $this->at($list, 120, PlaylistWindow::LIST_TOP + 2 * PlaylistWindow::ROW_HEIGHT + 4);        $this->dragView($x, $y0, $x, $y2);        self::assertSame([0, 1, 2], array_keys(array_filter($list->selection)), 'the three lines gone over');        self::assertNotNull($this->desk->main);    }}