# Local video playback and frame-derived artwork

Covers diff row E10 (frame artwork) and the stage-5 local-video playback check for
local-library anime (`isLocalArchive = true`, source `local`).

## Playback path

Episode tap → `PlayerViewModel` (no source matches `local`, so `source = null`) →
`ProfileReaderContent.videos(null, chapter)` → `resolveLocalEpisodeVideo` (in
`LocalLibraryPaths.kt`): the chapter's virtual `archivePath` (`<folder name>/<rest>`)
is mapped through the *current* folder configuration, then the file itself (video
extension) or the first video in a folder is used → `LocalFileService.readableUrl`
(`file://<path>` natively, the OPFS media-worker URL `…/__yokan_files__/…` on web) →
`DbVideo(quality = "Downloaded")` → `MediaPlayerController.load`. A missing file yields
no stream (never the virtual path).

Fixes made while verifying: libmpv refuses to create a client unless `LC_NUMERIC` is
"C", and the JVM adopts the user's locale (e.g. `LANG=en_US.UTF-8`), so desktop playback
and frame extraction failed whenever a locale was set. `vendor/kmp-mpv` now pins
`LC_NUMERIC` to "C" before `mpv_create` (macOS/Linux; Windows unaffected). Also, libmpv percent-decodes `file://` URLs, so a local file whose
name contains `%XX` (e.g. `Episode 2 100%20.mp4`) did not open. The mpv controller now
hands mpv the raw path for `file://` URLs without headers (Android/iOS/desktop).

Verified (see the counts below):
- commonTest `LocalEpisodePlaybackTest`: real scanner over an in-memory tree → virtual
  path → playable `file://` URL; re-pointed folder follows; missing file → no stream;
  no extension runtime is created.
- desktopTest `LocalVideoDesktopTest`: real temp files (MKV and MP4 fixtures in
  `RedVideoFixtures`), real scanner and `JvmLocalFileService`, the player's resolution,
  then the real `MpvMediaPlayerController` (software render loop like the desktop
  surface, `vo=libmpv`): duration becomes known (~1 s) and the decoded red frame renders,
  including the `%20` file name. Skipped with an assumption when libmpv is neither bundled
  nor installed. Manual probe on this Mac: both the bundled media-kit libmpv and Homebrew
  libmpv load the fixtures and render the frame.
- wasmJsTest `BrowserLocalVideoTest`: real OPFS scan → media-worker URL from
  `ProfileReaderContent.videos` → a real `<video>` decode of a WebM fixture.

Not verified: on-device Android/iOS playback (no instrumented/simulator tests here);
mpv's handling of SAF `content://` URLs is unchanged by this work.

## Frame artwork

After every successful `LocalLibraryController.rescan` (scan loop untouched), a
background job on the profile scope runs `LocalVideoArtwork.generate()`:
- **Cover**: for a local anime title with no `customCoverImage`, `imageUrl` or
  `customCoverFromTracker` (scanned `cover.*` files and `metadata.json`/tracker art
  populate those first), the first episode's frame becomes `customCoverImage`. A Seasons
  parent without episodes uses its first season's first episode. Yokan has no separate
  background image: the detail header uses the cover, so this also covers background art.
- **Thumbnails**: an episode whose `thumbnailUrl` is null (no `episodes.json` preview)
  gets the cached frame's readable URL. Scans keep it (`previewUrl ?: existing`); a
  sidecar preview added later replaces it, and a cover file added later replaces the
  frame cover.
- **Never overwrites**: every write re-reads the row inside `database.batch` while holding
  the library operation lock (the same lock scans and entry management hold), so a cover
  the user picks or a preview a scan writes while a frame decodes wins.
- **Bounds**: one decode at a time, at most 12 decodes per run (later scans continue),
  frames fit 512×512 px, JPEG output over 1 MiB is dropped. Only one run at a time;
  failures are remembered for the session and not retried until restart.
- **Cache**: `<downloadRoot>/.yokan-artwork/<sha256(virtual path|size|mtime)>.jpg`
  (OPFS on web). Written as `.part` then promoted; cancellation or failure deletes the
  partial file. Later runs, a cleared and rescanned library, or a new session reuse the
  file without decoding; a changed file (size/mtime) is a new key. When the provider
  exposes no size/mtime, the key falls back to the virtual path alone.
- **Lifetime**: the job is a child of the profile session scope; retirement cancels and
  joins it before the database and file service close.

Per-platform extraction (`createPlatformVideoFrameExtractor`), frame at ~10% of duration:
- **Android**: `MediaMetadataRetriever` (`setDataSource(path)` for files, `(context, uri)`
  for SAF `content://`), `getScaledFrameAtTime` on API 27+, scaled bitmap on API 26.
  Blocking work runs on `blockingDispatcher`; a decode in progress finishes before cancel.
- **iOS**: `AVAssetImageGenerator` (`appliesPreferredTrackTransform`, `maximumSize`) inside
  `IosSecurityScopedBookmarks.withAccessAsync`, so bookmarked/open-in-place folders work.
  Cancellation calls `cancelAllCGImageGeneration`. Containers AVFoundation cannot read
  (e.g. MKV, AVI) produce no artwork.
- **Desktop**: a headless instance of the player's libmpv (`vo=libmpv`, software render
  API scales; Skia encodes JPEG). The media-kit libmpv bundled for macOS/Windows lacks
  lavfi `scale` and image encoders, so `screenshot-to-file` is not usable. Linux needs a
  system libmpv; without any libmpv, extraction returns null (no artwork).
- **Web**: a muted detached `<video>` on the same-origin media-worker URL, canvas
  `drawImage` + `toBlob('image/jpeg')`. Codecs/containers the browser cannot decode
  (MKV/HEVC in most browsers) produce no artwork. Cancellation abandons, but cannot abort,
  the browser decode; a 20 s timeout bounds it.

No preference: the defaults only fill fields that were empty; stored data and backups
keep their existing shape (`customCoverImage` bytes, `thumbnailUrl` string).

Verification passed 167 desktop checks, 84 Kotlin/Wasm browser tests and 17 Android bridge unit checks without failures/errors/skips, and all four targets compiled (shared stage 5/6 run). The three desktop libmpv checks ran
(no skips) after the locale fix. Tests: commonTest `LocalVideoArtworkTest` (cache reuse and
content keys, per-run bound, failed/empty/oversized frames, existing artwork and
non-local titles untouched, concurrent edit and running-scan win, cancellation during
decode and during write leaves no partial file, Seasons parent); desktopTest
`LocalVideoDesktopTest` (real libmpv frames from MKV/MP4 within bounds, end-to-end run);
wasmJsTest `BrowserLocalVideoTest`.
