# winzik — notes for agents The WinZik audio player of 2001 (VB6) as a JumPHP graphic app. Read README.md first (which VB form became which file). - One shared state: `App\Core\WinZik` (a service; forms get it injected, call `attach($engine)`). It owns the player, the play list, lyrics, skin, `ui` (window positions / visibility) and `options`; it is saved to `var/winzik.json`. - Only the top scene updates: every form / scene calls `$wz->tick($dt)` (`WinZikDialog`, `FullScreen`, `MainForm`). - The skinned windows are not Gui widgets: `App\Gui\Desktop` (one widget filling `forms/MainForm.form.yaml`) draws `SkinWindow`s in skin pixels through `Canvas` at a zoom (`Desktop::$scale`). Controls are rectangles in `controls()`. - `Player` uses SDL_mixer's music; position = its own clock, duration from `AudioInfo`. Without audio it plays silently (tests rely on that: the end of a song really comes). - Tests: `tests/PlayerTestCase.php` clicks controls by window + control id. `MainForm` params: demo, fresh, seek, skin, expanded, phone (a phone's screen simulated: `true` = 9 / 19.5, or the width / height ratio). Keep French texts: the app speaks the French of 2001. - Phone mode (`Desktop::$phone`: "WinZik original" on the phone app, or the `phone` param): the windows stacked one under the other (player, film / equalizer, then the play list across the screen down to the bottom; two columns on its side), the zoom on a whole or half screen pixel when that loses little (`Desktop::phoneScale()`), nothing to drag, a finger slides the list, a long press (`Desktop::LONG_PRESS`, a ring fills around the finger) or the "Menu" button of the bar at the bottom (`Desktop::PHONE_BAR`, like the task bar of Windows 98: Menu, WinZik, the clock) opens the menu, a touch near a control is on it (`Desktop::TOUCH_SLOP`), no hover. The menus are made for a finger (`PopupMenu::$touch`: rows of 26, as wide as the screen, a submenu opens in its place with a row to go back, a finger slides a menu taller than the screen); Escape (the back button) goes back / closes. The karaoke and a wide film on the whole screen are drawn turned a quarter (`Desktop::turned()`, `renderTurned()`: a texture as wide as the screen is tall, copied at 90°; touches turned back): the user turns the phone, the app stays upright. The lyrics bar has two lines (buttons, then the line sung). The dialogs (`WinZikDialog::phoneScreen()`) are whole screens at the phone's width, their rows wrapped (not rows of a fixed height), closed by the back button, drawn at the phone's dp (`WinZikDialog::phoneZoom()`: the screen's width / `PHONE_DP` 392, the phone gives real pixels and no density), sliding when taller than the screen, narrower margins; what means nothing on a phone is hidden there (`WinZikDialog::hideOnPhone()`: task bar, starting with the computer, window size, mini bar offset, yt-dlp / ffmpeg / Whisper, joystick, folder choosers). The menus stay above the bar of the phone (`Desktop::popup()`), a label too long for a finger's row is drawn a little smaller (`PopupMenu::labelFont()`); no Mode compact, Réduire dans la barre, Configurer le Joystick, Quitter on the phone (the compact mode is switched off there). Tests: `tests/OriginalPhoneTest.php` (pictures `var/screenshots/tests/original-phone-*.png`) and `tests/PhonePopupsTest.php` (every menu, submenu, dialog, the karaoke and the film turned, on 720 x 1280, 1080 x 2400 and 1440 x 3200 pixels: whole on the screen, readable, back closes them; pictures `phone-popups--*.png`). - Settings files (`var/winzik.json`, `youtube-queue.json`, `stats.json`, `marks.json`): `WinZik::writeJsonFile()` / `readJsonFile()`. A name that is not UTF-8 (a Latin-1 file name) is kept as `b64:` + base64; a value JSON cannot hold never empties the file. - Lyrics WinZik gets (marketplace, LRCLIB, old site, Whisper, shifted): `WinZik::lyricsCachePath()` = `var/lyr/-.lyr`; looked for there, then next to the song, then `var/lyr/.lyr` (before 0.10.6). Nothing writes `var/lyr/.lyr` any more (a .LYR chosen in Ajouter des fichiers goes to each song of that name in the list). - Quitting (`WinZik::quit()` -> `stopHelpers()`): each helper's `stop()` (`Process::stop()`: ended, killed if needed, reaped), the tray icon and the foreground watcher closed: no ffmpeg / whisper / yt-dlp left running. A new helper that starts programs needs one. - Play list: a line chosen is drawn under `PlaylistWindow::veil()` with `inkOnVeil()` (its colour, or white / black: 4.5:1 at least on every skin, `SkinsTest`). - The list follows the song playing (`PlaylistWindow::reveal()`, called by `Desktop` when the active song changes): its line centred when out of view (the search's / the folders' line, `lineOf()`; hidden by them: nothing moves), not while scrolled by hand (`byHand()`: wheel, bar, finger, keys) for `FOLLOW_AFTER` s, then it catches up. The target of the foot (`locate`, « Aller au morceau en cours », lit while the song is out of view) = `revealActive()`. Phone UI: `MobileView` follows too (glides; `listByHand()`), the round button `locate` (target) above the mini player while the song is out of view, the row glows (`flash`). Tests: `tests/PlaylistFollowTest.php`, `tests/MobileFollowTest.php`. ## Lyrics (core: `App\Core\WinZik`, `App\Model\Lyrics`, `App\Media\LyricsSearch`, `App\Media\LyricsTranslator`) The screens (desktop `src/Gui` + `src/Form`, phone `src/Mobile`) only call this API; everything runs in the background (Tasks, `WinZik::tick()` polls Claude's process), nothing blocks a frame. **The .LYR file** (`App\Model\Lyrics`, documented in its docblock), backward compatible: the readers before 0.10.x read a time row then a text row and skip any other row, so the new rows come after a text row or before the first time. ``` [LYR] [LYR] [ 1.26 ] [NON SYNCHRONISEES] lyrics without times: lines only (an empty row = a blank I walk alone tonight I walk alone tonight between verses); an older WinZik sees no lyrics (never wrong times) [ 4.3 ] And the city... And the city... [LANGUE en] [LANGUE en] [TRADUCTION fr] [TRADUCTION fr] 1=Je marche seul ce soir 1=Je marche seul ce soir 2=Et la ville... 2=Et la ville... ``` `[LANGUE xx]` = the language of the lyrics (guessed when saved: `App\Model\Language::detect()`, no network); `[TRADUCTION xx]` then `n=text` = the translation of line n (from 1, in the file's order; blank lines have none). Written in UTF-8 by the core (the editor writes Windows-1252: `Text::lines()` reads both). `Lyrics`: `lines` (list of `[float time, string text]`, as before; for unsynced lyrics the times are ESTIMATES set by `spread($duration)`: the lyrics bar / karaoke keep working), `synced` (bool), `translations` (index => text), `translationLang`, `language`, `texts()` (lines without the `` of enhanced LRC), `translation($i)`, `hasTranslation(?$lang)`, `setTranslations($list, $lang)`, `keepTranslationsOf($old)` (an edit keeps the translations of the lines whose words did not change), `plainText()`, `fromText($text)` (.LYR, LRC = synced, else plain lines = unsynced), `toLyr()` (never writes estimated times). The editors: load `texts()` without times when `!synced`; save through `$wz->saveLyrics($file, $lyrics)` (keeps translations, guesses the language, cloud, reload) rather than writing the file. **WinZik API** | Call | | |---|---| | `hasLyrics($file)` | lyrics here (synced or not; cached, no network; a cloud pseudo line: the entry's `lyrics`) | | `lyricsSynced()` | the song playing has lyrics with times (false: none, or lines to scroll by hand) | | `estimatedLine(?$pos)` | the line about sung (unsynced: by the estimate; a slow automatic scroll can follow it), -1 before | | `songQuery($file)` | `[artist, title]` from the tag, else "Artiste - Titre" of the file's name | | `searchLyrics($artist, $title, ?$file)` | `?LyricsSearch` (the previous one cancelled; also `$wz->lyricsSearch`) | | `lyricsHelp($file)` | "the dot of the play list": starts the search for that song, returns `{file, artist, title, hasLyrics, synced, translated, search: ?LyricsSearch, text}` (`text`: one French line to show); open the search dialog filled with artist / title | | `importLyrics($candidate, ?$file)` | a candidate becomes the song's lyrics (synced: times kept; plain: lines without times), saved at `lyricsCachePath()`, sent to the cloud account (`Cloud::lyricsSaved()`), shown if playing. Returns the path or null | | `saveLyrics($file, Lyrics, $keepTranslations = true)` | the same for lyrics made / edited by the UI | | `translate(?$file, ?$lang)` | Task → `index => translation` (or an error: `getMessage()` in French); saved into the .LYR and to the account | | `translationState()` | `{state: idle\|translating\|done\|error, progress 0..1, engine: claude\|mymemory\|cache, file, lang, text}` | | `translations(?$file, ?$lang)`, `hasTranslation(?$file, ?$lang)` | the translations of a song's lyrics (default: `translationLang()`) | | `lyricsLanguage(?$file)`, `needsTranslation(?$file)`, `translationLang()` | language of the lyrics ('' unknown), "in another language than the translations'" | | `setLyricsOnly(bool)`, `playsLyricsOnly()`, `songsWithLyrics()` | the play mode "Seulement les morceaux avec paroles" | | `useLyricsServices($http, $runner, $claude)` | tests: fake Internet (`tests/Lyrics/FakeLyricsHttp`), fake `claude` (`Process::finished`) | Options (`$wz->options`): `lyricsOnly` (false; NOT `ui['lyricsOnly']`, which is the lyrics bar shown alone), `autoTranslate` (true: "Traduire automatiquement les paroles": the song playing, when its lyrics are known to be in another language and not translated yet; never in headless runs), `translateLang` ('fr'; codes of `Language::NAMES`), `lyricsClaude` (true: Claude Code, when installed on a computer, searches and translates). **`LyricsSearch`**: `candidates` (best first: same title / artist / length, synced before plain), `sources` (`lrclib|market|archive|claude` => `searching|found|none|error|off`), `task` (settles with all candidates), `done()`, `describe()` (French line), `cancel()`. A candidate: `{id, source, sourceName, artist, title, album, duration, synced, lines, preview, text, lyrics: Lyrics}`. Sources: LRCLIB `/api/search` (synced, else its plain text), the marketplace (4 first .LYR downloaded), the old site (Internet Archive), Claude Code (`claude -p` with WebSearch / WebFetch only and `--strict-mcp-config`: it answers WHERE (`LRCLIB:`, `URL:`), WinZik fetches; never this computer's network: `Transcriber::publicUrl()`). lyrics.ovh is gone (its domain no longer resolves, 2026-11). **Translation** (`LyricsTranslator`): a computer with Claude Code: `claude -p` with no tool, the different lines numbered `n|text`, kept only when every line comes back; else / on the phone / Claude failing: MyMemory (`api.mymemory.translated.net/get`, no key, no e-mail, User-Agent `WinZik`), the different lines in blocks of 450 bytes, one request after the other, a block whose line count changed asked line by line, its daily quota ending it with a clear error (auto translation then waits 6 h). Translated lines cached in memory. The phone gets the PC's translations through the cloud: `Cloud::lyricsCheck($file)` (called by `WinZik::open()`) asks the account's lyrics again with `If-None-Match` (at most every `LYRICS_RECHECK` s) and replaces the copy here unless it was changed here (ETag + SHA-1 kept in `var/cloud/lyrics.json`). **Only songs with lyrics**: `Playlist::next($accept)` / `previous($accept)` go to the next accepted line (Hasard: a random accepted one); `WinZik::next()` / `previous()` / the end of a song / a file that cannot be read use it; a line clicked plays anyway. No line has lyrics: the notice "Aucun morceau de la playlist n'a de paroles : lecture arrêtée" and it stops. Tests: `tests/LyricsFeaturesTest.php`, `CloudTest::testTheTranslationsMadeOnThePcComeDownToThePhoneInItsLyrics`. **Desktop UI of the lyrics** (also the original phone interface): - `App\Form\LyricsSearchForm` (`Host::openLyricsSearch($file)`, `Desktop::lyricsSearch(?$file)`: menu « Chercher les paroles (Internet, Claude)… », the "+" of the lyrics bar, the dot of a line): `lyricsHelp()` fills artist / title and starts the search; the candidates as they come (`SYNC` / `≡`, source, song, length, lines), what each source does (« Claude cherche sur le web… »), the first lines of the one chosen; Importer (`importLyrics`) then « Ouvrir dans l'éditeur » (`close(['openEditor' => file])`, `MainForm::resume()` plays it and opens the editor). Param `song` (NOT `file`: a Form's own property, its yaml), `editor: true` = from the editor: « Mettre dans l'éditeur » closes with the candidate (`LyricsEditorForm::resume()`). - `LyricsEditorForm`: unsynced lyrics loaded as plain lines (blanks kept), `preview()` unsynced while no line has a time, saved through `saveLyrics()` (translations of unchanged lines kept), « Chercher sur internet… » (`webSearch`). - `LyricsBar`: the translation under the line (`TRANSLATION` blue, smaller; `translationOf($i)`, option `lyricsShowTranslation`, `WinZik::toggleTranslation()`, key T, the T button of the whole screen); unsynced: the bar shows `barIndex()` (the wheel moves it, `FOLLOW_AFTER` s then the song again), badge `sync` (« ≡ non synchro » = the editor), no ±0.5 s. Whole screen: on the left `prev` / `play` / `next` (`sideButtons()`), unsynced lyrics = a page (`pageLayout()`, `page` px; wheel, drag on `page`, slow follow of `estimatedLine()` when option `lyricsAutoScroll`; `sync`, `scroll` buttons); Escape closes it before anything else (`Desktop::keys()`), checked natively by `WINZIK_CHECK_KARAOKE=1 tools/native/check.sh`. - `PlaylistWindow`: the dot of a line = `lyricsMark($file)` (none / synced / plain / translated; read from the .LYR, 3 s cache): the skin's lyrok / lyrno + a mark after it (two yellow bars = without times, blue dot = translated), tooltip, a click on it (x < `DOT_W`) = the search for that song (it does not play). Foot: `PAROLES n/total` while `playsLyricsOnly()`. - Menus (`Desktop::menuItems()`): Menu > Chercher les paroles…, Afficher la traduction (T), « Traduire les paroles maintenant (langue) » / « Traduction en cours… NN % »; top level « Seulement les morceaux avec paroles ». Options: Traduire automatiquement, Afficher la traduction, Utiliser Claude (PC; hidden on the phone), the language of the translations. - Tests: `tests/LyricsUiTest.php` (pictures `lyrics-search`, `karaoke-translation`, `karaoke-unsynced`, `karaoke-buttons`, `playlist-lyrics-dots`, `lyrics-bar-translation`, `lyrics-bar-unsynced`, `original-phone-lyrics-search`). ## Keys (`Desktop::keys()`) - Always: Space play / pause, the media keys (lecture, suivant, précédent, stop, muet), Escape (menu, film or lyrics on the whole screen). - The pointer over the play list: its own keys first (`PlaylistWindow::keys()`: arrows, pages, Entrée, Suppr, Ctrl+A, Ctrl+F, Ctrl+J, a letter searches); the search open: the letters and the arrows go to it. - With the "Plugins Clavier" (Options, on by default): X play, C pause, V stop, B / N next, Z / W previous, ← / → 5 s (Shift: 30 s), ↑ / ↓ and + / - volume (the computer's when the slider is on it), 0..9 to 0..90 % of the song, Enter play, H hasard, L / Ctrl+O load, K lyrics, F lyrics on the whole screen, P play list, M compact, E equalizer, Y YouTube, Suppr the lines chosen, F11 the film on the whole screen, Ctrl+Q quit (with the roll up). ## The desktop version: windows of the computer (src/Native/) On a computer (an executable or `bin/jumphp run`, not the browser, not the tests) `NativeShell::wanted()` is true and `WinZik::attach()` makes a `NativeShell` that runs on the engine's `frame` event: - the engine's own window is only the splash (alone, the size of its frame), the dialogs (a framed window in the middle), Lock / A propos (the whole screen); it hides while the player is on screen; - each SkinWindow (player, play list, equalizer, compact bar, lyrics bar) and the right click menu is a borderless, always-on-top SDL window with its own renderer (`NativeTextures`: pictures and SDL_ttf texts per renderer); only the player is in the task bar; the lyrics bar runs across the bottom of the screen, over the task bar; - the pointer: `SDL_GetMouseFocus()` for the window, the engine's mouse for x / y (`SDL_GetMouseState` of the binding does not fill its arguments): `viewToWindow()` turns it back into the window's pixels. The window position used is the one we set (SDL's comes back late while a window moves), and a drag is sent only on a real move of the mouse; - `Desktop::nativePointer()` gets them in desktop pixels (screen pixels / zoom); the form's own pointer events are ignored then. - `WINZIK_ONE_WINDOW=1` keeps the old single window. Check it for real: `tools/native/check.sh` (Xvfb + xdotool, screenshots of the whole screen in `var/screenshots/native/`). ## The phone app (src/Mobile/) The splash on the phone (`SplashScene::$phone`: the phone app, or the param `phone`) fills the screen held upright: the picture of 2001 (wider than tall) turned a quarter like the karaoke (`renderPhone()`: a texture as wide as the screen is tall, copied at 90°), its yellow lines turned with it, the teal of 2001 around; it stays `PHONE_SECONDS` (5 s: the jingle `WinZik::greet()` plays at each start lasts 4.9 s), a tap skips it after 1 s. Tests: `tests/SplashPhoneTest.php` (`splash-phone-1080x2400.png`, `-720x1280.png`). On a phone (`Platform::isPhoneApp()`: the Android / iOS app, held upright: `android.orientation: portrait`) the splash goes to `App\Form\MobileForm` instead of `MainForm` (`SplashScene::main($wz)`; `MainForm::loaded()` sends a phone there too), unless the option `phoneUi` is `'original'` (`MainForm::originalOnPhone()`: "WinZik original", the windows of 2001, see Phone mode above; its menu's "Interface mobile" sets it back to `'mobile'` and goes to MobileForm): one widget, `App\Mobile\MobileView`, draws a player of today in dp, on WinZik's own state (no second player): Lecteur (picture + bars, title, karaoke lyrics, a bar to seek, big buttons, Hasard, Répéter the song, volume), Playlist (search, Préférés d'abord, big rows, a finger scrolls them with inertia, tap = play, long press or ⋮ = the action sheet), Ajouter de la musique (the phone's folders), a bar of tabs, a mini player, bottom sheets (Plus, Égaliseur, Thème, Options, À propos, Infos). A touch anywhere but in the field typed in (or a drag) closes the phone's keyboard (`field` / `searching` emptied in `pointerDown()`) and still does what it does there. Back (Escape) closes the keyboard, the sheet, the add screen, then goes back to Lecteur. Icons drawn with GD (`Icons`), colours in `MobileTheme`. The features of the computer are pages of their own (`MobileView::PAGES`, full screen, back = where they came from), in traits: `YouTubePages` (YouTube: search, a link pasted, MP3 / MP4, the queue with retry / remove, `YouTube::cannotDownload()` shown as it is; Spotify: Client ID, connect, playlists imported through YouTube), `LyricsPages` (sheet Paroles: LRCLIB, marketplace, old site, a .lrc / .lyr imported, shifted ±0,5 s; the editor: lines typed then a tap per line while the song plays; the karaoke on the whole screen, opened in one tap: the Lecteur's lyrics card and its button, the mic of its top bar, the mic of the mini player (`karaokeOpen`; no lyrics: the sheet Paroles). Its « Paysage / Portrait » chip (`karaTurn`, remembered in `ui.mobile.karaokeLandscape`) draws it turned a quarter (`MobileView::renderTurned()`: a texture as wide as the screen is tall, copied at 90°; `local()` / `at()` turn the touches, `turned()`); a tap on a line (`karaLine`) seeks there and plays; a finger drags / flicks the lyrics (`karaScroll` in lines, `karaShift()` by dp; a drag never seeks): the line sung is no longer followed (`karaFree`) until « Revenir à la ligne chantée » (`karaFollow`) or `MobileView::KARAOKE_FOLLOW` s untouched; tests `tests/MobileKaraokeTest.php`), `LyricsWebPages` (the page `lyricsFind` « Chercher des paroles »: `openLyricsFind($file, 'song'|'editor')`, artist / title from `songQuery()`, `searchLyrics()`'s candidates as they come (rows `lyCand`: ⏱ Synchro / ≡ Texte chip, source, preview; `lySources`), the sheet `lyPreview` (Importer = `importLyrics()`, Importer dans l'éditeur = `fillEditor()`); reached from the lyrics sheet, the karaoke's ⋮, the row sheet « Paroles… » (`lyFind`), « Pas de paroles · touchez pour en trouver » and the editor's « Chercher sur Internet »; the Lecteur's card `renderLyrics()` (unsynced: drag = `scroll['lyCard']`, follows `estimatedLine()`, label « non synchronisées »); the translations under the lines in blue (`showTranslation()` = `ui.mobile.translation`, the karaoke's chip `trToggle` / `trNow`, `translationChip()`); the karaoke without times: plain lines, « Défiler seul » (`ui.mobile.lyricsAutoScroll`), « Synchroniser » (editor), a tap on a line does not seek; the play list's marks `lyricsMarks()` (clock / list / translate) and the chip « Seulement avec paroles » (`lyOnly` = `setLyricsOnly()`, the list then shows only those songs, an empty state when none); Options rows `lyricsOptionRows()`; the editor saves through `saveLyrics()` (« Enregistrer sans synchro »: lines without times); tests `tests/MobileLyricsTest.php`), `MediaPages` (the film on the Lecteur and on the whole screen, turned when wide; Tag + genre + marks + stars; Marketplace; Options; Skins; .FLS play lists; the update of the Android app: banner + sheet, `WinZik::androidUpdate()`). Their rows are the sheets' (`drawSheet`: input, chipset, result, job, stepper...) on cards (`renderPage`); text fields: `$view->fields[id]`, the one typed in `$view->field`. Plus > « Interface : WinZik original » sets `phoneUi` = 'original' and switches to MainForm. Tests of these: `tests/MobileFeaturesTest.php` (fake yt-dlp, Spotify, marketplace, update). Tests: `tests/MobileTest.php` (`MobileForm` param `phone: true` = a 390 x 844 dp screen in the middle of the view; `$view->at($id, $data)` gives where to tap), pictures `var/screenshots/tests/mobile-*.png` cropped to the phone. ## Cloud (src/Cloud/): the account, the cloud playlist, the songs sent from the PC to the phone The user's WinZik account on jumphp.net (pseudo + password, no e-mail; server: the playground's "comptes d'application", `/account/...`). project.yaml `cloud_url` (env `JUMPHP_CLOUD_URL`; headless: '' unless that is set) '' = no cloud: `state()` is `off` and every interface hides it. The MP3s are never stored on the server: the PC sends them (its LAN share first, else the relay of php-wasm-network, every message AES-256-GCM with the account's key of the week from `/cloud/link`). **`$wz->cloud(): ?App\Cloud\Cloud`** (made at `attach()`, ticked by `WinZik::tick()`, stopped by `stopHelpers()`; tests: `$wz->useCloud($cloud)`): | Call | | |---|---| | `state()` | `off` (no cloud here) \| `signedOut` \| `connecting` \| `online` \| `offline` (the server does not answer: changes are queued) | | `signUp($login, $password, ?$deviceName)` | Task → `{login, recovery}`: show `recovery` ONCE ("Notez ce code : sans e-mail, c'est le seul moyen de récupérer le compte."), never keep it | | `signIn($login, $password, ?$deviceName)` | Task → `{login}`; errors are `App\Cloud\CloudError` (`getMessage()` in French, `reason` = the server's code, `status`) | | `recover($login, $code, $newPassword, ?$deviceName)` | Task → `{login, recovery}` (a NEW code; every device signed out, this one in) | | `signOut()` | this device leaves the account (the cloud playlist is forgotten here, the copied files stay) | | `login()`, `deviceId()`, `deviceName()`, `setDeviceName($n)` | default names `Ordinateur` / `Téléphone` / `Navigateur` (nothing personal) | | `devices()` / `refreshDevices()` (Task) | `[{id, name, kind: desktop\|phone\|web, online: bool, lastSeen, current: bool}]` | | `revoke($deviceId)` | Task: signs another device out | | `entries()` | the server's entries: `{id (uuid), title, artist, duration, size, sha256, addedBy, source: {type: pc, device} \| {type: youtube, videoId, query}, lyrics: bool, at}` | | `rows()` | per entry, in order: the entry's fields + `file` (local path or null) + `state`, `progress` (0..1), `text` (French, short) | | `rowState($id)` | `{state, progress, text}`; `state`: `here` \| `sending` (this PC sends it: progress) \| `copying` (coming here: progress) \| `waiting` (asked the PC) \| `offline` ("PC hors ligne – en attente") \| `youtube` (downloading it from YouTube here) \| `absent` (`fetch()` copies it) \| `error` (`text` says why; `fetch()` = Réessayer) | | `fetch($id)` | copies an entry to this device now (or again after an error) | | `putFromPc($files)` / `putFromYoutube($files)` | "Mettre dans le cloud": the PC sends the MP3 / the phone gets it from YouTube (`youtubeSource($file)`: the video WinZik downloaded it from, `var/youtube-sources.json`, else a search: artist + title of the tag, or the file's name). Returns how many go (read first: SHA-256, 8 ms a frame); their .lyr goes to the account | | `remove($ids)` | out of the cloud playlist (every device; the files stay) | | `fileState($file)` | `{cloud: bool, sending: ?float}`: the marks of a line (cloud icon, % while sent) | | `view()` / `useView('local'\|'cloud')` | which playlist `$wz->playlist` is: the user's own ("Ma playlist") or the cloud's; `localPlaylist()` = the user's one while the cloud's is shown (what `winzik.json` keeps). In the cloud view a song not here is the line `cloud:.mp3` (`Cloud::isPseudo()`, `entryOfItem()`): playing it starts its copy; Suppr / + / moving lines change the cloud playlist | | `lyricsSaved($file)` | the lyrics editor saved them: up to the account when the song is in the cloud. The account's lyrics come down to `WinZik::lyricsCachePath(localFile)` | | `playSynced()` / `setPlaySync(bool)` | « Lecture synchronisée avec mes appareils »: Synchronisé (default) or Indépendant (sends nothing, applies nothing), saved in `var/cloud/settings.json` `playSync` of this device | | `syncCount()`, `syncLabel()`, `syncText()` | the devices playing together now (this one included; 0 independent / not in the room), the tiny indicator « Synchro · 2 appareils » ('' alone), one French line (« Synchronisé · 2 appareils · Téléphone mène la lecture », « Indépendant : … ») | | `deviceLabel($id)`, `playSync` | a device's name (else its kind); the `App\Cloud\PlaySync` (null without a relay): `leader`, `seq`, `following()`, `remote` | | `autoCopy` (default: phone), `wifiOnly` (default true: a copy started by itself never uses the relay, only the LAN), `receiveDir` (Music/WinZik/Cloud; the phone: Music/WinZik), `saveSettings()`, `message` (last French notice), `sync()` (reads the playlist again now) | | Files: `var/cloud.json` {login, deviceId, deviceName, token} (0600, never logged), `var/cloud/playlist.json` {version, entries, ops} (offline copy + operations replayed by id after a 412), `var/cloud/files.json` (entry id → local path, never sent), `var/cloud/settings.json`. Room protocol (`CloudLink`, types 40 JSON / 41 chunk, all sealed): hi, want, offer {lan: [urls]}, relay, done, thanks, nack {missing|busy}, got (progress), push; the synced playback: play {seq, leader, why: act|beat|state, song: {entry, sha256, artist, title, duration, name}|null, state, pos, vol, sent}, playAsk {} (answered by `play` why state to the asker alone), sync {on: false}. `LanShare` (PC only): `JumPHP\Net\HttpServer` on 47610+, open only while a token waits, one-time 128-bit tokens (10 min), private client addresses only; `WINZIK_CLOUD_NO_LAN=1` forces the relay, `JUMPHP_CLOUD_RELAY=ws://…` another relay than the one `/cloud/link` names (a local playground). `Transfer`: `.part`, resumed (Range / offset), SHA-256 checked before the rename. Phone UI (`App\Mobile\CloudPages`, a trait of MobileView): Plus > « Mon compte (cloud) » = the page `cloud` (Connexion / Créer un compte / Code de secours chips, the recovery code on a page of its own with a warning, « Copier le code », « J'ai noté le code »; signed in: the account, Mes appareils (online dot, « Cet appareil », sign another out after a sheet), the name of this phone, Copier automatiquement, Wi-Fi seulement (what the relay means), the folder, Se déconnecter); the Playlist tab's switch « Ce téléphone | Cloud » (`cloudView`, shown only when there is a cloud) and the cloud list drawn from `rows()` (badge + second line per state, Réessayer on an error, a card with the account / PC online / « Tout copier », refresh button and pull to refresh = `sync()`); ⋮ / long press on a cloud song = sheet `cloudActions` (Lire or Copier sur le téléphone, Paroles = play + karaoke, Retirer du cloud confirmed), ⋮ of the header = `cloudMenu`; the song sheet of « Ce téléphone » has « Mettre dans le cloud » (`putFromYoutube`). Tests: `tests/MobileCloudTest.php` (pictures `mobile-cloud-*.png`). Desktop UI: `App\Form\CloudForm` (Connexion / Créer un compte / Mot de passe oublié / Mes appareils / Déconnexion), the menu of the play list (`Desktop::cloudItems()`: Playlist : Ma playlist / Playlist cloud (mon compte), Mettre dans le cloud > Le PC envoie le MP3 / Le mobile la récupère sur YouTube, Copier sur cet appareil, Retirer du cloud, Mon compte cloud…; the original phone interface has the same menu), marks in `PlaylistWindow` (cloud icon, `NN %`). Tests: `tests/CloudTest.php`, `tests/CloudUiTest.php` (fakes in `tests/Cloud/`: `FakeCloudServer` = the API in memory, `FakeRelay` = the relay in memory). **Lecture synchronisée** (`App\Cloud\PlaySync`, owned by `Cloud`, ticked in `Cloud::tick()`: `observe()` before the room's messages, `tick()` after): every device of the account in the room plays the same song, playing / paused / stopped, position and WinZik's own volume (`Player::$volume`, never the computer's). No hook in the interfaces: each frame the player is compared with the frame before (file, state, `WinZik::$seeks` counted by `seek()`, volume); a change = the user acted here -> this device leads (`seq` + 1, `leader` = it) and sends `play` why act at once (the volume slider: one every 0.15 s); the leader sends why beat every `BEAT` 2 s while it plays and another synced device is there. A follower applies through `WinZik::playIndex / play / pause / stop / seek / setVolume`, then looks again (no echo), seeks when off by more than `DRIFT` 1.5 s (`NEAR` 0.5 s for an order), the message's age = its arrival - `sent` over the smallest such difference seen from that device (the clocks of two devices differ). Order: a newer seq wins, the same seq: the same leader (beats) or the bigger device id (two that acted at once end on the same one). `WinZik::$autoChanges` (the end of a song, the resume of the last time) never takes the lead: a follower whose song ended waits `AUTO_WAIT` 5 s for the leader's next one; `cancelResume()`: a follower does not resume its song of the last time. A device that enters the room resets its seq and sends playAsk: it joins what the others play. The leader leaves: the next one to act leads. The song on a follower: the cloud entry (its file here, else its cloud line in the cloud view: playing it starts its copy, tried again each second, then it plays where the others are), else the SHA-256 among the cloud entries, else the file's name, else artist + title + length (±3 s) in the shown play list then the other one; not found: « Synchro : « … » n'est pas sur cet appareil » once, it stays as it is. Casting: the Player is the clock (silent), so the cast follows. UI: desktop menu of the play list (« Lecture synchronisée avec mes appareils » checked + the indicator « Synchro · 2 appareils » greyed), `CloudForm` (box `playSync`, a line of explanation, `syncState` = `syncText()`), the notice « Synchro : Téléphone mène la lecture » when another device takes the lead; phone: the page `cloud` (section Lecture synchronisée, toggle `cdSync`, `syncText()`), the Lecteur's top line « ☁ Synchro · 2 appareils » instead of « En lecture » (a tap: the page `cloud`). Tests: `tests/PlaySyncTest.php` (two / three WinZik on the fakes), `CloudUiTest::testTheAccountWindowAndTheMenuTurnTheSyncedPlaybackOnAndOff` (`cloud-sync-menu`, `cloud-sync-window`), `MobileCloudTest::testTheSyncedPlaybackShowsOnThePlayerAndTheAccountPageTurnsItOff` (`mobile-cloud-sync-*`). ## Cast (src/Cast/): the music and the lyrics on the TV From the PC (installed WinZik) and the phone app (sockets; not in the browser: `Cast::supported()` false, `$wz->cast()` null). Two modes: **stream** (the TV plays the song; WinZik stays the remote, its karaoke follows the TV's position) and **interface** (the TV shows WinZik's TV screen: cover, title, the karaoke lyrics line by line with the syllable lit, a translation under a line when the lyrics have one (`Lyrics::$translations`; lyrics without times: lines only, no syllable sweep), the next songs; the TV plays the song, WinZik is the remote; the TV's own remote works: OK play / pause, ◀ ▶ song, ▲ ▼ ±10 s). How it works: WinZik's `Player` keeps playing, **silent** (`Player::$silent`, set by `Cast`), so every interface (desktop, phone, original) drives and shows the cast without knowing it. `CastSession::tick()` (from `WinZik::tick()`) compares the player with the frame before and tells the TV what changed (new song = its URL on `TvServer`; play, pause, stop, a seek, the volume), then follows the TV (its position when they drift > 1.5 s, a pause / play done with the TV's remote; not within 3 s of an order of ours). The end of a song is WinZik's own (its clock kept on the TV's): the next song goes to the TV like any other. **`$wz->cast(): ?App\Cast\Cast`** (made at the first call, ticked by `WinZik::tick()`, stopped by `stopHelpers()`; tests: `$wz->useCast($cast)`): | Call | | |---|---| | `search($seconds = 6)`, `searching()`, `devices()` | the screens of the network: `CastDevice` {kind `cast` \| `dlna`, id, name, model, host, port, label()} (the last one used is listed before a search finds it) | | `connect($deviceId, 'stream' \| 'interface')` | false + `message` (French) when it cannot start. DLNA: stream only (interface falls back, says so). Cast + interface: WinZik's receiver with an App ID, else the Default Media Receiver with the lyrics as WebVTT subtitles | | `openTvPage()` | interface in any browser of the network (smart TV, console, tablet): `tvUrl()` (`http://:47620+/tv/<8 letters>`), `qrPng()` (var/cast/tv-qr-*.png) | | `disconnect()` | the TV stops (our app closed there), WinZik's sound comes back, paused | | `active()`, `state()` | `off` \| `connecting` (also: waiting for the TV page) \| `casting` \| `lost` (no answer, still trying); the TV ending it (its remote, another phone) ends the cast by itself, paused, `message` says why | | `statusText()`, `message`, `failed` | one French line for the interfaces | | `mode()`, `how()`, `device()` | `stream` \| `interface`; `dlna` \| `cast-media` \| `cast-app` \| `browser` | | `appId()`, `setAppId($id)` | WinZik's Google Cast receiver (8 hex characters, '' none), in `var/cast.json` with the last device | | `openVlcStream($video = false)`, `vlcUrl()` | the stream for VLC (`how()` `vlc` \| `vlc-video`): `http://:47650+/live/<10 letters>.mp3` (or `.ts`), the same address every time (the code is kept in `var/cast.json` `vlc`); `tvUrl()` gives it too. false + `message` without ffmpeg, or `$video` with an ffmpeg lacking libx264 / libass / mpegts (`VlcTarget::canVideo()`: the phone's) | Pieces: `Discovery` (one UDP socket: SSDP M-SEARCH MediaRenderer to 239.255.255.250:1900 + mDNS PTR `_googlecast._tcp.local` to 224.0.0.251:5353 from an ordinary port = "legacy unicast": every answer comes back by unicast, no multicast group joined, so **no Android MulticastLock** is needed; private addresses only; sent 3 times), `Ssdp` / `Mdns` (packets; the description XML read with patterns: the phone's PHP has no XML extension), `LanHttp` (non-blocking HTTP client, private addresses only), `DlnaTarget` (SOAP AVTransport + RenderingControl, DIDL-Lite with title / artist / album / albumArtURI / DLNA protocolInfo, one action at a time, GetTransportInfo + GetPositionInfo each second, `lost` after 3 silences), `CastV2` (protobuf CastMessage + 4-byte framing, by hand), `CastClient` (TLS to port 8009 stepped each frame, the device's self-signed certificate not checked; CONNECT, PING / PONG every 5 s, LAUNCH, CONNECT to the transport, media LOAD / PLAY / PAUSE / SEEK / STOP / GET_STATUS, receiver SET_VOLUME / STOP; WinZik's receiver on `urn:x-cast:net.jumphp.winzik`), `TvServer` (engine `HttpServer` on 47620+, private clients only, a 128-bit token per cast: `/c//m|i|v|l/` song (Range, DLNA headers, CORS), cover, WebVTT, lyrics JSON; `/c//s` the state the page follows (its report in the query), `/c//k?do=` its remote keys; `/tv/` the page, a 40-bit code typed on a TV), `TvTarget` (the TV page's state: song, playing, position, seek counter, volume; its reports; over HTTP or over Cast messages), `TvPage` + `assets/cast/tv.html` (the page; transports `http` (polls 3 times a second) and `cast`), `Qr` (QR code, byte mode, level L, versions 1-6). These sockets are the LAN exception to rule 4 (like `LanShare`): never in the browser. **The stream for VLC** (`VlcTarget` + `LiveServer`; PC: right click « Caster sur la TV… » > « Flux pour VLC » (+ « En vidéo… »), phone: Plus > « Caster sur la TV » > « Flux pour VLC », audio only): a web radio of what WinZik plays, opened once in VLC on the TV (Parcourir > Flux réseau). `LiveServer` (its own socket on 47650+, private clients, one secret path, 404 elsewhere): an endless HTTP/1.0 answer per player, the last ~96 KB first, ICY metadata (`icy-metaint` 16000, `StreamTitle='Artiste - Titre'`) when the player asks (`Icy-MetaData: 1`, VLC does), a player whose queue passes 8 MB dropped. `VlcTarget` (a `CastTarget`): each new song, seek or play starts a new `ffmpeg -re -ss ` (cwd var/tmp/vlc, output `live-N.mp3|ts` read as it grows, the one before terminated and reaped later, never waited for); pause stops it (VLC waits); audio = MP3 192k without ID3 / Xing (pieces join); video = 1280x720 H.264 veryfast + AAC in MPEG-TS, the cover over 0x0d1020, `subtitles=filename=live-N.ass` (`VlcTarget::ass()`: title, artist, `\kf` syllables yellow over white, translation blue italic, next line grey; times shifted by the piece's start), `-output_ts_offset` = the seconds streamed so far (VLC sees one film; a discontinuity warning at each join, it plays on). `status()` is `connecting` until a player listens, never a position (WinZik keeps the clock; VLC is a few seconds behind). Tests: `tests/VlcStreamTest.php` (a fake ffmpeg script, the real one when the PATH has it; checked by hand with VLC 3 on Linux). Since 0.10.12: **the film from the phone too** — the app's ffmpeg (tools/android/build.sh) has libass (FreeType + HarfBuzz from SDL2_ttf's external/, FriBidi, no fontconfig) and `h264_mediacodec` (the phone's hardware H.264 encoder through the NDK, `-ndk_codec 1`; `--enable-jni --enable-mediacodec`, LGPL kept: no x264) and the mpegts muxer; `VlcTarget::videoEncoder()` picks libx264 else h264_mediacodec (NV12 out). Lato (assets/fonts/ui*.ttf) is copied to tmp/vlc/fonts and given as `fontsdir` (the same font on every device; the styles say `Lato`). The cover goes RGB → NV12 → yuv420p: the Android build without asm turns RGB into planar YUV wrongly (a garbled cover; checked on the x86_64 emulator). **The screen**: two columns (cover, title, artist on the left; on the right the line before dim, the line sung, its translation, then `VlcTarget::AHEAD` = 5 lines coming, fainter and fainter); the line sung never wraps (made smaller to fit, measured by `FontMetrics`: widths read from the TTF's cmap / hmtx, size = usWinAscent + usWinDescent as libass); **the karaoke's mark** = option `karaoke` (LyricsBar::KARAOKE: ball, star, note, bar, off — the lyrics bar's own choice, also offered in CastForm / the phone page cast): ASS drawings (`\p1`) moved by `\move` from syllable to syllable in four pieces of a parabola (a bounce), the bar under the syllable. **Quality** (option `castQuality`, `Cast::setQuality()`: auto | haute 1280x720 25 i/s 2.5 Mb/s | moyenne 960x540 1.5 Mb/s | basse 640x360 20 i/s 0.8 Mb/s; the ASS stays 1280x720, libass scales): automatic watches ffmpeg's `-progress live-progress.txt` each second and, speed < 0.95 four times in a row, goes down a level at once (`qualityNote` → a notice). **Pace**: `-readrate 1` + `-readrate_initial_burst 2` + `-readrate_catchup 1.5` when this ffmpeg has them (`ffmpeg -h long`), else plain -readrate 1: VLC gets 2 s at once and a slow moment is caught up; a new player gets the last ~768 KB of film (~2 s) first. **The TV page** (`assets/cast/tv.html`, receiver.html regenerated): the line sung at 26 % of the height (the lines coming fill the screen), the mark (ball / ★ / ♪ / bar: state `karaoke` from `TvTarget::$karaoke`, set by `CastSession`) bouncing over the syllables, styles written only when they change (a TV's browser is slow). **The media server** (`MediaServer`, UPnP AV / DLNA MediaServer:1; `Cast::setMediaServer(bool)`, option `mediaServer`, on by default, started by `WinZik::tick()` outside tests / the browser; PC: the box « Visible dans VLC… » of CastForm, phone: the toggle « Visible dans VLC » of the page cast): VLC (« Réseau local » > « Universal Plug'n'Play », on Android TV Parcourir > Réseau local), TVs and Kodi list « WinZik (PC) » / « WinZik (téléphone) » (`Cast::mediaName()`: never the computer's name). Content: `0` = « ▶ WinZik en direct : Artiste - Titre » (`/dlna/live.mp3`: `openVlcStream()` + WinZik plays + 302 to the LiveServer), « ▶ WinZik en direct (vidéo karaoké) » (`live.ts`, a computer whose ffmpeg can), the container `pl` « Playlist WinZik (n) » = the songs of the play list that are files here (`pl/<16 hex of md5(path)>`, `/dlna/m/.` served with Range + DLNA headers, `/dlna/i/` covers). SSDP: NOTIFY alive at start, +1 s, then every 20 s and byebye at the end (multicast sent from an ordinary socket: no Android MulticastLock needed for players to find it), M-SEARCH heard on 1900 with the **sockets** extension (SO_REUSEADDR / SO_REUSEPORT + MCAST_JOIN_GROUP; the micro and the Android PHP have it, the Docker dev image does not: there it only announces). HTTP: engine HttpServer on 47660+, private clients, SOAP Browse (DirectChildren / Metadata, StartingIndex / RequestedCount), the other actions answered; XML by strings and patterns. UUID kept in `var/cast.json` `media`. Tests: `VlcStreamTest::testVlcFindsWinZik…` (M-SEARCH answer, description, Browse, a song with Range, the live item's redirect). Checked by hand: VLC 3.0.24 on Linux lists « WinZik (PC) », browses it and plays a song of the list (the server run in the runtime image with `--network host`). **WinZik's own Cast receiver (interface on a Chromecast / Google TV)** — what the user does once: 1. host `site/cast/receiver.html` on HTTPS (it is `TvPage::html('cast')`: regenerate it with `php tools/cast-receiver.php` after changing `assets/cast/tv.html`; `CastTest` checks they match). Published with WinZik's site, its address is the site's address + `cast/receiver.html` (open it in a browser to check it answers); 2. https://cast.google.com/publish (Google Cast SDK Developer Console), the one-time 5 US$ registration, « Add new application » > « Custom Receiver », name WinZik, Receiver Application URL = that HTTPS address: it gives the **App ID** (8 characters); 3. until the application is published there, it only starts on the devices registered in the console (« Add new device »: the serial number of the Chromecast / Google TV, then restart it after ~15 min); or « Publish » it for every device; 4. type the App ID in WinZik: PC menu « Caster sur la TV… » (App ID Google Cast), phone Plus > « Caster sur la TV ». The receiver page gets its state over the Cast connection (an HTTPS page may not fetch WinZik's http:// LAN server), the song itself by its http:// URL in an `