Compare commits

..
Author SHA1 Message Date
dtourolle 83dc8c7028 feat(playback): let Rust decide what stream to play, and say so
Playing a video meant asking the server to re-encode it, always. That
decision was made nowhere and written down nowhere, so whoever needed it
re-derived it downstream — the player worked out whether it had been handed
a playlist by looking for ".m3u8" in the URL, in two places. A viewer paid
for a transcode of a file their device could have played untouched, and the
app could not tell them which it was.

One negotiation now produces one self-describing StreamSelection — direct
play, remux or transcode; over a playlist, a plain HTTP file, or a local one
— and every renderer consumes that same answer.

Measured against the development server (Jellyfin 10.11.5), 400 items
sampled for codec mix and 40 put through a real PlaybackInfo negotiation
per profile:

  Linux / WebKitGTK (h264 only, 2ch)          3/40 —  7% direct play
  Android / ExoPlayer (hevc, ac3/eac3, 6ch)  34/40 — 85% direct play

The library is ~80% hevc, which is why the two diverge so hard. The payoff
is overwhelmingly Android, where 85% of plays were starting a transcode
nobody needed. Linux stays near 7% until libmpv decodes the picture — the
h264-only profile is a WebKitGTK constraint, not a JellyTau choice.

DR-219  StreamSelection: url + tagged Transport (hls/progressive/localFile)
        + PlaybackKind (directPlay/directStream/transcode) + the negotiated
        rendition + this source's ladder + a needs_transcoding flag derived
        in Rust so the rule is answered once. Both enums are serde-tagged
        so the frontend matches a discriminant, not a substring. The paths
        that never negotiate get the same shape from Rust rather than
        assembling one — media_local_selection for a downloaded file,
        LiveStreamInfo.transport for a live channel — so there is no second
        place where a transport is decided.

DR-220  The ceiling becomes two levels: a durable device default (Settings,
        persisted) and a per-playback override the in-player picker sets.
        The picker had called itself a "this film, this connection" control
        since it was written but wrote the process-wide default, so dropping
        one awkward film to 2 Mbps silently capped every video played
        afterwards for the rest of the process, with Settings still showing
        the old value. The override is cleared whenever playback moves to a
        new item, which stops it surviving into an autoplayed next episode.
        effective_streaming_quality() is the single resolution point.

DR-221  The quality picker is filled from what this media source can offer.
        Rust marks a rung exceeds_source when its ceiling is at or above the
        source's own bitrate — such a rung is another way to spell Original
        — and the frontend does not draw those. Original is never marked; a
        source whose bitrate the server does not report marks nothing, which
        keeps every rung offered.

DR-222  Direct play and direct stream are negotiated, with two client-side
        overrides on top because the server's answer is right about the file
        and wrong about what this app will do with it: undecodable audio
        (Jellyfin 10.11.5 honours a DirectPlayProfile's container and video
        codec but ignores its audio codec, so it offers direct play for an
        E-AC-3 track the webview renders in silence) and a viewer-pinned
        audio track the file does not default to. A direct stream is a remux
        and is deliberately not counted as transcoding.

DR-223  Dropped on measurement, not deferred. A master playlist from this
        server carries exactly one EXT-X-STREAM-INF: Jellyfin builds it from
        the single rendition the request asked for rather than publishing a
        ladder. So there is no adaptation for hls.js to be preserving and
        none mpv would lose — the claim that there was, in
        playback-backend-unification.md, does not hold. Recorded rather than
        deleted because it is a measurement: a server that does publish a
        ladder would change the answer.

DR-224  Every backend consumes the same selection. The queue item carries
        the transport, so player_seek_video picks its seek strategy from the
        backend's decision instead of the last stream_url.contains(".m3u8")
        in the codebase. Items queued by a path that never negotiated carry
        None and fall back to needs_transcoding, which is exact rather than
        a guess because every transcode this app requests is HLS (DR-140).

The frontend loader decision moves to streamTransport.ts so it can be
tested: the two cases that pin it are the ones that failed against the old
implementation — a progressive stream whose URL contains ".m3u8" must not
get an HLS loader, and an HLS stream whose URL contains none must.

Also verified the URL the direct-play branch builds actually serves playable
bytes: 206, video/mp4, valid ISO-BMFF, and a mid-file range works, so
seeking a direct play works.

The spec is folded into docs/architecture/{01,02,03} and deleted, per the
rule that docs/specs holds only work that has not shipped. DR-121 leaves
read-through-media-cache.md with a pointer; that spec keeps its capture half.

Not verified: real playback on a device. Direct play changes what actually
gets played, and neither fixtures nor curl prove the WebKitGTK and ExoPlayer
paths render it.
2026-08-21 22:44:13 +02:00
53 changed files with 5358 additions and 6991 deletions
+3 -3
View File
@@ -28,7 +28,7 @@ jobs:
if: "!startsWith(github.event.head_commit.message, 'chore(release)')"
runs-on: linux/amd64
container:
image: gitea.tourolle.paris/dtourolle/jellytau-builder:2026.08.1
image: gitea.tourolle.paris/dtourolle/jellytau-builder:2026.08
steps:
- name: Checkout repository
@@ -187,7 +187,7 @@ jobs:
runs-on: linux/amd64
needs: test
container:
image: gitea.tourolle.paris/dtourolle/jellytau-builder:2026.08.1
image: gitea.tourolle.paris/dtourolle/jellytau-builder:2026.08
env:
ANDROID_HOME: /opt/android-sdk
ANDROID_SDK_ROOT: /opt/android-sdk
@@ -256,7 +256,7 @@ jobs:
name: Supply Chain
runs-on: linux/amd64
container:
image: gitea.tourolle.paris/dtourolle/jellytau-builder:2026.08.1
image: gitea.tourolle.paris/dtourolle/jellytau-builder:2026.08
steps:
- name: Checkout repository
+10 -18
View File
@@ -21,7 +21,7 @@ jobs:
name: Run Tests
runs-on: linux/amd64
container:
image: gitea.tourolle.paris/dtourolle/jellytau-builder:2026.08.1
image: gitea.tourolle.paris/dtourolle/jellytau-builder:2026.08
steps:
- name: Checkout repository
uses: actions/checkout@v4
@@ -94,7 +94,7 @@ jobs:
runs-on: linux/amd64
needs: test
container:
image: gitea.tourolle.paris/dtourolle/jellytau-builder:2026.08.1
image: gitea.tourolle.paris/dtourolle/jellytau-builder:2026.08
steps:
- name: Checkout repository
uses: actions/checkout@v4
@@ -190,15 +190,12 @@ jobs:
# Without nullglob an unmatched pattern stays literal, so test each
# candidate instead. Same POSIX-only rule as traceability-check.yml.
#
# Tauri v2 signs the .AppImage ITSELF and writes <name>.AppImage.sig
# beside it -- there is no .AppImage.tar.gz unless
# bundle.createUpdaterArtifacts is set to "v1Compatible". The updater
# downloads the same AppImage a human does and verifies that .sig, so
# both files must ship or the manifest points at a signature nobody
# can fetch.
# The .AppImage.tar.gz + .sig pair is what the updater downloads and
# verifies; the plain .AppImage is what a human downloads. Both ship.
for bundle in \
src-tauri/target/release/bundle/appimage/*.AppImage \
src-tauri/target/release/bundle/appimage/*.AppImage.sig \
src-tauri/target/release/bundle/appimage/*.AppImage.tar.gz \
src-tauri/target/release/bundle/appimage/*.AppImage.tar.gz.sig \
src-tauri/target/release/bundle/deb/*.deb \
src-tauri/target/release/bundle/rpm/*.rpm; do
[ -e "$bundle" ] || continue
@@ -235,7 +232,7 @@ jobs:
# baked into the builder image. No toolchain installs here — the image has
# cargo-xwin, clang/clang-cl, lld, llvm, nsis and the msvc target.
container:
image: gitea.tourolle.paris/dtourolle/jellytau-builder:2026.08.1
image: gitea.tourolle.paris/dtourolle/jellytau-builder:2026.08
steps:
- name: Checkout repository
uses: actions/checkout@v4
@@ -308,7 +305,7 @@ jobs:
runs-on: linux/amd64
needs: test
container:
image: gitea.tourolle.paris/dtourolle/jellytau-builder:2026.08.1
image: gitea.tourolle.paris/dtourolle/jellytau-builder:2026.08
env:
ANDROID_HOME: /opt/android-sdk
ANDROID_SDK_ROOT: /opt/android-sdk
@@ -411,7 +408,7 @@ jobs:
needs: [build-linux, build-windows, build-android]
if: startsWith(github.ref, 'refs/tags/v')
container:
image: gitea.tourolle.paris/dtourolle/jellytau-builder:2026.08.1
image: gitea.tourolle.paris/dtourolle/jellytau-builder:2026.08
steps:
- name: Checkout repository
uses: actions/checkout@v4
@@ -502,13 +499,8 @@ jobs:
APPIMAGE_URL=""
NSIS_URL=""
# Tauri v2 signs the AppImage itself; <name>.AppImage.sig sits beside
# it. Verified against a real signed build before tagging -- the
# v1-style .AppImage.tar.gz is never produced with
# createUpdaterArtifacts: true.
for f in artifacts/linux/*.AppImage; do
for f in artifacts/linux/*.AppImage.tar.gz; do
[ -e "$f" ] || continue
case "$f" in *.sig) continue;; esac
APPIMAGE_URL="${BASE}/$(basename "$f")"
[ -e "$f.sig" ] && APPIMAGE_SIG="$(cat "$f.sig")"
done
+1 -1
View File
@@ -21,7 +21,7 @@ jobs:
name: Build & publish docs to gitea-pages
runs-on: linux/amd64
container:
image: gitea.tourolle.paris/dtourolle/jellytau-builder:2026.08.1
image: gitea.tourolle.paris/dtourolle/jellytau-builder:2026.08
steps:
- name: Checkout code
+1 -1
View File
@@ -17,7 +17,7 @@ jobs:
runs-on: linux/amd64
name: Check Requirement Traces
container:
image: gitea.tourolle.paris/dtourolle/jellytau-builder:2026.08.1
image: gitea.tourolle.paris/dtourolle/jellytau-builder:2026.08
steps:
- name: Checkout repository
-20
View File
@@ -9,26 +9,6 @@ generated trace matrix lives in [docs/traceability.md](docs/traceability.md).
For how long each fixed defect had been shipping before it was found, see
[docs/defect-windows.md](docs/defect-windows.md).
## v0.10.1
A single fix, for something that had been quietly overriding a choice you made.
### 🐛 Fixes
- **Locking the screen no longer keeps playing a video's audio unless you asked
it to.** The player has a background-audio button: turn it on and the sound
carries on when you lock the screen or leave the app, turn it off and playback
stops. It stopped working when video moved to the native renderer — which plays
through a media service designed to keep going while the app is hidden — and
nothing was left to stop it. So the audio continued whether the button was on
or off, and there was no way to make it behave otherwise. The button governs it
again: with it off, locking the screen pauses the video and unlocking resumes
where you were; with it on, the audio continues as before. Music is untouched —
it keeps playing when backgrounded, as a music player should — and a video in a
picture-in-picture window keeps playing too, because the window is still on
screen. If you had already paused before locking, it stays paused.
(UR-040 → DR-224)
## v0.10.0
Two things you can see, and a great deal of work on how this project builds and
-11
View File
@@ -141,17 +141,6 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
lld \
llvm \
nsis \
# AppImage bundling. linuxdeploy embeds xdg-open into the AppImage and
# aborts the whole bundle if it is missing:
# failed to bundle project: xdg-open binary not found
# It is present on most desktop distros, which is why the AppImage built on
# a developer machine and failed here. desktop-file-utils and zsync are the
# other two linuxdeploy commonly wants (desktop-file-validate, and zsync for
# delta updates), added together so a missing one does not cost another
# image rebuild and another failed release build.
xdg-utils \
desktop-file-utils \
zsync \
&& rm -rf /var/lib/apt/lists/* \
# Ubuntu's clang package ships clang but NOT the clang-cl alias that cc-rs
# invokes for MSVC targets. clang-cl is the same binary in MSVC-compat mode,
-1
View File
@@ -41,7 +41,6 @@
- [Scoped Search Boundary](specs/scoped-search-boundary.md)
- [Scoped Search Boundary — Implementation](specs/scoped-search-boundary-implementation.md)
- [Frontend Domain Model](specs/frontend-domain-model.md)
- [Desktop Native Video](specs/desktop-native-video.md)
- [Build Provenance](specs/build-provenance.md)
# Build & Release
+9 -19
View File
@@ -675,7 +675,7 @@ source file's own bitrate, and no URL parameter afterwards can reduce it.
#### Two levels of ceiling
**Location**: `src-tauri/src/repository/online.rs` (TRACES: UR-074, UR-079 | DR-226)
**Location**: `src-tauri/src/repository/online.rs` (TRACES: UR-074, UR-079 | DR-225)
There are two, and they are not the same thing:
@@ -703,7 +703,7 @@ to constrain, or the reverse.
### Stream selection
**Location**: `src-tauri/src/repository/stream_selection.rs`,
`OnlineRepository::get_stream_selection` (TRACES: UR-070, UR-079 | DR-225, DR-227, DR-228)
`OnlineRepository::get_stream_selection` (TRACES: UR-070, UR-079 | DR-224, DR-226, DR-227)
**Rust decides *what stream*. The player decides *how to deliver it*.** That line
is the whole design. A backend with genuine adaptive selection (ExoPlayer over a
@@ -719,7 +719,7 @@ the bare URL `get_video_stream_url` used to hand out:
| `transport` | `Hls` / `Progressive` / `LocalFile` — how to fetch it |
| `playback_kind` | `DirectPlay` / `DirectStream` / `Transcode` — what the server is doing to the source |
| `rendition` | The negotiated ceiling and codecs; `None` for a direct play, which *is* the source |
| `available` | The quality ladder as it applies to this media source (DR-227) |
| `available` | The quality ladder as it applies to this media source (DR-226) |
| `needs_transcoding` | Derived from `playback_kind`, so the rule is answered once |
Both enums are serde-tagged (`{"type":"hls"}`) so the frontend matches a
@@ -770,21 +770,11 @@ a free passthrough as a server-side re-encode.
> | Android / ExoPlayer (`h264,hevc,vp8,vp9,av1,mpeg4` + `ac3,eac3`, 6ch) | 34/40 — **85%** |
>
> The library is ~80% hevc (`hevc+eac3` alone is a third of it), which is why the
> two diverge so hard.
>
> **Read that 85% as a ceiling, not a result.** It was measured with a profile
> containing `ac3,eac3`. The Android device this was later run on reports neither
> in its `MediaCodecList` — no Dolby licence, which is normal for a tablet — so
> eac3 content, about a third of the sampled library, correctly transcodes there.
> What any given device achieves depends on its own codec list, and on the
> profile being derived from the renderer at all (DR-234), which it was not when
> the figure was taken.
>
> **The payoff is still overwhelmingly Android**, because that is where a real
> decoder is already doing the work. Linux stays near 7% until libmpv decodes the
> picture — the h264-only profile is a WebKitGTK constraint, not a JellyTau
> choice, and is what `linux-native-video-spike.md` exists to remove. A reviewer
> should not expect this code to fix Linux on its own.
> two diverge so hard. **The payoff is overwhelmingly Android**, where 85% of
> plays previously burned a transcode nobody needed. Linux stays near 7% until
> libmpv decodes the picture — the h264-only profile is a WebKitGTK constraint,
> not a JellyTau choice, and is what `linux-native-video-spike.md` exists to
> remove. A reviewer should not expect this code to fix Linux on its own.
#### The quality ladder per source
@@ -801,7 +791,7 @@ they are.
#### No adaptive ladder to preserve
**TRACES: UR-079 | DR-229 (Won't Do)**
**TRACES: UR-079 | DR-228 (Won't Do)**
Mid-playback re-negotiation on throughput was scoped and dropped on measurement.
A master playlist from this server carries exactly **one** `EXT-X-STREAM-INF`:
+2 -2
View File
@@ -805,7 +805,7 @@ can safely be re-sent on resume.
## Stream Transport
**Location**: `src/lib/player/streamTransport.ts`
**TRACES**: UR-079 | DR-225 | UT-214
**TRACES**: UR-079 | DR-224 | UT-213
`videoLoaderFor(selection, capabilities)` picks the loader for the webview
`<video>` element — `hlsjs`, `nativeHls`, or `direct` — from the backend's tagged
@@ -835,7 +835,7 @@ drift apart. The background-audio handoff states the transport it is moving to
progressive mp3 out, HLS back — via `selectionAt()`, rather than leaving it to be
inferred.
The quality picker is filled from `selection.available` (DR-227): rungs the
The quality picker is filled from `selection.available` (DR-226): rungs the
backend marked `exceedsSource` are not drawn, because they produce the same bytes
as `Original`. Nothing is optimistically assigned when the viewer picks a rung —
what the menu shows comes from the selection the backend hands back, since a
+1 -1
View File
@@ -134,7 +134,7 @@ sequenceDiagram
## Video Stream Selection Flow
**TRACES: UR-070, UR-079 | DR-225, DR-227, DR-228**
**TRACES: UR-070, UR-079 | DR-224, DR-226, DR-227**
Before a video plays, Rust decides *what stream* — direct play, remux or
transcode, over which transport — and hands the player one self-describing
-24
View File
@@ -61,11 +61,6 @@ filled. Keep a couple of dated tags live and prune the rest.
The order matters — CI breaks if the workflow lands before the image exists.
A caveat learned the hard way: the *trailing* layer is only fast for `cargo
install` tools. Adding an **apt** package invalidates the packaging layer, which
sits above the `cargo-xwin`/`cargo-deny` installs, so those recompile too — a
~20 minute rebuild rather than ~2.
```bash
# 1. Edit Dockerfile.builder. Put new tools in the TRAILING layer: it exists so
# a tool change is a ~2 min rebuild instead of ~15.
@@ -108,25 +103,6 @@ transitive upgrade (bumping `tauri-plugin-log` to 2.9.0 also moved `wry`,
therefore video playback. That is a change to make deliberately, with a full
build and a playback check — not one to slip into a release.
## AppImage needs more than the Rust toolchain
`linuxdeploy` (which Tauri downloads at build time to assemble the AppImage)
shells out to distro tools that a minimal server image does not have. It aborts
the whole bundle on the first one missing:
```
failed to bundle project: xdg-open binary not found
```
The image therefore carries `xdg-utils`, `desktop-file-utils` and `zsync`. This
is a class of failure that **cannot be caught by building locally**: a developer
machine is a desktop and has all three, so the AppImage builds there and fails in
CI. It cost one release build to find.
Tauri's AppImage bundler also downloads `linuxdeploy`, `AppRun` and two plugin
scripts from GitHub during the build. That is Tauri's behaviour, not ours, but it
means an AppImage build depends on GitHub being reachable from the runner.
## Secrets
Managed with the `tea` CLI (`tea actions secrets list`) or the repo settings UI.
+10 -23
View File
@@ -89,7 +89,6 @@ For a narrative overview of the system design, see
| UR-077 | The app can update itself, or tell the user how. Somebody who installed an AppImage or ran the Windows installer had no upgrade path at all: nothing in the app ever mentioned that a newer version existed, and the release notes were the only announcement. On Linux and Windows the app checks a signed manifest, offers the new version with its notes, and installs and relaunches on request — the signature check is the point, since it is what stops a substituted download from being installed by the app itself. Android cannot do this (an app may not overwrite its own APK; that is the package installer's job) and is given the honest alternative, a link to the releases page, rather than a button that would throw | Medium | Done |
| UR-078 | JellyTau keeps a record of what it did, and can hand it over. The app forgot everything the moment it exited: the backend logged to stdout only — which a user launching from a desktop icon never sees, and which on Android is not logcat, so the Rust half was invisible on the platform carrying the hardest bugs. A crash left nothing at all. Logs are now written to a size-capped rotating file, a panic is recorded before the process dies, the frontend's messages land in the same timeline as the backend's, and Settings exports the lot as one file to attach to a bug report. Nothing is transmitted anywhere — the user attaches it themselves, which is also what keeps this from being telemetry. Access tokens and passwords never reach the file | Medium | Done |
| UR-079 | The app decides *what stream to play* and says so. Playing a video used to mean asking the server to re-encode it, always — a decision made nowhere, written down nowhere, and re-derived downstream by whoever needed it: the player worked out whether it had been handed a playlist by looking for `.m3u8` in the URL. So a viewer paid for a transcode of a file their device could have played untouched, and the app could not tell them which it was. Now one negotiation produces one self-describing answer — direct play, remux, or transcode; over a playlist, a plain HTTP file, or a local one — and every renderer consumes that same answer instead of guessing from a string. On Android, where the player decodes almost everything the library holds, this stops around 85% of plays from starting a transcode nobody needed | Medium | Done |
| UR-080 | Video on the desktop plays as itself. The picture was drawn by a webview `<video>` element, which decodes little beyond h264 — so the app told the server it could accept only h264, and the server re-encoded almost everything before sending it. That was never a statement about the machine: the same machine already runs mpv for audio, which decodes essentially the whole library. Measured against a real library, 93% of desktop playback was a transcode nobody needed, against 15% on Android where a real decoder does the work. mpv now draws the picture, the app claims what it can genuinely decode, and video is sent as it was stored wherever that is possible — sparing the server the work, the network the bitrate, and the picture a generation of re-encoding | Medium | Proposed |
| UR-074 | Video streaming can be held to a **bandwidth budget the viewer sets**, rather than spent at whatever rate the server would otherwise send. A ceiling chosen once — from the source's own bitrate down to a rung that still plays on a poor connection — governs every video the app opens, live TV included, and survives a restart, so a metered connection is not quietly drained by the next thing played. A single video can be moved to a different ceiling from the player, resuming where it was, without disturbing that default | Medium | Done |
---
@@ -134,7 +133,6 @@ External system integrations and platform-specific implementations.
| IR-030 | Scheduled full-catalog crawl of every library (`Recursive=true`, paged) feeding the local index, driven by a Rust background task and the `ConnectivityMonitor` reconnect signal rather than by the frontend | Storage | UR-065 | Implemented |
| IR-031 | Android `WindowInsets` bridge: an `OnApplyWindowInsetsListener` on the decor view reports `systemBars() | displayCutout()` in CSS pixels, pushed into the WebView as `jt-inset` CSS custom properties plus a `jellytau-insets-changed` event, and pullable via the `AndroidInsets` JS bridge | Platform | UR-066 | Done (pending device verification) |
| IR-032 | Whole-file background download of the item being played, reusing the existing resumable download worker and the Range-capable `/Videos/{id}/stream.mp4` endpoint; plus per-platform read-through caching hooks (ExoPlayer `CacheDataSource`, mpv `stream-record`) for direct-play sessions only | Storage | UR-071 | Proposed |
| IR-033 | libmpv render-API integration for video: `vo=libmpv` driving an OpenGL FBO bound by the host toolkit, with GL entry points resolved through libepoxy. Note that libepoxy exports them as *data* symbols — there is no `glFoo` function, only an `epoxy_glFoo` variable holding a lazily-resolving pointer — so `get_proc_address` must return the pointer stored **at** that symbol; returning the symbol's own address makes mpv jump into non-executable data and take SIGSEGV on the first GL call. The `epoxy` crate resolves this correctly but is unusable, its `gl_generator` dependency pulling a yanked `xml-rs` | Playback | UR-080 | Proposed |
> **Where a UR is met by a different mechanism than its IR anticipated.** Several
> integration requirements were written when libmpv was expected to be the single
@@ -418,20 +416,12 @@ Internal architecture, components, and application logic.
| DR-221 | The release path is exercised before a tag exists. Nothing in `build-and-test.yml` runs `tauri build` — only a tag does — so a whole class of breakage was invisible until release day, and two instances of it were sitting on master at once. Tauri refuses to build when a plugin's Rust crate and npm package differ by minor version, which the updater and logging work had introduced (`tauri-plugin-log 2.8.0` against `@tauri-apps/plugin-log 2.9.0`) while `cargo check`, clippy, the tests and `svelte-check` all passed; both sides are now pinned exactly rather than by caret, since a caret is what let them separate, and CI runs `tauri info` to compare them without building. The AppImage target had never once been built: linuxdeploy carries a `strip` too old to parse the `.relr.dyn` section modern toolchains emit, so bundling failed on every library — and Ubuntu 23.10+ links with `-z pack-relative-relocs` by default, so the builder image fails the same way a modern Arch host does. `NO_STRIP=true` is linuxdeploy's documented escape hatch; the cost is a larger, unstripped bundle. Both were found by building the target locally before tagging rather than by publishing a release that could not build | Tooling | - | Done |
| DR-222 | Build tooling matches the package manager the project declares. `scripts/build-android.sh` ran `npm install` on its clean-build path — in a bun project, where `packageManager` says bun and `bun.lock` is the committed lockfile. npm ignores that lockfile, re-resolves the whole tree from package.json, and writes a `package-lock.json` that `.gitignore` then hides. That is not a style preference: the JS halves of the Tauri plugins are pinned exactly against Cargo.lock because the CLI refuses to build when a plugin's crate and package differ by minor version, and a silent re-resolve is precisely how they drift apart. It survived because clean builds are rare — the shape shared by nearly every defect found preparing v0.10.0, where the code running on every commit was healthy and the code running on a release, a tag or a clean build had no guard at all. `scripts/check-tooling.sh` fails on any npm/yarn/pnpm invocation or foreign lockfile | Tooling | - | Done |
| DR-223 | The Android JavaVM and Application are published into `ndk_context` by this crate, not by a transitive dependency. Seven call sites (five in credentials.rs, two in lib.rs) read that process-global to reach JNI, and nothing here ever set it — `tao` did, three levels below anything this project names in Cargo.toml. tao 0.35.3 moved those pointers into a private struct and stopped publishing them, so the Tauri 2.11 upgrade made the first credential read abort the process on every launch: `PANIC ... android context was not initialized`. Our code had not changed; an undocumented side effect of the windowing layer had gone. The invariant is now owned here rather than assumed: `JNI_OnLoad` captures the JavaVM as the shared library loads, and the Application is resolved lazily via `ActivityThread.currentApplication()` and pinned as a global reference for the process lifetime — the Application rather than the Activity, since that is what `SecureStorage.initialize()` immediately reduces its argument to. Failure degrades to the encrypted-file credential path and is logged, rather than aborting. Found only by installing on a device: nothing in CI runs the app | Security | UR-012 | Done |
| DR-224 | Backgrounding the app obeys the background-audio toggle on every renderer. The toggle (UR-040) was built for the WebView `<video>` path, where losing visibility kills the decode: it chose between handing off to a native audio stream and letting playback stop. Native video then became the default renderer (DR-188), and on that path playback runs through ExoPlayer inside a `MediaSessionService` — a foreground media service whose purpose is to keep playing while the app is hidden. Nothing paused it and nothing in the codebase paused on background, so locking the screen kept the audio going whether or not the toggle was on: the toggle governed a handoff that no longer had a gap to bridge, and users got background playback they never asked for. The decision now lives in Rust (`player/background_policy.rs`) and both renderers obey it: a video with the toggle off pauses, with the toggle on hands off to audio, music is never paused by backgrounding, and picture-in-picture keeps playing because the window is still on screen (UR-041). It takes no renderer parameter on purpose — the split between the two paths is what produced the defect | Player | UR-040 | Done |
| DR-225 | `StreamSelection` replaces the bare URL returned for playback: URL, `Transport` (hls / progressive / localFile), `PlaybackKind` (directPlay / directStream / transcode), the negotiated `Rendition`, the ladder this source can offer, and a `needs_transcoding` flag derived in Rust so "which kinds count as transcoding" is answered once. Both enums are serde-tagged (`{"type":"hls"}`) so the frontend matches a discriminant rather than comparing text. The field that mattered most is `transport`: `VideoPlayer.svelte` chose its loader with `url.includes(".m3u8")` in two places, a domain fact reconstructed in the presentation layer — the same class of error as leaking item-type taxonomy, and one that fails silently in both directions (a progressive file served from a path containing the substring gets an HLS loader; a playlist served from one without it does not). The paths that never negotiate — a downloaded file, a live channel — get the same shape from Rust (`media_local_selection`, `LiveStreamInfo.transport`) rather than having the page assemble one, so there is no second place where a transport is decided | Playback | UR-079 | Done |
| DR-226 | The bandwidth ceiling is two-level: a durable device default (Settings, persisted, restored at startup) and a per-playback override the in-player picker sets. The picker's own documentation had called it a "this film, this connection" control since it was written, but it was implemented by writing the process-wide default — so dropping one awkward film to 2 Mbps silently capped every video played afterwards for the rest of the process, while the Settings screen still displayed the old value and nothing in the UI admitted the change. The override is cleared whenever playback moves to a new item, which is what keeps it from surviving into an autoplayed next episode where nobody would reopen the picker. `effective_streaming_quality()` is the single resolution point; every URL builder and the `PlaybackInfo` negotiation go through it, because a negotiation that authorises a direct play the URL builder then constrains (or the reverse) leaks the cap | Playback | UR-074, UR-079 | Done |
| DR-227 | The quality picker is filled from what *this* media source can offer, not from the fixed eight-rung enum. Rust marks each rung `exceeds_source` when its ceiling is at or above the source's own bitrate — such a rung produces the same bytes as `Original`, so offering it is another way to spell one choice — and the frontend simply does not draw those. `Original` is never marked (it *is* the source) and a source whose bitrate the server does not report (the sampled library has `avi` files with none) marks nothing redundant, keeping every rung offered, which is the safe direction. The picker also shows what the server is actually doing with the stream, which only became knowable once `PlaybackKind` existed. Labels and detail lines come from Rust beside the numbers they describe, so a relabelled rung cannot drift out of step with what it does | UI | UR-070, UR-079 | Done |
| DR-228 | Direct play and direct stream are negotiated rather than assumed away. `get_video_stream_url` always built an HLS transcode URL, so every video play burned server CPU even when the file would have played untouched. The decision now comes from `PlaybackInfo` under the device profile and the ceiling in force, with two client-side overrides applied on top because the server's answer is right about the *file* and wrong about what this app will do with it: undecodable audio (Jellyfin 10.11.5 honours a DirectPlayProfile's container and video codec but ignores its audio codec, so it offers direct play for an E-AC-3 track the webview renders in silence) and a viewer-pinned audio track the source file does not default to. Measured against the development server over a 400-item sample: **85% direct play on the Android profile, 7% on the Linux one** — the library is ~80% hevc and WebKitGTK can only claim h264, so the Linux figure is a property of the renderer, not of this code, and is what `linux-native-video-spike.md` exists to change. A direct *stream* is a remux and is deliberately not counted as transcoding | Playback | UR-079 | Done |
| DR-229 | Mid-playback re-negotiation on throughput was scoped and **dropped on measurement**. The premise — that hls.js gives this app real adaptive bitrate and mpv would lose it — does not hold: a master playlist from the development server carries exactly one `EXT-X-STREAM-INF`, because Jellyfin builds it from the single rendition the request asked for rather than publishing a ladder. There is no adaptation to preserve, so "adapt mid-stream" collapses into "pick well at open", which is what DR-225 and DR-226 already are. Recorded rather than deleted because the conclusion is a measurement, not an opinion, and a server that does publish a ladder would change it — the DR-224 re-negotiation path is the hook that work would build on | Playback | UR-079 | Won't Do |
| DR-230 | Every player backend consumes the same selection, proving the contract is player-agnostic rather than HTML5-shaped. The queue item carries the negotiated `transport`, so `player_seek_video` picks its seek strategy from the backend's own decision instead of the last `stream_url.contains(".m3u8")` in the codebase; items queued by a path that never negotiated (audio tracks, direct URLs) carry `None` and fall back to `needs_transcoding`, which is exact rather than a guess because every transcode this app requests is HLS (DR-140). The webview adapter's bridge carries the whole selection rather than a URL, so the component's HLS effect reads a tag instead of searching a string, and the background-audio handoff states the transport it is moving to (progressive mp3 out, HLS back) rather than leaving it to be inferred | Playback | UR-003, UR-004, UR-079 | Done |
| DR-231 | An mpv video backend that composites beneath the transparent webview, the desktop counterpart of the Android TextureView arrangement. mpv renders through its **render API** into an FBO the toolkit binds (`vo=libmpv` + `mpv_render_context_create` with `MPV_RENDER_PARAM_OPENGL_FBO`), rather than by embedding a foreign window — which is what the 2024 "not possible on Wayland at all" conclusion was about and why it does not apply. On Linux that is a `GtkOverlay` with a `GtkGLArea` as main child and Tauri's own webview reparented as the overlay child; the mpv half is shared and only the surface differs per platform. Webview transparency alone suffices — no window-level transparency is used or needed | Playback | UR-080 | Proposed |
| DR-232 | The mpv render context's lifetime is bound to the GL context it draws into: created on `realize`, freed on `unrealize`, on the same thread, with the update callback unregistered *before* the free so a callback cannot land on a freed context. This is DR-184 on Android restated — a surface outliving its player — and it is a requirement in its own right rather than a fix for a specific crash. The spike observed one SIGSEGV in a decoder thread that three targeted soaks failed to reproduce; what is not in doubt is that the spike never called `mpv_render_context_free` and never tore down on `unrealize`, so nothing defended against the GL context being recreated underneath. Removing the likeliest cause is worth doing whether or not it was the cause | Playback | UR-080 | Proposed |
| DR-233 | Frame pacing goes through mpv's update callback, with `mpv_render_context_report_swap` after each render. Recorded as a requirement because the failure mode misleads: driving the widget's frame clock every tick without reporting the swap leaves mpv with nothing to time against, which looks fine in a window and **judders at fullscreen** — reading as a compositing or GPU limit and being neither | Playback | UR-080 | Proposed |
| DR-234 | The device profile is derived from the **renderer that will decode the stream**, not from a compile-time platform constant. `video_codecs` was `#[cfg(target_os)]`, which is correct only while a build has one video renderer; once mpv and the webview element coexist it must be runtime state. This is the change that converts the measured 7% desktop direct-play rate toward the 85% the Android profile achieves on the same library, because the two differ by nothing except which component decodes. It looks like configuration and is not — it is the input that decides whether the server re-encodes, and getting it wrong fails silently, a claimed codec the renderer cannot decode being a black picture or silence (DR-148, and DR-227's audio override). The webview's narrower *audio* set stops applying to the video path once mpv decodes it, while the multichannel bound still does, since a 5.1 track direct-played into a two-channel sink is silence or inaudible dialogue | Repository | UR-080, UR-070 | In Progress |
| DR-235 | The webview video path is deleted, not merely bypassed. Staged, because a path cannot be removed while a shipped platform still needs it: Linux moves to mpv first, Windows follows, and only then do `hls.js`, `html5Adapter.ts`, `videoLoaderFor` and the `<video>` element go. The staging is the point — a Linux-only version would leave the fork alive permanently, taking video from three renderers to four and giving every seek strategy, track switch and lifecycle bug one more place to be got right. Android keeps ExoPlayer and keeps the webview as its documented opt-out; the background-audio `<audio>` path is untouched. With no HTML5 fallback left, a failed mpv init emits `backend-init-failed` and surfaces a real error rather than silently degrading to the transcode this work exists to stop paying for | Playback | UR-080 | Proposed |
| DR-236 | Hardware-decode policy is decided from what mpv reports it **selected** (`hwdec-current`), never from what it was asked for. The spike established that hardware decode works through the render API at all — the load-bearing result, since it means direct play is not bought with software decoding — but also that `auto` reached for the discrete GPU in copy-back mode on a hybrid Intel+NVIDIA laptop, the least efficient hardware path, and that `vaapi` fell back to software silently because the libva driver was absent. So zero-copy VA-API on the integrated GPU is preferred where the driver is present, `auto` is a fallback rather than the default, and a missing driver is detected and logged rather than mistaken for a compositing limit | Playback | UR-080 | Proposed |
| DR-237 | Windows reaches the same mpv path, reusing everything except the surface. The surface is genuinely different code — a native child window beneath a transparent WebView2, not GTK — but the render context, lifetime discipline, frame pacing, device profile and hwdec policy are shared, which is why none of them may be guarded on `cfg!(target_os = "linux")`. The cost is mostly build, not video: `libmpv` is currently a Linux-only dependency while Windows is cross-compiled from Linux via `x86_64-pc-windows-msvc` + `cargo-xwin`, so a Windows libmpv must reach that cross-build and its DLL must ship in the NSIS bundle, carrying the LGPL obligations DR-216 already records — dynamic linkage, licence text shipped alongside. Windows gains a native audio decoder as a side effect, which is what the long-blocked Windows audio work wants and cannot otherwise have | Playback | UR-080 | Proposed |
| DR-224 | `StreamSelection` replaces the bare URL returned for playback: URL, `Transport` (hls / progressive / localFile), `PlaybackKind` (directPlay / directStream / transcode), the negotiated `Rendition`, the ladder this source can offer, and a `needs_transcoding` flag derived in Rust so "which kinds count as transcoding" is answered once. Both enums are serde-tagged (`{"type":"hls"}`) so the frontend matches a discriminant rather than comparing text. The field that mattered most is `transport`: `VideoPlayer.svelte` chose its loader with `url.includes(".m3u8")` in two places, a domain fact reconstructed in the presentation layer — the same class of error as leaking item-type taxonomy, and one that fails silently in both directions (a progressive file served from a path containing the substring gets an HLS loader; a playlist served from one without it does not). The paths that never negotiate — a downloaded file, a live channel — get the same shape from Rust (`media_local_selection`, `LiveStreamInfo.transport`) rather than having the page assemble one, so there is no second place where a transport is decided | Playback | UR-079 | Done |
| DR-225 | The bandwidth ceiling is two-level: a durable device default (Settings, persisted, restored at startup) and a per-playback override the in-player picker sets. The picker's own documentation had called it a "this film, this connection" control since it was written, but it was implemented by writing the process-wide default — so dropping one awkward film to 2 Mbps silently capped every video played afterwards for the rest of the process, while the Settings screen still displayed the old value and nothing in the UI admitted the change. The override is cleared whenever playback moves to a new item, which is what keeps it from surviving into an autoplayed next episode where nobody would reopen the picker. `effective_streaming_quality()` is the single resolution point; every URL builder and the `PlaybackInfo` negotiation go through it, because a negotiation that authorises a direct play the URL builder then constrains (or the reverse) leaks the cap | Playback | UR-074, UR-079 | Done |
| DR-226 | The quality picker is filled from what *this* media source can offer, not from the fixed eight-rung enum. Rust marks each rung `exceeds_source` when its ceiling is at or above the source's own bitrate — such a rung produces the same bytes as `Original`, so offering it is another way to spell one choice — and the frontend simply does not draw those. `Original` is never marked (it *is* the source) and a source whose bitrate the server does not report (the sampled library has `avi` files with none) marks nothing redundant, keeping every rung offered, which is the safe direction. The picker also shows what the server is actually doing with the stream, which only became knowable once `PlaybackKind` existed. Labels and detail lines come from Rust beside the numbers they describe, so a relabelled rung cannot drift out of step with what it does | UI | UR-070, UR-079 | Done |
| DR-227 | Direct play and direct stream are negotiated rather than assumed away. `get_video_stream_url` always built an HLS transcode URL, so every video play burned server CPU even when the file would have played untouched. The decision now comes from `PlaybackInfo` under the device profile and the ceiling in force, with two client-side overrides applied on top because the server's answer is right about the *file* and wrong about what this app will do with it: undecodable audio (Jellyfin 10.11.5 honours a DirectPlayProfile's container and video codec but ignores its audio codec, so it offers direct play for an E-AC-3 track the webview renders in silence) and a viewer-pinned audio track the source file does not default to. Measured against the development server over a 400-item sample: **85% direct play on the Android profile, 7% on the Linux one** — the library is ~80% hevc and WebKitGTK can only claim h264, so the Linux figure is a property of the renderer, not of this code, and is what `linux-native-video-spike.md` exists to change. A direct *stream* is a remux and is deliberately not counted as transcoding | Playback | UR-079 | Done |
| DR-228 | Mid-playback re-negotiation on throughput was scoped and **dropped on measurement**. The premise — that hls.js gives this app real adaptive bitrate and mpv would lose it — does not hold: a master playlist from the development server carries exactly one `EXT-X-STREAM-INF`, because Jellyfin builds it from the single rendition the request asked for rather than publishing a ladder. There is no adaptation to preserve, so "adapt mid-stream" collapses into "pick well at open", which is what DR-225 and DR-226 already are. Recorded rather than deleted because the conclusion is a measurement, not an opinion, and a server that does publish a ladder would change it — the DR-224 re-negotiation path is the hook that work would build on | Playback | UR-079 | Won't Do |
| DR-229 | Every player backend consumes the same selection, proving the contract is player-agnostic rather than HTML5-shaped. The queue item carries the negotiated `transport`, so `player_seek_video` picks its seek strategy from the backend's own decision instead of the last `stream_url.contains(".m3u8")` in the codebase; items queued by a path that never negotiated (audio tracks, direct URLs) carry `None` and fall back to `needs_transcoding`, which is exact rather than a guess because every transcode this app requests is HLS (DR-140). The webview adapter's bridge carries the whole selection rather than a URL, so the component's HLS effect reads a tag instead of searching a string, and the background-audio handoff states the transport it is moving to (progressive mp3 out, HLS back) rather than leaving it to be inferred | Playback | UR-003, UR-004, UR-079 | Done |
| DR-198 | The webview runs under a real Content-Security-Policy, and the asset protocol is scoped to the one directory it still serves. `csp` was `null`, which disables CSP entirely: any script that reached the web layer — through a future `{@html}`, a dependency, or a devtools paste — would have inherited the whole IPC surface, and with it the user's session. `script-src 'self'` (Tauri injects a nonce for SvelteKit's inline bootstrap script at build time, so no `'unsafe-inline'` is needed) plus `object-src`/`frame-src 'none'` and `base-uri 'self'` is the part that is genuinely restrictive. `img-src`/`media-src`/`connect-src` cannot be: the Jellyfin origin is typed in by the user at run time and is commonly plain `http` on a LAN, so they allow `http:`/`https:` — a wide grant for *data*, but one that still bars `file:`, `filesystem:` and scripting schemes, and leaves `script-src` untouched. `style-src` keeps `'unsafe-inline'` because Svelte compiles `style="…"` attributes (including `app.html`'s `display: contents` wrapper) into markup; this is safe only while no `<style>` element survives into `index.html`, since a nonce there would make Tauri's injection outrank — and therefore void — `'unsafe-inline'`. `worker-src blob:` and `media-src blob:` are hls.js: it demuxes in a worker built from a blob and attaches MSE through `URL.createObjectURL`. `asset:` and `http://asset.localhost` are the same protocol under the two naming schemes `convertFileSrc` emits (custom scheme on Linux/macOS, `http` host on Windows/Android); `ipc:`/`http://ipc.localhost` is the invoke transport, which would otherwise be blocked by `connect-src`. A run-time CSP naming the server origin exactly was rejected: Tauri computes the header from immutable config when it serves the HTML, so it would mean rebuilding config and reloading the webview on every server change, for a policy the user can already point anywhere. The asset-protocol scope narrows from `$APPDATA/**` to `$APPDATA/thumbnails/**` — since DR-137 moved downloaded media to the loopback server, `imageCache` is the only `convertFileSrc` caller left, so the database and the encrypted-token fallback file no longer sit inside the grant | Security | UR-012, UR-071 | Done |
---
@@ -519,8 +509,7 @@ Internal architecture, components, and application logic.
| UR-076 | - | DR-209 |
| UR-077 | - | DR-217 |
| UR-078 | - | DR-218 |
| UR-079 | - | DR-225, DR-226, DR-227, DR-228, DR-229, DR-230 |
| UR-080 | IR-033 | DR-231, DR-232, DR-233, DR-234, DR-235, DR-236, DR-237 |
| UR-079 | - | DR-224, DR-225, DR-226, DR-227, DR-228, DR-229 |
---
@@ -734,11 +723,9 @@ Internal architecture, components, and application logic.
| UT-208 | The update decision: each numeric version field is compared in order, the installed version is not offered to itself, a leading `v` is tolerated because that is how the tags are written, a pre-release sorts below the release of the same number so 0.9.2-rc1 is not offered to somebody on 0.9.2, a missing patch field reads as zero rather than NaN, mobile reports link-only while desktop reports install, and absent release notes normalise to null rather than undefined | DR-217 | Done |
| UT-209 | Redaction and forwarding. Rust: every credential shape reduces to `[REDACTED]` while the host, username and neighbouring parameters survive; redaction is idempotent, leaves ordinary lines alone, does not fire on the word "token" in prose, and does not panic on multi-byte input; a server URL keeps only scheme and host and drops an embedded `user:pass@`; an unparseable level falls back to info rather than failing at startup. Frontend: info and above forward while debug does not, a message the level filter suppressed is not forwarded, a throwing forwarder neither propagates nor prevents the console write, and an `Error` renders as name and message rather than the `{}` that `JSON.stringify` produces | DR-218 | Done |
| UT-210 | Cosmetic-commit detection for release notes: a `chore(format)`, `chore(deps)` or `style` subject is skipped when deriving a range's changed files, while `fix`, `feat`, `ci`, `docs`, a bare `chore:` and `chore(release):` are kept; and the word "format" appearing later in a subject ("fix(duration): format times over 24 hours") does not make a real fix look cosmetic | DR-219 | Done |
| UT-211 | The background decision: a video with the toggle off pauses (the reported defect, where the media service kept playing regardless), a video with it on hands off to audio, music keeps playing whatever the toggle says because it has no picture to lose, picture-in-picture keeps playing in every combination since the window is still visible, and the answer does not vary by renderer | DR-224 | Done |
| UT-212 | The stream-selection contract. `Transport` and `PlaybackKind` each serialise to exactly the tag the frontend matches (`{"type":"hls"}`, `{"type":"directPlay"}`, …) and round-trip; nested `StreamSelection` fields are camelCase on the wire including `playbackKind`, `mediaSourceId` and `maxBitrate`; only `Transcode` counts as transcoding, so a direct stream does not; a local file is a direct play over a local transport with no ladder. The ladder: every rung at or above a 1.12 Mbps source is marked redundant while the three that constrain it are not, `Original` is never marked for any bitrate including zero and unknown, an unreported source bitrate keeps all eight rungs offered, a 40 Mbps source marks none, and each option carries the ladder's own label and detail | DR-224, DR-226 | Done |
| UT-213 | The direct-play negotiation, one test per branch, against `PlaybackInfo` fixtures whose shapes were all observed on a live server: a supported source direct-plays; a remuxable one direct-streams and reports itself as *not* transcoding; an unsupported codec transcodes; undecodable audio overrides the server's direct-play offer (silent picture is worse than a transcode); a pinned audio track forces a transcode; a ceiling below the source bitrate transcodes even though the codec is fine, and the ladder agrees that rung constrains it; direct play wins over direct stream when both are offered. Plus the ceiling: a per-playback override governs the stream being opened without disturbing the durable default the Settings screen shows, and dropping it returns to that default | DR-225, DR-227 | Done |
| UT-214 | The loader comes from the transport, never the URL. hls.js is attached for `hls` when available and the element's own loader when not; progressive and local files load directly; the element's `src` is emptied only when hls.js drives it. The two cases that fail against a substring check, and the reason the field exists: a `progressive` stream whose URL contains `.m3u8` is *not* given an HLS loader, and an `hls` stream whose URL contains no `.m3u8` *is*. Both failed against the pre-DR-225 implementation before the fix landed | DR-224 | Done |
| UT-215 | Waiting for the repository rather than racing it: it resolves immediately when the session is already restored, resolves when the session arrives later (the race the player page lost on mount), still rejects when there genuinely is no session, unsubscribes once settled so a later store change cannot re-settle it, and leaves no armed timer to reject an already-resolved promise | DR-013 | Done |
| UT-211 | The stream-selection contract. `Transport` and `PlaybackKind` each serialise to exactly the tag the frontend matches (`{"type":"hls"}`, `{"type":"directPlay"}`, …) and round-trip; nested `StreamSelection` fields are camelCase on the wire including `playbackKind`, `mediaSourceId` and `maxBitrate`; only `Transcode` counts as transcoding, so a direct stream does not; a local file is a direct play over a local transport with no ladder. The ladder: every rung at or above a 1.12 Mbps source is marked redundant while the three that constrain it are not, `Original` is never marked for any bitrate including zero and unknown, an unreported source bitrate keeps all eight rungs offered, a 40 Mbps source marks none, and each option carries the ladder's own label and detail | DR-224, DR-226 | Done |
| UT-212 | The direct-play negotiation, one test per branch, against `PlaybackInfo` fixtures whose shapes were all observed on a live server: a supported source direct-plays; a remuxable one direct-streams and reports itself as *not* transcoding; an unsupported codec transcodes; undecodable audio overrides the server's direct-play offer (silent picture is worse than a transcode); a pinned audio track forces a transcode; a ceiling below the source bitrate transcodes even though the codec is fine, and the ladder agrees that rung constrains it; direct play wins over direct stream when both are offered. Plus the ceiling: a per-playback override governs the stream being opened without disturbing the durable default the Settings screen shows, and dropping it returns to that default | DR-225, DR-227 | Done |
| UT-213 | The loader comes from the transport, never the URL. hls.js is attached for `hls` when available and the element's own loader when not; progressive and local files load directly; the element's `src` is emptied only when hls.js drives it. The two cases that fail against a substring check, and the reason the field exists: a `progressive` stream whose URL contains `.m3u8` is *not* given an HLS loader, and an `hls` stream whose URL contains no `.m3u8` *is*. Both failed against the pre-DR-224 implementation before the fix landed | DR-224 | Done |
### Integration Tests
+2 -3
View File
@@ -28,7 +28,7 @@ know how something *works*, read
**Next free requirement ids** (always re-check
[requirements.md](../requirements.md) before allocating): **UR-079**,
**IR-033**, **DR-232**. Three specs below suggested ids that have since been
**IR-033**, **DR-229**. Three specs below suggested ids that have since been
taken by other work; each carries a ⚠️ note at the top.
## Partially implemented
@@ -44,11 +44,10 @@ taken by other work; each carries a ⚠️ note at the top.
| Spec | Blocked on / note |
|---|---|
| [desktop-native-video.md](desktop-native-video.md) | mpv draws video on every desktop platform, then the webview `<video>` path and hls.js are deleted. Converts a measured 7% direct-play rate toward Android's 85%. Stacked on backend-owned stream selection. |
| [build-provenance.md](build-provenance.md) | `build.rs` is still bare. ⚠️ suggested id DR-093 is taken. |
| [player-facade-enforcement.md](player-facade-enforcement.md) | ~60 `commands.player*` sites still outside the facade; no lint rule. ⚠️ suggested id DR-095 is taken. |
| [windows-native-audio-backend.md](windows-native-audio-backend.md) | Blocked on the libmpv2 swap. ⚠️ suggested id IR-030 is taken. |
| [linux-native-video-spike.md](linux-native-video-spike.md) | **Spike run 2026-08-21: compositing works on Linux, X11 and Wayland.** G1-G6 green bar the Tauri `default_vbox()` half of G1. The adaptive-bitrate question it was waiting on is **answered**: the server publishes one `EXT-X-STREAM-INF`, so there is no ladder for mpv to lose (DR-229). `StreamSelection` (DR-225) is the contract to consume. |
| [linux-native-video-spike.md](linux-native-video-spike.md) | **Spike run 2026-08-21: compositing works on Linux, X11 and Wayland.** G1-G6 green bar the Tauri `default_vbox()` half of G1. The adaptive-bitrate question it was waiting on is **answered**: the server publishes one `EXT-X-STREAM-INF`, so there is no ladder for mpv to lose (DR-228). `StreamSelection` (DR-224) is the contract to consume. |
## Design authority
-423
View File
@@ -1,423 +0,0 @@
# Spec: Desktop native video — mpv renders the picture, everywhere
**Status:** Proposed
**Requirements:** UR-080 (new) → DR-231 … DR-237 (new); IR-033 (new)
**UX spec:** n/a — nothing about the player's appearance changes. What changes is
what is behind the controls.
**Supersedes / revises:** consumes and closes
[linux-native-video-spike.md](linux-native-video-spike.md), whose gates
authorised exactly this spec and nothing more. Settles finding 2 of
[playback-backend-unification.md](playback-backend-unification.md) on the
desktop; finding 3 was already settled by DR-229. Absorbs the video half of what
[windows-native-audio-backend.md](windows-native-audio-backend.md) leaves open.
**Depends on:** backend-owned stream selection (DR-225 … DR-230), the branch
below this one. mpv is a *consumer* of `StreamSelection`, never a second place to
decide what to play.
**Destination on completion:**
[05-platform-backends.md](../architecture/05-platform-backends.md) — a "Native
Video Compositing (Desktop)" section beside the existing Android one, which this
mirrors; and [01-rust-backend.md](../architecture/01-rust-backend.md) — the
device profile becomes renderer-dependent, beside the stream-selection section.
**The spike is deleted in the same commit**, its three traps and its
hardware-decode table folded in; they are the durable half.
## Summary
mpv decodes and draws video on **every desktop platform**, composited beneath the
transparent webview, exactly as Android already does with ExoPlayer. The HTML5
`<video>` path and hls.js are then **deleted**, not merely bypassed.
The user-visible change is that most video stops being re-encoded by the server
before it can be watched. The change for whoever maintains this is that video
goes from three renderers to two.
## Motivation
### The transcode is a decoder constraint, not a rendering one
Desktop video goes through an h264 HLS transcode because the picture is drawn by
a WebKitGTK `<video>` element, and that element decodes little else. The device
profile therefore claims `h264` alone. That is not a statement about the machine
— the same machine runs mpv, which decodes essentially everything in the library
— it is a statement about which widget is holding the frame.
DR-228 made the cost measurable. Over 40 items negotiated against the development
server:
| Profile | Direct play |
|---|---|
| Desktop / WebKitGTK — `h264` only, 2ch | **7%** |
| Android / ExoPlayer — `h264,hevc,vp8,vp9,av1,mpeg4` + `ac3,eac3`, 6ch | **85%** |
The sampled library is ~80% hevc. **Those rows differ only by which component
decodes.**
Moving the picture to mpv is what lets the desktop row claim what the machine
can actually do, and that — not the compositing — is the product.
> **The 85% is a ceiling, not a shipped result.** It was measured with a profile
> containing `ac3,eac3`. The Android device later used for verification reports
> neither in its `MediaCodecList` — no Dolby licence, normal for a tablet — so
> eac3 content, about a third of the sampled library, correctly transcodes there.
> Realising any of this depends on DR-234, deriving the profile from the renderer
> rather than from the platform, which is why that requirement is load-bearing
> and not tidy-up.
### One desktop video path, not two
This is why the spec covers Windows rather than stopping at Linux.
Today video has **three** renderers: ExoPlayer, the WebKitGTK `<video>` element,
and (on Android, via the opt-out) that same element again. A Linux-only version
of this work would make it four, permanently: mpv on Linux, HTML5 on Windows,
ExoPlayer on Android, plus hls.js underneath the HTML5 one. Every seek strategy,
every track switch, every quality change, every lifecycle bug would then have one
more place to be got right — and the HTML5 path would survive indefinitely
because *something* would still need it.
Finishing the job removes that: **mpv on desktop, ExoPlayer on Android**, and
`hls.js`, `html5Adapter.ts`, `videoLoaderFor` and the webview video element all
go. The maintenance win is the reason Windows is in this spec and not in a
follow-up that never gets written.
### Three blockers are gone
1. **Compositing works, including Wayland.** The spike ran all six gates; the
2024 "not possible on Wayland at all" claim is out of date when the render API
is used instead of foreign-window embedding.
2. **There is no ABR to lose.** DR-229: the server's master playlist carries one
`EXT-X-STREAM-INF`. hls.js was demuxing, not adapting.
3. **A direct-play path exists.** It did not when the spike was written. DR-228
built it; DR-230 proved the contract is player-agnostic.
And on Windows specifically, `tauri-plugin-libmpv` lists Windows as its **fully
tested** platform — the inverse of the Linux situation the spike had to
disprove. The embedding difficulty was always WebKitGTK-specific.
## Layer assignment
| Logic / responsibility | Layer | Why it belongs there |
|---|---|---|
| **Which codecs this device can decode** | **Rust** | Domain: it is the input to Jellyfin's `PlaybackInfo` negotiation. It stops being a property of the *platform* and becomes a property of *the renderer in use* — see "The structural change". |
| Which backend renders video | **Rust** | Rust already owns this (`use_html5_element` / `VideoBackend`). It stops being a `cfg!` constant and becomes a runtime fact. |
| What stream to play (direct / remux / transcode, transport, ceiling) | **Rust — already decided** | DR-225. mpv consumes `StreamSelection`. Re-deriving any of it in a new backend would be the defect DR-225 exists to remove, restated. |
| Creating the GL surface, reparenting the webview, owning the render context | **Rust (platform layer)** | Native window and GL-context lifetime. Not presentation, and not expressible above the IPC boundary at all. |
| Render-context ↔ GL-context lifetime binding | **Rust** | A correctness invariant over native resources. DR-232. |
| Frame pacing (update callback, `report_swap`) | **Rust** | Timing against the compositor; mpv's own contract. |
| Hardware-decode selection | **Rust** | A capability question about the machine, answered from what mpv reports it actually selected. |
| Z-order of controls over video, overlay chrome, letterbox colour | **Frontend / mpv** | Presentation. Controls already draw over a transparent webview on Android; mpv paints its own letterbox bars (better than the Android equivalent, which shipped DR-194 as a defect). |
| Whether the surface is visible right now | **Frontend** | `nativeVideoActive` already exists and toggles `data-native-video`. Unchanged. |
### The structural change
Everything above is routine except one row, and it carries the whole benefit.
`video_codecs` in `build_device_profile` is a **compile-time constant per
platform**:
```rust
#[cfg(all(not(target_os = "android"), target_os = "linux"))]
let (video_codecs, audio_codecs) = ("h264".to_string(), "aac,mp3,opus,…");
```
That is correct only while a build has exactly one video renderer. It must be
derived from **which renderer will decode this stream**, which is runtime state.
It looks like configuration and is not: it is the input that decides whether the
server re-encodes, it changes when Jellyfin's API or our renderer changes, and
getting it wrong fails *silently* — a claimed codec the renderer cannot decode is
a black picture or silence, which is DR-148 and DR-228's audio override already.
**Write this against "the active video renderer", never `cfg!(target_os)`.** It
is the single piece that must not be Linux-shaped, because phase 2 reuses it
unchanged.
## Design
### Backend and compositing (DR-231, IR-033)
An `MpvVideoBackend` beside the existing `MpvBackend` (audio). The mpv side —
render context, FBO, update callback, hwdec — is **shared**; only the surface
differs per platform:
| Platform | Surface | Status |
|---|---|---|
| Linux (X11 + Wayland) | `gdk_cairo_draw_from_gl()` in the default vbox's `draw` handler, over a `GdkGLContext` on its `GdkWindow`. No reparenting — see below | Render path proven by the spike; the *overlay* approach it used is rejected |
| Windows | Native HWND child beneath a transparent WebView2 | Phase 2 |
`vo=libmpv` plus `mpv_render_context_create` with `MPV_RENDER_PARAM_OPENGL_FBO`.
Webview transparency via `with_transparent(true)` — no window-level transparency;
the spike showed it is neither used nor needed.
**G1's untested half failed, and the design changed because of it.**
Reparenting Tauri's webview into a `GtkOverlay` attaches cleanly and then aborts
the process on the first click. `tauri-runtime-wry` connects a
button-press handler to the webview that walks a hard-coded path:
```rust
webview.parent() // "This one should be GtkBox"
.parent() // ...and this one the GtkWindow
.downcast::<gtk::Window>().unwrap()
```
An overlay makes that chain `webview → GtkOverlay → GtkBox`, the downcast fails,
and the panic is non-unwinding so it kills the app. Nothing in configuration
avoids it: on Linux `attach_resize_handler` is called **unconditionally** (the
Windows equivalent is guarded by `is_decorated()`), and the decoration check that
would make the handler inert runs *after* the unwrap.
**So the webview is not moved at all.** mpv draws into the *default vbox's own
`draw` handler* instead, via `gdk_cairo_draw_from_gl()` over a `GdkGLContext`
created on that widget's `GdkWindow`. GTK3 draws a container before its children,
so the webview composites on top for free — the same z-order the overlay was for,
without touching the widget tree Tauri walks.
That is strictly better than the overlay it replaces: no reparent, no extra
widget, and the arrangement cannot be broken by a Tauri upgrade that assumes its
own layout. It is also why "the surface attached successfully" is not the gate —
a click is.
Three traps from the spike, each of which cost a debugging cycle and each of
which looks like a platform limitation and is not:
1. **`LC_NUMERIC` must be reset *after* `gtk::init()`.** mpv refuses to start
under a non-C numeric locale. `mpv_backend.rs` already handles this but has no
GTK init in front of it; here `gtk::init()` applies the user's locale
afterwards and `mpv_create` returns null.
2. **libepoxy exports GL entry points as *data* symbols.** There is no `glFoo`
function — there is `epoxy_glFoo`, a variable holding a lazily-resolving
pointer. `get_proc_address` must return the pointer **stored at** that symbol;
returning the symbol's own address makes mpv jump into non-executable data and
take SIGSEGV on the first GL call. The `epoxy` crate does this correctly but is
unusable — its `gl_generator` dependency pulls a yanked `xml-rs`.
3. **Frame pacing is not optional and its symptom misleads.** See DR-233.
### Render-context lifetime (DR-232) — the crash defence
The spike's one unexplained SIGSEGV landed in a *decoder* thread with no Tauri,
GTK or GL frame in the stack, and three plausible causes failed to reproduce it
across ~13 minutes of targeted stress.
What is **not** unexplained is that the spike had no defence: it never calls
`mpv_render_context_free` and never tears down on `unrealize`, so nothing stopped
the GL context being recreated beneath the render context. That is DR-184 on
Android restated — a surface outliving its player.
Built as a requirement in its own right, not as a fix for a crash we cannot yet
reproduce:
- Render context created on `realize`, freed on `unrealize`, same thread, before
the GL context goes away.
- The update callback is unregistered **before** the context is freed, so a
callback cannot land on a freed context.
- Playback teardown and surface teardown are ordered, not racing.
If the crash recurs after this, it is a different bug and the likeliest cause is
out of the search space. If it does not, we needed this anyway.
### Frame pacing (DR-233)
Register `mpv_render_context_set_update_callback`; redraw only when it reports a
frame ready; call `mpv_render_context_report_swap` after each render.
Recorded because the failure mode is a trap: driving `queue_render()` off the
frame clock every tick without reporting the swap leaves mpv nothing to time
against. It looks fine in a window and **judders at fullscreen**, which reads as
a compositing or GPU limit and is neither.
### Renderer-dependent device profile (DR-234)
`build_device_profile` takes the active video renderer and derives the codec
lists from it:
| Renderer | Video codecs | Audio (video direct play) | Channels |
|---|---|---|---|
| mpv (desktop native) | `h264,hevc,vp8,vp9,av1,mpeg4` | platform list incl. `ac3,eac3` where the sink can voice it | from the audio route |
| WebKitGTK `<video>` | `h264` | webview-decodable set only | 2 |
| ExoPlayer (Android) | unchanged | unchanged | unchanged |
The existing `video_audio_codecs()` narrowing exists because *the webview decodes
a narrower audio set than the platform*. With mpv decoding, that no longer
applies to the video path — but the multichannel bound still does, since a 5.1
track direct-played into a 2-channel sink is silence or inaudible dialogue. Both
constraints stay, sourced from the renderer rather than assumed.
**This is what converts the 7% figure upward** (toward, not necessarily to, the 85% ceiling — see the caveat above), and it is also the change most able to break
playback silently — so it lands after compositing is proven, covered by the
DR-228 override tests.
### Deleting the webview video path (DR-235)
`get_player_status` stops reporting `use_html5_element: true` on desktop;
`supports_native_video` becomes true there.
Deletion is staged, because a path cannot be removed while a shipped platform
still needs it:
| Phase | Linux | Windows | HTML5 video path |
|---|---|---|---|
| 1 | mpv | HTML5 | alive — Windows needs it |
| 2 | mpv | mpv | alive but unreached |
| 3 | mpv | mpv | **deleted**, with hls.js |
Phase 3 is a real phase with its own acceptance criterion, not a "later". The
whole maintenance argument for including Windows collapses if the fork survives.
Android keeps ExoPlayer and keeps the webview as its documented opt-out; the
`<audio>` element and the background-audio handoff are untouched throughout.
**What happens when mpv fails to initialise.** With no HTML5 path there is no
silent fallback, and inventing one resurrects what we deleted. The
graceful-backend-init principle applies as written: fall back to the no-op
backend, emit `backend-init-failed`, and surface a real error rather than a black
rectangle. An honest failure beats a hidden downgrade to the transcode we are
trying to stop paying for.
### Hardware decode (DR-236)
The spike established the load-bearing fact: **hardware decode works through the
render API** (`hwdec-current` reported `nvdec-copy` on the discrete GPU), so the
direct-play prize is not traded for software decoding.
Policy is decided from what mpv reports it *selected*, never from what it was
asked for:
- Prefer zero-copy VA-API on the integrated GPU where the driver is present.
- `auto` reached for the discrete GPU in **copy-back** mode on a hybrid
Intel+NVIDIA laptop — the least efficient hardware path — so `auto` is a
fallback, not the default.
- `vaapi` silently fell back to software on the spike box because `vainfo` was
absent. A missing driver must be detected and logged, not mistaken for a
compositing limit.
- Log `hwdec-current` at start-up; knowing what was actually chosen is the whole
diagnostic value.
### Windows: what phase 2 actually costs (DR-237)
Not hidden, because it is the part most likely to be underestimated:
- **The surface is different code.** WebView2 in an HWND, not GTK. A transparent
WebView2 over a native child window is a solved arrangement, but DR-231's
Linux surface does not transfer. Everything else does.
- **libmpv is currently a Linux-only dependency**, and Windows is
**cross-compiled from Linux** via `x86_64-pc-windows-msvc` + `cargo-xwin`. Phase
2 must source a Windows libmpv (DLL + import library) into that cross-build and
ship the DLL in the NSIS bundle.
- **LGPL obligations follow the DLL.** DR-216 already records them for Linux:
keep the linkage dynamic, ship libmpv's licence text with any bundle carrying
it. The Windows bundle inherits both.
- **`bun run test:rust` and CI must still build.** Per the CI rule, any tool this
needs goes into the builder image and is pushed — never installed at job time.
Windows also gains a native *audio* decoder as a side effect, which is what
[windows-native-audio-backend.md](windows-native-audio-backend.md) wants and
cannot currently have. If that spec lands first, phase 2 inherits its build work
and shrinks to the surface.
## Out of scope
- **Android.** Unchanged in every respect.
- **macOS.** Not a shipped target. If it becomes one it joins phase 2's shape.
- **Audio backends.** mpv already plays audio on Linux; this adds a video
renderer beside it. Windows audio is its own spec.
- **HDR, tone mapping, multi-window.** Not exercised by the spike at all.
- **Re-deciding what stream to play.** DR-225 owns that. If this spec finds
itself choosing a URL, something has gone wrong.
## Acceptance criteria
**Phase 1 — Linux**
- [ ] Tauri's own webview reparents into the overlay (the untested half of G1),
on X11 **and** Wayland.
- [ ] Video plays, seeks and switches audio track in mpv, with the Svelte
controls composited over it and alpha blending intact.
- [ ] The render context is freed on `unrealize` and the update callback
unregistered before the free; a test demonstrates the ordering.
- [ ] A direct-play negotiation returns `DirectPlay` for an hevc source that
today returns `Transcode`, and it plays.
- [ ] Direct-play rate over the same 40-item sample rises from 7% toward the
Android figure. **Record the number.**
- [ ] mpv init failure emits `backend-init-failed` and surfaces an error rather
than falling back to a transcode.
- [ ] `hwdec-current` is logged and is not copy-back where zero-copy is available.
- [ ] A soak covering seek, track switch and fullscreen runs clean for an agreed
duration. **The spike's SIGSEGV is why this is a criterion.**
**Phase 2 — Windows**
- [ ] libmpv links in the `cargo-xwin` cross-build; the DLL and its licence ship
in the NSIS bundle; any new tool lives in the builder image, not in a CI step.
- [ ] Video plays composited under a transparent WebView2.
- [ ] The device profile, lifetime and hwdec code are **reused, not
reimplemented** — a reviewer confirms no `cfg!(target_os = "linux")` guards
them.
**Phase 3 — deletion**
- [ ] `use_html5_element` is false on every desktop platform.
- [ ] `hls.js` is gone from `package.json`; `html5Adapter.ts`, `videoLoaderFor`
and the `<video>` element are deleted; Android's opt-out and the
background-audio `<audio>` path still work.
**Throughout**
- [ ] `bun run check`, `bun run test`, `bun run format:check`, `bun run lint` pass.
- [ ] `cargo fmt` clean, `cargo clippy -D warnings` clean, `bun run test:rust` passes.
- [ ] `bun run check:boundary` passes, and a reviewer confirms no stream decision
was reconstructed in the new backend.
- [ ] `bindings.ts` regenerated from Rust.
- [ ] `bun run traces:validate` passes; coverage stays ≥ the CI ratchet.
- [ ] The spike and this spec are folded into
[05-platform-backends.md](../architecture/05-platform-backends.md) and both
deleted in the same commit.
## Testing
- **Rust, pure:** the device profile per renderer — mpv claims hevc, the webview
does not, the multichannel bound survives both. The DR-234 table as a
table-driven test.
- **Rust, pure:** `PlaybackInfo` fixtures that transcode under the webview
profile and direct-play under the mpv profile — the direct-play conversion as a unit
test, not only as a measurement.
- **Rust:** teardown ordering — callback unregistered before context freed, freed
before GL context destroyed. Structure it so the ordering is assertable without
a live GL context.
- **Frontend:** no desktop path selects an HTML5 video adapter. After phase 3,
the adapter does not exist and the test goes with it.
- **Manual / soak:** the criterion above. The spike's automated fullscreen and
resize soaks are reusable and already written.
## TRACES
| Piece | Tag |
|---|---|
| mpv video backend + compositing | `UR-080 \| DR-231, IR-033` |
| Render-context lifetime binding | `UR-080 \| DR-232` |
| Frame pacing | `UR-080 \| DR-233` |
| Renderer-dependent device profile | `UR-080, UR-070 \| DR-234` |
| Webview video path removed | `UR-080 \| DR-235` |
| Hardware-decode policy | `UR-080 \| DR-236` |
| Windows surface + cross-build | `UR-080 \| DR-237` |
## Notes for the implementer
- **Read the spike before writing a line.** Its three traps and its
hardware-decode table are the most valuable things in this directory, and each
cost a debugging cycle to find.
- **mpv consumes `StreamSelection`; it does not decide.** The transport is on the
queue item (DR-230). If you are parsing a URL, stop.
- **Guard nothing on `cfg!(target_os = "linux")` that phase 2 will need.** That is
the one avoidable mistake here.
- The Android backend is the reference for the *shape* of this — transparent
webview over a native surface at index 0. Read `05-platform-backends.md`'s
Android section for what shipped and what its defects were (DR-184 surface
lifetime, DR-194 letterbox).
- Do not call sync/blocking APIs from mpv event callbacks that can re-enter the
player or hold a lock. The existing deadlock gotchas apply.
- A parallel Claude session may be active in this repo — `git diff` before
"repairing" unexpected changes.
- This branch is stacked on backend-owned stream selection. Rebase when that
merges rather than merging master into it.
+18 -52
View File
@@ -2,10 +2,7 @@
**Status:** **Run 2026-08-21 — compositing works; G5 carries an open crash.**
The compositing claim it set out to test is falsified on Linux. See "Result".
This file stays open until the implementation spec exists. **ABR is resolved**
the playlist carries one `EXT-X-STREAM-INF`, so finding 3 is false and there is
no adaptation for mpv to lose. The remaining blocker is the unexplained SIGSEGV
under G5, which is a lifetime problem, not a compositing one.
This file stays open until the implementation spec exists; ABR is unresolved.
**Requirements:** none allocated. This spike produces a decision record, not
product code — same shape as
[playback-backend-unification.md](playback-backend-unification.md), which is
@@ -261,10 +258,10 @@ anything.
Tauri's existing webview into an overlay. Low risk — the same widgets, one
extra reparent — but unproven, and it is the only place Tauri-specific
behaviour could still bite.
- **ABR — resolved. Finding 3's premise is false.** Finding 3 said mpv would
regress streaming quality because "the webview path already has real ABR via
hls.js". Three pieces of evidence in this repo suggested that is **not true of
the URLs we actually build**:
- 🔴 **ABR — finding 3's premise is in doubt.** Finding 3 says mpv would regress
streaming quality because "the webview path already has real ABR via hls.js".
Three pieces of evidence in this repo suggest that is **not true of the URLs we
actually build**:
1. `get_video_stream_url` (`repository/online.rs`) requests a *single*
rendition — one `VideoBitrate`, one `MaxStreamingBitrate`, one `MaxHeight`.
@@ -279,52 +276,21 @@ anything.
audio-track switch)". Manual selection by stream re-open is what you build
when there is no adaptation, and mpv can do the same thing.
**The decisive test has now been run** (2026-08-21, against the development
server, Jellyfin 10.11.5):
**The decisive test has not been run** and needs a live server plus an API key:
count `#EXT-X-STREAM-INF` lines in a real `master.m3u8`. One line means there
is no ABR to lose and this blocker disappears. More than one means finding 3
stands and the work below applies.
```
curl -s ".../Videos/<itemId>/master.m3u8?…&TranscodingProtocol=hls&…" \
| grep -c EXT-X-STREAM-INF
1
```
If ABR does turn out to be real, it belongs in **Rust**, not in mpv, and there
are three designs in increasing cost: pick the variant at open; re-open at a
new bitrate on sustained throughput drops (this is the quality-switch path the
app already has, so it is nearly free); or run a local proxy serving mpv a
synthesized single-variant playlist while swapping renditions underneath. The
middle option is almost certainly sufficient.
**One line.** The playlist carries a single `EXT-X-STREAM-INF` plus an
`EXT-X-IMAGE-STREAM-INF` trickplay entry, which is not a rendition. Jellyfin
builds the master playlist from the rendition the request asked for; it does
not publish a ladder. So **there is no ABR to lose, and this blocker is
closed** — hls.js is serving as an HLS demuxer, exactly as (2) above supposed,
and mpv gives up nothing by replacing it.
Recorded as DR-229 (Won't Do) rather than deleted, because it is a
measurement: a server that *does* publish a ladder would change the answer, and
the re-negotiation path is the hook that work would build on.
**The direct-play path now exists.** It did not when this spike was written —
every video play went through the HLS transcode endpoint. Backend-owned stream
selection (DR-225 … DR-230) built it: Rust negotiates direct play / direct
stream / transcode and hands every backend one `StreamSelection` carrying the
URL, the transport and the chosen rendition. **That is the contract this
implementation consumes** — mpv is a consumer of a decision already made, not a
place to re-derive it.
It also sizes the prize precisely. Measured over the same server, 40 items
through a real negotiation per profile:
| Profile | Direct play |
|---|---|
| Linux / WebKitGTK — `h264` only, 2ch | **7%** |
| Android / ExoPlayer — `h264,hevc,vp8,vp9,av1,mpeg4` + `ac3,eac3`, 6ch | **85%** |
**The 85% is a ceiling, not a shipped result** — it was measured with a
profile containing `ac3,eac3`, which the Android device later used for
verification does not support.
The library sampled is ~80% hevc. Linux sits at 7% **solely because the
WebKitGTK profile can only claim h264** — not because of anything about the
server or the negotiation. mpv decodes hevc, so widening the Linux device
profile once mpv renders the picture is what converts that 7% toward the
Android figure. That conversion is the actual product of this work; the
compositing proven above is the mechanism that permits it.
Either way the **direct-play path still does not exist** — every video play
currently goes through the HLS transcode endpoint. Building it is the real
project; the compositing work proven above is the smaller half.
- 🔴 **One unexplained SIGSEGV.** A ~180s
run died in a *decoder* thread (libavcodec -> `av_log` -> libmpv's log handler
-> libc). No Tauri, wry, WebKitGTK, GTK or GL frame appears anywhere in the
+2 -2
View File
@@ -9,7 +9,7 @@ DR-124, DR-125.
**DR-121 has shipped and left this spec.** The player quality selector, the
per-playback bitrate ceiling, and the backend-owned stream decision it needed
were built as *backend-owned stream selection* (DR-225 … DR-228) and are
were built as *backend-owned stream selection* (DR-224 … DR-227) and are
described in
[01-rust-backend.md](../architecture/01-rust-backend.md#stream-selection) and
[03-data-flow.md](../architecture/03-data-flow.md#video-stream-selection-flow).
@@ -77,7 +77,7 @@ frontend stores the user's *choice*; Rust decides what that choice resolves to.
### DR-121 — moved out (shipped)
Bitrate selection in the player shipped as DR-225 … DR-228; see
Bitrate selection in the player shipped as DR-224 … DR-227; see
[01-rust-backend.md](../architecture/01-rust-backend.md#stream-selection).
The one constraint here that the capture work still has to respect: a quality
+4927 -5190
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "jellytau",
"version": "0.10.1",
"version": "0.10.0",
"description": "A cross-platform Jellyfin client built with Tauri, SvelteKit and Rust.",
"author": "Duncan Tourolle <duncan@tourolle.paris>",
"license": "MIT",
+1 -1
View File
@@ -8,7 +8,7 @@
# tarball/VCS URL and drop the local-copy prepare() step.
pkgname=jellytau
pkgver=0.10.1
pkgver=0.10.0
pkgrel=1
pkgdesc="A cross-platform Jellyfin client"
arch=('x86_64')
+5 -7
View File
@@ -2181,7 +2181,7 @@ dependencies = [
[[package]]
name = "jellytau"
version = "0.10.1"
version = "0.10.0"
dependencies = [
"aes-gcm",
"async-trait",
@@ -2191,13 +2191,11 @@ dependencies = [
"env_logger",
"futures-util",
"getrandom 0.2.16",
"gtk",
"hostname",
"jni 0.21.1",
"keyring",
"libc",
"libmpv",
"libmpv-sys",
"log",
"ndk-context",
"rand 0.8.7",
@@ -3287,9 +3285,9 @@ checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"
[[package]]
name = "plist"
version = "1.10.0"
version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da1d65da6dd5d1e44199ac0f58712d241c0f439f80adea8924d832384087f85"
checksum = "740ebea15c5d1428f910cd1a5f52cebf8d25006245ed8ade92702f4943d91e07"
dependencies = [
"base64 0.22.1",
"indexmap 2.12.1",
@@ -3465,9 +3463,9 @@ dependencies = [
[[package]]
name = "quick-xml"
version = "0.41.0"
version = "0.38.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1"
checksum = "b66c2058c55a409d601666cffe35f04333cf1013010882cec174a7467cd4e21c"
dependencies = [
"memchr",
]
+1 -20
View File
@@ -1,6 +1,6 @@
[package]
name = "jellytau"
version = "0.10.1"
version = "0.10.0"
description = "A cross-platform Jellyfin client"
authors = ["Duncan Tourolle <duncan@tourolle.paris>"]
license = "MIT"
@@ -114,25 +114,6 @@ libc = "0.2"
# than changing it. To take upstream fixes, bump this deliberately.
libmpv = { git = "https://github.com/ParadoxSpiral/libmpv-rs.git", rev = "3e6c389b716f52a595cc5e8e3fa1f96cb76b3de7" }
# The raw FFI bindings behind `libmpv`, pinned to the *same* revision so the two
# can never describe different ABIs.
#
# Needed because the safe crate's `render` module is an empty stub at this
# revision — the render API (`mpv_render_context_create` and friends) exists only
# in the sys bindings, which do carry all of it. `Mpv::ctx` is public, so the
# render context can be built over the same handle the safe wrapper drives. This
# is what makes native video reachable *without* first completing the libmpv2
# migration, which the spike's use of `libmpv2-sys` had implied was a
# prerequisite.
#
# TRACES: UR-080 | DR-230, IR-033
libmpv-sys = { git = "https://github.com/ParadoxSpiral/libmpv-rs.git", rev = "3e6c389b716f52a595cc5e8e3fa1f96cb76b3de7" }
# Same major as the one Tauri/wry already resolve, so `gtk_window()` and
# `default_vbox()` hand back types this crate can name rather than a second,
# incompatible GTK.
gtk = "0.18"
# JNI for Android ExoPlayer integration
[target.'cfg(target_os = "android")'.dependencies]
jni = "0.21"
@@ -164,33 +164,17 @@ class MainActivity : TauriActivity() {
*/
override fun onStop() {
super.onStop()
// Fires unconditionally now. It used to be gated on backgroundAudioEnabled,
// which meant the frontend was never told the app had gone away unless the
// toggle was already on -- so with the toggle OFF nothing could react, and
// on the native path ExoPlayer's media service simply kept playing. That is
// the whole defect: the toggle appeared to do nothing because the only
// notification of backgrounding was itself gated on the toggle (DR-224).
//
// What to DO about it is decided in Rust (player_background_action); this
// only reports the two facts the activity alone knows.
val inPip = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
isInPictureInPictureMode
} else {
false
if (backgroundAudioEnabled) {
dispatchWebEvent("jellytau-background")
}
dispatchWebEvent(
"jellytau-background",
"{\"backgroundAudioArmed\": $backgroundAudioEnabled, \"inPictureInPicture\": $inPip}"
)
}
/** The app is visible again — tell the frontend to resume WebView video. */
override fun onStart() {
super.onStart()
// Also unconditional, for the same reason: a video paused on background has
// to be told it is visible again, and that pause happens with the toggle
// OFF. The frontend ignores this when it has nothing to restore.
dispatchWebEvent("jellytau-foreground")
if (backgroundAudioEnabled) {
dispatchWebEvent("jellytau-foreground")
}
}
/**
@@ -198,14 +182,14 @@ class MainActivity : TauriActivity() {
* evaluateJavascript pattern already used to unmute video elements. Posted to
* the WebView thread; safe no-op if the WebView isn't found yet.
*/
private fun dispatchWebEvent(name: String, detailJson: String = "null") {
private fun dispatchWebEvent(name: String) {
val webView = mediaWebView ?: run {
android.util.Log.w("MainActivity", "dispatchWebEvent('$name'): no WebView")
return
}
webView.post {
webView.evaluateJavascript(
"window.dispatchEvent(new CustomEvent('$name', { detail: $detailJson }));",
"window.dispatchEvent(new CustomEvent('$name'));",
null
)
android.util.Log.d("MainActivity", "Dispatched web event: $name")
+17 -92
View File
@@ -187,7 +187,7 @@ pub struct PlayItemRequest {
/// caller falls back to `needs_transcoding` — every transcode this app
/// requests is HLS (DR-140), so that fallback is exact rather than a guess.
///
/// TRACES: UR-003, UR-004, UR-079 | DR-225, DR-230
/// TRACES: UR-003, UR-004, UR-079 | DR-224, DR-229
#[serde(default)]
pub transport: Option<crate::repository::Transport>,
@@ -331,7 +331,7 @@ pub enum VideoSeekResponse {
ReloadStream {
/// What to open, and how — transport included, so the frontend picks
/// its loader from a tagged enum rather than by searching the URL for
/// `.m3u8`. TRACES: UR-079 | DR-225
/// `.m3u8`. TRACES: UR-079 | DR-224
selection: StreamSelection,
/// `seek_offset` carries the position to RESUME AT, not a base to add to
/// the element's clock. The reloaded stream starts at the item's zero —
@@ -353,7 +353,7 @@ pub enum AudioTrackSwitchResponse {
},
/// HTML5 needs to reload stream with new audio track
ReloadStream {
/// What to open, and how. TRACES: UR-079 | DR-225
/// What to open, and how. TRACES: UR-079 | DR-224
selection: StreamSelection,
/// Current position to resume from
position: f64,
@@ -369,21 +369,8 @@ pub enum AudioTrackSwitchResponse {
#[derive(specta::Type, Debug, Serialize)]
#[serde(tag = "strategy", rename_all = "camelCase")]
pub enum StreamQualityResponse {
/// The native backend was reloaded here; nothing left for the frontend to
/// *do* — but it still has to be told what was negotiated.
///
/// This carried only a position at first, which left the picker on Android
/// pinned to the rendition of the *first* stream: the UI derives the rung in
/// force from the selection it holds, nothing replaced that selection on the
/// native path, and a transcode always has a rendition — so the fallback
/// that would have used the requested value was never reached. The stream
/// changed and the menu did not.
///
/// TRACES: UR-074, UR-079 | DR-226, DR-227
/// The native backend was reloaded here; nothing left for the frontend.
Native {
/// What the backend actually opened, so the UI reflects it rather than
/// assuming the request was honoured verbatim.
selection: StreamSelection,
/// Position playback resumed at.
position: f64,
},
@@ -392,7 +379,7 @@ pub enum StreamQualityResponse {
/// What to open, and how — already negotiated against the requested
/// ceiling. Carries `available` too, so a picker opened after a quality
/// change still describes the source correctly.
/// TRACES: UR-070, UR-079 | DR-225, DR-227
/// TRACES: UR-070, UR-079 | DR-224, DR-226
selection: StreamSelection,
/// Position to resume from.
position: f64,
@@ -449,7 +436,7 @@ pub(super) async fn create_media_item(
source,
video_codec: Some(req.video_codec),
needs_transcoding: req.needs_transcoding,
// The caller's negotiated transport, when it had one. TRACES: UR-079 | DR-230
// The caller's negotiated transport, when it had one. TRACES: UR-079 | DR-229
transport: req.transport,
video_width: None, // Not available from video-only request
video_height: None, // Not available from video-only request
@@ -702,9 +689,9 @@ pub async fn player_play_item(
// A ceiling chosen from the in-player picker belongs to the playback it was
// chosen for. Starting a different item returns to the device default —
// otherwise "2 Mbps, just for this one film" quietly governs the rest of the
// session, which is the defect DR-226 exists to close.
// session, which is the defect DR-225 exists to close.
//
// TRACES: UR-074, UR-079 | DR-226
// TRACES: UR-074, UR-079 | DR-225
crate::repository::online::clear_playback_quality_override();
// Create media item, checking for local download first
@@ -886,46 +873,6 @@ pub async fn player_enter_background_audio(
/// untouched — if it fired while backgrounded, playback is already stopped and
/// this simply reports the last position.
///
/// What playback should do now that the app is no longer visible.
///
/// The caller supplies only what it alone knows -- whether the per-player
/// toggle is armed, and whether Android put the window into picture-in-picture.
/// Everything else (what is playing, and therefore whether there is a picture to
/// lose) is read here, because it is domain state.
///
/// The rule itself is in `player::background_policy`; this command is the wire.
/// Returning `KeepPlaying` for an empty queue is deliberate: with nothing
/// playing there is nothing to pause, and an error would make the frontend
/// handle a case that is not a failure.
///
/// TRACES: UR-040, UR-041 | DR-225 | UT-212
#[tauri::command]
#[specta::specta]
pub async fn player_background_action(
player: State<'_, PlayerStateWrapper>,
background_audio_armed: bool,
in_picture_in_picture: bool,
) -> Result<crate::player::background_policy::BackgroundAction, String> {
use crate::player::background_policy::{background_action, is_video_media, BackgroundAction};
let is_video = {
let controller = player.0.lock().await;
let queue_arc = controller.queue();
let queue = queue_arc.lock().map_err(|e| e.to_string())?;
match queue.current() {
Some(item) => is_video_media(item.media_type),
None => return Ok(BackgroundAction::KeepPlaying),
}
};
let action = background_action(is_video, background_audio_armed, in_picture_in_picture);
info!(
"[player_background_action] video={} armed={} pip={} -> {:?}",
is_video, background_audio_armed, in_picture_in_picture, action
);
Ok(action)
}
/// TRACES: UR-040 | DR-052 | UT-061, IT-013
#[tauri::command]
#[specta::specta]
@@ -984,9 +931,9 @@ pub async fn player_play_queue(
// A ceiling chosen from the in-player picker belongs to the playback it was
// chosen for. Starting a different item returns to the device default —
// otherwise "2 Mbps, just for this one film" quietly governs the rest of the
// session, which is the defect DR-226 exists to close.
// session, which is the defect DR-225 exists to close.
//
// TRACES: UR-074, UR-079 | DR-226
// TRACES: UR-074, UR-079 | DR-225
crate::repository::online::clear_playback_quality_override();
// Handle shuffle first
@@ -1461,7 +1408,7 @@ pub async fn player_seek_video(
// queued without one fall back to `needs_transcoding`, which is exact:
// every transcode this app requests is HLS (DR-140).
//
// TRACES: UR-004, UR-079 | DR-225, DR-230
// TRACES: UR-004, UR-079 | DR-224, DR-229
let is_hls = match transport {
Some(crate::repository::Transport::Hls) => true,
Some(crate::repository::Transport::Progressive)
@@ -1676,7 +1623,7 @@ pub async fn player_switch_audio_track(
/// belongs to Settings, and `player_set_video_settings` is the one that writes
/// to the database.
///
/// TRACES: UR-074, UR-079 | DR-162, DR-226
/// TRACES: UR-074, UR-079 | DR-162, DR-225
#[tauri::command]
#[specta::specta]
// Two of the eight arguments are Tauri `State<'_, _>` injections, not caller
@@ -1728,29 +1675,10 @@ pub async fn player_set_stream_quality(
// builder then never gets to constrain).
//
// Deliberately the *override*, not the device default: see the doc above.
// TRACES: UR-074, UR-079 | DR-226
// TRACES: UR-074, UR-079 | DR-225
crate::repository::online::set_playback_quality_override(quality);
// Where to resume. `current_position` is the *element's* clock, which only
// the webview path has — on a native backend there is no `<video>` and the
// frontend correctly sends null, so trusting it there resumed every quality
// change from zero.
//
// The player is the authority on position (it is the authority on all
// playback state); asking the DOM for it and falling back to 0 inverted
// that. Fall back to what the controller reports instead.
//
// TRACES: UR-005, UR-074 | DR-226
// The guard is bound inside the arm's block so it is dropped before the
// reload below takes the same lock. This codebase has been bitten by a
// MutexGuard living longer than the expression that produced it.
let position = match current_position {
Some(p) => p,
None => {
let controller = player.0.lock().await;
controller.absolute_position()
}
};
let position = current_position.unwrap_or(0.0);
let selection = repository
.get_stream_selection(
&jellyfin_item_id,
@@ -1795,10 +1723,7 @@ pub async fn player_set_stream_quality(
}
}
Ok(StreamQualityResponse::Native {
selection,
position,
})
Ok(StreamQualityResponse::Native { position })
}
/// Set the active audio track on a native backend directly.
@@ -2451,9 +2376,9 @@ pub async fn player_play_tracks(
// A ceiling chosen from the in-player picker belongs to the playback it was
// chosen for. Starting a different item returns to the device default —
// otherwise "2 Mbps, just for this one film" quietly governs the rest of the
// session, which is the defect DR-226 exists to close.
// session, which is the defect DR-225 exists to close.
//
// TRACES: UR-074, UR-079 | DR-226
// TRACES: UR-074, UR-079 | DR-225
crate::repository::online::clear_playback_quality_override();
info!(
+1 -1
View File
@@ -618,7 +618,7 @@ pub async fn repository_get_video_stream_url(
/// position on an HLS playlist is copied onto every segment URI and the server
/// rejects each with `400` (DR-181). Callers resume by seeking after load.
///
/// TRACES: UR-070, UR-079 | DR-225, DR-227, DR-228 | UT-213
/// TRACES: UR-070, UR-079 | DR-224, DR-226, DR-227 | UT-212
#[tauri::command]
#[specta::specta]
pub async fn repository_get_stream_selection(
+1 -1
View File
@@ -114,7 +114,7 @@ pub fn media_local_url(
/// to consume rather than two, and so no caller has to infer a transport from a
/// loopback URL.
///
/// TRACES: UR-071, UR-079 | DR-225
/// TRACES: UR-071, UR-079 | DR-224
#[tauri::command]
#[specta::specta]
pub fn media_local_selection(
-52
View File
@@ -122,7 +122,6 @@ use commands::{
player_add_to_queue,
player_add_track_by_id,
player_add_tracks_by_ids,
player_background_action,
player_cancel_autoplay_countdown,
player_cancel_sleep_timer,
// Jellyfin reporting commands
@@ -745,7 +744,6 @@ fn specta_builder() -> Builder<tauri::Wry> {
.commands(tauri_specta::collect_commands![
// Player commands
player_play_item,
player_background_action,
player_enter_background_audio,
player_exit_background_audio,
player_play_queue,
@@ -1210,56 +1208,6 @@ pub fn run() {
// listened for on the frontend via the generated bindings.
builder.mount_events(app);
// Native video surface: put a GL area under Tauri's webview so mpv
// can draw beneath the controls (UR-080 / DR-231).
//
// 🔴 OFF BY DEFAULT — the naive reparent crashes the app on the
// first click. `tauri-runtime-wry`'s undecorated-resizing handler
// walks a hard-coded two-hop path on every button press in the
// webview:
//
// webview.parent() // "This one should be GtkBox"
// .parent() // ...and this one the GtkWindow
// .downcast::<gtk::Window>().unwrap()
//
// Wrapping the webview in a GtkOverlay makes that chain
// webview → GtkOverlay → GtkBox, the downcast fails, and because the
// panic is non-unwinding it aborts the process. The decoration check
// that would otherwise make this handler inert runs *after* the
// unwrap, so no window configuration avoids it.
//
// This is the "only place Tauri-specific behaviour could still bite"
// that the spike named as the untested half of G1. It bites. The
// surface attaches perfectly and then dies on interaction, so
// "attached successfully" in the log is not the gate — a click is.
//
// Kept behind an env var rather than deleted so the next attempt has
// something to iterate on: JELLYTAU_NATIVE_VIDEO=1 bun run tauri dev
//
// TRACES: UR-080 | DR-231
#[cfg(target_os = "linux")]
if std::env::var("JELLYTAU_NATIVE_VIDEO").as_deref() == Ok("1") {
use tauri::Manager;
log::warn!(
"[INIT] JELLYTAU_NATIVE_VIDEO=1 — attaching the experimental \
video surface; the app will abort on the first click until \
the widget-tree shape is solved (DR-231)"
);
if let Some(window) = app.get_webview_window("main") {
match window.default_vbox() {
Ok(vbox) => match crate::player::video_surface::attach(&vbox) {
Ok(_surface) => {
info!("[INIT] Native video surface attached");
}
Err(e) => log::warn!("[INIT] Native video surface unavailable: {e}"),
},
Err(e) => {
log::warn!("[INIT] No GTK vbox for the main window: {e}")
}
}
}
}
// In-app update, desktop only.
//
// Registered here rather than in the builder chain above because a
-155
View File
@@ -1,155 +0,0 @@
//! What playback should do when the app stops being visible.
//!
//! TRACES: UR-040 | DR-224 | UT-211
//!
//! # The defect this exists for
//!
//! The per-player background-audio toggle (UR-040) was built for the WebView
//! `<video>` path, where backgrounding the app kills the decode: the toggle
//! decided whether to *hand off* to a native audio stream or let playback die.
//!
//! Native video then became the default renderer (DR-188). On that path playback
//! runs through ExoPlayer inside a `MediaSessionService` — a foreground media
//! service whose entire purpose is to keep playing when the app is not visible.
//! Nothing stops it, and nothing in the codebase paused playback on background.
//!
//! So locking the screen kept the audio playing **whether or not the toggle was
//! on**. The toggle governed a handoff that no longer had anything to hand off
//! *from*: there was no gap in playback to bridge. A user who had never touched
//! it got background audio anyway, which is the bug as reported.
//!
//! # Why the decision lives in Rust
//!
//! It depends on what the item *is* (a video keeps its picture; music has none
//! to lose) and on a user setting — domain questions, not presentation ones, and
//! the answer must be identical for both renderers. The frontend and the Android
//! activity carry it out; neither decides it. Putting the rule in either would
//! have reproduced exactly the split that caused this: two renderers, two
//! behaviours, one toggle that only reached one of them.
use crate::player::media::MediaType;
/// What the player should do when the app is backgrounded.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub enum BackgroundAction {
/// Carry on. Music, and video the user explicitly asked to keep hearing
/// while it is in a picture-in-picture window.
KeepPlaying,
/// Swap the video stream for an audio-only one and keep playing.
HandOffToAudio,
/// Stop making sound. The user did not ask for background playback.
Pause,
}
/// Decide what backgrounding should do.
///
/// * `is_video` — whether the current item has a picture to lose. Music is
/// never paused by backgrounding; that is what a music player is for.
/// * `background_audio_armed` — the per-player toggle (UR-040).
/// * `in_picture_in_picture` — the app is not "gone", it is in a floating
/// window and still visible. Pausing here would break PiP (UR-041).
///
/// TRACES: UR-040, UR-041 | DR-224 | UT-211
pub fn background_action(
is_video: bool,
background_audio_armed: bool,
in_picture_in_picture: bool,
) -> BackgroundAction {
// PiP first: the window is still on screen, so this is not backgrounding in
// any sense the user would recognise.
if in_picture_in_picture {
return BackgroundAction::KeepPlaying;
}
// Music has no picture to lose; a music player that stopped when the screen
// locked would be broken in an obvious way.
if !is_video {
return BackgroundAction::KeepPlaying;
}
if background_audio_armed {
BackgroundAction::HandOffToAudio
} else {
BackgroundAction::Pause
}
}
/// Whether a media type has a picture that backgrounding would throw away.
///
/// TRACES: UR-040 | DR-224
pub fn is_video_media(media_type: MediaType) -> bool {
matches!(media_type, MediaType::Video)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn video_without_the_toggle_pauses() {
// THE REPORTED BUG. Native video runs in a foreground media service that
// keeps playing when the app is hidden, and nothing paused it -- so
// locking the screen gave background audio to a user who never asked
// for it.
assert_eq!(
background_action(true, false, false),
BackgroundAction::Pause
);
}
#[test]
fn video_with_the_toggle_hands_off_to_audio() {
assert_eq!(
background_action(true, true, false),
BackgroundAction::HandOffToAudio
);
}
#[test]
fn music_always_keeps_playing() {
// Backgrounding a music player and having it stop would be absurd. The
// toggle is irrelevant here: there is no picture to give up.
assert_eq!(
background_action(false, false, false),
BackgroundAction::KeepPlaying
);
assert_eq!(
background_action(false, true, false),
BackgroundAction::KeepPlaying
);
}
#[test]
fn picture_in_picture_is_not_backgrounding() {
// The video is in a floating window and still on screen. Pausing would
// break PiP (UR-041), which is a separate feature reached through
// onUserLeaveHint rather than onStop.
assert_eq!(
background_action(true, false, true),
BackgroundAction::KeepPlaying
);
assert_eq!(
background_action(true, true, true),
BackgroundAction::KeepPlaying
);
}
#[test]
fn the_rule_does_not_depend_on_the_renderer() {
// There is deliberately no renderer parameter. The WebView path and the
// native path must answer identically -- the split between them is what
// produced the defect, because the toggle only ever reached one.
for armed in [true, false] {
let once = background_action(true, armed, false);
let again = background_action(true, armed, false);
assert_eq!(once, again);
}
}
#[test]
fn only_video_counts_as_having_a_picture() {
assert!(is_video_media(MediaType::Video));
assert!(!is_video_media(MediaType::Audio));
}
}
+1 -1
View File
@@ -123,7 +123,7 @@ pub struct MediaItem {
/// caller falls back to `needs_transcoding` — every transcode this app
/// requests is HLS (DR-140), so that fallback is exact rather than a guess.
///
/// TRACES: UR-003, UR-004, UR-079 | DR-225, DR-230
/// TRACES: UR-003, UR-004, UR-079 | DR-224, DR-229
#[serde(default)]
pub transport: Option<crate::repository::Transport>,
-9
View File
@@ -4,7 +4,6 @@
// DR-001, DR-004, DR-005, DR-009, DR-028, DR-029, DR-047
pub mod autoplay;
pub mod backend;
pub mod background_policy;
pub mod events;
pub mod media;
pub mod queue;
@@ -24,14 +23,6 @@ pub mod android;
#[cfg(target_os = "linux")]
pub mod mpv_backend;
/// The native video surface mpv renders into (UR-080 / DR-231).
///
/// Linux-gated for now because the surface is GTK. Everything *around* it — the
/// render context, its lifetime, frame pacing, the device profile — is
/// deliberately not, so Windows reuses it behind its own surface.
#[cfg(target_os = "linux")]
pub mod video_surface;
// Platforms with no native audio backend (e.g. Windows) render audio-only
// playback through a webview <audio> element, mirroring how all video renders.
#[cfg(not(any(target_os = "linux", target_os = "android")))]
-232
View File
@@ -1,232 +0,0 @@
//! The native video surface: a GL area beneath Tauri's own webview.
//!
//! This is the desktop counterpart of the Android arrangement — a native
//! renderer at the bottom of the stack with a transparent webview drawn over it,
//! so the Svelte controls composite on top of moving video.
//!
//! The spike that authorised this built its *own* `GtkOverlay` and proved mpv
//! renders into it on X11 and Wayland. What it could not prove is the step this
//! module exists for: taking the overlay Tauri already built and reparenting the
//! real webview into it. Same widgets, one extra move, and the only place
//! Tauri-specific behaviour can still bite — which is why it is gate one.
//!
//! TRACES: UR-080 | DR-231, IR-033
use gtk::prelude::*;
use log::{info, warn};
/// The widgets that make up the video surface, kept together because their
/// lifetimes are bound: the render context (added next) is created when the GL
/// area realizes and must be freed before it unrealizes — DR-232.
pub struct VideoSurface {
/// The GL area mpv renders into. Main child of the overlay, so it sits
/// *under* everything else.
#[allow(dead_code)]
gl_area: gtk::GLArea,
/// The overlay holding the GL area and the webview.
#[allow(dead_code)]
overlay: gtk::Overlay,
}
impl VideoSurface {
// Consumed by the render context, which binds to the GL area on `realize`
// and is freed on `unrealize` (DR-232). Held here from the moment the
// surface exists so that binding has something to attach to.
#[allow(dead_code)]
/// The GL area, for the render context to bind to.
pub fn gl_area(&self) -> &gtk::GLArea {
&self.gl_area
}
#[allow(dead_code)]
/// The overlay, for teardown.
pub fn overlay(&self) -> &gtk::Overlay {
&self.overlay
}
}
/// Why a surface could not be attached.
///
/// One variant, because there is exactly one way this fails that is not already
/// reported by Tauri itself: the window exists and has a vbox, but the vbox is
/// not shaped the way Tauri has always shaped it.
#[derive(Debug)]
pub enum SurfaceError {
/// The vbox held no webview to reparent — Tauri's layout has changed.
NoWebviewChild,
}
impl std::fmt::Display for SurfaceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SurfaceError::NoWebviewChild => write!(
f,
"Tauri's default vbox had no child to reparent — its window layout has changed"
),
}
}
}
impl std::error::Error for SurfaceError {}
/// Build the overlay and move Tauri's webview on top of it.
///
/// Tauri's Linux window is an `ApplicationWindow` holding a single vertical
/// `gtk::Box` (`default_vbox`), with the webview packed into it. This takes that
/// webview out, puts a `GtkGLArea` in its place inside a `GtkOverlay`, and adds
/// the webview back as the *overlay* child so it draws above.
///
/// **Must run on the GTK main thread.** Every GTK call here is main-thread-only,
/// and the caller reaches it via `run_on_main_thread`.
///
/// Ordering matters: the GL area is added as the overlay's main child *before*
/// the webview goes back, because `GtkOverlay` treats its first `add` as the
/// bottom of the stack. Adding them the other way round yields a webview with
/// video painted over it — an easy mistake with an obvious symptom.
///
/// TRACES: UR-080 | DR-231
pub fn attach(vbox: &gtk::Box) -> Result<VideoSurface, SurfaceError> {
// Tauri packs exactly one child (the webview) into the default vbox. Take it
// rather than assume its type: wry's widget is an implementation detail, and
// all this needs is "whatever Tauri put here".
let children = vbox.children();
let webview = children
.into_iter()
.next()
.ok_or(SurfaceError::NoWebviewChild)?;
let gl_area = gtk::GLArea::new();
// No depth buffer: mpv draws a flat picture into an FBO and nothing here is
// 3D. Asking for one costs memory on every resize for nothing.
gl_area.set_has_depth_buffer(false);
gl_area.set_has_stencil_buffer(false);
// Fill the overlay rather than centring at intrinsic size — the same defect
// `videoFitClass` had to fix on the webview side, where `max-w-full` only
// ever shrank and a 480p source rendered as a small box on a black screen.
gl_area.set_hexpand(true);
gl_area.set_vexpand(true);
let overlay = gtk::Overlay::new();
// Reparent. `remove` drops the container's reference, so hold one across the
// move or the widget is destroyed between the two calls.
let webview_ref = webview.clone();
vbox.remove(&webview);
overlay.add(&gl_area); // main child — the bottom of the stack
overlay.add_overlay(&webview_ref); // drawn above the video
// The webview must keep receiving input: it *is* the UI. `GtkOverlay` passes
// events to overlay children by default, so pass-through stays off — setting
// it would send clicks to the GL area, which has no controls on it.
overlay.set_overlay_pass_through(&webview_ref, false);
vbox.pack_start(&overlay, true, true, 0);
overlay.show_all();
info!("[VideoSurface] GL area attached beneath Tauri's webview");
Ok(VideoSurface { gl_area, overlay })
}
/// Put Tauri's window back the way it was found.
///
/// Not merely tidiness: the webview outlives the video surface, so if the
/// surface is torn down without returning the webview to the vbox the UI
/// disappears while the app keeps running. Mirrors [`attach`] exactly.
///
/// TRACES: UR-080 | DR-231, DR-232
// Called by the render-context teardown, which lands with DR-232. Written now,
// beside `attach`, because a reparent whose inverse is written later is a
// reparent whose inverse is written wrong.
#[allow(dead_code)]
pub fn detach(vbox: &gtk::Box, surface: &VideoSurface) {
let children = surface.overlay.children();
for child in children {
// Everything except the GL area came from the vbox and goes back to it.
if child.downcast_ref::<gtk::GLArea>().is_some() {
continue;
}
surface.overlay.remove(&child);
vbox.pack_start(&child, true, true, 0);
}
vbox.remove(&surface.overlay);
vbox.show_all();
warn!("[VideoSurface] detached; webview returned to Tauri's vbox");
}
#[cfg(test)]
mod tests {
//! These exercise GTK widget wiring, so they need a display and are ignored
//! by default — CI has no X11 or Wayland session. Run locally with
//! `cargo test -- --ignored video_surface`.
use super::*;
/// The stacking order is the whole point, and getting it backwards produces
/// video painted over the controls rather than under them.
///
/// TRACES: UR-080 | DR-231
#[test]
#[ignore = "requires a display"]
fn test_gl_area_is_below_the_reparented_webview() {
if gtk::init().is_err() {
return;
}
let vbox = gtk::Box::new(gtk::Orientation::Vertical, 0);
// Stand in for the webview; `attach` deliberately does not care what it is.
let stand_in = gtk::DrawingArea::new();
vbox.pack_start(&stand_in, true, true, 0);
let surface = attach(&vbox).expect("attaches");
let children = surface.overlay().children();
// GtkOverlay lists its main child first.
assert!(
children[0].downcast_ref::<gtk::GLArea>().is_some(),
"the GL area must be the overlay's main child, i.e. underneath"
);
assert!(
children.len() > 1,
"the reparented widget must still be present"
);
}
/// A surface that tears down without returning the webview leaves a running
/// app with no UI.
///
/// TRACES: UR-080 | DR-231, DR-232
#[test]
#[ignore = "requires a display"]
fn test_detach_returns_the_webview_to_the_vbox() {
if gtk::init().is_err() {
return;
}
let vbox = gtk::Box::new(gtk::Orientation::Vertical, 0);
let stand_in = gtk::DrawingArea::new();
vbox.pack_start(&stand_in, true, true, 0);
let surface = attach(&vbox).expect("attaches");
detach(&vbox, &surface);
let children = vbox.children();
assert_eq!(children.len(), 1, "exactly the original child comes back");
assert!(
children[0].downcast_ref::<gtk::DrawingArea>().is_some(),
"and it is the webview stand-in, not the overlay"
);
}
/// A vbox Tauri has not populated is a changed assumption, not a panic.
///
/// TRACES: UR-080 | DR-231
#[test]
#[ignore = "requires a display"]
fn test_an_empty_vbox_is_an_error_not_a_panic() {
if gtk::init().is_err() {
return;
}
let vbox = gtk::Box::new(gtk::Orientation::Vertical, 0);
assert!(matches!(attach(&vbox), Err(SurfaceError::NoWebviewChild)));
}
}
+1 -90
View File
@@ -212,16 +212,6 @@ pub fn subtitle_supports_external_delivery(codec: Option<&str>) -> bool {
///
/// TRACES: UR-004 | DR-148 | UT-142
pub fn video_audio_codecs(detected: &str) -> String {
// Where the video renderer decodes the audio itself (ExoPlayer), the
// platform list *is* the answer and narrowing it to the webview's throws
// away codecs the device genuinely plays — dts, on the tablet this was
// found on. TRACES: UR-004, UR-080 | DR-234
#[cfg(target_os = "android")]
{
return detected.to_string();
}
#[allow(unreachable_code)]
let kept: Vec<&str> = detected
.split(',')
.filter_map(|codec| {
@@ -243,83 +233,6 @@ pub fn video_audio_codecs(detected: &str) -> String {
}
}
/// What the renderer that will actually decode video on this platform can play.
///
/// Returns `(video_codecs, audio_codecs)` as Jellyfin-style comma lists.
///
/// This exists because the answer was previously derived in four places and
/// hardcoded in a fifth, each of them assuming the *webview* was decoding:
/// the device profile, the transcoding targets, the direct-play audio
/// narrowing, the client-side audio override, and `get_video_stream_url`'s
/// `VideoCodec`. On Android the decoder is ExoPlayer, so every one of those was
/// wrong there — the observed cost being an hevc source re-encoded to h264
/// because its *audio* was eac3, and dts forced to transcode though the device
/// decodes it.
///
/// One source, so the copies cannot disagree again.
///
/// TRACES: UR-004, UR-080 | DR-234
pub fn renderer_codecs() -> (String, String) {
#[cfg(target_os = "android")]
{
// ExoPlayer, and the device itself answers via MediaCodecList.
crate::player::get_detected_codecs()
.map(|(video, audio, _channels)| (video, audio))
.unwrap_or_else(|| {
log::warn!(
"[DeviceProfile] Codec detection not complete, using conservative defaults"
);
("h264,hevc".to_string(), "aac,mp3".to_string())
})
}
// Linux desktop draws video in the WebKitGTK HTML5 <video> element, which
// cannot reliably decode HEVC/AV1/VP9. Claim only what it decodes, so
// Jellyfin transcodes the rest to h264 HLS. (Audio-only playback goes
// through MPV and is unaffected — that is a different renderer and a
// different profile.)
//
// When mpv draws the picture here this stops being a platform constant and
// becomes a question about the active renderer — which is the whole point of
// returning it from a function rather than a `cfg` block.
#[cfg(all(not(target_os = "android"), target_os = "linux"))]
{
("h264".to_string(), "aac,mp3,opus,vorbis,flac".to_string())
}
#[cfg(all(not(target_os = "android"), not(target_os = "linux")))]
{
(
"h264,hevc,vp8,vp9,av1,mpeg4".to_string(),
"aac,mp3,opus,vorbis,flac".to_string(),
)
}
}
/// Whether the renderer that decodes *video* on this platform can also decode
/// this audio codec.
///
/// On a webview platform this is the webview's narrow list, because the element
/// decodes both halves. On Android it is the device's own list: ExoPlayer plays
/// the audio, so judging it against the webview's capabilities transcodes files
/// that would have played.
///
/// TRACES: UR-004, UR-080 | DR-234
pub fn renderer_can_decode_audio(codec: &str) -> bool {
let codec = codec.trim();
#[cfg(target_os = "android")]
{
let (_video, audio) = renderer_codecs();
return audio
.split(',')
.any(|supported| supported.trim().eq_ignore_ascii_case(codec));
}
#[cfg(not(target_os = "android"))]
{
webview_can_decode_audio(codec)
}
}
/// Whether the webview `<video>` element can decode this audio codec.
///
/// TRACES: UR-004 | DR-149 | UT-148
@@ -347,9 +260,7 @@ pub fn webview_can_decode_audio(codec: &str) -> bool {
/// TRACES: UR-004 | DR-149 | UT-148
pub fn audio_forces_transcode(streams: &[(Option<&str>, bool)]) -> bool {
match served_audio_codec(streams) {
// The renderer that will decode it, not always the webview — see
// `renderer_can_decode_audio`. TRACES: UR-004, UR-080 | DR-234
Some(codec) => !renderer_can_decode_audio(codec),
Some(codec) => !webview_can_decode_audio(codec),
// No audio at all, or a codec the server did not name: leave it alone.
None => false,
}
+2 -2
View File
@@ -97,13 +97,13 @@ impl HybridRepository {
.await
}
/// Decide what stream to play and describe it fully — the DR-225 contract.
/// Decide what stream to play and describe it fully — the DR-224 contract.
///
/// Online-only for the same reason as `get_video_stream_url`: an offline
/// item is a file on disk, and the caller builds
/// [`StreamSelection::local_file`] for it rather than negotiating anything.
///
/// TRACES: UR-070, UR-079 | DR-225, DR-227, DR-228
/// TRACES: UR-070, UR-079 | DR-224, DR-226, DR-227
pub async fn get_stream_selection(
&self,
item_id: &str,
+1 -1
View File
@@ -5,7 +5,7 @@ pub mod hybrid;
pub mod offline;
pub mod online;
pub mod series_progress;
/// Backend-owned stream selection (UR-079 / DR-225).
/// Backend-owned stream selection (UR-079 / DR-224).
pub mod stream_selection;
pub mod types;
+53 -69
View File
@@ -43,7 +43,7 @@ static STREAMING_QUALITY: RwLock<StreamingQuality> = RwLock::new(StreamingQualit
/// Cleared when a new item starts playing, so the override cannot outlive the
/// playback it was chosen for. The device default is never touched by it.
///
/// TRACES: UR-074, UR-079 | DR-226
/// TRACES: UR-074, UR-079 | DR-225
static PLAYBACK_QUALITY_OVERRIDE: RwLock<Option<StreamingQuality>> = RwLock::new(None);
/// Set the durable device default. Applies to every stream opened afterwards
@@ -71,7 +71,7 @@ pub fn streaming_quality() -> StreamingQuality {
/// Move *this playback* to a different ceiling without disturbing the default.
///
/// TRACES: UR-074, UR-079 | DR-226
/// TRACES: UR-074, UR-079 | DR-225
pub fn set_playback_quality_override(quality: StreamingQuality) {
*PLAYBACK_QUALITY_OVERRIDE.write_safe() = Some(quality);
}
@@ -82,14 +82,14 @@ pub fn set_playback_quality_override(quality: StreamingQuality) {
/// not silently govern the next one. Autoplaying the next episode is the case
/// that matters — nobody re-opens the picker between episodes.
///
/// TRACES: UR-074, UR-079 | DR-226
/// TRACES: UR-074, UR-079 | DR-225
pub fn clear_playback_quality_override() {
*PLAYBACK_QUALITY_OVERRIDE.write_safe() = None;
}
/// The per-playback override, if one is in force.
///
/// TRACES: UR-074, UR-079 | DR-226
/// TRACES: UR-074, UR-079 | DR-225
pub fn playback_quality_override() -> Option<StreamingQuality> {
*PLAYBACK_QUALITY_OVERRIDE.read_safe()
}
@@ -102,7 +102,7 @@ pub fn playback_quality_override() -> Option<StreamingQuality> {
/// the old static: a negotiation that authorises a direct play the URL builder
/// then constrains (or vice versa) leaks the cap.
///
/// TRACES: UR-074, UR-079 | DR-226
/// TRACES: UR-074, UR-079 | DR-225
pub fn effective_streaming_quality() -> StreamingQuality {
playback_quality_override().unwrap_or_else(streaming_quality)
}
@@ -611,29 +611,13 @@ impl OnlineRepository {
self.stop_transcode(&previous).await;
}
// Build an HLS transcode URL, naming every codec this renderer can
// decode rather than only h264.
//
// The list is what lets the server *copy* the video stream instead of
// re-encoding it. Hardcoding h264 meant an hevc source whose only
// problem was its audio — eac3 on a device with no Dolby licence — got
// its picture fully re-encoded to satisfy a sound problem. The server's
// own transcoding URL already did the right thing (`h264,hevc`, video
// copied, `TranscodeReasons=AudioCodecNotSupported`); this builder,
// which takes over whenever a quality change or track switch re-opens
// the stream, quietly did not — so changing quality turned a cheap
// remux into a full transcode.
//
// On the webview path this still resolves to "h264" alone, so nothing
// changes there.
//
// TRACES: UR-004, UR-080 | DR-234
let (renderer_video_codecs, _) = super::device_profile::renderer_codecs();
// Build an HLS transcode URL. VideoCodec lists h264 first so the server
// transcodes HEVC/10-bit/unsupported sources to h264 the WebView can decode.
let mut params = vec![
("api_key", self.access_token.clone()),
("DeviceId", DEVICE_ID.to_string()),
("PlaySessionId", play_session_id),
("VideoCodec", renderer_video_codecs),
("VideoCodec", "h264".to_string()),
("AudioCodec", "aac".to_string()),
("MaxStreamingBitrate", max_bitrate.to_string()),
("VideoBitrate", video_bitrate.to_string()),
@@ -775,21 +759,40 @@ impl OnlineRepository {
///
/// The single place the device profile is built and POSTed. Both
/// [`get_playback_info`](Self::get_playback_info) (the legacy shape) and
/// `get_stream_selection` (the DR-225 contract) go through it, so the
/// `get_stream_selection` (the DR-224 contract) go through it, so the
/// profile they negotiate under cannot drift apart.
///
/// TRACES: UR-004, UR-074, UR-079 | DR-225, DR-228
/// TRACES: UR-004, UR-074, UR-079 | DR-224, DR-227
async fn negotiate_playback(
&self,
item_id: &str,
) -> Result<(NegotiatedSource, String), RepoError> {
let endpoint = format!("/Items/{}/PlaybackInfo", urlencoding::encode(item_id));
// What the renderer that will decode this can play. One source, shared
// with the transcode URL builder and the client-side audio override, so
// the profile we advertise and the stream we then ask for cannot
// disagree. TRACES: UR-004, UR-080 | DR-234
let (video_codecs, audio_codecs) = super::device_profile::renderer_codecs();
// Get detected codecs from Android MediaCodecList or use platform defaults
#[cfg(target_os = "android")]
let (video_codecs, audio_codecs) = crate::player::get_detected_codecs()
.map(|(video, audio, _channels)| (video, audio))
.unwrap_or_else(|| {
warn!("[DeviceProfile] Codec detection not complete, using conservative defaults");
("h264,hevc".to_string(), "aac,mp3".to_string())
});
// Linux desktop plays video through the WebKitGTK HTML5 <video> element,
// which cannot reliably decode HEVC/AV1/VP9. Advertise only codecs the
// WebView can decode so Jellyfin transcodes anything else to h264 HLS.
// (Audio-only files still direct-play via MPV; these codecs are what
// both renderers handle, and the audio profile keeps them in full while
// the video profile is narrowed below.)
#[cfg(all(not(target_os = "android"), target_os = "linux"))]
let (video_codecs, audio_codecs) =
("h264".to_string(), "aac,mp3,opus,vorbis,flac".to_string());
#[cfg(all(not(target_os = "android"), not(target_os = "linux")))]
let (video_codecs, audio_codecs) = (
"h264,hevc,vp8,vp9,av1,mpeg4".to_string(),
"aac,mp3,opus,vorbis,flac".to_string(),
);
// Video plays in a webview <video> element on every platform, which
// decodes a narrower audio set than the platform does — so the video
@@ -859,26 +862,7 @@ impl OnlineRepository {
context: "Streaming".to_string(),
protocol: "hls".to_string(),
container: "ts".to_string(),
// The server may only transcode *to* something this renderer
// can decode. This said "h264,hevc" unconditionally while the
// direct-play profile claims h264 alone on the webview path —
// a straight contradiction: it tells the server "I cannot
// play hevc, so re-encode it" and then "re-encoding it to
// hevc is fine". When the server took that option the webview
// got a stream it could not decode, which presents as video
// stuck on its first frame rather than as an error.
//
// Capped at the two codecs a Jellyfin server actually
// encodes, so a wider decode list never asks it for an av1
// encode. TRACES: UR-004, UR-080 | DR-234
video_codec: Some(
if video_codecs.contains("hevc") {
"h264,hevc"
} else {
"h264"
}
.to_string(),
),
video_codec: Some("h264,hevc".to_string()),
audio_codec: "aac,mp3".to_string(),
max_audio_channels: max_audio_channels.clone(),
},
@@ -948,7 +932,7 @@ impl OnlineRepository {
/// frontend stops testing the URL for `.m3u8`, and the quality ladder for
/// *this* source so the picker stops offering rungs that mean nothing for it.
///
/// TRACES: UR-070, UR-079 | DR-225, DR-226, DR-227, DR-228 | UT-213
/// TRACES: UR-070, UR-079 | DR-224, DR-225, DR-226, DR-227 | UT-212
pub async fn get_stream_selection(
&self,
item_id: &str,
@@ -1512,7 +1496,7 @@ impl JellyfinItem {
// exactly how the cap used to leak (a negotiation authorising a direct play the
// URL builder then never got to constrain).
//
// TRACES: UR-079 | DR-225, DR-228
// TRACES: UR-079 | DR-224, DR-227
// ---------------------------------------------------------------------------
#[derive(Debug, Serialize)]
@@ -1605,7 +1589,7 @@ pub struct NegotiatedSource {
/// The source's own bitrate, when the server reports one.
///
/// Fills the quality picker's "this rung is the same as Original" judgement
/// (DR-227). Absent for some containers — the sampled library has `avi`
/// (DR-226). Absent for some containers — the sampled library has `avi`
/// files with no bitrate at all — in which case nothing is judged redundant
/// and every rung stays offered.
#[serde(default)]
@@ -1640,7 +1624,7 @@ pub struct NegotiatedStream {
/// separately, or that the viewer has pinned a track the file does not default
/// to.
///
/// TRACES: UR-079 | DR-228 | UT-213
/// TRACES: UR-079 | DR-227 | UT-212
pub fn decide_playback_kind(
source: &NegotiatedSource,
audio_forces_transcode: bool,
@@ -3157,7 +3141,7 @@ mod tests {
set_streaming_quality(StreamingQuality::Original);
// A leaked per-playback override would cap every later test's
// expectations without appearing anywhere in its setup.
// TRACES: UR-074, UR-079 | DR-226
// TRACES: UR-074, UR-079 | DR-225
clear_playback_quality_override();
}
}
@@ -4217,7 +4201,7 @@ mod tests {
}
// -----------------------------------------------------------------------
// Direct-play negotiation (DR-228)
// Direct-play negotiation (DR-227)
//
// Fixtures rather than a live server, but the *shapes* are real: every one
// below was observed in a `PlaybackInfo` response from the development
@@ -4242,11 +4226,11 @@ mod tests {
}
}
/// The whole point of DR-228: a source the server will serve untouched is
/// The whole point of DR-227: a source the server will serve untouched is
/// served untouched. Before this, every video play built an HLS transcode
/// URL regardless.
///
/// TRACES: UR-079 | DR-228 | UT-213
/// TRACES: UR-079 | DR-227 | UT-212
#[test]
fn test_a_supported_source_direct_plays() {
let source = source_fixture();
@@ -4259,7 +4243,7 @@ mod tests {
/// The server can remux without re-encoding. That is not a transcode and
/// must not be reported as one — the difference is a whole CPU core.
///
/// TRACES: UR-079 | DR-228 | UT-213
/// TRACES: UR-079 | DR-227 | UT-212
#[test]
fn test_a_remuxable_source_direct_streams() {
let source = NegotiatedSource {
@@ -4278,7 +4262,7 @@ mod tests {
/// An unsupported codec — the hevc that is ~80% of the sampled library,
/// under the Linux h264-only profile — transcodes.
///
/// TRACES: UR-079 | DR-228 | UT-213
/// TRACES: UR-079 | DR-227 | UT-212
#[test]
fn test_an_unsupported_source_transcodes() {
let source = NegotiatedSource {
@@ -4297,7 +4281,7 @@ mod tests {
/// track the webview cannot decode, which renders as picture with no sound.
/// The client's verdict has to win over the server's.
///
/// TRACES: UR-079 | DR-228, DR-148 | UT-213
/// TRACES: UR-079 | DR-227, DR-148 | UT-212
#[test]
fn test_undecodable_audio_overrides_the_servers_direct_play_offer() {
let source = source_fixture();
@@ -4313,7 +4297,7 @@ mod tests {
/// different one. Honouring the viewer's choice means asking the server to
/// build a stream around it.
///
/// TRACES: UR-021, UR-079 | DR-228 | UT-213
/// TRACES: UR-021, UR-079 | DR-227 | UT-212
#[test]
fn test_pinning_an_audio_track_forces_a_transcode() {
let source = source_fixture();
@@ -4329,7 +4313,7 @@ mod tests {
/// arrives here as `supports_direct_play: false`; this pins the mapping so a
/// future refactor cannot quietly direct-play past a cap.
///
/// TRACES: UR-074, UR-079 | DR-226, DR-228 | UT-213
/// TRACES: UR-074, UR-079 | DR-225, DR-227 | UT-212
#[test]
fn test_a_ceiling_below_the_source_bitrate_transcodes() {
// 6.65 Mbps source, 2 Mbps ceiling — the server refuses direct play.
@@ -4357,7 +4341,7 @@ mod tests {
/// Direct play wins over direct stream when both are on offer: copying the
/// file is strictly cheaper than repackaging it.
///
/// TRACES: UR-079 | DR-228 | UT-213
/// TRACES: UR-079 | DR-227 | UT-212
#[test]
fn test_direct_play_is_preferred_over_direct_stream() {
let source = source_fixture();
@@ -4369,15 +4353,15 @@ mod tests {
}
// -----------------------------------------------------------------------
// Per-playback quality ceiling (DR-226)
// Per-playback quality ceiling (DR-225)
// -----------------------------------------------------------------------
/// The defect DR-226 exists to fix: the in-player picker documented itself
/// The defect DR-225 exists to fix: the in-player picker documented itself
/// as a "this film, this connection" control but was implemented by writing
/// the device default, so one awkward film silently capped everything played
/// afterwards. The override must not touch the default.
///
/// TRACES: UR-074, UR-079 | DR-226 | UT-213
/// TRACES: UR-074, UR-079 | DR-225 | UT-212
#[test]
fn test_a_playback_override_does_not_disturb_the_device_default() {
let _guard = QUALITY_LOCK.lock_safe();
@@ -4410,7 +4394,7 @@ mod tests {
/// autoplayed next episode is the case that matters, since nobody reopens
/// the picker between episodes.
///
/// TRACES: UR-074, UR-079 | DR-226 | UT-213
/// TRACES: UR-074, UR-079 | DR-225 | UT-212
#[test]
fn test_the_override_is_droppable_so_it_cannot_outlive_its_playback() {
let _guard = QUALITY_LOCK.lock_safe();
+21 -21
View File
@@ -12,7 +12,7 @@
//! decides *how to deliver it*** — is the point. A multi-variant playlist handed
//! to ExoPlayer is still ExoPlayer's to adapt over; Rust never paces bytes.
//!
//! TRACES: UR-079 | DR-225
//! TRACES: UR-079 | DR-224
use serde::{Deserialize, Serialize};
@@ -30,7 +30,7 @@ use crate::settings::StreamingQuality;
/// Tagged (`{"type":"hls"}`) rather than a bare string so the frontend matches a
/// discriminant instead of comparing text.
///
/// TRACES: UR-079 | DR-225
/// TRACES: UR-079 | DR-224
#[derive(specta::Type, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum Transport {
@@ -52,7 +52,7 @@ pub enum Transport {
/// lets the UI say "this is not costing the server anything" without inferring
/// it from a URL shape.
///
/// TRACES: UR-079 | DR-228
/// TRACES: UR-079 | DR-227
#[derive(specta::Type, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum PlaybackKind {
@@ -73,7 +73,7 @@ impl PlaybackKind {
/// that several seek/reload paths still branch on; this keeps the two from
/// drifting by making one derive from the other.
///
/// TRACES: UR-079 | DR-228
/// TRACES: UR-079 | DR-227
pub fn needs_transcoding(&self) -> bool {
matches!(self, PlaybackKind::Transcode)
}
@@ -85,7 +85,7 @@ impl PlaybackKind {
/// there is no *chosen* rendition in that case, only the file itself, and
/// reporting the ceiling that happened to be set would misdescribe it.
///
/// TRACES: UR-079 | DR-225, DR-226
/// TRACES: UR-079 | DR-224, DR-225
#[derive(specta::Type, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Rendition {
@@ -108,7 +108,7 @@ pub struct Rendition {
/// them indistinguishable from Original. `exceeds_source` is what lets the
/// frontend render that honestly without knowing anything about bitrates.
///
/// TRACES: UR-070, UR-079 | DR-227, DR-121
/// TRACES: UR-070, UR-079 | DR-226, DR-121
#[derive(specta::Type, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct QualityOption {
@@ -133,7 +133,7 @@ pub struct QualityOption {
///
/// Replaces the bare `String` URL that `get_video_stream_url` used to return.
///
/// TRACES: UR-079 | DR-225, DR-227, DR-228
/// TRACES: UR-079 | DR-224, DR-226, DR-227
#[derive(specta::Type, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StreamSelection {
@@ -145,7 +145,7 @@ pub struct StreamSelection {
pub playback_kind: PlaybackKind,
/// The negotiated rendition; `None` when direct-playing the source as-is.
pub rendition: Option<Rendition>,
/// What this media source can offer, for the quality picker (DR-227).
/// What this media source can offer, for the quality picker (DR-226).
pub available: Vec<QualityOption>,
/// The media source this selection is for, so a later re-open (quality
/// change, audio-track switch, transcoded seek) targets the same one.
@@ -160,7 +160,7 @@ pub struct StreamSelection {
/// queue's long-standing `needs_transcoding` flag and the seek strategy both
/// read this, so there is one answer rather than three.
///
/// TRACES: UR-079 | DR-225, DR-228
/// TRACES: UR-079 | DR-224, DR-227
pub needs_transcoding: bool,
}
@@ -171,7 +171,7 @@ impl StreamSelection {
/// source's — and offering a quality ladder over it would be a lie, since
/// nothing about a local file can be re-negotiated.
///
/// TRACES: UR-071, UR-079 | DR-225
/// TRACES: UR-071, UR-079 | DR-224
pub fn local_file(url: impl Into<String>) -> Self {
Self {
url: url.into(),
@@ -199,7 +199,7 @@ impl StreamSelection {
/// all). In that case nothing can be judged redundant and every rung is offered,
/// which is the safe direction: the viewer keeps every choice they had before.
///
/// TRACES: UR-070, UR-079 | DR-227, DR-121 | UT-212
/// TRACES: UR-070, UR-079 | DR-226, DR-121 | UT-211
pub fn quality_options_for_source(source_bitrate: Option<u64>) -> Vec<QualityOption> {
StreamingQuality::ALL
.iter()
@@ -226,7 +226,7 @@ mod tests {
/// The tag the frontend matches on has to be exactly what it expects, and
/// it is a *string in TypeScript* — nothing but a test keeps the two in step.
///
/// TRACES: UR-079 | DR-225 | UT-212
/// TRACES: UR-079 | DR-224 | UT-211
#[test]
fn test_transport_serialises_with_the_tag_the_frontend_matches() {
let cases = [
@@ -242,7 +242,7 @@ mod tests {
}
}
/// TRACES: UR-079 | DR-228 | UT-212
/// TRACES: UR-079 | DR-227 | UT-211
#[test]
fn test_playback_kind_serialises_with_the_tag_the_frontend_matches() {
let cases = [
@@ -261,7 +261,7 @@ mod tests {
/// Only a transcode costs the server encoder time. A direct *stream* is a
/// remux — cheap, and not what `needs_transcoding` has ever meant.
///
/// TRACES: UR-079 | DR-228 | UT-212
/// TRACES: UR-079 | DR-227 | UT-211
#[test]
fn test_only_transcode_counts_as_transcoding() {
assert!(PlaybackKind::Transcode.needs_transcoding());
@@ -272,7 +272,7 @@ mod tests {
/// A local file is a direct play over a local transport, with no ladder:
/// nothing about a file on disk can be re-negotiated.
///
/// TRACES: UR-071, UR-079 | DR-225 | UT-212
/// TRACES: UR-071, UR-079 | DR-224 | UT-211
#[test]
fn test_local_file_selection_offers_no_ladder() {
let selection = StreamSelection::local_file("http://127.0.0.1:9000/media/x.mkv");
@@ -286,7 +286,7 @@ mod tests {
/// The camelCase rule applies to nested struct fields too, and
/// `playbackKind` is the one the frontend branches on.
///
/// TRACES: UR-079 | DR-225 | UT-212
/// TRACES: UR-079 | DR-224 | UT-211
#[test]
fn test_stream_selection_fields_are_camel_case_on_the_wire() {
let selection = StreamSelection {
@@ -321,7 +321,7 @@ mod tests {
/// The measured library has 1.1 Mbps sources in it. Offering those a choice
/// of 20, 10, 8, 4 and 2 Mbps is offering five ways to spell "Original".
///
/// TRACES: UR-070, UR-079 | DR-227, DR-121 | UT-212
/// TRACES: UR-070, UR-079 | DR-226, DR-121 | UT-211
#[test]
fn test_rungs_above_the_source_bitrate_are_marked_redundant() {
let options = quality_options_for_source(Some(1_122_137));
@@ -361,7 +361,7 @@ mod tests {
/// `Original` is the source, so it is never "above" it — not even for a
/// source whose bitrate is unknown or zero.
///
/// TRACES: UR-070, UR-079 | DR-227 | UT-212
/// TRACES: UR-070, UR-079 | DR-226 | UT-211
#[test]
fn test_original_is_never_marked_as_exceeding_the_source() {
for bitrate in [None, Some(0), Some(1), Some(50_000_000)] {
@@ -377,7 +377,7 @@ mod tests {
/// An `avi` with no reported bitrate must not lose the picker. Judging
/// nothing redundant is the safe direction — the viewer keeps every choice.
///
/// TRACES: UR-070, UR-079 | DR-227 | UT-212
/// TRACES: UR-070, UR-079 | DR-226 | UT-211
#[test]
fn test_an_unknown_source_bitrate_keeps_every_rung_offered() {
let options = quality_options_for_source(None);
@@ -391,7 +391,7 @@ mod tests {
/// A 4K remux constrains at every rung — the ladder is fully meaningful.
///
/// TRACES: UR-070, UR-079 | DR-227 | UT-212
/// TRACES: UR-070, UR-079 | DR-226 | UT-211
#[test]
fn test_a_source_above_the_ladder_marks_nothing_redundant() {
let options = quality_options_for_source(Some(40_000_000));
@@ -401,7 +401,7 @@ mod tests {
/// The picker's text comes from Rust, beside the numbers it describes, so a
/// relabelled rung cannot drift out of step with what it does.
///
/// TRACES: UR-070, UR-079 | DR-227 | UT-212
/// TRACES: UR-070, UR-079 | DR-226 | UT-211
#[test]
fn test_options_carry_the_ladder_labels() {
let options = quality_options_for_source(Some(6_652_961));
+2 -2
View File
@@ -474,9 +474,9 @@ pub struct LiveStreamInfo {
/// A live channel is always an HLS transcode — the server has to repackage a
/// broadcast mux into something a browser can play, and there is no static
/// file to direct-play. Saying so here means the player page never has to
/// work it out from the URL, which is the whole of DR-225.
/// work it out from the URL, which is the whole of DR-224.
///
/// TRACES: UR-079 | DR-225
/// TRACES: UR-079 | DR-224
pub transport: super::stream_selection::Transport,
}
+1 -2
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "JellyTau",
"version": "0.10.1",
"version": "0.10.0",
"identifier": "com.dtourolle.jellytau",
"build": {
"beforeDevCommand": "bun run dev",
@@ -44,7 +44,6 @@
},
"bundle": {
"active": true,
"createUpdaterArtifacts": true,
"targets": [
"deb",
"rpm",
+23 -68
View File
@@ -19,31 +19,6 @@ export const commands = {
async playerPlayItem(item: PlayItemRequest) : Promise<PlayerStatus> {
return await TAURI_INVOKE("player_play_item", { item });
},
/**
* Exit background-audio mode: stop the native audio player and return its final
* position so the frontend can reload the WebView `<video>` there (UR-040).
*
* Returns the position in seconds. The sleep timer is intentionally left
* untouched if it fired while backgrounded, playback is already stopped and
* this simply reports the last position.
*
* What playback should do now that the app is no longer visible.
*
* The caller supplies only what it alone knows -- whether the per-player
* toggle is armed, and whether Android put the window into picture-in-picture.
* Everything else (what is playing, and therefore whether there is a picture to
* lose) is read here, because it is domain state.
*
* The rule itself is in `player::background_policy`; this command is the wire.
* Returning `KeepPlaying` for an empty queue is deliberate: with nothing
* playing there is nothing to pause, and an error would make the frontend
* handle a case that is not a failure.
*
* TRACES: UR-040, UR-041 | DR-225 | UT-212
*/
async playerBackgroundAction(backgroundAudioArmed: boolean, inPictureInPicture: boolean) : Promise<BackgroundAction> {
return await TAURI_INVOKE("player_background_action", { backgroundAudioArmed, inPictureInPicture });
},
/**
* Enter background-audio mode: hand playback of the currently-watched video off
* to the native ExoPlayer *audio* path so the audio keeps playing while the app
@@ -66,6 +41,13 @@ async playerEnterBackgroundAudio(item: PlayItemRequest, positionSeconds: number)
return await TAURI_INVOKE("player_enter_background_audio", { item, positionSeconds });
},
/**
* Exit background-audio mode: stop the native audio player and return its final
* position so the frontend can reload the WebView `<video>` there (UR-040).
*
* Returns the position in seconds. The sleep timer is intentionally left
* untouched if it fired while backgrounded, playback is already stopped and
* this simply reports the last position.
*
* TRACES: UR-040 | DR-052 | UT-061, IT-013
*/
async playerExitBackgroundAudio() : Promise<number> {
@@ -273,7 +255,7 @@ async playerGetStreamingQualities() : Promise<([StreamingQuality, string, string
* belongs to Settings, and `player_set_video_settings` is the one that writes
* to the database.
*
* TRACES: UR-074, UR-079 | DR-162, DR-226
* TRACES: UR-074, UR-079 | DR-162, DR-225
*/
async playerSetStreamQuality(repositoryHandle: string, quality: StreamingQuality, useHtml5: boolean, currentPosition: number | null, mediaSourceId: string | null, audioStreamIndex: number | null) : Promise<StreamQualityResponse> {
return await TAURI_INVOKE("player_set_stream_quality", { repositoryHandle, quality, useHtml5, currentPosition, mediaSourceId, audioStreamIndex });
@@ -1048,7 +1030,7 @@ async mediaLocalUrl(path: string) : Promise<string> {
* to consume rather than two, and so no caller has to infer a transport from a
* loopback URL.
*
* TRACES: UR-071, UR-079 | DR-225
* TRACES: UR-071, UR-079 | DR-224
*/
async mediaLocalSelection(path: string) : Promise<StreamSelection> {
return await TAURI_INVOKE("media_local_selection", { path });
@@ -1651,7 +1633,7 @@ async repositoryGetVideoStreamUrl(handle: string, itemId: string, mediaSourceId:
* position on an HLS playlist is copied onto every segment URI and the server
* rejects each with `400` (DR-181). Callers resume by seeking after load.
*
* TRACES: UR-070, UR-079 | DR-225, DR-227, DR-228 | UT-213
* TRACES: UR-070, UR-079 | DR-224, DR-226, DR-227 | UT-212
*/
async repositoryGetStreamSelection(handle: string, itemId: string, mediaSourceId: string | null, audioStreamIndex: number | null) : Promise<StreamSelection> {
return await TAURI_INVOKE("repository_get_stream_selection", { handle, itemId, mediaSourceId, audioStreamIndex });
@@ -2032,23 +2014,6 @@ countdownSeconds: number;
* Maximum number of episodes to auto-play consecutively (0 = unlimited)
*/
maxEpisodes?: number }
/**
* What the player should do when the app is backgrounded.
*/
export type BackgroundAction =
/**
* Carry on. Music, and video the user explicitly asked to keep hearing
* while it is in a picture-in-picture window.
*/
"keepPlaying" |
/**
* Swap the video stream for an audio-only one and keep playing.
*/
"handOffToAudio" |
/**
* Stop making sound. The user did not ask for background playback.
*/
"pause"
/**
* Smart caching configuration
*/
@@ -2374,9 +2339,9 @@ export type LiveStreamInfo = { streamUrl: string; playSessionId: string | null;
* A live channel is always an HLS transcode the server has to repackage a
* broadcast mux into something a browser can play, and there is no static
* file to direct-play. Saying so here means the player page never has to
* work it out from the URL, which is the whole of DR-225.
* work it out from the URL, which is the whole of DR-224.
*
* TRACES: UR-079 | DR-225
* TRACES: UR-079 | DR-224
*/
transport: Transport }
/**
@@ -2626,7 +2591,7 @@ needsTranscoding: boolean;
* caller falls back to `needs_transcoding` every transcode this app
* requests is HLS (DR-140), so that fallback is exact rather than a guess.
*
* TRACES: UR-003, UR-004, UR-079 | DR-225, DR-230
* TRACES: UR-003, UR-004, UR-079 | DR-224, DR-229
*/
transport?: Transport | null;
/**
@@ -2750,7 +2715,7 @@ export type PlaybackInfo = { mediaSourceId: string; playSessionId: string; strea
* lets the UI say "this is not costing the server anything" without inferring
* it from a URL shape.
*
* TRACES: UR-079 | DR-228
* TRACES: UR-079 | DR-227
*/
export type PlaybackKind =
/**
@@ -2875,7 +2840,7 @@ needsTranscoding?: boolean;
* caller falls back to `needs_transcoding` every transcode this app
* requests is HLS (DR-140), so that fallback is exact rather than a guess.
*
* TRACES: UR-003, UR-004, UR-079 | DR-225, DR-230
* TRACES: UR-003, UR-004, UR-079 | DR-224, DR-229
*/
transport?: Transport | null;
/**
@@ -3168,7 +3133,7 @@ skipped: number }
* them indistinguishable from Original. `exceeds_source` is what lets the
* frontend render that honestly without knowing anything about bitrates.
*
* TRACES: UR-070, UR-079 | DR-227, DR-121
* TRACES: UR-070, UR-079 | DR-226, DR-121
*/
export type QualityOption = { quality: StreamingQuality;
/**
@@ -3207,7 +3172,7 @@ export type RemoteSessionStatus = { position: number; duration: number | null; i
* there is no *chosen* rendition in that case, only the file itself, and
* reporting the ceiling that happened to be set would misdescribe it.
*
* TRACES: UR-079 | DR-225, DR-226
* TRACES: UR-079 | DR-224, DR-225
*/
export type Rendition = {
/**
@@ -3343,19 +3308,9 @@ export type StreamKind = "audio" | "video" | "subtitle" |
*/
export type StreamQualityResponse =
/**
* The native backend was reloaded here; nothing left for the frontend to
* *do* but it still has to be told what was negotiated.
*
* This carried only a position at first, which left the picker on Android
* pinned to the rendition of the *first* stream: the UI derives the rung in
* force from the selection it holds, nothing replaced that selection on the
* native path, and a transcode always has a rendition so the fallback
* that would have used the requested value was never reached. The stream
* changed and the menu did not.
*
* TRACES: UR-074, UR-079 | DR-226, DR-227
* The native backend was reloaded here; nothing left for the frontend.
*/
{ strategy: "native"; selection: StreamSelection; position: number } |
{ strategy: "native"; position: number } |
/**
* HTML5 must reload its element with this selection.
*/
@@ -3366,7 +3321,7 @@ export type StreamQualityResponse =
*
* Replaces the bare `String` URL that `get_video_stream_url` used to return.
*
* TRACES: UR-079 | DR-225, DR-227, DR-228
* TRACES: UR-079 | DR-224, DR-226, DR-227
*/
export type StreamSelection = {
/**
@@ -3386,7 +3341,7 @@ playbackKind: PlaybackKind;
*/
rendition: Rendition | null;
/**
* What this media source can offer, for the quality picker (DR-227).
* What this media source can offer, for the quality picker (DR-226).
*/
available: QualityOption[];
/**
@@ -3407,7 +3362,7 @@ playSessionId: string | null;
* queue's long-standing `needs_transcoding` flag and the seek strategy both
* read this, so there is one answer rather than three.
*
* TRACES: UR-079 | DR-225, DR-228
* TRACES: UR-079 | DR-224, DR-227
*/
needsTranscoding: boolean }
/**
@@ -3503,7 +3458,7 @@ export type ThumbnailCacheStats = { totalSizeBytes: number; itemCount: number; l
* Tagged (`{"type":"hls"}`) rather than a bare string so the frontend matches a
* discriminant instead of comparing text.
*
* TRACES: UR-079 | DR-225
* TRACES: UR-079 | DR-224
*/
export type Transport =
/**
+1 -1
View File
@@ -260,7 +260,7 @@ export class RepositoryClient {
* start position on an HLS playlist makes Jellyfin reject every segment behind
* it with `400` (DR-181). Resume by seeking once loaded.
*
* TRACES: UR-070, UR-079 | DR-225, DR-227, DR-228 | UT-213
* TRACES: UR-070, UR-079 | DR-224, DR-226, DR-227 | UT-212
*/
async getStreamSelection(
itemId: string,
+25 -120
View File
@@ -4,12 +4,7 @@
import { get } from "svelte/store";
import { goto } from "$app/navigation";
import { commands } from "$lib/api/bindings";
import type {
JRayActor,
StreamingQuality,
BackgroundAction,
StreamSelection,
} from "$lib/api/bindings";
import type { JRayActor, StreamingQuality, StreamSelection } from "$lib/api/bindings";
import { listen } from "@tauri-apps/api/event";
import Hls from "hls.js";
import type { MediaItem } from "$lib/api/types";
@@ -68,7 +63,6 @@
import {
setBackgroundAudioEnabled,
subscribeAppBackgrounded,
type BackgroundSignal,
subscribeAppForegrounded,
} from "$lib/utils/backgroundAudio";
import { platform } from "@tauri-apps/plugin-os";
@@ -82,7 +76,7 @@
type BackgroundAudioState,
} from "./backgroundAudioHandoff";
import { createLogger } from "$lib/utils/logger";
import { elementSrcFor, loaderForTransport } from "$lib/player/streamTransport";
import { elementSrcFor, videoLoaderFor } from "$lib/player/streamTransport";
const log = createLogger("VideoPlayer");
@@ -94,7 +88,7 @@
* which forced this component to re-derive the transport by searching for
* `.m3u8`.
*
* TRACES: UR-079 | DR-225, DR-227
* TRACES: UR-079 | DR-224, DR-226
*/
selection: StreamSelection;
mediaSourceId?: string; // Media source ID for subtitle URLs
@@ -196,15 +190,9 @@
// The selection currently loaded. Starts from the prop and is replaced
// wholesale by a reload (quality change, audio-track switch, transcoded seek)
// so transport and URL can never disagree.
// TRACES: UR-079 | DR-225
// TRACES: UR-079 | DR-224
let currentSelection = $state<StreamSelection>(untrack(() => selection));
const currentStreamUrl = $derived(currentSelection.url);
/**
* The transport as a plain string, so effects can depend on its *value*.
* A `$derived` primitive only notifies when it actually changes, which is what
* keeps the HLS teardown from re-running for an unchanged stream.
*/
const transportKind = $derived(currentSelection.transport.type);
let hasReportedStart = $state(false);
let progressInterval: ReturnType<typeof setInterval> | null = null;
let isMediaReady = $state(false); // Track if media is ready to play (implements Loading state from DR-001)
@@ -281,11 +269,11 @@
* Used by the paths that swap the stream without re-negotiating — the
* background-audio handoff and its return. Each states the transport it is
* moving to rather than letting it be inferred, which is the whole point of
* DR-225: the audio handoff really is a progressive mp3, and the rebuilt
* DR-224: the audio handoff really is a progressive mp3, and the rebuilt
* video stream really is an HLS transcode, and neither is knowable from the
* URL text.
*
* TRACES: UR-040, UR-079 | DR-225
* TRACES: UR-040, UR-079 | DR-224
*/
function selectionAt(url: string, transport: StreamSelection["transport"]): StreamSelection {
// A re-opened stream is a new transcode job; the old session id is stale.
@@ -326,14 +314,14 @@
/**
* The rungs to offer for the stream that is playing, straight from the
* backend (DR-227). Rungs whose ceiling is at or above the source bitrate are
* backend (DR-226). Rungs whose ceiling is at or above the source bitrate are
* dropped: they produce the same bytes as Original, so listing five of them is
* five ways to spell one choice. Rust decides which those are — this only
* decides not to draw them.
*
* `Original` is always kept; it is the source, never redundant with it.
*
* TRACES: UR-070, UR-079 | DR-227, DR-121
* TRACES: UR-070, UR-079 | DR-226, DR-121
*/
const qualityOptions = $derived(
currentSelection.available.filter((o) => !o.exceedsSource || o.quality === "original"),
@@ -647,15 +635,8 @@
}
// The loader comes from the backend's tagged transport, never from the URL.
//
// Read through the *primitive* `transportKind`, never `currentSelection`
// itself: this effect tears down and rebuilds hls.js, and a selection object
// is replaced on every reload — so depending on the object re-ran the whole
// teardown for an unchanged stream and left the element showing nothing
// until a seek forced another cycle.
//
// TRACES: UR-079 | DR-225 | UT-214
const loader = loaderForTransport(transportKind, {
// TRACES: UR-079 | DR-224 | UT-213
const loader = videoLoaderFor(currentSelection, {
hlsJsSupported: Hls.isSupported(),
nativeHlsSupported: !!videoElement.canPlayType("application/vnd.apple.mpegurl"),
});
@@ -892,7 +873,7 @@
});
});
// The quality *ladder* now arrives with the stream selection (DR-227), so all
// The quality *ladder* now arrives with the stream selection (DR-226), so all
// this still needs is the device default, for the case where the stream is a
// direct play and has no rendition of its own.
//
@@ -901,7 +882,7 @@
// HTML5 mode and breaks native seeking, and nothing about playback waits on
// this value.
//
// TRACES: UR-074, UR-079 | DR-162, DR-227
// TRACES: UR-074, UR-079 | DR-162, DR-226
onMount(() => {
commands
.playerGetVideoSettings()
@@ -921,7 +902,7 @@
// flip the component into HTML5 mode). Unsubscribers go into nativeUnlisteners
// so onDestroy tears them down.
if (backgroundAudioSupported) {
nativeUnlisteners.push(subscribeAppBackgrounded(onAppBackgrounded));
nativeUnlisteners.push(subscribeAppBackgrounded(enterBackgroundAudioHandoff));
nativeUnlisteners.push(subscribeAppForegrounded(exitBackgroundAudioHandoff));
}
@@ -974,7 +955,7 @@
videoCodec: needsTranscoding ? "hevc" : "h264",
needsTranscoding: needsTranscoding,
// Carry the negotiated transport onto the queue item so a later seek
// reads it instead of falling back. TRACES: UR-079 | DR-230
// reads it instead of falling back. TRACES: UR-079 | DR-229
transport: currentSelection.transport,
// Order matters: player_set_subtitle_track(n) is a position in this
// array. Previously this array was built and then dropped, so
@@ -1823,9 +1804,6 @@
const backgroundAudioSupported = platform() === "android";
let backgroundAudioOn = $state(false); // v1: default OFF each session
let handoffState: BackgroundAudioState = { ...initialHandoffState };
// Set when backgrounding paused playback, so foregrounding resumes only
// what we stopped -- never something the user paused themselves.
let pausedByBackgrounding = false;
function toggleBackgroundAudio() {
backgroundAudioOn = !backgroundAudioOn;
@@ -1841,43 +1819,6 @@
// App went to background/locked while background-audio is armed: hand off to
// native audio and stop the WebView video decode.
async function onAppBackgrounded(signal: BackgroundSignal) {
// What to do is a domain decision, not a presentation one: it depends on
// whether the item has a picture to lose, which is Rust's to know. This used
// to be decided implicitly by Kotlin gating the event on the toggle, which
// is why the native path -- whose media service keeps playing regardless --
// ignored the toggle entirely (DR-225).
let action: BackgroundAction;
try {
action = await commands.playerBackgroundAction(
signal.backgroundAudioArmed,
signal.inPictureInPicture,
);
} catch (e) {
// Never leave playback in an undefined state because a decision call
// failed. Continuing is the old behaviour and the safer default: it
// cannot silently stop something the user is listening to.
log.warn("Background action lookup failed; leaving playback alone:", e);
return;
}
log.debug("Background action:", action);
switch (action) {
case "keepPlaying":
return;
case "pause":
// The user did not ask for background playback. Remember that WE paused
// it, so returning to the foreground can resume rather than leaving a
// video mysteriously stopped.
pausedByBackgrounding = isPlaying;
if (isPlaying) await playerController.pause();
return;
case "handOffToAudio":
await enterBackgroundAudioHandoff();
return;
}
}
async function enterBackgroundAudioHandoff() {
if (!shouldEnterBackgroundAudio(backgroundAudioOn, handoffState)) return;
// `currentTime` is the component's authoritative ABSOLUTE position (the RAF
@@ -1938,20 +1879,6 @@
// App returned to foreground: stop native audio, reload the WebView <video> at
// the position native reached, and restore play/pause.
async function exitBackgroundAudioHandoff() {
// Resume what backgrounding paused, before the handoff check: the pause path
// and the handoff path are mutually exclusive, and this one leaves no
// handoff state to unwind. Only resumes if WE paused it -- a user who
// paused before locking the screen stays paused.
if (pausedByBackgrounding) {
pausedByBackgrounding = false;
try {
await playerController.play();
} catch (e) {
log.warn("Failed to resume after backgrounding:", e);
}
return;
}
if (!shouldExitBackgroundAudio(handoffState)) return;
// Read the native player's state BEFORE exiting — the exit stops it. If the
// user hit pause on the lockscreen while backgrounded, that pause must
@@ -2034,7 +1961,7 @@
id: media.id,
videoCodec: needsTranscoding ? "hevc" : "h264",
needsTranscoding,
// TRACES: UR-079 | DR-230
// TRACES: UR-079 | DR-229
transport: targetSelection.transport,
subtitles: nativeSubtitleTracks(sentSubtitleTracks),
});
@@ -2395,12 +2322,12 @@
* only supplies the position to resume at.
*
* The change applies to this playback alone; the durable Settings default is
* untouched (DR-226). Nothing is optimistically assigned here: what the picker
* untouched (DR-225). Nothing is optimistically assigned here: what the picker
* shows comes from the selection the backend hands back, because what you get
* is not always what you asked for — a ceiling above the source bitrate is the
* source, and claiming otherwise is the kind of lie the old picker told.
*
* TRACES: UR-074, UR-079 | DR-162, DR-226, DR-227
* TRACES: UR-074, UR-079 | DR-162, DR-225, DR-226
*/
async function selectQuality(quality: StreamingQuality) {
showQualityMenu = false;
@@ -2415,18 +2342,11 @@
mediaSourceId ?? null,
selectedAudioTrackIndex,
);
// Adopt whatever the backend says it opened. The HTML5 path has already
// set this via the adapter bridge, so this is a no-op there; the native
// path reloads inside Rust and this is the only thing that updates the UI.
//
// Assigning it is what keeps the picker honest: `selectedQuality` reads
// the selection's rendition, and a transcode always has one — so without
// this the menu stayed on the first stream's rung while the stream itself
// changed underneath.
//
// TRACES: UR-074, UR-079 | DR-226, DR-227
if (negotiated) {
currentSelection = negotiated;
// The HTML5 path reloads through the adapter, which already set the new
// selection via the bridge. The native path reloads inside Rust and
// returns nothing, so record what was asked for as the ceiling in force.
if (!negotiated) {
defaultQuality = quality;
}
if (videoElement && !videoElement.paused) {
startTimeUpdates();
@@ -2533,22 +2453,7 @@
aria-label="Video player"
>
<!-- Video -->
<!--
`min-h-0` / `min-w-0` are load-bearing, not defensive. A flex item defaults
to `min-height: auto`, which refuses to shrink below its content's intrinsic
size — and the <video> inside reports the *media's* natural dimensions. So
without them this wrapper grows past the viewport whenever the picture is
larger than the window: the overflow goes off the bottom, which reads as the
image being cropped and aligned to the top rather than letterboxed and
centred. `object-contain` was never the problem; it was doing its job inside
a box that was itself the wrong size.
Reproduces by resizing the window during playback, and by entering
fullscreen — where the same overflow put the picture at the bottom.
TRACES: UR-005 | DR-024
-->
<div class="flex-1 min-h-0 min-w-0 flex items-center justify-center relative">
<div class="flex-1 flex items-center justify-center relative">
{#if !!useHtml5Element}
<!-- HTML5 video for desktop/non-Android platforms -->
<video
@@ -2898,7 +2803,7 @@
<!--
Streaming quality (bandwidth ceiling), populated from what this media
source can actually offer. TRACES: UR-070, UR-074 | DR-162, DR-227
source can actually offer. TRACES: UR-070, UR-074 | DR-162, DR-226
-->
{#if qualityOptions.length > 1}
<div class="relative">
@@ -2925,7 +2830,7 @@
<div class="text-white text-sm font-semibold">Quality</div>
<!--
What the server is actually doing. Only knowable now that
the backend reports it. TRACES: UR-079 | DR-228
the backend reports it. TRACES: UR-079 | DR-227
-->
<div class="text-xs text-gray-400 mt-0.5">{playbackKindLabel}</div>
</div>
+37 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
import { videoFitClass } from "./videoFit";
import { videoFitClass, fittedVideoSize } from "./videoFit";
describe("videoFitClass", () => {
it("fills the container instead of capping at the source's intrinsic size", () => {
@@ -19,3 +19,39 @@ describe("videoFitClass", () => {
expect(cls).not.toContain("object-fill");
});
});
describe("fittedVideoSize", () => {
it("scales a 480p source up to fill a larger window (the reported bug)", () => {
// Exact 16:9 480p in a 1920x1080 window -> scales up to fill, rather than
// staying a 854x480 box in the middle.
const size = fittedVideoSize(853.33, 480, 1920, 1080);
expect(size.width).toBeCloseTo(1920, 0);
expect(size.height).toBeCloseTo(1080, 0);
});
it("fits to the constraining dimension when aspect ratios differ", () => {
// 4:3 source in a 16:9 window -> height-constrained, pillarboxed.
const size = fittedVideoSize(640, 480, 1920, 1080);
expect(size.height).toBeCloseTo(1080, 0);
expect(size.width).toBeCloseTo(1440, 0);
expect(size.width).toBeLessThan(1920);
});
it("fits to width when the source is wider than the window", () => {
// 21:9 source in a 16:9 window -> width-constrained, letterboxed.
const size = fittedVideoSize(2560, 1080, 1920, 1080);
expect(size.width).toBeCloseTo(1920, 0);
expect(size.height).toBeCloseTo(810, 0);
expect(size.height).toBeLessThan(1080);
});
it("shrinks oversized media to fit rather than overflowing", () => {
const size = fittedVideoSize(3840, 2160, 1280, 720);
expect(size.width).toBeCloseTo(1280, 0);
expect(size.height).toBeCloseTo(720, 0);
});
it("returns a zero size for unknown intrinsic dimensions", () => {
expect(fittedVideoSize(0, 0, 1920, 1080)).toEqual({ width: 0, height: 0 });
});
});
+29
View File
@@ -15,3 +15,32 @@
export function videoFitClass(): string {
return "w-full h-full object-contain";
}
export interface FittedSize {
width: number;
height: number;
}
/**
* The rendered size of a video of the given intrinsic dimensions once it has
* been fitted into the container - i.e. scaled (up or down) so that it touches
* the container on its constraining axis, with the other axis letter/pillar
* boxed. Mirrors what `object-fit: contain` on a full-size element does.
*/
export function fittedVideoSize(
intrinsicWidth: number,
intrinsicHeight: number,
containerWidth: number,
containerHeight: number,
): FittedSize {
if (intrinsicWidth <= 0 || intrinsicHeight <= 0) {
return { width: 0, height: 0 };
}
const scale = Math.min(containerWidth / intrinsicWidth, containerHeight / intrinsicHeight);
return {
width: intrinsicWidth * scale,
height: intrinsicHeight * scale,
};
}
+3 -3
View File
@@ -37,7 +37,7 @@ const log = createLogger("Html5PlayerAdapter");
* This is the one place a fallback is tolerable, and it is explicitly a
* fallback: the negotiated path never reaches it.
*
* TRACES: UR-079 | DR-225
* TRACES: UR-079 | DR-224
*/
function selectionForLoad(streamUrl: string, options: PlayerLoadOptions): StreamSelection {
if (options.selection) return options.selection;
@@ -75,9 +75,9 @@ export interface Html5ElementBridge {
*
* Carries the whole [`StreamSelection`], not just the URL: the component's
* effect has to know the transport to choose a loader, and deriving that from
* the URL is the substring check DR-225 removes.
* the URL is the substring check DR-224 removes.
*
* TRACES: UR-079 | DR-225
* TRACES: UR-079 | DR-224
*/
setStreamSelection(selection: StreamSelection): void;
/** Tear down the component-owned hls.js instance (dual-audio prevention). */
+2 -2
View File
@@ -51,7 +51,7 @@ export interface PlayerLoadOptions {
* plugin's direct URL where the adapter falls back to what the other
* options already say rather than to reading the URL.
*
* TRACES: UR-079 | DR-225
* TRACES: UR-079 | DR-224
*/
selection?: StreamSelection | null;
/** The source is a file on disk (or the loopback server in front of one). */
@@ -127,7 +127,7 @@ export interface PlayerAdapter {
* already decided to reload, and `selection.transport` says how to open it, so
* no adapter has to infer that from the URL.
*
* TRACES: UR-079 | DR-225
* TRACES: UR-079 | DR-224
*/
reloadSource(selection: StreamSelection, offset: number): Promise<void>;
+3 -4
View File
@@ -199,7 +199,7 @@ async function switchAudioTrack(
* actually got, which is not always what was asked for: a ceiling above the
* source bitrate is the source.
*
* TRACES: UR-074, UR-079 | DR-162, DR-226
* TRACES: UR-074, UR-079 | DR-162, DR-225
*/
async function setStreamQuality(
quality: StreamingQuality,
@@ -221,9 +221,8 @@ async function setStreamQuality(
await adapter.reloadSource(response.selection, response.position ?? currentPosition ?? 0);
return response.selection;
}
// The native backend reloaded itself, but still reports what it opened — the
// caller needs it to show the rung actually in force.
return response.selection ?? null;
// A native backend reloaded itself; there is no selection on that branch.
return null;
}
async function next() {
+72 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
import { downloadedFilePath } from "./localSource";
import { downloadedFilePath, resolveVideoSource } from "./localSource";
describe("downloadedFilePath", () => {
// The download worker rewrites `downloads.file_path` to the absolute path it
@@ -29,3 +29,74 @@ describe("downloadedFilePath", () => {
expect(downloadedFilePath("C:\\Users\\u\\AppData\\jellytau", stored)).toBe(stored);
});
});
// A stand-in for Tauri's convertFileSrc, so the module stays pure.
const toAssetUrl = (p: string) => `asset://localhost/${encodeURIComponent(p)}`;
describe("resolveVideoSource", () => {
it("plays the downloaded file when one exists", () => {
const decision = resolveVideoSource({
localPath: "/home/u/.local/share/jellytau/movie.mp4",
remoteUrl: "https://server/Videos/abc/master.m3u8",
remoteNeedsTranscoding: true,
toAssetUrl,
});
expect(decision.isLocal).toBe(true);
expect(decision.url).toBe(toAssetUrl("/home/u/.local/share/jellytau/movie.mp4"));
});
it("never marks a local file as needing transcoding, even when the remote did", () => {
// The transcoded path re-requests a whole new stream URL on every seek.
// A local file seeks natively; sending it down that route would ask the
// server for a stream we deliberately avoided.
const decision = resolveVideoSource({
localPath: "/downloads/film.mkv",
remoteUrl: "https://server/Videos/abc/master.m3u8",
remoteNeedsTranscoding: true,
toAssetUrl,
});
expect(decision.needsTranscoding).toBe(false);
});
it("streams when nothing is downloaded, preserving the transcoding flag", () => {
const decision = resolveVideoSource({
localPath: null,
remoteUrl: "https://server/Videos/abc/master.m3u8",
remoteNeedsTranscoding: true,
toAssetUrl,
});
expect(decision).toEqual({
url: "https://server/Videos/abc/master.m3u8",
needsTranscoding: true,
isLocal: false,
});
});
it("streams a direct-play remote without claiming it transcodes", () => {
const decision = resolveVideoSource({
localPath: null,
remoteUrl: "https://server/Videos/abc/stream.mp4",
remoteNeedsTranscoding: false,
toAssetUrl,
});
expect(decision.needsTranscoding).toBe(false);
expect(decision.isLocal).toBe(false);
});
it("falls back to streaming for a blank path rather than building a dead asset URL", () => {
for (const localPath of ["", " "]) {
const decision = resolveVideoSource({
localPath,
remoteUrl: "https://server/stream",
remoteNeedsTranscoding: false,
toAssetUrl,
});
expect(decision.isLocal).toBe(false);
expect(decision.url).toBe("https://server/stream");
}
});
});
+50
View File
@@ -1,3 +1,41 @@
/**
* Choosing between a downloaded file and a server stream for video playback.
*
* Audio has preferred local files since the queue is built (the Rust queue
* resolves `MediaSource::Local`), but video asks the repository for a stream URL
* and never consults `downloads` so a downloaded film was streamed anyway,
* spending bandwidth that had already been spent and failing outright offline.
*
* Pure so it can be unit-tested: the component only supplies the two inputs and
* the asset-URL converter.
*
* TRACES: UR-071 | DR-123 | UT-118
*/
export interface VideoSourceInputs {
/** Absolute on-disk path of a completed download, or null to stream. */
localPath: string | null;
/** Stream URL the repository resolved (already transcoded if it had to be). */
remoteUrl: string;
/** Whether the *remote* stream is a transcode. */
remoteNeedsTranscoding: boolean;
/** Usually Tauri's `convertFileSrc`; injected so this module stays pure. */
toAssetUrl: (path: string) => string;
}
export interface VideoSourceDecision {
/** What to hand the `<video>` element. */
url: string;
/**
* Local files are never transcodes, so this is always false for them. It
* matters because the transcoded path re-requests a whole new stream URL on
* every seek; a local file seeks natively and must not go down that route.
*/
needsTranscoding: boolean;
/** True when playing from disk — for logging and the offline badge. */
isLocal: boolean;
}
/** Absolute on POSIX (`/…`), Windows (`C:\…`, `C:/…`) or a UNC share (`\\…`). */
function isAbsolute(path: string): boolean {
return path.startsWith("/") || path.startsWith("\\") || /^[A-Za-z]:[\\/]/.test(path);
@@ -19,3 +57,15 @@ function isAbsolute(path: string): boolean {
export function downloadedFilePath(storageRoot: string, filePath: string): string {
return isAbsolute(filePath) ? filePath : `${storageRoot}/${filePath}`;
}
export function resolveVideoSource(inputs: VideoSourceInputs): VideoSourceDecision {
const { localPath, remoteUrl, remoteNeedsTranscoding, toAssetUrl } = inputs;
// Treat blank/whitespace paths as absent — a malformed `downloads` row must
// not produce an asset URL pointing at nothing.
if (localPath && localPath.trim() !== "") {
return { url: toAssetUrl(localPath), needsTranscoding: false, isLocal: true };
}
return { url: remoteUrl, needsTranscoding: remoteNeedsTranscoding, isLocal: false };
}
+1 -1
View File
@@ -1,7 +1,7 @@
/**
* The loader is chosen from the backend's `transport` tag, never from the URL.
*
* TRACES: UR-079 | DR-225 | UT-214
* TRACES: UR-079 | DR-224 | UT-213
*/
import { describe, expect, it } from "vitest";
+2 -22
View File
@@ -4,7 +4,7 @@
* Extracted from `VideoPlayer.svelte` so the decision can be unit-tested the
* same pattern as `episodeStrip.ts` and `TrackList.logic.test.ts`.
*
* TRACES: UR-079 | DR-225 | UT-214
* TRACES: UR-079 | DR-224 | UT-213
*/
import type { StreamSelection, Transport } from "$lib/api/bindings";
@@ -44,27 +44,7 @@ export function videoLoaderFor(
selection: Pick<StreamSelection, "url" | "transport">,
capabilities: LoaderCapabilities,
): VideoLoader {
return loaderForTransport(selection.transport.type, capabilities);
}
/**
* The same decision, taken from the transport *tag* alone.
*
* Exists because a Svelte `$effect` that reads the whole selection re-runs
* whenever the selection **object** is replaced even with an identical URL and
* transport and the HLS effect's teardown/rebuild is not idempotent: it
* destroys the hls.js instance and reattaches, which leaves the element with no
* video until something forces another cycle. The pre-DR-225 code read a plain
* URL *string*, so re-assigning the same value was a no-op and the effect stayed
* put. Passing primitives restores that.
*
* TRACES: UR-079 | DR-225 | UT-214
*/
export function loaderForTransport(
transport: Transport["type"],
capabilities: LoaderCapabilities,
): VideoLoader {
if (transport !== "hls") {
if (selection.transport.type !== "hls") {
// Progressive and local files are what the element loads natively. No
// MediaSource, no playlist parsing.
return "direct";
-44
View File
@@ -64,49 +64,6 @@ function createAuthStore() {
return repository;
}
/**
* The repository, waiting for session restore rather than failing the instant
* it is asked.
*
* `getRepository()` throws immediately, which is right for a click handler
* the user is present and an error is honest. It is wrong for anything that
* runs *on mount*: the session is restored asynchronously at startup, so a
* page that loads before that finishes gets "Not connected to a server" and
* shows a fatal error for a session that was about to arrive. The player page
* hit this, where the symptom is a playback error on a perfectly good stream.
*
* Resolves as soon as the repository exists, rejects only if it genuinely has
* not appeared so a real logged-out state still surfaces, just not as a race.
*
* TRACES: UR-002 | DR-013
*/
async function waitForRepository(timeoutMs = 5000): Promise<RepositoryClient> {
if (repository) return repository;
return new Promise<RepositoryClient>((resolve, reject) => {
let settled = false;
const finish = (fn: () => void) => {
if (settled) return;
settled = true;
clearTimeout(timer);
unsubscribe();
fn();
};
// Every store change is a chance the session landed. `subscribe` fires
// synchronously on registration, which also covers the case where it
// arrived between the check above and here.
const unsubscribe = subscribe(() => {
if (repository) finish(() => resolve(repository as RepositoryClient));
});
const timer = setTimeout(
() => finish(() => reject(new Error("Not connected to a server"))),
timeoutMs,
);
});
}
/**
* Initialize event listeners from Rust backend.
* These should be called once during app initialization.
@@ -615,7 +572,6 @@ function createAuthStore() {
logout,
clearError,
getRepository,
waitForRepository,
getCurrentSession,
getUserId,
getServerUrl,
@@ -1,114 +0,0 @@
/**
* Waiting for the repository rather than racing it.
*
* The defect: the player page asks for the repository *on mount*, but the
* session is restored asynchronously at startup. Losing that race produced
* "Not connected to a server" as a fatal playback error for a stream that was
* perfectly fine.
*
* These test the waiting contract itself rather than the auth store's internals,
* because the contract is the part the player depends on: resolve as soon as it
* exists, still reject when it genuinely is not there, and never settle twice.
*
* TRACES: UR-002, UR-004 | DR-013 | UT-215
*/
import { describe, expect, it, vi } from "vitest";
type Listener = () => void;
/**
* The shape `waitForRepository` is built on: a store you can subscribe to, and
* a value that appears at some later point. Mirrors the real implementation
* without dragging in Tauri.
*/
function makeWaiter() {
let repository: object | null = null;
const listeners = new Set<Listener>();
const subscribe = (fn: Listener) => {
listeners.add(fn);
fn(); // stores fire synchronously on subscribe
return () => listeners.delete(fn);
};
const publish = (value: object | null) => {
repository = value;
listeners.forEach((fn) => fn());
};
async function waitForRepository(timeoutMs = 5000): Promise<object> {
if (repository) return repository;
return new Promise<object>((resolve, reject) => {
let settled = false;
const finish = (fn: () => void) => {
if (settled) return;
settled = true;
clearTimeout(timer);
unsubscribe();
fn();
};
const unsubscribe = subscribe(() => {
if (repository) finish(() => resolve(repository as object));
});
const timer = setTimeout(
() => finish(() => reject(new Error("Not connected to a server"))),
timeoutMs,
);
});
}
return { waitForRepository, publish, listenerCount: () => listeners.size };
}
describe("waitForRepository", () => {
it("resolves immediately when the session is already restored", async () => {
const w = makeWaiter();
const repo = {};
w.publish(repo);
await expect(w.waitForRepository(50)).resolves.toBe(repo);
});
it("resolves when the session arrives later — the race the player lost", async () => {
const w = makeWaiter();
const repo = {};
const pending = w.waitForRepository(1000);
// Nothing yet; the page has already mounted and asked.
setTimeout(() => w.publish(repo), 10);
await expect(pending).resolves.toBe(repo);
});
it("still rejects when there genuinely is no session", async () => {
vi.useFakeTimers();
const w = makeWaiter();
const pending = w.waitForRepository(500);
const assertion = expect(pending).rejects.toThrow("Not connected to a server");
await vi.advanceTimersByTimeAsync(600);
await assertion;
vi.useRealTimers();
});
it("unsubscribes once settled, so a later change cannot resolve it twice", async () => {
const w = makeWaiter();
const repo = {};
const pending = w.waitForRepository(1000);
expect(w.listenerCount()).toBe(1);
w.publish(repo);
await pending;
expect(w.listenerCount()).toBe(0);
// A further change must not throw or re-settle.
expect(() => w.publish(null)).not.toThrow();
});
it("does not leave a pending timer that fires after success", async () => {
vi.useFakeTimers();
const w = makeWaiter();
const repo = {};
const pending = w.waitForRepository(200);
w.publish(repo);
await expect(pending).resolves.toBe(repo);
// If the timeout were still armed it would reject an already-settled
// promise, which surfaces as an unhandled rejection rather than a failure.
await vi.advanceTimersByTimeAsync(500);
vi.useRealTimers();
});
});
+3 -24
View File
@@ -66,31 +66,10 @@ export function setBackgroundAudioEnabled(enabled: boolean): boolean {
* Returns an unsubscribe function. No-op where unsupported (the event never
* fires on non-Android platforms).
*/
export interface BackgroundSignal {
/** Whether the per-player background-audio toggle was armed (UR-040). */
backgroundAudioArmed: boolean;
/** Whether Android put the window into picture-in-picture (UR-041). */
inPictureInPicture: boolean;
}
/**
* Older builds dispatched this event with no detail, and only when the toggle
* was already armed. Treat a missing detail as "armed, not PiP" so a mismatched
* pair degrades to the previous behaviour rather than pausing unexpectedly.
*/
function readSignal(event: Event): BackgroundSignal {
const detail = (event as CustomEvent).detail as Partial<BackgroundSignal> | null | undefined;
return {
backgroundAudioArmed: detail?.backgroundAudioArmed ?? true,
inPictureInPicture: detail?.inPictureInPicture ?? false,
};
}
export function subscribeAppBackgrounded(handler: (signal: BackgroundSignal) => void): () => void {
export function subscribeAppBackgrounded(handler: () => void): () => void {
if (typeof window === "undefined") return () => {};
const listener = (event: Event) => handler(readSignal(event));
window.addEventListener("jellytau-background", listener);
return () => window.removeEventListener("jellytau-background", listener);
window.addEventListener("jellytau-background", handler);
return () => window.removeEventListener("jellytau-background", handler);
}
/** Subscribe to the native "app foregrounded" signal. Returns an unsubscribe fn. */
+5 -10
View File
@@ -82,7 +82,7 @@
* Replaces a bare URL string: the transport travels with it, so neither this
* page nor VideoPlayer has to work out whether the URL is a playlist.
*
* TRACES: UR-079 | DR-225
* TRACES: UR-079 | DR-224
*/
let selection = $state<StreamSelection | null>(null);
let mediaSourceId = $state<string | null>(null);
@@ -325,7 +325,7 @@
//
// A downloaded file is a direct play over a local transport, and Rust
// says so rather than this page assuming it.
// TRACES: UR-071 | DR-137, DR-225
// TRACES: UR-071 | DR-137, DR-224
selection = await commands.mediaLocalSelection(fullPath);
videoNeedsTranscoding = false;
// Use explicit startPosition, or fall back to retrieved progress from database
@@ -354,12 +354,7 @@
} else {
// Online playback - get playback info from server
isOfflinePlayback = false;
// Wait for session restore rather than failing on a race: this runs on
// mount, and at startup (or after a hot reload) the repository may be a
// few hundred milliseconds behind. Failing instantly showed "Not
// connected to a server" as a *playback* error for a stream that was
// fine. TRACES: UR-002, UR-004 | DR-013
const repo = await auth.waitForRepository();
const repo = auth.getRepository();
if (isLive) {
// Live TV channels must be "opened" before streaming; the server returns
@@ -402,7 +397,7 @@
// to stop it a moment later. Observed in the log as a pair of
// `[StreamSelection]` lines for one play.
//
// TRACES: UR-071 | DR-123, DR-137, DR-225
// TRACES: UR-071 | DR-123, DR-137, DR-224
const localPath = await commands.playerLocalMediaPath(id);
if (localPath) {
// A downloaded file is a direct play over a local transport, served
@@ -418,7 +413,7 @@
// the device profile and the ceiling in force, and returns the
// transport and the media-source id with it. This page no longer
// decides — or separately asks for — any of that.
// TRACES: UR-070, UR-079 | DR-225, DR-227, DR-228
// TRACES: UR-070, UR-079 | DR-224, DR-226, DR-227
selection = await repo.getStreamSelection(id, null, null);
mediaSourceId = selection.mediaSourceId;
// Rust's own verdict — "which kinds count as transcoding" is a