.cfg of 2001: written with VB's Write #1). */ final class WinZik { /** the version of the settings file's format (not WinZik's own: version()) */ public const VERSION = '0.9.92'; /** WinZik's version (config/project.yaml): the splash and the desktop show it */ public function version(): string { return (string)($this->engine?->config->get('version', '') ?: self::VERSION); } public const SETTINGS = 'winzik.json'; /** the old site of the lyrics (Form7.findlyr_Click), today kept by the Internet Archive */ public const LYRICS_ROOT = 'http://winster.free.fr/LYR/'; public const ARCHIVE = 'https://web.archive.org/web/2004id_/'; /** the 10 actions a button of the joystick can do (Form11.Combo1, filled by Form1.Form_Load) */ public const ACTIONS = ['Son +', 'Son -', 'Morceau suivant', 'Morceau précédent', 'Hasard ON/OFF', 'Play/Pause', 'Parole Activé/désactivé', 'Mode compact ON/OFF', 'Balance +', 'Balance -']; /** the plug-ins of 2001 (PLUGS//infoplug.txt), one at a time like the Winsock of Form16 */ public const PLUGINS = [ 'clavier' => ['Plugins Clavier', 'Les raccourcis du clavier : Z précédent, X play, C pause, V stop, B / N suivant, flèches (Maj : 30 s), 0 à 9, H, L, P, M, E, K, Ctrl+O, Ctrl+Q, Suppr, F11. Espace et les touches multimédia marchent toujours.'], 'led' => ['Plugins LED', 'Les voyants Verr Num, Verr Maj et Arrêt défil du clavier suivent le son (dessinés près de la barre des paroles).'], ]; /** the LED plug-in: [scroll, caps, num] of its greeting, 84 ms a step (#1plugs.frm, Form_Load: rvd = 84) */ public const LED_INTRO = [[0, 0, 0], [1, 0, 0], [1, 1, 0], [1, 1, 1], [0, 1, 1], [0, 0, 1], [0, 0, 0], [0, 0, 0], [0, 0, 0], [1, 0, 0], [1, 0, 0], [1, 1, 0], [1, 1, 0], [1, 1, 1], [1, 1, 1], [1, 1, 0], [1, 1, 0], [1, 0, 0], [1, 0, 0], [0, 0, 0], [0, 0, 0]]; /** seconds since the LED plug-in started (its greeting), or since it was stopped (it blinks 20 times: -1 = not) */ public float $ledClock = 0.0; public float $ledBye = -1.0; /** no settings file was there (preums = 1 of 2001: "Premier démarage ; création d'un fichier CFG") */ public bool $firstStart = false; /** the skin viewer was shown at the start (Choix du skin automatique: once per run) */ public bool $skinAsked = false; private bool $greeted = false; public \App\Model\Equalizer $eq; /** @var array> AUTO: the bands of each song */ public array $eqSongs = []; public Player $player; public Playlist $playlist; public Skin $skin; public Id3Tag $tag; public ?Lyrics $lyrics = null; /** where the lyrics of the song come from ('' = none) */ public string $lyricsFile = ''; /** @var array the windows: where they are, shown or not (Form1..Form5 of 2001) */ public array $ui = []; /** @var array the options */ public array $options = []; /** @var array joystick: axis / button => action (jxp, jxm, jyp, jym, bt1..bt4) */ public array $controls = []; /** the scrolling title (Text4): the rotation, in characters (iv of Timer2) */ public int $titleShift = 0; /** the bargraph (Label8..13): 0..1 left and right */ public float $vuLeft = 0.0; public float $vuRight = 0.0; /** a short message shown instead of the title for a moment ("Telechargement des paroles"...) */ public string $notice = ''; public float $noticeTime = 0.0; /** the password of the Lock mode */ public string $lockPassword = ''; private ?Engine $engine = null; private bool $booted = false; private float $titleClock = 0.0; private float $saveClock = 0.0; /** seconds of play since the position was last kept */ private float $positionClock = 0.0; /** the position of the song playing is saved this often (seconds) */ public const POSITION_EVERY = 5.0; private bool $dirty = false; private int $errors = 0; /** @var array file => has lyrics (the icons of the play list) */ private array $lyricsCache = []; /** @var array */ private array $infoCache = []; private float $vuTarget = 0.0; private float $vuClock = 0.0; /** @var \Closure(): float */ private \Closure $noise; public function __construct() { $this->player = new Player(); $this->playlist = new Playlist(); $this->tag = new Id3Tag(); $this->eq = new \App\Model\Equalizer(); $this->spectrum = new \App\Media\Spectrum(); $this->skin = new Skin(''); $this->noise = static fn (): float => mt_rand() / mt_getrandmax(); $this->defaults(); } /** The engine's services (sound, storage, config): done once, by the first form shown. */ public function attach(Engine $engine): self { if ($this->booted && $this->engine === $engine) { return $this; } $this->engine = $engine; $this->booted = true; $this->player = new Player($engine->sound); $this->lyricsCache = $this->infoCache = []; $this->defaults(); // started with the computer (the entry of the session's start): no sound by itself, no jingle $exe = defined('JUMPHP_EXECUTABLE') && is_file((string)constant('JUMPHP_EXECUTABLE')) ? (string)constant('JUMPHP_EXECUTABLE') : null; $this->autostart = new \JumPHP\Native\Autostart('winzik', 'WinZik', 'net.jumphp.winzik', Platform::isHeadless() ? null : $exe, PHP_OS_FAMILY, null, array_values(array_map('strval', (array)($_SERVER['argv'] ?? [])))); $this->startedAtBoot = $this->autostart->startedAtLogin(); $this->load(); $this->applyAutostart(); $this->cloud(); // cloud: online with the account from the start (the PC serves its songs to the phone) $pub = $engine->config->path('config/update.pub'); // --- updater (AutoUpdate): the computer replaces its executable, the phone app offers its APK --- $this->updater = Platform::isPhoneApp() ? AutoUpdate::phone($engine->http(), Platform::isHeadless() ? '' : (string)$engine->config->get('update_url', ''), (string)$engine->config->get('version', '0.0.0'), (string)$engine->config->get('id', 'winzik'), is_file($pub) ? (string)file_get_contents($pub) : null, $this->storagePath('update')) : new AutoUpdate($engine->http(), Platform::isHeadless() ? '' : (string)$engine->config->get('update_url', ''), (string)$engine->config->get('version', '0.0.0'), (string)$engine->config->get('id', 'winzik'), is_file($pub) ? (string)file_get_contents($pub) : null, defined('JUMPHP_EXECUTABLE') && is_file((string)constant('JUMPHP_EXECUTABLE')) ? (string)constant('JUMPHP_EXECUTABLE') : null); if ($this->updater->isPhone()) { // the phone updates itself as a computer does (option autoUpdate): the new APK goes in at a good moment, the // app restarts by itself and plays on where it was (load(): the state and the position saved just before) $this->updater->goodMoment = fn (): bool => $this->goodMomentToUpdate(); $this->updater->beforeInstall = fn () => $this->save(); } // --- end updater --- $phone = Platform::isPhoneApp(); // --- media tools (YouTube / films): the computer's yt-dlp + ffmpeg; the phone: no yt-dlp nor Whisper, YouTube by its own // API (YouTubeInnerTube), the app's ffmpeg (JUMPHP_FFMPEG) if ($this->tools === null && !$phone && Platform::isDesktop() && !Platform::isWasm() && !Platform::isHeadless() && function_exists('proc_open')) { $this->useMedia(new \App\Media\Tools($this->storagePath('bin'), $this->storagePath('tmp'))); } elseif ($this->tools === null && $phone) { $this->useMedia(\App\Media\Tools::forPhone($this->storagePath('bin'), $this->storagePath('tmp'))); } // --- end of the media tools if (!$phone && Platform::isDesktop() && !Platform::isWasm() && !Platform::isHeadless()) { $this->singleInstance(); } if ($this->native === null && \App\Native\NativeShell::wanted()) { // the desktop version: each window of WinZik is a window of the computer, from the splash on $shell = $this->native = new \App\Native\NativeShell($engine, (string)($this->options['zoom'] ?? 'auto')); $engine->on('frame', fn (float $dt) => $shell->frame($dt)); } elseif ($this->native === null && Platform::isDesktop() && !Platform::isWasm() && !Platform::isHeadless()) { // WinZik in its one window (WINZIK_ONE_WINDOW, the phone app): the engine's window starts hidden (window_hidden): shown here $win = $engine->sdl->getWindow()?->getWindow(); if ($win !== null) { \SDL_ShowWindow($win); } } return $this; } /** * YouTube and the films (the installed WinZik; the tests give fakes). * @param (\Closure(list): \App\Media\Process)|null $runner */ public function useMedia(\App\Media\Tools $tools, ?\Closure $runner = null, string $musicDir = '', string $videoDir = ''): void { $tools->look(); // at once: a film or a search right at the start finds the computer's ffmpeg / yt-dlp $this->tools = $tools; $this->youtube = new \App\Media\YouTube($tools, $this->storagePath('tmp/logs'), $runner, $musicDir, $videoDir, $this->engine?->http()); $this->youtube->importsFile = $this->storagePath('imports.json'); $this->youtube->sourcesFile = $this->storagePath('youtube-sources.json'); // cloud: the video id of a song // the downloads not finished when WinZik ended: in the queue again (yt-dlp goes on from what it had) $saved = self::readJsonFile($this->storagePath('youtube-queue.json')); foreach (is_array($saved) ? $saved : [] as $e) { if (is_array($e) && is_string($e['url'] ?? null) && $e['url'] !== '') { $this->youtube->download(['id' => $e['url'], 'title' => (string)($e['title'] ?? $e['url']), 'url' => $e['url']], ($e['format'] ?? 'mp3') === 'mp4' ? 'mp4' : 'mp3', (string)($e['key'] ?? '')); } } $this->youtube->changed = false; $this->video = new \App\Media\VideoCache($this->storagePath('cache/video'), $tools, $runner); $this->sounds = new \App\Media\SoundCache($this->storagePath('cache/sound'), $tools, $runner); // Whisper: not on a phone (no Python) $this->transcriber = $tools->whisper() ? new \App\Media\Transcriber($tools, rtrim($this->storagePath(''), '/'), $this->storagePath('lyr'), $runner, true, $this->engine?->http()) : null; if ($this->transcriber !== null) { // the .LYR made goes straight to the song's own copy (never over var/lyr/.lyr of another song of that name) $this->transcriber->lyricsPath = fn (string $song): string => $this->lyricsCachePath($song); } } /** Something works in the background (the player shows a loader). */ public function working(): bool { return $this->waitVideo !== '' || $this->scans !== [] || ($this->transcriber?->busy() ?? false) || ($this->youtube?->busy() ?? false) || ($this->sounds?->busy() ?? false) || ($this->download !== null && !$this->download->finished()); } /** The picture of the film playing now (null: no film, or none made yet). */ public function videoFrame(): ?string { $file = $this->player->file; return $file !== null && $this->video !== null && \App\Model\Playlist::isVideo($file) ? $this->video->frame($file, $this->player->position) : null; } public function playingVideo(): bool { return $this->player->file !== null && \App\Model\Playlist::isVideo($this->player->file); } /** @var resource|null the lock of the one WinZik running on this computer */ private $instanceLock = null; private float $wakeClock = 0.0; /** * One WinZik at a time on a computer: the second one started wakes the first (its windows come back, in front) * and ends at once. A lock in the data folder (flock: released by the system if WinZik dies). */ private function singleInstance(): void { // a WinZik just restarted (WINZIK_RELAUNCH: an update, the options reset) starts once the old one ended (it waits // 15 s at most); any other second WinZik (the session restored, a double click) ends at once and brings the // first one to the front $lock = Relaunch::takeLock($this->storagePath('winzik.lock'), getenv('WINZIK_RELAUNCH') === '1' ? 15.0 : 0.0); if ($lock === null) { @file_put_contents($this->storagePath('winzik.wake'), (string)time()); fwrite(STDERR, "WinZik is already running: it comes to the front\n"); exit(0); } $this->instanceLock = $lock; } /** The first WinZik, asked by a second one: its windows come back, in front. */ private function tickWake(float $dt): void { $this->wakeClock += $dt; if ($this->instanceLock === null || $this->wakeClock < 0.5) { return; } $this->wakeClock = 0.0; $wake = $this->storagePath('winzik.wake'); if (is_file($wake)) { @unlink($wake); // WinZik started again while it runs: this one in front, on the screen the mouse is on, whatever mode it was in $this->ui['tray'] = false; $this->ui['lyricsOnly'] = false; if ($this->native !== null) { $this->native->wakeUp(); } $this->touch(); } } public ?\JumPHP\Native\Autostart $autostart = null; /** started with the computer: the song of the last time is ready, not played */ public bool $startedAtBoot = false; /** The option "Démarrer avec l'ordinateur" put in the session's start (the installed WinZik only). */ public function applyAutostart(): void { $a = $this->autostart; if ($a === null || !$a->isSupported()) { return; } $on = (bool)($this->options['autostart'] ?? true); if ($on !== $a->isEnabled()) { $a->set($on); } } /** Back to the first start (the settings file is gone): the tests, "fresh" of MainForm. */ public function reset(): void { if (Platform::isHeadless()) { // the tests: no tools of another test (each one gives its own) $this->tools = $this->youtube = $this->video = $this->sounds = $this->transcriber = null; $this->waitVideo = ''; $this->cloud?->stop(); // cloud: each test gives its own $this->cloud = null; $this->cloudMade = false; $this->cast?->stop(); // cast: each test gives its own $this->cast = null; $this->castMade = false; } $this->eq = new \App\Model\Equalizer(); $this->eqSongs = []; $this->player->stop(); $this->player->file = null; $this->lyricsCache = $this->infoCache = []; $this->download = null; $this->notice = ''; $this->titleShift = 0; $this->lockPassword = ''; $this->greeted = false; $this->defaults(); $this->load(); } public function engine(): ?Engine { return $this->engine; } /** Tests: the bargraph's randomness. @param \Closure(): float $noise 0..1 */ public function setNoise(\Closure $noise): void { $this->noise = $noise; } // paths ------------------------------------------------------------------------------------------------------ /** A file of the application (assets/...) or of the computer, as an absolute path. */ public function path(string $file): string { if (($file !== '' && Platform::isAbsolutePath($file)) || preg_match('#^[A-Za-z]:[\\\\/]#', $file)) { return $file; } return $this->engine !== null ? $this->engine->config->path($file) : $file; } /** The other way: a file inside the application is kept relative (assets/music/x.mp3), so the list works anywhere. */ public function relative(string $file): string { $root = rtrim($this->path(''), '/') . '/'; return $root !== '/' && str_starts_with($file, $root) ? substr($file, strlen($root)) : $file; } /** var/ of the application (downloaded lyrics, imported songs, skins of the user). */ public function storagePath(string $name = ''): string { return $this->engine !== null ? $this->engine->storage->path($name) : rtrim(sys_get_temp_dir(), '/') . '/winzik/' . $name; } // settings --------------------------------------------------------------------------------------------------- private function defaults(): void { $this->ui = [ 'main' => ['x' => 12, 'y' => 12, 'visible' => true, 'expanded' => true], 'playlist' => ['x' => 12, 'y' => 111, 'visible' => true, 'attached' => true, 'top' => 0, 'edit' => false, 'shift' => 0, 'paths' => false, 'width' => 258, 'rows' => 23], 'lyrics' => ['visible' => true], 'eq' => ['visible' => false, 'x' => 272, 'y' => 12], 'video' => ['visible' => true, 'x' => 272, 'y' => 140, 'big' => false], 'compact' => ['active' => false, 'x' => -1, 'y' => 4, 'expanded' => false], 'lyricsOnly' => false, 'tray' => false, 'vu' => true, ]; $this->options = [ // Form17 of 0.9.85, "Options d'esthétisme" 'splash' => true, // Charger l'image au démarrage 'splashSteps' => true, // Afficher l'opération en cours lors du chargement (afc) 'unroll' => true, // Activer l'effet de défilement au chargement 'unrollQuit' => true, // Activer l'effet de défilement lorsque WinZiK se quitte // "Options de fonctionnement" 'autoSkin' => false, // Choix du skin automatique au démarrage 'taskbar' => false, // Affichage de WinZik dans la barre des taches 'joystick' => false, // joyok 'pad' => 0, // njoy 'autoLyrics' => false, // télécharger les paroles à chaque nouveau morceau (Form8, 2001) 'marketLyrics' => true, // les paroles de la marketplace, à chaque morceau qui n'en a pas 'autoUpdate' => true, // la version installée se met à jour toute seule 'autostart' => true, // démarrer avec l'ordinateur (sans lancer la musique) 'ytTools' => true, 'whisperClaude' => true, 'lrclib' => true, // les paroles synchronisées de LRCLIB pour chaque morceau qui n'en a pas // les paroles de Whisper corrigées par Claude Code (claude -p) s'il est installé // yt-dlp et ffmpeg téléchargés tout seuls (YouTube, vidéos) 'ytFormat' => 'mp3', 'snap' => true, // les fenêtres s'aimantent aux bords (nbcot) 'zoom' => 'auto', 'zoomPct' => 75, // le zoom du menu : 200 150 125 100 75 50 %, Ctrl + molette (échelle sur des demis) 'lyricsDir' => '', // rep2: le répertoire secondaire des paroles 'lyricsOnly' => false, // lire seulement les morceaux qui ont des paroles (suivant, précédent, hasard, fin d'un morceau) 'autoTranslate' => true, // traduire automatiquement les paroles (dans la langue translateLang, quand elles sont dans une autre) 'translateLang' => 'fr', // la langue des traductions 'lyricsClaude' => true, // Claude Code (s'il est installé) cherche et traduit les paroles 'lyricsShowTranslation' => true, // la traduction sous chaque ligne (barre des paroles, plein écran ; touche T) 'lyricsAutoScroll' => true, // paroles non synchronisées : la page défile doucement toute seule 'plugin' => 'clavier', // Form19: le plugins en cours ('' = aucun) ]; $this->controls = ['xp' => 5, 'xm' => 6, 'yp' => 7, 'ym' => 8, 'b1' => 1, 'b2' => 2, 'b3' => 3, 'b4' => 4]; $this->playlist = new Playlist(['assets/music/winzik.mp3', 'assets/music/archettes-city.ogg', 'assets/music/chaine-hifi.wav', 'assets/music/partage.mp3']); $this->playlist->shuffle = true; // Hasard (the H button) on by default $this->player->setVolume(80); $this->player->setBalance(0); $this->useSkin('assets/skins/givre'); } /** The saved settings (or the first start: the demo songs, the Givre skin: the default one, desktop and web). */ public function load(): void { $saved = $this->engine !== null ? self::readJsonFile($this->storagePath(self::SETTINGS)) : null; $this->firstStart = $this->engine !== null && !is_array($saved); if (is_array($saved)) { $this->ui = array_replace_recursive($this->ui, (array)($saved['ui'] ?? [])); if ((int)($saved['uiVersion'] ?? 0) < 2) { // the settings of a WinZik before 0.9.92: the play list docked under the player (the default now), once $this->ui['playlist']['attached'] = true; } $this->options = array_replace($this->options, (array)($saved['options'] ?? [])); $this->controls = array_replace($this->controls, array_map('intval', (array)($saved['controls'] ?? []))); $this->playlist = new Playlist(array_values(array_map('strval', (array)($saved['playlist'] ?? [])))); $this->playlist->active = min((int)($saved['active'] ?? 0), $this->playlist->count() - 1); $this->playlist->shuffle = (bool)($saved['shuffle'] ?? true); if ((int)($saved['uiVersion'] ?? 0) < 3) { $this->playlist->shuffle = true; // Hasard on by default (0.9.93): once for the settings of before } $this->eq = \App\Model\Equalizer::fromArray((array)($saved['eq'] ?? [])); $this->eqSongs = array_map(fn ($b) => array_map('floatval', (array)$b), (array)($saved['eqSongs'] ?? [])); $this->player->setVolume((int)($saved['volume'] ?? 80)); $this->player->setBalance((int)($saved['balance'] ?? 0)); if (!$this->useSkin((string)($saved['skin'] ?? ''))) { $this->useSkin('assets/skins/givre'); } } // the song of the last time, where it was (FileName, filenamepos, filenameinfo of the .cfg) if ($this->playlist->current() !== null) { $this->open($this->playlist->active); $position = (float)($saved['position'] ?? 0); $state = (string)($saved['state'] ?? Player::STOPPED); if ($position > 0) { $this->player->seek($position); } if ($state === Player::PLAYING && !Platform::isWasm() && !$this->startedAtBoot) { // not now: once it is known that no update comes (a song started then cut by the restart of an update: no) $this->resumePlay = true; } elseif ($state !== Player::STOPPED) { $this->player->play(); $this->player->pause(); // the browser waits for a click before any sound } } $this->player->setPreamp($this->eq->preampDb()); $this->dirty = false; } private float $restartClock = 0.0; /** * WINZIK_RESTART_AFTER=N (checks of the restart): after N seconds this WinZik restarts as after an update. The new one * does not get it (no loop). */ private function restartTest(float $dt): void { $after = (float)getenv('WINZIK_RESTART_AFTER'); if ($after <= 0 || $this->engine === null) { return; } $this->restartClock += $dt; if ($this->restartClock >= $after) { putenv('WINZIK_RESTART_AFTER'); fwrite(STDERR, '[restart-test] pid ' . getmypid() . " restarts\n"); $this->save(); Relaunch::afterExit(Relaunch::command()); $this->engine->quit(); } } private ?\App\Media\SpotifyAccount $spotify = null; private string $spotifyFor = ''; /** The user's Spotify account (their playlists to import), with their own app's Client ID (Options); null: no ID. */ public function spotify(): ?\App\Media\SpotifyAccount { $id = trim((string)($this->options['spotifyId'] ?? '')); if ($id === '' || $this->engine === null || Platform::isHeadless() && $this->spotifyRequest === null) { return $this->spotify = null; } if ($this->spotify === null || $this->spotifyFor !== $id) { $this->spotifyFor = $id; $http = $this->engine->http(); $this->spotify = new \App\Media\SpotifyAccount($id, $this->spotifyRequest ?? fn (string $method, string $url, ?string $body, array $headers) => $http->request($method, $url, $body, $headers, 20), fn (string $url): bool => \JumPHP\Native\Shell::openUrl($url), (string)($this->options['spotifyRefresh'] ?? ''), function (string $refresh): void { $this->options['spotifyRefresh'] = $refresh; $this->touch(); }); } return $this->spotify; } /** the tests: a fake Spotify (method, url, body, headers) -> Task */ public ?\Closure $spotifyRequest = null; private ?\App\Model\Marks $marks = null; /** the song whose start mark was applied (once per play) */ private string $startDone = ''; /** @var array songs whose blanks are being looked for */ private array $blanksAsked = []; public function marks(): \App\Model\Marks { return $this->marks ??= new \App\Model\Marks($this->storagePath('marks.json')); } /** "Sauter les blancs et les intros" (on by default) */ public function skipBlanks(): bool { return (bool)($this->options['skipBlanks'] ?? true); } /** * Where a song is played from and to: the marks set by hand (its ID3 tag, then marks.json), YouTube's, then the ones * found in its sound. @return array{0: float, 1: float, 2: string} start, end (0: its end), where they come from ('' : none) */ public function bounds(string $file): array { $path = $this->path($file); if ($this->tag->markStart !== null || $this->tag->markEnd !== null) { if ($this->player->file !== null && $this->path($this->player->file) === $path) { return [(float)$this->tag->markStart, (float)$this->tag->markEnd, 'manual']; } } $m = $this->marks()->get($path); return $m === null ? [0.0, 0.0, ''] : [$m['s'], $m['e'], $m['src']]; } /** Marks set by hand: into marks.json and the MP3's ID3 tag. */ public function setBounds(string $file, float $start, float $end): void { $path = $this->path($file); $this->marks()->set($path, $start, $end, 'manual'); $this->marks()->save(); if (strtolower(pathinfo($path, PATHINFO_EXTENSION)) === 'mp3') { \App\Model\Id3Tag::writeMarks($path, $start > 0 ? $start : null, $end > 0 ? $end : null); } if ($this->player->file !== null && $this->path($this->player->file) === $path) { [$this->tag->markStart, $this->tag->markEnd] = [$start > 0 ? $start : null, $end > 0 ? $end : null]; } $this->forget($file); $this->touch(); } /** Each frame: the blanks (and an intro) left out of the song playing; its marks found when it has none. */ private function tickBounds(): void { $file = $this->player->file; if ($file === null || !$this->skipBlanks()) { return; } $path = $this->path($file); [$start, $end, $src] = $this->bounds($file); if ($src === '' && !isset($this->blanksAsked[$path]) && $this->sounds !== null) { $wav = $this->sounds->plain($file); if ($wav !== null) { $this->findBlanks($path, $wav); } } if ($this->player->state !== Player::PLAYING) { return; } $at = $this->player->position; if ($this->startDone !== $path) { $this->startDone = $path; if ($start > 0.3 && $at < $start - 0.2 && $at < 3) { $this->seek($start); // the blank / the intro left out } } $length = $this->player->duration(); if ($end > 0 && $at >= $end && $length - $end > 0.5) { $this->next(); // the blank at the end left out: the next song } } /** Its blanks looked for in its WAV (a helper process; here at once without helpers). */ private function findBlanks(string $path, string $wav): void { $this->blanksAsked[$path] = true; $save = function (float $start, float $end) use ($path): void { $this->marks()->set($path, $start, $end, 'auto'); $this->marks()->save(); }; $work = $this->work(); if ($work === null) { [$start, $end] = \App\Media\Blanks::find($wav); $save($start, $end); return; } $work->submit('blanks', ['wav' => $wav], 30.0)->then( fn (mixed $v) => is_array($v) ? $save((float)($v['start'] ?? 0), (float)($v['end'] ?? 0)) : null, fn () => null, ); } private ?\App\Model\Stats $stats = null; /** the song whose listen was counted in this play ('' : not yet) */ private string $countedFor = ''; /** How often each song was heard, skipped, and its stars (var/stats.json). */ public function stats(): \App\Model\Stats { return $this->stats ??= new \App\Model\Stats($this->storagePath('stats.json')); } /** Each frame: the song heard past half of it (or 4 minutes) counts as one listen. */ private function countListen(): void { $file = $this->player->file; if ($file === null || $this->player->state !== Player::PLAYING) { return; } $path = $this->path($file); $length = $this->player->duration(); if ($this->countedFor !== $path && $length > 0 && $this->player->position >= min($length * 0.5, 240.0)) { $this->countedFor = $path; $this->stats()->listened($path); $this->touch(); } } /** Another song is opened: the one before, changed before a quarter of it, counts as skipped. */ private function leaving(): void { $file = $this->player->file; if ($file !== null) { $path = $this->path($file); $length = $this->player->duration(); $at = $this->player->position; if ($this->countedFor !== $path && $length > 0 && $at > 2 && $at < $length * 0.25) { $this->stats()->skipped($path); $this->touch(); } } $this->countedFor = ''; $this->startDone = ''; // the next play (even of the same song) leaves its blank out again } /** Stars given to a line of the list (the same stars again: none). */ public function rate(string $file, int $stars): void { $path = $this->path($file); $this->stats()->rate($path, $this->stats()->rating($path) === $stars ? 0 : $stars); $this->touch(); } public function byPreference(): bool { return (bool)($this->ui['playlist']['byPref'] ?? false); } /** * "Par préférence": the list sorted by the stars, then the listening mark; again: back to the order it had (the * songs added meanwhile at its end). The song playing stays the one playing. */ public function togglePreferenceOrder(): void { $current = $this->playlist->current(); $items = $this->playlist->items; if (!$this->byPreference()) { $this->ui['playlist']['order'] = $items; $stats = $this->stats(); $rank = []; foreach ($items as $i => $f) { $rank[$i] = [$stats->preference($this->path($f)), -$i]; } uksort($items, fn ($a, $b) => $rank[$b] <=> $rank[$a]); $items = array_values($items); $this->ui['playlist']['byPref'] = true; } else { $present = array_flip($items); // a set: one look-up per song (thousands of songs stay instant) $before = array_values(array_filter((array)($this->ui['playlist']['order'] ?? []), fn ($f) => is_string($f) && isset($present[$f]))); $items = [...$before, ...array_values(array_diff($items, $before))]; $this->ui['playlist']['byPref'] = false; unset($this->ui['playlist']['order']); } $this->playlist->items = $items; $this->playlist->active = $current !== null ? (int)array_search($current, $items, true) : -1; $this->ui['playlist']['top'] = 0; $this->touch(); } /** the song of the last time plays again once the update is known (tick: resumeWhenKnown) */ private bool $resumePlay = false; private float $resumeWait = 0.0; /** * The song of the last time again, but only once it is known whether WinZik updates itself: no update (or none * looked for, or no network): it plays; an update installs: it never starts here (the new WinZik restarts it). */ private function resumeWhenKnown(float $dt): void { if (!$this->resumePlay) { return; } $this->resumeWait += $dt; $u = $this->updater; $looking = $u !== null && $u->enabled() && (bool)($this->options['autoUpdate'] ?? true) && in_array($u->state, ['idle', 'checking', 'installing', 'installed'], true); if ($u !== null && $u->state === 'installed') { return; // the new version is in place: this one ends } // 'idle': the splash has not asked yet (it asks at once); not shown (option): 1 second at most if ($looking && !($u->state === 'idle' && $this->resumeWait > 1.0)) { return; } $this->resumePlay = false; if ($this->player->state !== Player::PLAYING && $this->playlist->current() !== null) { $this->autoChanges++; // cloud: not the user's doing (App\Cloud\PlaySync) $this->player->play(); } } /** the settings were wiped (Options: Réinitialiser...): nothing is written again before the restart */ private bool $wiped = false; /** * Options > "Réinitialiser les options et redémarrer": every setting of WinZik erased (its options, its windows, its * play list, its equalizer, the engine's options), then a WinZik with the defaults starts. The downloaded lyrics and * tools (yt-dlp, ffmpeg) stay: they are not settings. @return bool the new WinZik started (not in the tests) */ public function resetAndRestart(): bool { $this->wiped = true; $this->dirty = false; foreach ([self::SETTINGS, 'options.json'] as $file) { @unlink($this->storagePath($file)); } if (Platform::isHeadless() || Platform::isWasm()) { return false; } Relaunch::afterExit(Relaunch::command()); $this->engine?->quit(); return true; } public function save(): void { if ($this->wiped) { return; } $this->stats?->save(); $this->dirty = false; if ($this->engine === null) { return; } self::writeJsonFile($this->storagePath(self::SETTINGS), [ 'version' => self::VERSION, 'ui' => $this->ui, 'uiVersion' => 3, 'options' => $this->options, 'controls' => $this->controls, // cloud: while the cloud's playlist is shown, the user's own one is what is kept 'playlist' => ($this->cloud?->localPlaylist() ?? $this->playlist)->items, 'active' => ($this->cloud?->localPlaylist() ?? $this->playlist)->active, 'shuffle' => ($this->cloud?->localPlaylist() ?? $this->playlist)->shuffle, 'volume' => $this->player->volume, 'balance' => $this->player->balance, 'skin' => $this->relative($this->skin->dir), 'position' => round($this->player->position, 2), 'state' => $this->player->state, 'eq' => $this->eq->toArray(), 'eqSongs' => array_slice($this->eqSongs, -500, null, true), ]); } /** the mark of a name that is not UTF-8 (a Latin-1 file name of an old disk) in the JSON files: b64: + its bytes */ public const RAW = 'b64:'; /** * Strings (values and keys) that are not UTF-8 made writable in JSON: "b64:" + base64 of their bytes (a UTF-8 string * that starts with "b64:" too, so it comes back as it was). Everything else unchanged. */ public static function encodeNames(mixed $value): mixed { if (is_string($value)) { return mb_check_encoding($value, 'UTF-8') && !str_starts_with($value, self::RAW) ? $value : self::RAW . base64_encode($value); } if (!is_array($value)) { return $value; } $out = []; foreach ($value as $k => $v) { $out[is_string($k) ? self::encodeNames($k) : $k] = self::encodeNames($v); } return $out; } /** The other way (what was read from a JSON file). */ public static function decodeNames(mixed $value): mixed { if (is_string($value)) { if (str_starts_with($value, self::RAW)) { $raw = base64_decode(substr($value, strlen(self::RAW)), true); return $raw === false ? $value : $raw; } return $value; } if (!is_array($value)) { return $value; } $out = []; foreach ($value as $k => $v) { $out[is_string($k) ? self::decodeNames($k) : $k] = self::decodeNames($v); } return $out; } /** * A JSON file written whole or not at all: never replaced by an empty or broken one (a value JSON cannot hold leaves * the file of before as it was). Write then rename: a crash never leaves half a file. @return bool written */ public static function writeJsonFile(string $file, mixed $value, int $flags = JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES): bool { try { $json = json_encode(self::encodeNames($value), $flags | JSON_THROW_ON_ERROR); } catch (\JsonException $e) { error_log('WinZik: ' . basename($file) . ' not written: ' . $e->getMessage()); return false; } @mkdir(dirname($file), 0777, true); $tmp = $file . '.tmp'; if (@file_put_contents($tmp, $json) === false) { return false; } return @rename($tmp, $file); } /** A JSON file written by writeJsonFile() (its names as they were), null: none or broken. */ public static function readJsonFile(string $file): mixed { $data = is_file($file) ? @file_get_contents($file) : false; if ($data === false || $data === '') { return null; } $value = json_decode($data, true); return $value === null ? null : self::decodeNames($value); } /** Something changed: saved a little later (not at every pixel of a slider). */ public function touch(): void { $this->dirty = true; } // the songs -------------------------------------------------------------------------------------------------- /** Opens a line of the list without playing it: its tag, its length, its lyrics. */ public function open(int $index): bool { $this->leaving(); $file = $this->playlist->select($index); if ($file === null || \App\Cloud\Cloud::isPseudo($file)) { return false; // cloud: a song of the cloud not on this device yet (playIndex starts its copy) } $path = $this->path($file); $this->waitVideo = ''; $this->playWhenReady = false; if (\App\Model\Playlist::isVideo($path)) { // a film: its sound (and its pictures) are made by ffmpeg first $sound = $this->video?->audio($path); if ($sound !== null) { $ok = $this->player->load($path, $sound); } elseif ($this->video !== null && $this->video->error($path) === '') { $this->player->wait($path); $this->waitVideo = $path; $this->notice('Préparation de la vidéo...', 30); $ok = true; } else { $this->player->load($path, ''); $this->notice('Vidéo illisible : ' . ($this->video?->error($path) ?: 'seulement dans la version installée'), 6); $ok = false; } } else { $ok = $this->player->load($path); } [$this->tag] = $this->describe($file); if ($this->eq->auto && isset($this->eqSongs[$file])) { $this->eq->bands = array_map(fn ($v) => \App\Model\Equalizer::clamp((float)$v), $this->eqSongs[$file]); } $this->loadLyrics($file); $this->cloud?->lyricsCheck($file); // cloud: lyrics changed on another device (translated on the PC) come down $this->titleShift = 0; $this->touch(); return $ok; } /** Command1_Click: plays the line playing (or the first one). */ public function play(): void { $this->resumePlay = false; // the user decides: the song of the last time does not start by itself if ($this->playlist->current() === null) { return; } if ($this->player->file === null || $this->player->file !== $this->path((string)$this->playlist->current())) { $this->open(max(0, $this->playlist->active)); } if ($this->player->error) { $this->skipBroken(); return; } $this->startPlayer(); $this->errors = 0; $this->skipPending = false; $this->touch(); } /** play(), or later for a film whose sound is not ready. */ private function startPlayer(): void { if ($this->waitVideo !== '') { $this->playWhenReady = true; return; } $this->player->play(); } /** A line of the list clicked (malist_MouseUp): it plays. */ public function playIndex(int $index): void { $this->resumePlay = false; // the user decides: the song of the last time does not start by itself // --- cloud: a line of the cloud playlist whose song is not here: its copy starts; going through the list, the next one $item = $this->playlist->items[$index] ?? ''; if (\App\Cloud\Cloud::isPseudo($item)) { $this->playlist->select($index); $this->cloud?->fetchItem($item); if ($this->cloudHops > 0 && $this->cloudHops < 50) { $this->next(); } return; } // --- end cloud if ($this->open($index)) { $this->startPlayer(); $this->errors = 0; $this->skipPending = false; $this->afterNewSong(); } else { $this->skipBroken(); } } public function pause(): void { $this->resumePlay = false; // the user decides: the song of the last time does not start by itself $this->player->pause(); $this->touch(); } public function togglePause(): void { $this->resumePlay = false; // the user decides: the song of the last time does not start by itself $this->player->state === Player::PLAYING ? $this->pause() : $this->play(); } /** Command8_Click */ public function stop(): void { $this->resumePlay = false; // the user decides: the song of the last time does not start by itself $this->skipPending = false; $this->player->stop(); $this->touch(); } /** Picture15_Click / Command3_Click: the next song, played. */ public function next(): void { $this->resumePlay = false; // the user decides: the song of the last time does not start by itself $this->cloudHops++; try { if ($this->playlist->next($this->lyricsFilter()) !== null) { $this->playIndex($this->playlist->active); } elseif ($this->lyricsOnlyActive()) { $this->noLyricsToPlay(); } } finally { $this->cloudHops--; } } /** Picture16_Click / Command2_Click */ public function previous(): void { $this->resumePlay = false; // the user decides: the song of the last time does not start by itself if ($this->playlist->previous($this->lyricsFilter()) !== null) { $this->playIndex($this->playlist->active); } elseif ($this->lyricsOnlyActive()) { $this->noLyricsToPlay(); } } public function seek(float $seconds): void { $this->seeks++; // cloud: a seek asked (App\Cloud\PlaySync tells it from the clock's own corrections) $this->player->seek($seconds); $this->touch(); } public function setVolume(int $volume): void { $this->player->setVolume($volume); $this->touch(); } public function setBalance(int $balance): void { $this->player->setBalance($balance); $this->touch(); } /** Picture8_Click: Hasard on / off. */ public function toggleShuffle(): void { $this->playlist->shuffle = !$this->playlist->shuffle; $this->touch(); } /** a file could not be read: the next song is tried at the next frame (never the whole list in one frame) */ private bool $skipPending = false; /** * MediaPlayer1_Error -> Timer5: a file that cannot be read is skipped, one a frame (a disk unplugged: a list of files * that are all gone does not freeze WinZik), each line once: every line tried, it stops and says so. */ private function skipBroken(): void { $this->errors++; if ($this->errors < max(1, $this->playlist->count())) { $this->skipPending = true; } else { $this->errors = 0; $this->skipPending = false; $this->player->stop(); $this->notice($this->playlist->count() > 1 ? 'Aucun fichier lisible dans la playlist' : 'Fichier illisible : ' . Text::baseName((string)$this->playlist->current())); } } /** Each frame: the song after the one that could not be read. */ private function tickSkip(): void { if (!$this->skipPending) { return; } $this->skipPending = false; if ($this->playlist->count() === 0) { $this->errors = 0; return; } $this->notice('Fichier illisible : ' . Text::baseName((string)$this->playlist->current()), 3); $this->next(); } private function afterNewSong(): void { $this->fetchMarketLyrics(); if ($this->engine !== null && !Platform::isHeadless()) { // a moment later: the marketplace answers first when it has them $this->engine->gameLoop->addTimer(2.5, fn () => $this->fetchSyncedLyrics()); } if (($this->options['autoLyrics'] ?? false) && $this->lyrics === null && $this->tag->artist !== '' && $this->tag->title !== '') { $this->startDownload(); } $this->autoTranslate(); } // the play list ---------------------------------------------------------------------------------------------- /** @param list $files */ public function addFiles(array $files): int { $added = 0; foreach ($files as $file) { if (Playlist::isMedia($file)) { $this->playlist->add($this->relative($file)); $added++; } } if ($added > 0 && $this->player->file === null) { $this->open($this->playlist->active); } $this->touch(); return $added; } /** * Files and whole folders (with their sub-folders, in name order) into the play list. @param list $paths * @return int how many files were added */ public function addPaths(array $paths): int { if (!Platform::isHeadless() && array_filter($paths, 'is_dir') !== []) { // a folder: looked through a little each frame (8 ms at most): WinZik stays quick with a big collection $this->scans[] = ['paths' => array_values($paths), 'it' => null, 'found' => [], 'added' => 0]; $this->notice('Lecture du dossier...', 30); return 0; } $files = []; foreach ($paths as $path) { if (is_dir($path)) { $found = []; try { $it = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path, \FilesystemIterator::SKIP_DOTS)); foreach ($it as $f) { if ($f->isFile() && Playlist::isMedia($f->getFilename())) { $found[] = $f->getPathname(); } } } catch (\Throwable) { // a folder that cannot be read: what was found } natcasesort($found); array_push($files, ...array_values($found)); } elseif (is_file($path)) { $files[] = $path; } } return $this->addFiles($files); } /** A line of the list moved (drag and drop): the song playing stays the one playing. */ public function moveLine(int $from, int $to): void { $this->playlist->move($from, $to); $this->touch(); } /** @var list, it: ?\Iterator, found: list, added: int}> the folders being looked through */ private array $scans = []; /** A little of the folders being looked through, each frame; their songs go to the list as they are found. */ private function tickScans(): void { if ($this->scans === []) { return; } $until = microtime(true) + 0.008; $scan = &$this->scans[0]; while (microtime(true) < $until) { if ($scan['it'] === null || !$scan['it']->valid()) { $path = array_shift($scan['paths']); if ($path === null) { break; } if (is_file($path)) { $scan['found'][] = $path; $scan['it'] = null; continue; } try { $scan['it'] = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path, \FilesystemIterator::SKIP_DOTS)); $scan['it']->rewind(); } catch (\Throwable) { $scan['it'] = null; } continue; } $f = $scan['it']->current(); if ($f instanceof \SplFileInfo && $f->isFile() && Playlist::isMedia($f->getFilename())) { $scan['found'][] = $f->getPathname(); } try { $scan['it']->next(); } catch (\Throwable) { $scan['it'] = null; } } $done = $scan['paths'] === [] && ($scan['it'] === null || !$scan['it']->valid()); if (count($scan['found']) >= 200 || $done) { natcasesort($scan['found']); $added = $this->addFiles(array_values($scan['found'])); $scan['found'] = []; $scan['added'] += $added; } if ($done) { $this->notice($scan['added'] > 0 ? $scan['added'] . ' fichier(s) ajouté(s) à la playlist' : 'Aucun fichier de musique ou de vidéo ici', 4); unset($scan); array_shift($this->scans); return; } unset($scan); } /** * Lines removed. The song playing removed: the one that took its line plays (it was playing), or is ready (it was * not); the list empty: nothing left, not even a film still being made (it would start once ready). * @param list $indexes */ public function removeLines(array $indexes): void { $playing = $this->playlist->current(); $wasPlaying = $this->player->state === Player::PLAYING || $this->playWhenReady; $this->playlist->remove($indexes); if ($this->playlist->current() !== $playing) { $this->player->stop(); $this->player->file = null; if ($this->playlist->current() === null) { $this->noSong(); } elseif ($wasPlaying) { $this->playIndex($this->playlist->active); } else { $this->open($this->playlist->active); } } $this->touch(); } /** No song any more (the list emptied): nothing playing, nothing waited for. */ private function noSong(): void { $this->player->stop(); $this->player->file = null; $this->waitVideo = ''; $this->playWhenReady = false; $this->skipPending = false; $this->errors = 0; $this->lyrics = null; $this->lyricsFile = ''; $this->tag = new Id3Tag(); } /** Form2.Command5_Click: the list as a .FLS file. */ public function saveFls(string $file): bool { $file = preg_match('/\.fls$/i', $file) ? $file : $file . '.fls'; @mkdir(dirname($file), 0777, true); return @file_put_contents($file, $this->playlist->toFls()) !== false; } /** Form2.Command6_Click: a .FLS replaces the list. */ public function loadFls(string $file): bool { $content = is_file($file) ? @file_get_contents($file) : false; $files = $content === false ? null : Playlist::parseFls($content); if ($files === null) { return false; } $this->player->stop(); $this->player->file = null; $this->playlist->clear(); foreach ($files as $f) { $this->playlist->add($f); } if ($this->playlist->current() !== null) { $this->open(0); } else { $this->noSong(); } $this->touch(); return true; } /** @return array{0: Id3Tag, 1: AudioInfo} the tag and the length of a file of the list (cached) */ /** @var array songs whose tag and length a helper process is reading */ private array $infoAsked = []; /** grows each time a song's tag and length came back (the play list by folders is sorted again then) */ public int $infoVersion = 0; private ?\App\Work\WorkerPool $work = null; private bool $workTried = false; private float $workIdle = 0.0; /** * WinZik's helper processes (other PHP processes, on other cores): the desktop version only (the browser has Web * Workers, the tests read at once). Null: none (the work is then done here). */ public function work(): ?\App\Work\WorkerPool { if ($this->workTried) { return $this->work !== null && $this->work->available() ? $this->work : null; } $this->workTried = true; if (Platform::isWasm() || Platform::isHeadless() || getenv('WINZIK_WORKERS') === '0') { return null; } $command = \App\Work\WorkerPool::command(); if ($command === null) { return null; } $size = max(1, min(4, \App\Work\WorkerPool::cores() - 1)); return $this->work = new \App\Work\WorkerPool($command[0], $command[1], $size); } /** * The tag and the length of a song for the play list and its card: what is known now, never a wait. Not known yet: * a helper process reads it (an empty tag and no length meanwhile; the line shows its file name, then its tag). * @return array{0: Id3Tag, 1: AudioInfo} */ public function describeLater(string $file): array { $path = $this->path($file); if (isset($this->infoCache[$path])) { return $this->infoCache[$path]; } $work = $this->work(); if ($work === null) { return $this->describe($file); } if (!isset($this->infoAsked[$path])) { $this->infoAsked[$path] = true; $work->submit('describe', ['path' => $path, 'covers' => $this->storagePath('cache/covers')], 30.0)->then( function (mixed $v) use ($path): void { unset($this->infoAsked[$path]); if (is_array($v) && is_array($v['tag'] ?? null) && is_array($v['info'] ?? null)) { $i = $v['info']; $this->infoCache[$path] = [\App\Work\Worker::tagFrom($v['tag']), new AudioInfo((float)($i['duration'] ?? 0), (int)($i['kbps'] ?? 0), (int)($i['sampleRate'] ?? 0), (int)($i['channels'] ?? 0))]; $this->infoVersion++; } }, function (\Throwable $e) use ($path): void { // the helpers are off (or failed on it): read here, once unset($this->infoAsked[$path]); $this->describe($path); $this->infoVersion++; }, ); } return [new Id3Tag(), new AudioInfo()]; } private function tickWork(float $dt): void { if ($this->work === null) { return; } $this->work->poll(0.004); // nothing to do for a minute: the helpers are let go (they start again with the next job) $this->workIdle = $this->work->pending() > 0 ? 0.0 : $this->workIdle + $dt; if ($this->workIdle > 60) { $this->work->idle(); $this->workIdle = 0.0; } } public function describe(string $file): array { $path = $this->path($file); if (!isset($this->infoCache[$path])) { $this->infoCache[$path] = [Text::extension($path) === 'mp3' ? Id3Tag::read($path) : new Id3Tag(), AudioInfo::of($path)]; } return $this->infoCache[$path]; } /** The folders of the lyrics changed (or new .LYR came): every song is looked at again. */ public function refreshLyrics(): void { $this->lyricsCache = []; if ($this->playlist->current() !== null) { $this->loadLyrics((string)$this->playlist->current()); } } /** A file changed (its tag written, its lyrics downloaded): read again next time. */ public function forget(string $file): void { unset($this->infoCache[$this->path($file)], $this->lyricsCache[$file], $this->lyricsCache[$this->relative($file)]); } // lyrics ----------------------------------------------------------------------------------------------------- /** * Where the lyrics of a song are (Form1.Command1_Click): the user's own copy for this very file (var/lyr/-.lyr: downloaded, shifted, made by Whisper), else next to it (song.lyr), else the copy of before 0.10.6 * (var/lyr/.lyr: shared by every song of that name, so after the song's own), else in the secondary folder of * the lyrics (rep2 + song.LYR). A song of the application (assets/...) cannot be written: its var/lyr copy first. */ public function findLyricsFile(string $file): ?string { $path = $this->path($file); $base = Text::withoutExtension($path); $name = Text::baseName($base); $old = rtrim($this->storagePath('lyr'), '/') . '/' . $name; $ofTheApp = $this->relative($path) !== $path; $candidates = [Text::withoutExtension($this->lyricsCachePath($file))]; array_push($candidates, ...($ofTheApp ? [$old, $base] : [$base, $old])); foreach (array_filter([(string)($this->options['lyricsDir'] ?? '')]) as $dir) { $candidates[] = rtrim($this->path($dir), '/\\') . '/' . $name; } foreach ($candidates as $candidate) { foreach (['.lyr', '.LYR', '.Lyr'] as $ext) { if (is_file($candidate . $ext)) { return $candidate . $ext; } } } return null; } /** * Where WinZik keeps lyrics it got for a song (var/lyr/-.lyr): two "01 - Intro.mp3" of * two albums never share them. A song of the application: the crc of its path inside it (the same wherever it is installed). */ public function lyricsCachePath(string $file): string { $path = $this->path($file); return rtrim($this->storagePath('lyr'), '/') . '/' . Text::baseName(Text::withoutExtension($path)) . '-' . sprintf('%08x', crc32($this->relative($path))) . '.lyr'; } /** * The song has lyrics here (synchronised or not): a .LYR found for it (looked for once, then remembered until they * change: no network, a few file checks). A song of the cloud not on this device: the account says. */ public function hasLyrics(string $file): bool { if (\App\Cloud\Cloud::isPseudo($file)) { return (bool)($this->cloud?->entryOfItem($file)['lyrics'] ?? false); } return $this->lyricsCache[$file] ??= $this->findLyricsFile($file) !== null; } public function loadLyrics(string $file): void { $found = $this->findLyricsFile($file); $this->lyricsFile = $found ?? ''; $this->lyrics = $found !== null ? Lyrics::load($found) : null; if ($this->lyrics !== null && $this->lyrics->isEmpty()) { $this->lyrics = null; } // lines without times: their moments estimated over the song's length if ($this->lyrics !== null && !$this->lyrics->synced) { $duration = $this->player->file === $this->path($file) ? $this->player->duration() : 0.0; $this->lyrics->spread($duration > 0 ? $duration : $this->describe($file)[1]->duration); } } /** * The lyrics come too late / too early (well in time between them, all shifted): every time moved by $seconds and the * .LYR saved (its own file when it can be written, else a copy in var/lyr, which is looked at first). */ public function shiftLyrics(float $seconds): void { $file = $this->playlist->current(); if ($this->lyrics === null || $file === null) { $this->notice('Pas de paroles à décaler', 3); return; } if (!$this->lyrics->synced) { $this->notice('Paroles non synchronisées : rien à décaler (synchronisez-les dans l\'éditeur)', 4); return; } $this->lyrics->lines = array_map(fn (array $l) => [max(0.0, round($l[0] + $seconds, 2)), $l[1]], $this->lyrics->lines); $target = $this->lyricsFile; $inApp = $target === '' || str_starts_with($target, rtrim($this->path(''), '/') . '/') || !is_writable($target); if ($inApp) { $target = $this->lyricsCachePath($file); @mkdir(dirname($target), 0777, true); } file_put_contents($target, $this->lyrics->toLyr()); $this->lyricsFile = $target; unset($this->lyricsCache[$file]); $this->shiftTotal = round(($this->shiftFile === $target ? $this->shiftTotal : 0) + $seconds, 2); $this->shiftFile = $target; $this->notice(sprintf('Paroles %s de %.1f s (%+.1f s en tout), enregistrées', $seconds < 0 ? 'avancées' : 'retardées', abs($seconds), $this->shiftTotal), 3); } // lyrics: found on the Internet, without times, translated, only the songs that have some --------------------- /** the last search of lyrics (searchLyrics(), lyricsHelp()), null before */ public ?\App\Media\LyricsSearch $lyricsSearch = null; /** the translation running, or the last one */ public ?\App\Media\LyricsTranslator $translator = null; /** the song of $translator */ private string $translating = ''; private ?\JumPHP\Http\Http $lyricsHttp = null; private ?\Closure $lyricsRunner = null; /** Claude Code for the lyrics: null = looked for on the PATH, false = none, a string = that program (tests) */ private string|false|null $claudeProgram = null; /** the free translation's quota is over until then (time()) */ private int $translateQuotaUntil = 0; /** * Tests: the network of the lyrics (search, translation) and how `claude -p` runs; $claude: its program, false = no * Claude Code, null = the computer's. * @param (\Closure(list): \App\Media\Process)|null $runner */ public function useLyricsServices(?\JumPHP\Http\Http $http, ?\Closure $runner = null, string|false|null $claude = false): void { $this->lyricsHttp = $http; $this->lyricsRunner = $runner; $this->claudeProgram = $claude; } private function lyricsHttp(): ?\JumPHP\Http\Http { return $this->lyricsHttp ?? $this->engine?->http(); } /** * Claude Code's program when it searches and translates the lyrics: on a computer where it is installed (`claude` * on the PATH) and the option `lyricsClaude` is on; never on a phone or in the browser. null: the free services. */ public function lyricsClaude(): ?string { if (!($this->options['lyricsClaude'] ?? true) || $this->claudeProgram === false) { return null; } if (is_string($this->claudeProgram)) { return $this->claudeProgram; } if (Platform::isPhoneApp() || Platform::isWasm() || Platform::isHeadless()) { return null; } return \App\Media\Transcriber::claude(); } /** * What is known of a song for a search: [artist, title] from its tag, else from its file's name ("Artiste - Titre"), * a song of the cloud from its entry. * @return array{0: string, 1: string} */ public function songQuery(string $file): array { if (\App\Cloud\Cloud::isPseudo($file)) { $e = $this->cloud?->entryOfItem($file) ?? []; return [(string)($e['artist'] ?? ''), (string)($e['title'] ?? '')]; } $tag = $this->playlist->current() === $file ? $this->tag : $this->describe($file)[0]; if ($tag->title !== '') { return [$tag->artist, $tag->title]; } [$artist, $title] = array_pad(array_map('trim', explode(' - ', Text::baseName(Text::withoutExtension($this->path($file))), 2)), 2, ''); return $title === '' ? ['', $artist] : [$artist, $title]; } /** * Searches lyrics on the Internet (LRCLIB, the marketplace, the old site, Claude Code when it is there): the * candidates come in as the sources answer (`$search->candidates`, best first; `$search->task` settles with all of * them). The search before is stopped. null without network services. */ public function searchLyrics(string $artist, string $title, ?string $file = null): ?\App\Media\LyricsSearch { $http = $this->lyricsHttp(); if ($http === null) { return null; } $this->lyricsSearch?->cancel(); $file ??= $this->playlist->current(); $duration = 0.0; if ($file !== null && !\App\Cloud\Cloud::isPseudo($file)) { $duration = $this->player->file === $this->path($file) ? $this->player->duration() : $this->describe($file)[1]->duration; } $market = $this->market(); $this->lyricsSearch = new \App\Media\LyricsSearch($http, $artist, $title, $duration, $market?->enabled() ? $market : null, $this->lyricsRunner, $this->lyricsClaude(), $this->storagePath('tmp/logs')); return $this->lyricsSearch->start(); } /** * "Click the dot of the play list": what to do for the lyrics of this song. Starts a search for it (artist and title * of its tag or its name) and says what it has: {file, artist, title, hasLyrics, synced, translated, search, text}. * The screens open their search with artist / title filled in and show `search` as it fills. * @return array{file: string, artist: string, title: string, hasLyrics: bool, synced: bool, translated: bool, search: ?\App\Media\LyricsSearch, text: string} */ public function lyricsHelp(string $file): array { [$artist, $title] = $this->songQuery($file); $has = $this->hasLyrics($file); $lyrics = $has && !\App\Cloud\Cloud::isPseudo($file) ? Lyrics::load((string)$this->findLyricsFile($file)) : null; $search = $title !== '' || $artist !== '' ? $this->searchLyrics($artist, $title, $file) : null; $text = match (true) { $search === null && $title === '' => 'Donnez l\'artiste et le titre pour chercher les paroles', $search === null => 'Pas de réseau ici : collez les paroles dans l\'éditeur', $lyrics !== null && !$lyrics->synced => 'Paroles non synchronisées : en chercher des synchronisées, ou les synchroniser dans l\'éditeur', $has => 'Ce morceau a déjà des paroles : en chercher d\'autres', default => 'Recherche des paroles de « ' . trim($artist . ' - ' . $title, ' -') . ' »...', }; return ['file' => $file, 'artist' => $artist, 'title' => $title, 'hasLyrics' => $has, 'synced' => $lyrics !== null && $lyrics->synced, 'translated' => $lyrics?->hasTranslation() ?? false, 'search' => $search, 'text' => $text]; } /** * A candidate of a search becomes the lyrics of a song ($file: the song playing by default): synchronised ones keep * their times, plain ones are lines without times. Saved in var/lyr (lyricsCachePath), to the account when the song * is in the cloud, shown at once when it is the song playing. The path written, or null. * @param array $candidate */ public function importLyrics(array $candidate, ?string $file = null): ?string { $file ??= $this->playlist->current(); $lyrics = $candidate['lyrics'] ?? null; if (!$lyrics instanceof Lyrics) { $lyrics = Lyrics::fromText((string)($candidate['lrc'] ?? $candidate['text'] ?? '')); } if ($file === null || $lyrics === null || $lyrics->isEmpty() || \App\Cloud\Cloud::isPseudo($file)) { return null; } $copy = clone $lyrics; $copy->translations = []; $copy->translationLang = ''; $saved = $this->saveLyrics($file, $copy, false); if ($saved !== null && $this->playlist->current() === $file) { $this->ui['lyrics']['visible'] = true; $this->notice($lyrics->synced ? 'Paroles synchronisées enregistrées' : 'Paroles enregistrées (non synchronisées : défilez-les pendant la lecture)', 4); $this->autoTranslate(); } return $saved; } /** * The lyrics of a song saved (var/lyr/-.lyr, looked at first), UTF-8, their language guessed; the * translations of the lyrics there before are kept for the lines that did not change ($keepTranslations). The * account gets them when the song is in the cloud; shown again when it is the song playing. The path, or null. */ public function saveLyrics(string $file, Lyrics $lyrics, bool $keepTranslations = true): ?string { $before = $this->findLyricsFile($file); if ($keepTranslations && $before !== null) { $lyrics->keepTranslationsOf(Lyrics::load($before)); } if ($lyrics->language === '') { $lyrics->language = \App\Model\Language::detect($lyrics->plainText()); } $target = $this->lyricsCachePath($file); @mkdir(dirname($target), 0777, true); $tmp = $target . '.tmp'; if (@file_put_contents($tmp, $lyrics->toLyr()) === false || !@rename($tmp, $target)) { @unlink($tmp); $this->notice('Paroles NON enregistrées : impossible d\'écrire ' . Text::baseName($target), 5); return null; } $this->forget($file); $this->cloud?->lyricsSaved($file); if ($this->playlist->current() === $file) { $this->loadLyrics($file); } return $target; } /** The lyrics of the song playing have times of their own (false: none, or lines to scroll by hand). */ public function lyricsSynced(): bool { return $this->lyrics !== null && $this->lyrics->synced; } /** * The line of the lyrics about sung now: the line itself for synchronised lyrics, an estimate for the others * (their lines spread over the song by their length): a slow scroll of their text can follow it. -1 before. */ public function estimatedLine(?float $position = null): int { return $this->lyrics?->indexAt($position ?? $this->player->position) ?? -1; } /** The language translations are made in (option translateLang, French by default). */ public function translationLang(): string { return (string)($this->options['translateLang'] ?? 'fr') ?: 'fr'; } private function songLyrics(?string $file): ?Lyrics { $file ??= $this->playlist->current(); if ($file === null) { return null; } if ($file === $this->playlist->current() && $this->lyrics !== null) { return $this->lyrics; } $found = \App\Cloud\Cloud::isPseudo($file) ? null : $this->findLyricsFile($file); $lyrics = $found !== null ? Lyrics::load($found) : null; return $lyrics !== null && !$lyrics->isEmpty() ? $lyrics : null; } /** The language of a song's lyrics ('en'...; '' = none, or it cannot tell). */ public function lyricsLanguage(?string $file = null): string { $lyrics = $this->songLyrics($file); return $lyrics === null ? '' : ($lyrics->language ?: \App\Model\Language::detect($lyrics->plainText())); } /** The song's lyrics are known to be in another language than the translations'. */ public function needsTranslation(?string $file = null): bool { $lang = $this->lyricsLanguage($file); return $lang !== '' && $lang !== $this->translationLang(); } /** @return array the translation of each line of the song's lyrics (index of the line => text), in $lang (default: translationLang()) */ public function translations(?string $file = null, ?string $lang = null): array { $lyrics = $this->songLyrics($file); return $lyrics !== null && $lyrics->translationLang === ($lang ?? $this->translationLang()) ? $lyrics->translations : []; } public function hasTranslation(?string $file = null, ?string $lang = null): bool { return $this->songLyrics($file)?->hasTranslation($lang ?? $this->translationLang()) ?? false; } /** * Translates the lyrics of a song ($file: the song playing) into $lang (default translationLang()), line by line: * Claude Code on a computer that has it, else the free translation (MyMemory). Saved into its .LYR (and to the * account: the phone gets the translations of the PC). The Task settles with the translations (index => text), or * an error; its progress: translationState(). */ public function translate(?string $file = null, ?string $lang = null): \JumPHP\Async\Task { $file ??= $this->playlist->current(); $lang = strtolower($lang ?? $this->translationLang()); $lyrics = $this->songLyrics($file); if ($file === null || $lyrics === null) { return self::failedTask('pas de paroles à traduire'); } if ($this->translator !== null && $this->translator->busy()) { if ($this->translating === $file && $this->translator->lang === $lang) { return $this->translator->task; } $this->translator->stop(); } $from = $lyrics->language ?: \App\Model\Language::detect($lyrics->plainText()); $this->translator = new \App\Media\LyricsTranslator($this->lyricsHttp(), $this->lyricsRunner, $this->lyricsClaude(), $this->storagePath('tmp/logs')); $this->translator->song = $this->translating = $file; $translator = $this->translator; $result = new \JumPHP\Async\Task(); $count = count($lyrics->lines); $translator->start($lyrics->texts(), $from, $lang)->then(function (array $texts) use ($file, $lang, $from, $count, $result): void { // the lyrics as they are now (an edit meanwhile: the lines must still be the same) $now = $this->songLyrics($file); if ($now === null || count($now->lines) !== $count) { $result->settle(null, new \RuntimeException('les paroles ont changé pendant la traduction')); return; } $now = clone $now; $now->setTranslations($texts, $lang); $now->language = $now->language ?: $from; $this->writeTranslated($file, $now); if ($this->playlist->current() === $file) { $this->notice('Paroles traduites (' . \App\Model\Language::name($lang) . ')', 3); } $result->settle($now->translations); }, function (\Throwable $e) use ($result): void { if (str_contains($e->getMessage(), 'quota')) { $this->translateQuotaUntil = time() + 6 * 3600; } $result->settle(null, $e); }); return $result; } /** The lyrics with their translations written where they are read from (the song's own copy in var/lyr). */ private function writeTranslated(string $file, Lyrics $lyrics): void { $content = $lyrics->toLyr(); // lines without times: their estimated times are never written $target = $this->lyricsCachePath($file); @mkdir(dirname($target), 0777, true); if (@file_put_contents($target . '.tmp', $content) !== false && @rename($target . '.tmp', $target)) { $this->forget($file); $this->cloud?->lyricsSaved($file); if ($this->playlist->current() === $file) { $this->loadLyrics($file); } } } /** * Where the translation is: {state: idle | translating | done | error, progress: 0..1, engine: claude | mymemory | * cache | '', file, lang, text (French, one line)}. * @return array{state: string, progress: float, engine: string, file: string, lang: string, text: string} */ public function translationState(): array { $t = $this->translator; if ($t === null) { return ['state' => 'idle', 'progress' => 0.0, 'engine' => '', 'file' => '', 'lang' => '', 'text' => '']; } return ['state' => $t->state, 'progress' => $t->progress, 'engine' => $t->engine, 'file' => $this->translating, 'lang' => $t->lang, 'text' => $t->describe()]; } /** "Traduire automatiquement les paroles": the song playing, when its lyrics are in another language and not translated yet. */ public function autoTranslate(): void { $file = $this->playlist->current(); if (!($this->options['autoTranslate'] ?? true) || $file === null || $this->lyrics === null || $this->engine === null || Platform::isHeadless() || time() < $this->translateQuotaUntil || ($this->translator?->busy() ?? false) || $this->lyricsHttp() === null) { return; } if ($this->needsTranslation($file) && !$this->hasTranslation($file)) { $this->translate($file); } } private static function failedTask(string $why): \JumPHP\Async\Task { $t = new \JumPHP\Async\Task(); $t->settle(null, new \RuntimeException($why)); return $t; } /** "Seulement les morceaux avec paroles": next, previous, Hasard and the end of a song skip the songs without lyrics. */ public function playsLyricsOnly(): bool { return (bool)($this->options['lyricsOnly'] ?? false); } public function setLyricsOnly(bool $on): void { $this->options['lyricsOnly'] = $on; $this->touch(); if ($on && $this->songsWithLyrics() === 0) { $this->notice('Aucun morceau de la playlist n\'a de paroles : cherchez-en (le point de la playlist)', 6); } else { $this->notice($on ? 'Lecture : seulement les morceaux avec paroles' : 'Lecture : tous les morceaux', 3); } } /** How many songs of the play list have lyrics here. */ public function songsWithLyrics(): int { $n = 0; foreach ($this->playlist->items as $file) { $n += $this->hasLyrics($file) ? 1 : 0; } return $n; } private function lyricsOnlyActive(): bool { return $this->playsLyricsOnly() && $this->playlist->count() > 0; } /** @return (\Closure(string): bool)|null */ private function lyricsFilter(): ?\Closure { return $this->lyricsOnlyActive() ? fn (string $file): bool => $this->hasLyrics($file) : null; } private function noLyricsToPlay(): void { $this->player->stop(); $this->skipPending = false; $this->notice('Aucun morceau de la playlist n\'a de paroles : lecture arrêtée (mode « seulement avec paroles »)', 6); } /** Each frame: Claude's answers of the search and the translation. */ private function tickLyricsWork(): void { $this->lyricsSearch?->poll(); $this->translator?->poll(); } private ?\App\Media\Covers $covers = null; public function covers(): \App\Media\Covers { return $this->covers ??= new \App\Media\Covers($this->storagePath('cache/covers'), Platform::isHeadless() ? null : $this->engine?->http()); } /** the volume slider: WinZik's own, or the computer's (a click on its label) */ public string $volumeMode = 'winzik'; public ?\App\Media\SystemVolume $systemVolume = null; public function toggleVolumeMode(): void { if ($this->volumeMode === 'winzik') { if (Platform::isWasm() || Platform::isHeadless() || !\App\Media\SystemVolume::supported()) { $this->notice('Le volume du système : seulement dans la version installée', 3); return; } $this->systemVolume ??= new \App\Media\SystemVolume($this->storagePath('tmp/logs')); $this->systemVolume->read(); $this->volumeMode = 'system'; $this->notice('Le curseur règle maintenant le volume du système', 3); } else { $this->volumeMode = 'winzik'; $this->notice('Le curseur règle maintenant le volume de WinZik', 3); } $this->options['volumeMode'] = $this->volumeMode; $this->touch(); } /** What the volume slider shows and sets. */ public function volumeValue(): int { return $this->volumeMode === 'system' && $this->systemVolume !== null ? $this->systemVolume->volume : $this->player->volume; } public function setVolumeValue(int $v): void { if ($this->volumeMode === 'system' && $this->systemVolume !== null) { $this->systemVolume->set($v); } else { $this->setVolume($v); } } private float $shiftTotal = 0.0; private string $shiftFile = ''; /** The line of the lyrics bar (Form5.Label1). */ public function lyricLine(): string { if ($this->lyrics === null) { return Lyrics::NONE; } return $this->lyrics->lineAt($this->player->position); } private ?Market $market = null; /** the updates of the installed WinZik (null outside an engine) */ public ?AutoUpdate $updater = null; // --- updater: what the phone's UI calls (AutoUpdate) --- /** * The newer version of the phone app, when one was found: version, notes, size (bytes), state (available | * downloading | opened | error), progress (0..1), error (French). null: none (or not the phone app). * @return array{version: string, notes: string, size: int, state: string, progress: float, error: string}|null */ public function androidUpdate(): ?array { return $this->updater?->androidUpdate(); } /** Downloads the newer APK, checks it (size, SHA-256) and opens Android's installer. False: nothing to install. */ public function installAndroidUpdate(): bool { return $this->updater?->installAndroidUpdate() ?? false; } /** Looks for an update now (Rechercher une mise à jour): $wz->updater->state then says checking, latest, available, error. */ public function checkUpdates(): void { $this->updater?->check(); } /** the first seconds of a song: the phone's update may restart the app then (the song starts again after it) */ public const UPDATE_SONG_START = 1.5; /** * May the phone app restart for its update now? Nothing plays (paused, stopped), or a song has just started (between * two songs) while the screen is off: never in the middle of a song. The screen off, Android reopens the updated app * by itself and the music goes on; on, only its notification can (a tap), so the music waits for the screen to go off. */ public function goodMomentToUpdate(?bool $screenOn = null): bool { if ($this->player->state !== Player::PLAYING) { return true; } $screenOn ??= \JumPHP\Native\AndroidApp::screenOn(); return $this->player->position < self::UPDATE_SONG_START && $screenOn !== true; } // --- end updater --- /** the desktop version: the windows of the computer (made once, by the first MainForm) */ public ?\App\Native\NativeShell $native = null; /** the installed WinZik: yt-dlp + ffmpeg, the YouTube search and downloads, the films (null in a browser) */ public ?\App\Media\Tools $tools = null; public ?\App\Media\YouTube $youtube = null; public ?\App\Media\VideoCache $video = null; /** the songs as WAV (the visualizer's samples) and through the equalizer (ffmpeg) */ public ?\App\Media\SoundCache $sounds = null; /** lyrics made by Whisper (+ Claude Code) */ public ?\App\Media\Transcriber $transcriber = null; private string $transcriberSaid = ''; /** the visualizer's bars (always there: they stay down without samples) */ public \App\Media\Spectrum $spectrum; private ?\App\Media\Wav $wav = null; private string $wavFile = ''; private float $visClock = 0.0; /** seconds since the equalizer last moved: its sound is made once it stays still */ private float $eqStill = 99.0; /** a film whose sound is being made: it starts when ready ($playWhenReady) */ public string $waitVideo = ''; private bool $playWhenReady = false; private string $updateSaid = ''; /** Another marketplace (tests, a local playground): '' = none. */ public function useMarket(string $url): void { if ($this->engine !== null) { $this->market = new Market($this->engine->http(), rtrim($url, '/')); } } /** The marketplace of skins and lyrics (jumphp.net), null without network services. */ public function market(): ?Market { if ($this->market === null && $this->engine !== null) { $env = getenv('JUMPHP_MARKET_URL'); $url = is_string($env) ? $env : (Platform::isHeadless() ? '' : (string)$this->engine->config->get('market_url', Market::DEFAULT_URL)); $this->market = new Market($this->engine->http(), rtrim($url, '/')); } return $this->market; } /** * The lyrics of the song from the marketplace, when it has none here: looked for by artist and title (the ID3 tag) * or by the file's name; the first that matches is kept in var/lyr and shown. */ public function fetchMarketLyrics(): void { $file = $this->playlist->current(); $market = $this->market(); if ($file === null || $this->lyrics !== null || $market === null || !$market->enabled() || !($this->options['marketLyrics'] ?? true)) { return; } $base = Text::baseName(Text::withoutExtension($this->path($file))); $artist = mb_strtolower($this->tag->artist); $title = mb_strtolower($this->tag->title); $query = $artist !== '' && $title !== '' ? $this->tag->artist . ' ' . $this->tag->title : $base; $market->list('lyrics', $query)->then(function (array $items) use ($market, $file, $base, $artist, $title): void { foreach ($items as $item) { $same = ($artist !== '' && mb_strtolower((string)($item['artist'] ?? '')) === $artist && mb_strtolower((string)($item['title'] ?? '')) === $title) || mb_strtolower((string)($item['name'] ?? '')) === mb_strtolower($base); if (!$same) { continue; } $market->download('lyrics', (string)$item['id'])->then(function (string $bytes) use ($file): void { if (\App\Model\Lyrics::parse($bytes) === null) { return; } $target = $this->lyricsCachePath($file); @mkdir(dirname($target), 0777, true); file_put_contents($target, $bytes); unset($this->lyricsCache[$file]); if ($this->playlist->current() === $file) { $this->loadLyrics($file); $this->notice('Paroles trouvées sur la marketplace', 3); $this->autoTranslate(); } }, fn () => null); return; } }, fn () => null); } /** * Synchronised lyrics from LRCLIB for the song playing (after the marketplace, when it had none): written in var/lyr. * $asked: from the menu (it says when there are none). */ public function fetchSyncedLyrics(bool $asked = false): void { $file = $this->playlist->current(); if ($file === null || $this->engine === null || ($this->lyrics !== null && !$asked) || (!$asked && !($this->options['lrclib'] ?? true))) { return; } [$artist, $title] = $this->tag->artist !== '' && $this->tag->title !== '' ? [$this->tag->artist, $this->tag->title] : array_pad(array_map('trim', explode(' - ', Text::baseName(Text::withoutExtension($this->path($file))), 2)), 2, ''); if ($title === '') { [$artist, $title] = ['', $artist]; } if ($asked) { $this->notice('Recherche des paroles synchronisées (LRCLIB)...', 10); } (new \App\Media\Lrclib($this->engine->http()))->find($artist, $title, $this->player->duration())->then(function (mixed $lyrics) use ($file, $asked): void { if (!$lyrics instanceof \App\Model\Lyrics) { $asked && $this->notice('Pas de paroles synchronisées sur LRCLIB pour ce morceau', 5); return; } $target = $this->lyricsCachePath($file); @mkdir(dirname($target), 0777, true); file_put_contents($target, $lyrics->toLyr()); unset($this->lyricsCache[$file]); if ($this->playlist->current() === $file) { $this->loadLyrics($file); $this->notice('Paroles synchronisées trouvées (LRCLIB)', 4); $this->autoTranslate(); } }, fn () => $asked && $this->notice('LRCLIB injoignable', 4)); } /** Download of the lyrics from the old site (Form7.findlyr_Click / Form20). */ public ?LyricsDownload $download = null; public function startDownload(): ?LyricsDownload { if ($this->download !== null && !$this->download->finished()) { return $this->download; } $file = $this->playlist->current(); if ($file === null || $this->engine === null) { return null; } $target = $this->lyricsCachePath($file); $this->download = new LyricsDownload($this->engine->http(), $this->tag->artist, $this->tag->title, $target); $this->download->onDone = function (bool $ok) use ($file): void { unset($this->lyricsCache[$file]); if ($ok && $this->playlist->current() === $file) { $this->loadLyrics($file); } }; $this->download->start(); return $this->download; } // the title, the bargraph ------------------------------------------------------------------------------------- /** The text that scrolls in the title (msg2 of Timer2), before its rotation. */ public function titleText(): string { if ($this->notice !== '') { return '* ' . $this->notice . ' * '; } if ($this->player->file === null) { return str_pad('* WinZik * ', 95); } $artist = $this->tag->artist; $title = $this->tag->title; if ($artist === '' && $title === '') { $text = ' --- ' . Text::baseName($this->player->file) . ' --- '; } elseif ($artist === '') { $text = ' --- artiste inconnu --- ' . $title; } else { $text = ' --- ' . $artist . ' --- ' . $title . ' --- '; } return $text . str_repeat(' ', 30); } /** The title as shown: turned left by titleShift characters (Right$(msg2, iv) + Left$(msg2, Len - iv)). */ public function scrolledTitle(): string { $text = $this->titleText(); $chars = mb_str_split($text) ?: ['']; $shift = (($this->titleShift % count($chars)) + count($chars)) % count($chars); return implode('', array_slice($chars, $shift)) . implode('', array_slice($chars, 0, $shift)); } /** The title without its rotation and its padding (fom14: what crosses the screen of the Lock mode). */ public function plainTitle(): string { return trim($this->titleText()); } public function notice(string $text, float $seconds = 4.0): void { $this->notice = $text; $this->noticeTime = $seconds; $this->titleShift = 0; } // joystick / keys -------------------------------------------------------------------------------------------- /** One of the 10 actions of Form11 (Timer3 of Form1 did them for each button / axis). */ public function action(int $action, ?callable $ui = null): void { match ($action) { 0 => $this->setVolumeValue($this->volumeValue() + 5), 1 => $this->setVolumeValue($this->volumeValue() - 5), 2 => $this->next(), 3 => $this->previous(), 4 => $this->toggleShuffle(), 5 => $this->togglePause(), 6 => $this->toggleLyrics(), 7 => $this->toggleCompact(), 8 => $this->setBalance($this->player->balance + 14), 9 => $this->setBalance($this->player->balance - 14), default => null, }; } /** * The first start says hello: "WinZik! It really kicks the Winamp ass!" (assets/sfx/winzik.ogg). The phone app says it * at every start, with its splash (the user wants to hear it each time). */ public function greet(): bool { if ((!$this->firstStart && !Platform::isPhoneApp()) || $this->greeted || $this->engine === null) { return false; } $this->greeted = true; $sound = $this->engine->sound; try { if (!$sound->hasSfx('winzik')) { $sound->loadSfx('winzik', 'assets/sfx/winzik.ogg'); } $sound->playSfx('winzik'); } catch (\Throwable) { // no sound: the hello is silent } return true; } /** Form19: a plug-in started (the one before stops), '' = none. */ public function usePlugin(string $plugin): void { $old = (string)($this->options['plugin'] ?? ''); if ($old === 'led' && $plugin !== 'led') { $this->ledBye = 0.0; // the LEDs blink 20 times before they go out (fin: of Timer2) } $this->options['plugin'] = isset(self::PLUGINS[$plugin]) ? $plugin : ''; if ($plugin === 'led' && $old !== 'led') { $this->ledClock = 0.0; $this->ledBye = -1.0; } $this->touch(); } public function plugin(): string { return (string)($this->options['plugin'] ?? ''); } /** @return array{0: int, 1: int, 2: int}|null the LEDs now: [scroll, caps, num], null = not shown */ public function leds(): ?array { if ($this->ledBye >= 0) { $on = (int)floor($this->ledBye / 0.084) % 2 === 0 ? 1 : 0; return [$on, $on, $on]; } if ($this->plugin() !== 'led') { return null; } $step = (int)floor($this->ledClock / 0.084); if ($step < count(self::LED_INTRO)) { return self::LED_INTRO[$step]; } // Timer2: the level of the sound lights 0, 1, 2 or 3 of them $level = max($this->vuLeft, $this->vuRight); $lit = $level < 0.3 ? 0 : ($level < 0.5 ? 1 : ($level < 0.7 ? 2 : 3)); return [$lit >= 1 ? 1 : 0, $lit >= 2 ? 1 : 0, $lit >= 3 ? 1 : 0]; } /** The equalizer changed: the preamp goes to the sound, AUTO keeps the bands of the song. */ public function eqChanged(): void { $this->eqStill = 0.0; $this->player->setPreamp($this->eq->preampDb()); $file = $this->playlist->current(); if ($this->eq->auto && $file !== null) { $this->eqSongs[$file] = $this->eq->bands; } $this->touch(); } public function toggleEq(): void { $this->ui['eq']['visible'] = !$this->ui['eq']['visible']; $this->touch(); } /** "Afficher la traduction" (T): the translation under each line of the lyrics, when they have one. */ public function showsTranslation(): bool { return (bool)($this->options['lyricsShowTranslation'] ?? true); } public function toggleTranslation(): void { $this->options['lyricsShowTranslation'] = !$this->showsTranslation(); $this->notice($this->showsTranslation() ? 'Traduction des paroles affichée' : 'Traduction des paroles cachée', 2); $this->touch(); } public function toggleLyrics(): void { $this->ui['lyrics']['visible'] = !$this->ui['lyrics']['visible']; $this->touch(); } public function toggleCompact(): void { $this->ui['compact']['active'] = !$this->ui['compact']['active']; $this->touch(); } // --- cloud: the account, the cloud playlist, the songs sent from the PC to the phone (src/Cloud, AGENTS.md "Cloud") --- private ?\App\Cloud\Cloud $cloud = null; private bool $cloudMade = false; /** next() going through lines of the cloud whose songs are not here */ private int $cloudHops = 0; /** * WinZik's cloud (null outside an engine). Its server: project.yaml `cloud_url`, env JUMPHP_CLOUD_URL; none in the * tests (they give their own with useCloud()): then state() is 'off'. */ public function cloud(): ?\App\Cloud\Cloud { if (!$this->cloudMade && $this->engine !== null) { $this->cloudMade = true; $engine = $this->engine; $env = getenv('JUMPHP_CLOUD_URL'); $url = is_string($env) ? $env : (Platform::isHeadless() ? '' : (string)$engine->config->get('cloud_url', '')); $kind = Platform::isPhoneApp() ? 'phone' : (Platform::isWasm() ? 'web' : 'desktop'); $account = new \App\Cloud\CloudAccount(fn (string $m, string $u, string|array|null $b, array $h, float $t) => $engine->http()->request($m, $u, $b, $h, $t), $url, $this->storagePath('cloud.json'), $kind); $net = \JumPHP\Net\NetSession::isAvailable() ? fn () => new \JumPHP\Net\NetSession($engine->config) : null; $lan = $kind === 'desktop' && \App\Cloud\LanShare::supported() ? new \App\Cloud\LanShare() : null; $this->useCloud(new \App\Cloud\Cloud($this, $account, $this->storagePath('cloud'), $net, $lan)); } return $this->cloud; } /** Another cloud (tests: fake server, fake relay). */ public function useCloud(?\App\Cloud\Cloud $cloud): void { $this->cloud?->stop(); $this->cloud = $cloud; $this->cloudMade = true; if ($cloud !== null && $cloud->signedIn() && $cloud->wantsCloudView()) { $cloud->useView('cloud'); } } /** cloud (PlaySync): how many seeks were asked (seek()), how many changes WinZik made by itself (end of a song, the resume) */ public int $seeks = 0; public int $autoChanges = 0; /** cloud (PlaySync): another device leads the playback: the song of the last time does not start by itself here */ public function cancelResume(): void { $this->resumePlay = false; } // --- end cloud --- // --- cast: the music and the lyrics on the TV (src/Cast, AGENTS.md "Cast") --- private ?\App\Cast\Cast $cast = null; private bool $castMade = false; private bool $mediaAsked = false; /** Casting to the TV (null in the browser: no sockets there; made at the first call). */ public function cast(): ?\App\Cast\Cast { if (!$this->castMade) { $this->castMade = true; if (\App\Cast\Cast::supported()) { $this->cast = new \App\Cast\Cast($this, $this->storagePath('cast.json')); } } return $this->cast; } /** Another one (tests: fakes). */ public function useCast(?\App\Cast\Cast $cast): void { $this->cast?->stop(); $this->cast = $cast; $this->castMade = true; } // --- end cast --- // each frame ------------------------------------------------------------------------------------------------- public function tick(float $dt): void { if ($this->player->update($dt)) { // the end of a song (MediaPlayer1_PlayStateChange 2 -> 0): the next one $this->autoChanges++; // cloud: not the user's doing (App\Cloud\PlaySync) $this->next(); } $this->tickSkip(); $this->download?->update(); $this->tickLyricsWork(); $this->tickMedia($dt); $this->cloud?->tick($dt); // cloud: after the media (a YouTube song of the cloud is known before it is listed) $this->cast?->tick($dt); // cast: after the player (a new song goes to the TV in the same frame) if (!$this->mediaAsked && $this->engine !== null && !Platform::isHeadless() && !Platform::isWasm() && ($this->options['mediaServer'] ?? true)) { // WinZik in VLC's "Réseau local" from the start (option mediaServer, on by default; not in tests nor the browser) $this->mediaAsked = true; $this->cast()?->setMediaServer(true); } $this->tickWake($dt); $this->tickScans(); $this->tickWork($dt); $this->countListen(); $this->tickBounds(); $this->spotify?->poll(); $this->resumeWhenKnown($dt); $this->restartTest($dt); $this->systemVolume?->poll(); $this->tickEqualizer($dt); $this->tickVisualizer($dt); $this->updater?->poll(); $this->updater?->tick($dt, (bool)($this->options['autoUpdate'] ?? true)); if ($this->updater !== null && $this->updater->state !== $this->updateSaid) { $this->updateSaid = $this->updater->state; match ($this->updater->state) { 'installed' => $this->notice('WinZik ' . $this->updater->version . ' est installé : il démarre au prochain lancement (menu : Redémarrer)', 12), 'latest' => $this->notice('WinZik est à jour', 3), 'available' => $this->notice('WinZik ' . $this->updater->version . ' est disponible', 6), // updater: the phone app 'ready' => $this->notice('WinZik ' . $this->updater->version . ' est téléchargé : il s\'installe à la pause, ou entre deux chansons écran éteint', 6), 'confirm' => $this->notice('Android demande de confirmer la mise à jour (une seule fois)', 8), default => null, }; } // the title moves one character every 200 ms (Timer2) $this->titleClock += $dt; while ($this->titleClock >= 0.2) { $this->titleClock -= 0.2; $this->titleShift++; } if ($this->notice !== '') { $this->noticeTime -= $dt; if ($this->noticeTime <= 0) { $this->notice = ''; } } $this->updateVu($dt); $this->ledClock += $dt; if ($this->ledBye >= 0) { $this->ledBye += $dt; if ($this->ledBye > 40 * 0.084) { $this->ledBye = -1.0; } } // where the song is, kept every few seconds while it plays: a crash or the end of the session resumes near there if ($this->player->state === Player::PLAYING) { $this->positionClock += $dt; if ($this->positionClock >= self::POSITION_EVERY) { $this->positionClock = 0.0; $this->touch(); } } $this->saveClock += $dt; if ($this->dirty && $this->saveClock > 2.0) { $this->saveClock = 0; $this->save(); } } private function tickMedia(float $dt): void { if ($this->tools === null) { return; } $this->tools->tick($dt, (bool)($this->options['ytTools'] ?? true)); $this->youtube?->poll(); if ($this->youtube !== null && $this->youtube->changed) { $this->saveQueue(); } $this->video?->poll(); $this->sounds?->poll(); $this->tickTranscriber(); foreach ($this->youtube?->finished() ?? [] as $got) { // a download finished: into the play list (2001: the files of Form3); a film's sound and pictures made at once $this->addFiles([$got['file']]); if ($got['bounds'] ?? null) { $this->marks()->set($got['file'], $got['bounds'][0], $got['bounds'][1], 'yt'); // its intro / outro (chapters) $this->marks()->save(); } if ($got['format'] === 'mp4') { $this->video?->audio($got['file']); } $this->notice('Ajouté à la playlist : ' . Text::baseName($got['file']), 6); } if ($this->waitVideo !== '' && $this->video !== null) { $sound = $this->video->audio($this->waitVideo); $error = $this->video->error($this->waitVideo); if ($sound !== null || $error !== '') { $film = $this->waitVideo; $play = $this->playWhenReady; $this->waitVideo = ''; $this->playWhenReady = false; $this->notice = ''; if ($sound !== null && $this->player->load($film, $sound)) { $play && $this->player->play(); } else { $this->notice('Vidéo illisible : ' . ($error ?: 'son impossible à lire'), 6); if ($play) { $this->skipBroken(); // it was to play (the list going on): the next song } } } } } /** Lyrics of the song playing made by Whisper (then put right by Claude Code when it is there). */ public function transcribe(string $mode = 'whisper'): bool { $file = $this->player->file; $t = $this->transcriber; if ($t === null || $file === null) { $this->notice('Whisper : seulement dans la version installée, avec un morceau choisi', 5); return false; } $t->useClaude = (bool)($this->options['whisperClaude'] ?? true); $base = Text::baseName(Text::withoutExtension($file)); [$artist, $title] = $this->tag->artist !== '' ? [$this->tag->artist, $this->tag->title ?: $base] : array_pad(array_map('trim', explode(' - ', $base, 2)), 2, ''); $hint = $title === '' ? ['title' => $artist, 'duration' => $this->player->duration()] : ['artist' => $artist, 'title' => $title, 'duration' => $this->player->duration()]; if (!$t->start(\App\Model\Playlist::isVideo($file) ? $file : $this->path($file), $mode, $hint)) { $this->notice($t->busy() ? $t->describe() : 'Whisper : ' . ($t->error ?: 'impossible'), 5); return false; } return true; } private function tickTranscriber(): void { $t = $this->transcriber; if ($t === null) { return; } $t->poll(); $said = $t->describe(); if ($said === $this->transcriberSaid) { return; } $this->transcriberSaid = $said; if ($t->state === 'done') { // its .LYR under the song's own name (written there already; a Transcriber without lyricsPath: moved there) $own = $t->song !== '' ? $this->lyricsCachePath($t->song) : ''; if ($own !== '' && $t->result !== '' && $t->result !== $own && is_file($t->result) && @rename($t->result, $own)) { $t->result = $own; } $this->refreshLyrics(); $this->ui['lyrics']['visible'] = true; $this->touch(); } if ($said !== '') { $this->notice($said, $t->busy() ? 600 : 8); } } /** The sound the song should have now: through the equalizer when it is on and not flat (once made), else as it is. */ private function tickEqualizer(float $dt): void { $this->eqStill += $dt; $player = $this->player; if ($this->sounds === null || $player->file === null || $player->error || $this->waitVideo !== '') { return; } $base = \App\Model\Playlist::isVideo($player->file) ? ($this->video?->audio($player->file) ?? '') : $player->file; if ($base === '') { return; } $flat = !$this->eq->on || ($this->eq->preamp == 0.0 && max(array_map('abs', $this->eq->bands)) < 0.1); $wanted = $base; if (!$flat && $this->eqStill > 0.5) { $wanted = $this->sounds->equalized($base, $this->eq->bands, $this->eq->preamp) ?? $player->heard; } elseif (!$flat) { $wanted = $player->heard; // still moving: what plays now goes on } if ($wanted !== $player->heard && $player->swapSound($wanted)) { // the preamp is in the equalizer's sound: not twice $player->setPreamp($wanted === $base ? $this->eq->preampDb() : 0.0); } } /** The visualizer: the spectrum of the samples heard now (the song's WAV made by ffmpeg, or the WAV played). */ private function tickVisualizer(float $dt): void { $this->visClock += $dt; // only when it is seen: the visualizer (the player unrolled) 20 times a second, the light of the bass alone 12; // the player hidden (tray, mini bar, lyrics alone): not at all $ui = $this->ui; $seen = ($ui['main']['visible'] ?? true) && !$ui['compact']['active'] && !$ui['tray'] && !$ui['lyricsOnly']; $every = !$seen ? 0.0 : ($ui['main']['expanded'] ? 1 / 20 : ($ui['vu'] ? 1 / 12 : 0.0)); if ($every === 0.0 || $this->visClock < $every) { return; } $step = $this->visClock; $this->visClock = 0.0; $player = $this->player; $file = ''; if ($player->heard !== '' && strtolower(pathinfo($player->heard, PATHINFO_EXTENSION)) === 'wav') { $file = $player->heard; } elseif ($player->file !== null && $this->sounds !== null && !\App\Model\Playlist::isVideo($player->file)) { $file = $this->sounds->plain($player->file) ?? ''; } if ($file !== $this->wavFile) { $this->wavFile = $file; $this->wav = $file !== '' ? \App\Media\Wav::open($file) : null; $this->spectrum->newSong(); } $this->spectrum->update($step, $this->wav, $player->position, $player->state === Player::PLAYING); } /** The bargraph: it dances with the music and the volume (2001: Label8..13; the sound card's input in winster4.bas). */ private function updateVu(float $dt): void { $playing = $this->player->state === Player::PLAYING; $this->vuClock += $dt; if ($this->vuClock >= 0.06) { $this->vuClock = 0; $level = $playing ? ($this->player->volume / 100) * (0.35 + 0.65 * ($this->noise)()) : 0.0; $this->vuTarget = $level; } $pan = $this->player->balance / 100; $follow = min(1.0, $dt * 18); $this->vuLeft += ($this->vuTarget * min(1, 1 - $pan) * (0.85 + 0.15 * ($this->noise)()) - $this->vuLeft) * $follow; $this->vuRight += ($this->vuTarget * min(1, 1 + $pan) * (0.85 + 0.15 * ($this->noise)()) - $this->vuRight) * $follow; } // skins ------------------------------------------------------------------------------------------------------ /** @return list the skins of the application and of the user (var/skins) */ public function skins(): array { return Skin::findAll([$this->path('assets/skins'), $this->storagePath('skins')]); } public function useSkin(string $dir): bool { if ($dir === '') { return false; } $path = $this->path($dir); if (!Skin::isSkin($path)) { return false; } $this->skin = new Skin($path); $this->touch(); return true; } /** The downloads still to do, in their file (they go on at the next start). */ public function saveQueue(): void { if ($this->youtube === null) { return; } $this->youtube->changed = false; self::writeJsonFile($this->storagePath('youtube-queue.json'), $this->youtube->pending(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); } /** Quits (Command5_Click: the .cfg written, then End). */ public function quit(): void { // the download going on stops; it stays in the queue (written): the next start goes on with it $this->youtube?->stopAll(); $this->saveQueue(); $this->save(); $this->player->stop(); $this->stopHelpers(); $this->engine?->quit(); } /** * Every program WinZik started in the background ends with it (no ffmpeg / whisper left running alone): the helper * processes (told to end: they read "exit"), and whatever the media classes and the desktop shell can stop. */ public function stopHelpers(): void { $this->work?->close('quit'); foreach ([$this->transcriber, $this->lyricsSearch, $this->translator, $this->video, $this->sounds, $this->tools, $this->systemVolume, $this->native, $this->cloud, $this->cast] as $helper) { if ($helper !== null) { try { $helper->stop(); } catch (\Throwable) { // ending anyway } } } } }