Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
58f2506966 | ||
|
|
a818fee297 | ||
|
|
a26a853f01 | ||
|
|
9d099268b9 | ||
|
|
e381d626c1 | ||
|
|
b12e99b7e1 | ||
|
|
dc8b732465 | ||
|
|
b98a530f48 | ||
|
|
b565c4ae6f | ||
|
|
79e10d7485 | ||
|
|
a2dbde5492 | ||
|
|
75cd07a5c0 | ||
|
|
64d07b8940 | ||
|
|
5b810f7fc3 | ||
|
|
1ae213ff39 | ||
|
|
98a6bca645 | ||
|
|
984e594006 | ||
|
|
f49e6e4648 | ||
|
|
105cc082ea | ||
|
|
0a3ee0791f | ||
|
|
0da0a9f16c | ||
|
|
75bae2556c | ||
|
|
48f63dd763 | ||
|
|
36ef231e2f | ||
|
|
cb79a376b3 | ||
|
|
b11188e9dd | ||
|
|
f636b6b151 | ||
|
|
37ffabee06 | ||
|
|
13e0860401 | ||
|
|
d1c01a6bc3 | ||
|
|
e5d3cc06f2 | ||
|
|
5759a97289 | ||
|
|
b9f026e215 | ||
|
|
b7a7037194 | ||
|
|
124da29fc7 | ||
|
|
5927299c0f | ||
|
|
7650efcb7f | ||
|
|
4b9350c949 | ||
|
|
d01c1216b8 | ||
|
|
fb967433f0 | ||
|
|
ee584aced2 | ||
|
|
eb76c96e94 | ||
|
|
c3ead64748 | ||
|
|
742ad88a29 | ||
|
|
d4e2cd120c | ||
|
|
c543f90ad3 | ||
|
|
589f08b873 | ||
|
|
e2c9d68311 | ||
|
|
57b24f8c74 | ||
|
|
6391720d23 | ||
|
|
90f03dd142 |
@@ -121,6 +121,64 @@ jobs:
|
||||
path: dist/linux/
|
||||
retention-days: 30
|
||||
|
||||
build-windows:
|
||||
name: Build Windows
|
||||
runs-on: linux/amd64
|
||||
needs: test
|
||||
# Cross-compiled from Linux via the official Tauri path (MSVC + cargo-xwin),
|
||||
# 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:latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Cache Rust dependencies
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
~/.cache/cargo-xwin
|
||||
src-tauri/target
|
||||
key: ${{ runner.os }}-cargo-windows-${{ hashFiles('**/Cargo.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-cargo-windows-
|
||||
|
||||
- name: Cache Node dependencies
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: |
|
||||
~/.bun/install/cache
|
||||
node_modules
|
||||
key: ${{ runner.os }}-bun-${{ hashFiles('**/bun.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-bun-
|
||||
|
||||
- name: Set app version from tag
|
||||
run: |
|
||||
# On a tag build the tag is the single source of truth for the version.
|
||||
if echo "$GITHUB_REF" | grep -q '^refs/tags/v'; then
|
||||
VERSION="${GITHUB_REF#refs/tags/v}"
|
||||
echo "Setting version to $VERSION"
|
||||
sed -i "s/\"version\": \"[^\"]*\"/\"version\": \"$VERSION\"/" src-tauri/tauri.conf.json
|
||||
fi
|
||||
grep '"version"' src-tauri/tauri.conf.json
|
||||
|
||||
- name: Build Windows (NSIS installer + exe)
|
||||
run: OUTPUT_DIR="$PWD/dist/windows" WIN_BUNDLES=nsis ./scripts/build-windows-cross.sh
|
||||
|
||||
- name: List Windows artifacts
|
||||
run: ls -lah dist/windows/
|
||||
|
||||
- name: Upload Windows build artifact
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: jellytau-windows
|
||||
path: dist/windows/
|
||||
retention-days: 30
|
||||
|
||||
build-android:
|
||||
name: Build Android
|
||||
runs-on: linux/amd64
|
||||
@@ -239,7 +297,7 @@ jobs:
|
||||
create-release:
|
||||
name: Create Release
|
||||
runs-on: linux/amd64
|
||||
needs: [build-linux, build-android]
|
||||
needs: [build-linux, build-windows, build-android]
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
container:
|
||||
image: gitea.tourolle.paris/dtourolle/jellytau-builder:latest
|
||||
@@ -259,6 +317,12 @@ jobs:
|
||||
name: jellytau-linux
|
||||
path: artifacts/linux/
|
||||
|
||||
- name: Download Windows artifacts
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: jellytau-windows
|
||||
path: artifacts/windows/
|
||||
|
||||
- name: Download Android artifacts
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
@@ -277,6 +341,9 @@ jobs:
|
||||
echo "- **AppImage** - Run directly on most Linux distributions" >> release_notes.md
|
||||
echo "- **DEB** - Install via \`sudo dpkg -i jellytau_*.deb\` (Ubuntu/Debian)" >> release_notes.md
|
||||
echo "" >> release_notes.md
|
||||
echo "#### Windows" >> release_notes.md
|
||||
echo "- **Installer (.exe)** - Run \`jellytau_*-setup.exe\` (NSIS). Unsigned — SmartScreen may warn on first run." >> release_notes.md
|
||||
echo "" >> release_notes.md
|
||||
echo "#### Android" >> release_notes.md
|
||||
echo "- **APK** - Install via \`adb install jellytau-release.apk\` or sideload via file manager" >> release_notes.md
|
||||
echo "- **AAB** - Upload to Google Play Console or testing platforms" >> release_notes.md
|
||||
@@ -358,7 +425,7 @@ jobs:
|
||||
fi
|
||||
echo "Release id=$RELEASE_ID"
|
||||
|
||||
for f in artifacts/android/* artifacts/linux/*; do
|
||||
for f in artifacts/android/* artifacts/linux/* artifacts/windows/*; do
|
||||
[ -f "$f" ] || continue
|
||||
echo "⬆️ Uploading $(basename "$f")"
|
||||
curl -fsS -X POST \
|
||||
|
||||
@@ -42,30 +42,45 @@ jobs:
|
||||
echo "📊 Validating requirement traceability..."
|
||||
echo ""
|
||||
|
||||
# Parse JSON
|
||||
# Denominators come from docs/requirements.md at run time — NEVER
|
||||
# hardcode them here. This step previously divided by frozen literals
|
||||
# (UR/39, IR/24, DR/48, JA/3, total 114) while the file had grown to
|
||||
# 211 requirements, so it reported 158% coverage and the threshold
|
||||
# below could never trip. See docs/specs/traceability-gate-repair.md.
|
||||
TOTAL_TRACES=$(jq '.totalTraces' traces-report.json)
|
||||
UR=$(jq '.byType.UR | length' traces-report.json)
|
||||
IR=$(jq '.byType.IR | length' traces-report.json)
|
||||
DR=$(jq '.byType.DR | length' traces-report.json)
|
||||
JA=$(jq '.byType.JA | length' traces-report.json)
|
||||
COVERED=$(jq '.coverage.covered' traces-report.json)
|
||||
TOTAL_REQS=$(jq '.coverage.total' traces-report.json)
|
||||
COVERAGE=$(jq '.coverage.percent' traces-report.json)
|
||||
|
||||
# Print coverage report
|
||||
echo "✅ TRACES Found: $TOTAL_TRACES"
|
||||
echo ""
|
||||
echo "📋 Coverage Summary:"
|
||||
echo " User Requirements (UR): $UR / 39 ($(( UR * 100 / 39 ))%)"
|
||||
echo " Integration Requirements (IR): $IR / 24 ($(( IR * 100 / 24 ))%)"
|
||||
echo " Development Requirements (DR): $DR / 48 ($(( DR * 100 / 48 ))%)"
|
||||
echo " Jellyfin API Requirements (JA): $JA / 3 ($(( JA * 100 / 3 ))%)"
|
||||
echo "📋 Coverage Summary (traced / defined):"
|
||||
for T in UR IR DR JA; do
|
||||
TRACED=$(jq --arg t "$T" '[.byType[$t][] | select(. != null)] | length' traces-report.json)
|
||||
DEFINED=$(jq --arg t "$T" '.defined[$t]' traces-report.json)
|
||||
echo " $T: $TRACED / $DEFINED"
|
||||
done
|
||||
echo ""
|
||||
|
||||
COVERED=$((UR + IR + DR + JA))
|
||||
TOTAL_REQS=114
|
||||
COVERAGE=$((COVERED * 100 / TOTAL_REQS))
|
||||
|
||||
echo "📈 Overall Coverage: $COVERED / $TOTAL_REQS ($COVERAGE%)"
|
||||
echo ""
|
||||
|
||||
# Traced IDs that requirements.md does not define (typo, or a deleted
|
||||
# requirement). These do not count toward coverage.
|
||||
ORPHANED=$(jq -c '.coverage.orphaned' traces-report.json)
|
||||
if [ "$ORPHANED" != "[]" ]; then
|
||||
echo "⚠️ Traced but not defined in requirements.md: $ORPHANED"
|
||||
echo ""
|
||||
fi
|
||||
|
||||
# A ratio above 100% means the computation is broken — the exact
|
||||
# condition that hid the stale-denominator bug. Fail loudly.
|
||||
if [ "$COVERAGE" -gt 100 ]; then
|
||||
echo "❌ ERROR: Coverage ($COVERAGE%) exceeds 100% — the gate is miscomputing."
|
||||
echo " Orphaned IDs: $ORPHANED"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Check minimum threshold
|
||||
MIN_THRESHOLD=50
|
||||
if [ "$COVERAGE" -lt "$MIN_THRESHOLD" ]; then
|
||||
|
||||
@@ -64,3 +64,9 @@ src-tauri/.cargo/config.toml
|
||||
/docs/README.md
|
||||
/docs/api-redirect.md
|
||||
/docs-site/book/
|
||||
|
||||
# Arch packaging build artifacts (vendored cargo cache, makepkg workdir, output package)
|
||||
/.cargo-arch/
|
||||
/packaging/arch/pkg/
|
||||
/packaging/arch/src/
|
||||
/packaging/arch/*.pkg.tar.zst
|
||||
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to JellyTau are documented here.
|
||||
|
||||
Entries are grouped by the capability they change, not by commit. Requirement
|
||||
IDs in parentheses point at [docs/requirements.md](docs/requirements.md); the
|
||||
generated trace matrix lives in [docs/traceability.md](docs/traceability.md).
|
||||
|
||||
## v0.2.0
|
||||
|
||||
### ✨ Features
|
||||
|
||||
- **Audio settings now work on Android.** The equalizer, volume normalization
|
||||
and gapless playback controls in Settings › Audio previously rendered on
|
||||
Android and did nothing — `ExoPlayerBackend` was the only backend that never
|
||||
implemented `set_audio_settings`, and the trait's default silently reported
|
||||
success while applying nothing. All three now take effect:
|
||||
- **Equalizer** — the canonical 10-band ISO curve is resampled onto whatever
|
||||
bands the device's equalizer actually exposes (commonly 5), by nearest
|
||||
centre frequency.
|
||||
- **Volume normalization** — via `LoudnessEnhancer`. Note this is a gain
|
||||
stage, not a true EBU R128 normalizer like the Linux `dynaudnorm` path, so
|
||||
it approximates rather than matches Linux behaviour.
|
||||
- **Gapless playback** — honours the setting via `pauseAtEndOfMediaItems`
|
||||
(ExoPlayer is gapless by default, so this disables it when you turn it off).
|
||||
|
||||
The effects re-attach automatically when ExoPlayer rebuilds its audio sink on
|
||||
a format change, so the equalizer no longer stops applying part-way through a
|
||||
queue. (UR-027, UR-032, UR-033 → DR-030, DR-035, DR-036, IR-004)
|
||||
|
||||
⚠️ **Not yet verified on a physical device.** `AudioEffect` availability and
|
||||
band layouts vary by device and OEM ROM; where an effect is unavailable it is
|
||||
logged and skipped rather than crashing playback.
|
||||
|
||||
### 📋 Documentation
|
||||
|
||||
- **Playback backend unification investigation.** Six new specs in
|
||||
[docs/specs/](docs/specs/) record why the playback backends cannot be unified
|
||||
onto a single engine: every candidate (mpv, GStreamer, libVLC) fails the same
|
||||
webview-compositing constraint, because WebKitGTK/WebView2/Android WebView each
|
||||
own their compositor surface and native video cannot interleave with HTML.
|
||||
Audio *can* unify; video cannot. Also specifies the Android native-video spike,
|
||||
a Windows native audio backend, and the `libmpv2` migration.
|
||||
|
||||
### 🐛 Corrected requirement statuses
|
||||
|
||||
These were documented as working and were not. No behaviour changed — the docs
|
||||
were wrong.
|
||||
|
||||
- **Crossfade (UR-031, DR-034) was marked "Done (Linux only)". It is implemented
|
||||
nowhere**, and is architecturally blocked on mpv: its audio chain is
|
||||
single-stream, and FFmpeg's `acrossfade` requires two inputs. Real crossfade
|
||||
would need two libmpv instances.
|
||||
- The platform parity matrix listed crossfade as a Linux/Android gap (it is
|
||||
neither) and omitted the equalizer (which was a genuine gap, now closed).
|
||||
- `nativeAdapter.ts` cited tauri#10152 as blocking native Android video. That
|
||||
issue is a stale feature request; the capability shipped in September 2024.
|
||||
What remains unproven is SurfaceView-behind-WebView compositing, now tracked
|
||||
by a spec rather than asserted as an upstream blocker.
|
||||
|
||||
<!--
|
||||
Note: v0.1.3–v0.1.5 have no entries here. Their changes are in the git log
|
||||
and docs/traceability.md.
|
||||
-->
|
||||
|
||||
## v0.1.2
|
||||
|
||||
### ✨ Features
|
||||
|
||||
- **Search results are ordered by how well they match.** A name that *starts*
|
||||
with the query now outranks one matching mid-word — typing "parks" finds
|
||||
"Parks and Recreation" before "Sparks of Love" — and at equal match quality a
|
||||
container outranks its contents, so a series lands above its own episodes.
|
||||
Ranking is applied to the instant cached results and to the merged
|
||||
cache+server list alike, so the list no longer reshuffles when server results
|
||||
arrive. (UR-060, DR-090)
|
||||
- **Separate Shows, Episodes and People result groups.** The combined "TV Shows"
|
||||
group splits into Shows and Episodes so a show never competes with its own
|
||||
episodes for a slot, and a new People group means searching an actor's name
|
||||
reaches their bio page. Default order is Shows → Episodes → Movies → Songs →
|
||||
Albums → Artists → People; a group order saved before the split keeps the
|
||||
position it was dragged to. (UR-060, DR-091)
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
- **The library header search bar works on every library page.** It previously
|
||||
searched in place and depended on `/library` rendering results inline, so on
|
||||
any other `/library/**` route the results were fetched and never shown.
|
||||
`/search` is now the single surface that renders results, and the header bar
|
||||
hands its query and scope over via the URL. (UR-049, DR-063)
|
||||
- **Video smaller than the window is scaled up to fit.** Sizing only ever shrank
|
||||
oversized media, so a 480p source on a 1080p display played as a small picture
|
||||
in the middle of a black frame. The picture now fits whichever axis constrains
|
||||
it, in both directions, preserving aspect ratio. (UR-005)
|
||||
|
||||
### 📋 Requirements
|
||||
|
||||
**Linux:** 64-bit, GLIBC 2.29+
|
||||
**Android:** 8.0+
|
||||
|
||||
## v0.1.1 and earlier
|
||||
|
||||
Released before this file existed — see the git history and the release notes on
|
||||
each tag.
|
||||
@@ -35,6 +35,20 @@ CI runs on **Gitea Actions** (`.gitea/workflows/`), not GitHub. Use the `gh` CLI
|
||||
only against the mirror if one exists; the canonical remote is
|
||||
`gitea.tourolle.paris`.
|
||||
|
||||
> **🔴 CI installs no system tools.** Never add an `apt-get`, `rustup`,
|
||||
> `sdkmanager`, mingw/nsis, or any other *toolchain/system-package* install to a
|
||||
> CI workflow step. Every build, test, and packaging **tool** must already live
|
||||
> in the Docker image the job runs in — the unified builder (`Dockerfile.builder`
|
||||
> → `gitea.tourolle.paris/dtourolle/jellytau-builder`) for Android/Linux/Windows,
|
||||
> or `Dockerfile.arch` for Arch. If a job needs a tool the image lacks, **add it
|
||||
> to the image, rebuild + push it** (`scripts/build-builder-image.sh`), and use
|
||||
> it from CI — do not install it at job time. This keeps builds reproducible and
|
||||
> fast, and is why the packaging stages are thin `FROM ${BUILDER_IMAGE}` layers.
|
||||
>
|
||||
> `bun install` (fetching the project's own JS deps per the lockfile) is **not**
|
||||
> a violation — that's project dependencies, not a toolchain. The rule is about
|
||||
> system tools, not npm/bun/cargo *packages* declared by the project.
|
||||
|
||||
## Before Committing
|
||||
|
||||
- Frontend: `bun run check` and `bun run test` must pass.
|
||||
@@ -169,8 +183,14 @@ and [docs/build-release.md](docs/build-release.md).
|
||||
backend expand it. Single-type presentation (`itemType: "Movie"`, "this page
|
||||
shows albums") is fine; a *category → set of types* mapping in `src/` is a leak.
|
||||
`bun run check:boundary` is the tripwire; the real gate is the spec's layer
|
||||
assignment. See [scoped-search-boundary.md](docs/specs/scoped-search-boundary.md)
|
||||
for the incident this rule came from.
|
||||
assignment. The canonical example lives in Rust:
|
||||
`SearchScope::item_types()` in `repository/types.rs` expands an opaque scope the
|
||||
frontend sends. See [scoped-search-boundary.md](docs/specs/scoped-search-boundary.md)
|
||||
for the incident this rule came from — note the tripwire missed that leak for
|
||||
months because the mapping was assigned to a named const rather than written
|
||||
inline at the query, so **a green `check:boundary` is not proof**; it flags
|
||||
item-type array literals only, not run-time-built sets or `switch`/`||`
|
||||
taxonomy.
|
||||
|
||||
## Writing specs
|
||||
|
||||
@@ -252,6 +272,23 @@ tagged responses keep the Rust field names as-is (e.g. `new_url`, not `newUrl`).
|
||||
|
||||
## Testing
|
||||
|
||||
### 🔴 Bug fixes: failing test FIRST, then the fix
|
||||
|
||||
When fixing a bug, **write a test that reproduces it and watch it fail before
|
||||
touching the fix.** Red → green, in that order:
|
||||
|
||||
1. Write a test that exercises the broken behavior and **run it — it must fail**,
|
||||
proving the test actually catches the bug (a test that passes before the fix
|
||||
proves nothing).
|
||||
2. Apply the fix.
|
||||
3. Re-run — the test now passes, and so does the rest of the suite.
|
||||
|
||||
Never fix first and backfill the test afterward: a test written against
|
||||
already-fixed code can pass for the wrong reason and silently fails to guard the
|
||||
regression. If the logic is buried in a component, extract the pure part into a
|
||||
plain `.ts` module (e.g. `episodeStrip.ts`) so it can be unit-tested — the same
|
||||
pattern as `TrackList.logic.test.ts`.
|
||||
|
||||
```bash
|
||||
# Rust
|
||||
cd src-tauri && cargo test
|
||||
|
||||
+35
@@ -1,4 +1,11 @@
|
||||
# Multi-stage build for JellyTau - Tauri Jellyfin client
|
||||
#
|
||||
# The desktop packaging stages (desktop-linux-build, windows-cross) build FROM
|
||||
# the unified registry builder image, which carries every packaging tool. Declared
|
||||
# here (before the first FROM) so it's in scope for those stages' FROM lines.
|
||||
# Override for local iteration: --build-arg BUILDER_IMAGE=jellytau-builder:latest
|
||||
ARG BUILDER_IMAGE=gitea.tourolle.paris/dtourolle/jellytau-builder:latest
|
||||
|
||||
FROM ubuntu:24.04 AS builder
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive \
|
||||
@@ -108,6 +115,34 @@ RUN cd src-tauri && cargo fetch && cd .. && \
|
||||
bun run tauri android build --apk true && \
|
||||
echo "APK build complete!"
|
||||
|
||||
# Desktop packaging stages build FROM the unified registry builder image (see the
|
||||
# BUILDER_IMAGE ARG at the top), which already carries every packaging tool
|
||||
# (rpm/file for Linux, cargo-xwin + nsis + the x86_64-pc-windows-msvc rust
|
||||
# target for Windows). ONE source of dependency truth, shared with CI — no
|
||||
# per-stage apt/rustup here.
|
||||
#
|
||||
# NOTE: Windows uses the MSVC target via cargo-xwin, NOT mingw/GNU — the GNU
|
||||
# toolchain cannot bundle an NSIS installer from Linux. See
|
||||
# scripts/build-windows-cross.sh.
|
||||
|
||||
# Linux desktop packaging environment (deb + rpm; Arch is Dockerfile.arch).
|
||||
# Thin layer over the builder — the actual build runs at container-run time on
|
||||
# the bind-mounted source (see docker-compose.yml / scripts/build-desktop-linux.sh),
|
||||
# matching the `dev` service model. Run standalone with:
|
||||
# docker run --rm -v "$PWD:/app" -v "$PWD/dist:/app/dist" <img> \
|
||||
# bash -c "OUTPUT_DIR=/app/dist scripts/build-desktop-linux.sh"
|
||||
FROM ${BUILDER_IMAGE} AS desktop-linux-build
|
||||
WORKDIR /app
|
||||
CMD ["bash", "-c", "OUTPUT_DIR=/app/dist scripts/build-desktop-linux.sh"]
|
||||
|
||||
# Windows cross-compile environment (MSVC target via cargo-xwin). Video works via
|
||||
# WebView2 and audio via the webview <audio> backend; NSIS installer is produced
|
||||
# from Linux by cargo-xwin. Default bundles NSIS; override WIN_BUNDLES=none for
|
||||
# exe-only. Build runs at container-run time like above.
|
||||
FROM ${BUILDER_IMAGE} AS windows-cross
|
||||
WORKDIR /app
|
||||
CMD ["bash", "-c", "OUTPUT_DIR=/app/dist WIN_BUNDLES=${WIN_BUNDLES:-nsis} scripts/build-windows-cross.sh"]
|
||||
|
||||
# Final output stage
|
||||
FROM ubuntu:24.04 AS final
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
# JellyTau Arch Linux package builder.
|
||||
#
|
||||
# Tauri has no pacman bundle target, so we build a real .pkg.tar.zst with makepkg
|
||||
# from packaging/arch/PKGBUILD. makepkg refuses to run as root, so we create a
|
||||
# non-root `builder` user with passwordless sudo (for `makepkg -s` pacman calls).
|
||||
#
|
||||
# docker build -f Dockerfile.arch -t jellytau-arch .
|
||||
# docker run --rm -v "$PWD/dist:/out" jellytau-arch
|
||||
FROM archlinux:latest
|
||||
|
||||
RUN pacman -Syu --noconfirm \
|
||||
base-devel git sudo \
|
||||
rust cargo nodejs \
|
||||
webkit2gtk-4.1 mpv gtk3 libayatana-appindicator \
|
||||
libsoup3 pkgconf openssl \
|
||||
&& pacman -Scc --noconfirm
|
||||
|
||||
# Bun is not in the official repos; install the upstream binary.
|
||||
RUN curl -fsSL https://bun.sh/install | bash && \
|
||||
ln -s /root/.bun/bin/bun /usr/local/bin/bun
|
||||
|
||||
# Non-root build user with passwordless sudo for makepkg's dependency step.
|
||||
RUN useradd -m builder && \
|
||||
echo 'builder ALL=(ALL) NOPASSWD: ALL' > /etc/sudoers.d/builder && \
|
||||
ln -sf /root/.bun/bin/bun /usr/local/bin/bun
|
||||
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
RUN chown -R builder:builder /app
|
||||
|
||||
USER builder
|
||||
ENV OUTPUT_DIR=/out
|
||||
RUN mkdir -p /out
|
||||
VOLUME ["/out"]
|
||||
|
||||
# Default: build the package. Output lands in /out (mount it to collect the pkg).
|
||||
CMD ["bash", "-c", "OUTPUT_DIR=/out scripts/build-arch.sh"]
|
||||
+33
-1
@@ -1,5 +1,9 @@
|
||||
# JellyTau Builder Image
|
||||
# Pre-built image with all dependencies for building and testing
|
||||
# Pre-built image with all dependencies for building, testing, and packaging:
|
||||
# - Android APK (SDK/NDK), Linux desktop (deb/rpm),
|
||||
# - Windows cross via the official Tauri path: MSVC target + cargo-xwin + NSIS
|
||||
# Arch packages build in a separate archlinux image (Dockerfile.arch) since
|
||||
# makepkg is Arch-specific.
|
||||
# Push to your registry: docker build -f Dockerfile.builder -t gitea.tourolle.paris/dtourolle/jellytau-builder:latest .
|
||||
|
||||
FROM ubuntu:24.04
|
||||
@@ -83,6 +87,34 @@ RUN $ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager --sdk_root=$ANDROID_HOME \
|
||||
# Set NDK environment variable
|
||||
ENV NDK_HOME=$ANDROID_HOME/ndk/$NDK_VERSION
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Desktop packaging tools — kept in a trailing layer ON PURPOSE so that adding
|
||||
# or changing a packaging tool doesn't invalidate the expensive apt/rust/Android
|
||||
# layers above (a tool tweak becomes a ~1-2 min rebuild, not ~15). Covers Linux
|
||||
# (deb/rpm) and Windows cross (MSVC via cargo-xwin + NSIS).
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
# Linux desktop packaging: rpmbuild for the .rpm bundle (deb needs nothing extra)
|
||||
rpm \
|
||||
file \
|
||||
# Windows cross-compile (official Tauri path: MSVC target via cargo-xwin).
|
||||
# clang provides clang-cl, the MSVC-compatible C compiler cc-rs uses to build
|
||||
# C deps (bundled sqlite, ring, ...); lld = linker; llvm = llvm-lib/ar etc;
|
||||
# nsis = installer generator.
|
||||
clang \
|
||||
lld \
|
||||
llvm \
|
||||
nsis \
|
||||
&& 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,
|
||||
# so provide it as a symlink.
|
||||
&& ln -sf /usr/bin/clang /usr/local/bin/clang-cl
|
||||
|
||||
# Windows rust target + cargo-xwin (downloads the MSVC CRT/SDK at build time).
|
||||
RUN . $HOME/.cargo/env && \
|
||||
rustup target add x86_64-pc-windows-msvc && \
|
||||
cargo install --locked cargo-xwin
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
ENTRYPOINT ["/bin/bash"]
|
||||
|
||||
@@ -33,6 +33,58 @@ services:
|
||||
ports:
|
||||
- "5172:5172" # In case you want to run dev server
|
||||
|
||||
# Linux desktop packages - deb + rpm + pacman into ./dist
|
||||
desktop-linux-build:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
target: desktop-linux-build
|
||||
args:
|
||||
# Defaults to the registry builder (Dockerfile's ARG). Point at a locally
|
||||
# built builder with: BUILDER_IMAGE=jellytau-builder:latest docker compose ...
|
||||
BUILDER_IMAGE: ${BUILDER_IMAGE:-gitea.tourolle.paris/dtourolle/jellytau-builder:latest}
|
||||
container_name: jellytau-desktop-linux-build
|
||||
volumes:
|
||||
- .:/app
|
||||
- cargo-cache:/root/.cargo
|
||||
- bun-cache:/root/.bun
|
||||
environment:
|
||||
- RUST_BACKTRACE=1
|
||||
- OUTPUT_DIR=/app/dist
|
||||
command: bash -c "OUTPUT_DIR=/app/dist scripts/build-desktop-linux.sh"
|
||||
|
||||
# Arch Linux package (.pkg.tar.zst via makepkg) into ./dist
|
||||
arch-build:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.arch
|
||||
container_name: jellytau-arch-build
|
||||
volumes:
|
||||
- ./dist:/out
|
||||
environment:
|
||||
- RUST_BACKTRACE=1
|
||||
- OUTPUT_DIR=/out
|
||||
|
||||
# Windows cross-compile (MSVC via cargo-xwin). Emits NSIS installer + .exe to
|
||||
# ./dist. Override WIN_BUNDLES=none for exe-only.
|
||||
windows-cross:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
target: windows-cross
|
||||
args:
|
||||
BUILDER_IMAGE: ${BUILDER_IMAGE:-gitea.tourolle.paris/dtourolle/jellytau-builder:latest}
|
||||
container_name: jellytau-windows-cross
|
||||
volumes:
|
||||
- .:/app
|
||||
- cargo-cache:/root/.cargo
|
||||
- bun-cache:/root/.bun
|
||||
environment:
|
||||
- RUST_BACKTRACE=1
|
||||
- OUTPUT_DIR=/app/dist
|
||||
- WIN_BUNDLES=${WIN_BUNDLES:-nsis}
|
||||
command: bash -c "OUTPUT_DIR=/app/dist WIN_BUNDLES=${WIN_BUNDLES:-nsis} scripts/build-windows-cross.sh"
|
||||
|
||||
# Development container - for interactive development
|
||||
dev:
|
||||
build:
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
# Desktop packaging (Linux, Arch, Windows)
|
||||
|
||||
How to produce distributable desktop packages for JellyTau. All three flows can
|
||||
run in Docker so no host toolchain setup is required. Outputs land in `./dist`.
|
||||
|
||||
## One builder image (shared with CI)
|
||||
|
||||
The deb/rpm and Windows-cross flows build on the **unified registry builder**
|
||||
([../Dockerfile.builder](../Dockerfile.builder) →
|
||||
`gitea.tourolle.paris/dtourolle/jellytau-builder`), the same image CI uses. It
|
||||
carries every packaging tool: Android SDK/NDK, `rpm`/`file` (Linux bundler),
|
||||
`cargo-xwin` + `lld` + `llvm` + `nsis` + the `x86_64-pc-windows-msvc` rust target
|
||||
(Windows). There is **one** dependency source of truth — no per-stage tool
|
||||
installs.
|
||||
|
||||
The desktop stages in [../Dockerfile](../Dockerfile) are thin `FROM
|
||||
${BUILDER_IMAGE}` environments; the actual build runs at container-run time on
|
||||
your bind-mounted source (like the `dev` service), so source edits need no image
|
||||
rebuild.
|
||||
|
||||
**If you changed `Dockerfile.builder`** (e.g. added a tool), rebuild and push it
|
||||
first, or the packaging flows use the stale registry image:
|
||||
|
||||
```bash
|
||||
scripts/build-builder-image.sh # build + push :latest to the registry
|
||||
# ...or iterate locally without pushing:
|
||||
docker build -f Dockerfile.builder -t jellytau-builder:latest .
|
||||
BUILDER_IMAGE=jellytau-builder:latest bun run docker:build:windows
|
||||
```
|
||||
|
||||
Arch uses a separate `archlinux` image ([../Dockerfile.arch](../Dockerfile.arch))
|
||||
because `makepkg` is Arch-specific — it is not part of the unified builder.
|
||||
|
||||
| Target | Format | Docker command | Functional? |
|
||||
|--------|--------|----------------|-------------|
|
||||
| Debian/Ubuntu, Fedora | `.deb`, `.rpm` | `bun run docker:build:linux` | ✅ yes |
|
||||
| Arch Linux | `.pkg.tar.zst` | `bun run docker:build:arch` | ✅ yes |
|
||||
| Windows | NSIS installer + `.exe` | `bun run docker:build:windows` | ✅ yes (unsigned) |
|
||||
|
||||
## Linux: deb + rpm
|
||||
|
||||
Tauri's bundler produces these natively. The build runs on the existing Ubuntu
|
||||
builder image ([../Dockerfile](../Dockerfile), `desktop-linux-build` stage):
|
||||
|
||||
```bash
|
||||
bun run docker:build:linux # deb + rpm -> ./dist
|
||||
# or, on a host with the Tauri Linux deps installed:
|
||||
BUNDLES="deb,rpm" scripts/build-desktop-linux.sh
|
||||
```
|
||||
|
||||
Runtime dependency: the app links libmpv (audio) and WebKitGTK (webview + HTML5
|
||||
transcoded video). The deb/rpm declare these.
|
||||
|
||||
> Note: `appimage` is also a valid Tauri target if you want a portable bundle —
|
||||
> add it to `BUNDLES`.
|
||||
|
||||
## Arch Linux: pacman package
|
||||
|
||||
**Tauri has no `pacman` bundle target** (as of tauri-cli 2.9.x — valid targets
|
||||
are deb/rpm/appimage/msi/nsis/app/dmg). So we ship a hand-written PKGBUILD in
|
||||
[../packaging/arch/PKGBUILD](../packaging/arch/PKGBUILD) and build it with
|
||||
`makepkg` on an Arch base image ([../Dockerfile.arch](../Dockerfile.arch)):
|
||||
|
||||
```bash
|
||||
bun run docker:build:arch # .pkg.tar.zst -> ./dist
|
||||
```
|
||||
|
||||
The PKGBUILD is AUR-ready: swap its `source=()` for a release tarball/VCS URL to
|
||||
publish. Runtime deps: `webkit2gtk-4.1`, `mpv`, `gtk3`, `libayatana-appindicator`.
|
||||
|
||||
`makepkg` refuses to run as root, so the Docker stage builds as a non-root
|
||||
`builder` user. Because the image `COPY`s the source at build time, the
|
||||
`arch-build` compose service does **not** bind-mount the repo — rebuild the image
|
||||
to pick up source changes.
|
||||
|
||||
## Windows: NSIS installer cross-compiled from Linux
|
||||
|
||||
Produces a working (unsigned) NSIS installer + `.exe` via the official Tauri
|
||||
cross-compile path — the `x86_64-pc-windows-msvc` target driven by `cargo-xwin`.
|
||||
Video plays via WebView2 and audio via the webview `<audio>` backend. See
|
||||
[build-windows.md](build-windows.md) for the full explanation.
|
||||
|
||||
```bash
|
||||
bun run docker:build:windows # NSIS installer + .exe -> ./dist
|
||||
WIN_BUNDLES=none bun run docker:build:windows # exe only, skip bundling
|
||||
```
|
||||
|
||||
The Docker `windows-cross` stage is a thin layer over the builder, which carries
|
||||
`cargo-xwin` + `lld` + `llvm` + `nsis` + the `x86_64-pc-windows-msvc` target.
|
||||
Cross-compilation is Tauri's "last resort" path (less tested than building on
|
||||
Windows); a `windows-latest` CI job is the fallback if it misbehaves.
|
||||
@@ -0,0 +1,78 @@
|
||||
# Windows build
|
||||
|
||||
JellyTau targets Linux and Android primarily, but a working Windows build —
|
||||
including an **NSIS installer cross-compiled from Linux** — is produced by the
|
||||
Docker tooling. It is not yet a first-class release target (no code signing / CI
|
||||
job / SMTC lockscreen), but it runs and plays media.
|
||||
|
||||
## How playback works on Windows
|
||||
|
||||
- **Video** — renders through the webview HTML5 `<video>` element (hls.js) on
|
||||
*every* platform; on Windows that is WebView2 (Chromium/Edge), which plays HLS +
|
||||
h264 fine. No Windows-specific code.
|
||||
- **Audio-only (music)** — the native audio backends are libmpv (Linux) and
|
||||
ExoPlayer (Android); neither exists on Windows. Instead
|
||||
`create_player_backend()` in [../src-tauri/src/lib.rs](../src-tauri/src/lib.rs)
|
||||
uses `WebviewAudioBackend` on non-Linux/non-Android targets: it hands the stream
|
||||
URL to a webview `<audio>` element (see
|
||||
[../src/lib/services/webviewAudio.ts](../src/lib/services/webviewAudio.ts)),
|
||||
which reports state back through the same `player_report_*` round-trip the video
|
||||
path uses. Pure Rust + Tauri events.
|
||||
|
||||
## Cross-compiling from Linux (MSVC + cargo-xwin)
|
||||
|
||||
We use the [official Tauri cross-compile path](https://v2.tauri.app/distribute/windows-installer/):
|
||||
the **MSVC** target (`x86_64-pc-windows-msvc`) driven by
|
||||
[`cargo-xwin`](https://github.com/rust-cross/cargo-xwin), which downloads the MSVC
|
||||
CRT / Windows SDK headers and links with `lld`. MSVC is the target Tauri
|
||||
officially supports for Windows (mingw/GNU is not), and — unlike GNU — it lets the
|
||||
Tauri CLI bundle the **NSIS installer from a Linux host**.
|
||||
|
||||
> Why not mingw/GNU? The GNU target *does* link a valid `.exe`, but the Tauri CLI
|
||||
> gates `--bundles` by the host OS unless it recognizes a real Windows build.
|
||||
> `--runner cargo-xwin --target x86_64-pc-windows-msvc` is what flips it into
|
||||
> Windows mode and enables the `nsis`/`msi` bundlers on Linux.
|
||||
|
||||
The builder image ([../Dockerfile.builder](../Dockerfile.builder)) bakes in the
|
||||
whole toolchain: the `x86_64-pc-windows-msvc` rust target, `cargo-xwin`, `lld`,
|
||||
`llvm`, and `nsis`.
|
||||
|
||||
```bash
|
||||
bun run docker:build:windows # NSIS installer + .exe -> ./dist
|
||||
WIN_BUNDLES=none bun run docker:build:windows # exe only, skip bundling
|
||||
```
|
||||
|
||||
Or directly on a host that has the toolchain:
|
||||
|
||||
```bash
|
||||
scripts/build-windows-cross.sh # nsis installer + exe
|
||||
WIN_BUNDLES=none scripts/build-windows-cross.sh # exe only
|
||||
```
|
||||
|
||||
Under the hood the build runs:
|
||||
|
||||
```bash
|
||||
tauri build --runner cargo-xwin --target x86_64-pc-windows-msvc --bundles nsis
|
||||
```
|
||||
|
||||
Outputs:
|
||||
- `.exe` — `src-tauri/target/x86_64-pc-windows-msvc/release/jellytau.exe`
|
||||
- NSIS installer — `.../release/bundle/nsis/*-setup.exe`
|
||||
|
||||
(both copied to `./dist` when `OUTPUT_DIR` is set).
|
||||
|
||||
## Caveats
|
||||
|
||||
- **Cross-compilation is a last resort** per Tauri's own docs — it's less tested
|
||||
than building on Windows. If it misbehaves, a `windows-latest` CI job or a
|
||||
Windows VM building natively (`tauri build --bundles nsis`) is the fallback.
|
||||
- **Code signing is not wired up** — the installer is unsigned, so Windows
|
||||
SmartScreen will warn on first run.
|
||||
|
||||
## Outstanding for a first-class Windows release
|
||||
|
||||
1. Gapless/crossfade + SMTC (lockscreen) — currently no-ops in the webview audio
|
||||
path.
|
||||
2. Downloaded (`Local` source) file playback needs `convertFileSrc` on the
|
||||
frontend; streaming works today.
|
||||
3. Code signing + a Windows packaging CI job.
|
||||
+105
-33
@@ -37,11 +37,11 @@ For a narrative overview of the system design, see
|
||||
| UR-024 | View recently added content on server | Medium | Done |
|
||||
| UR-025 | Sync watch history and progress back to Jellyfin | High | Done |
|
||||
| UR-026 | Sleep timer for audio and video playback (roller UI, time/track/episode modes) | Low | Done |
|
||||
| UR-027 | Audio equalizer for sound customization | Low | Planned |
|
||||
| UR-027 | Audio equalizer for sound customization | Low | Done (Linux only) |
|
||||
| UR-028 | Navigate to artist/album by tapping names in now playing view | High | Done |
|
||||
| UR-029 | Toggle between grid and list view in library | Medium | Done |
|
||||
| UR-030 | Quick genre browsing and filtering | Medium | Done |
|
||||
| UR-031 | Crossfade between audio tracks | Low | Done (Linux only) |
|
||||
| UR-031 | Crossfade between audio tracks | Low | Not implemented (blocked — see DR-034) |
|
||||
| UR-032 | Gapless playback for seamless album listening | Medium | Done (Linux only) |
|
||||
| UR-033 | Volume normalization to prevent volume jumps between tracks | Low | Done (Linux only) |
|
||||
| UR-034 | Rich home screen with hero banners, carousels, and personalized sections | High | Done |
|
||||
@@ -62,12 +62,19 @@ For a narrative overview of the system design, see
|
||||
| UR-049 | Search is scoped by where it was started — inside a library it searches that library, from Home/library-root/search-tab it searches everything — with the scope shown as filter chips under the search bar that preselect from context and can be changed without retyping (see [ux-flows.md §6.1](ux-flows.md)) | High | Implemented |
|
||||
| UR-050 | Reorder search result groups (Songs, Albums, Artists, Movies, TV Shows) by drag and drop in settings, so the media a user cares about most appears first (see [ux-flows.md §6.3](ux-flows.md)) | Medium | Implemented |
|
||||
| UR-051 | Browse library pages in a consistent layout where card shape signals media type (square music, poster video, thumbnail episode), ordinal content stays listed, and the grid/list preference persists across pages (see [ux-flows.md §5A](ux-flows.md)) | Medium | Partial (implemented; toggle not reachable from settings) |
|
||||
| UR-052 | While offline, library pages show only media available on the device by default, with an opt-in toggle that additionally reveals the cached server catalog as greyed-out entries which can be queued for download on the next reconnect | High | Broken (toggle does not gate the listing; see issue #10) |
|
||||
| UR-052 | While offline, library pages show only media available on the device by default, with an opt-in toggle that additionally reveals the cached server catalog as greyed-out entries which can be queued for download on the next reconnect | High | Done |
|
||||
| UR-053 | Restrict media downloads to unmetered networks via a "WiFi Only" setting: when enabled, queued downloads are held while the device is on cellular or a metered connection (including metered WiFi hotspots) and resume automatically once an unmetered network is available | Medium | Done (pending device verification) |
|
||||
| UR-054 | Reach account actions (Settings, Downloads, Display preferences, Sign out) from every authenticated screen via a single account menu anchored to the user's name, identical on desktop and mobile (see [ux-flows.md §1.2](ux-flows.md)) | High | Done |
|
||||
| UR-055 | Browse downloaded media as an offline-scoped library — reusing the same library grids, cards, and detail pages as online browsing, showing only libraries/containers with downloaded content — with the transfer-progress list demoted to a secondary "Transfers" view (see [ux-flows.md §7.2](ux-flows.md)) | High | Planned |
|
||||
| UR-056 | See how much disk each downloaded item/album/series consumes, in familiar rounded units shown on the card and detail page, with a device total on the Downloaded surface and a reclaim amount stated at the point of removal (see [ux-flows.md §7.3.1](ux-flows.md)) | Medium | Planned |
|
||||
| UR-055 | Browse downloaded media as an offline-scoped library — reusing the same library grids, cards, and detail pages as online browsing, showing only libraries/containers with downloaded content — with the transfer-progress list demoted to a secondary "Transfers" view (see [ux-flows.md §7.2](ux-flows.md)) | High | Done |
|
||||
| UR-056 | See how much disk each downloaded item/album/series consumes, in familiar rounded units shown on the card and detail page, with a device total on the Downloaded surface and a reclaim amount stated at the point of removal (see [ux-flows.md §7.3.1](ux-flows.md)) | Medium | Done |
|
||||
| UR-057 | Settings apply the instant a control is changed — no "Save" button and no save/dirty state — so leaving the page never loses a change; sliders show a live readout while dragging but persist on release (see [ux-flows.md §8.1](ux-flows.md)) | Medium | Done |
|
||||
| UR-058 | On the home screen, a tap on a media card opens the item (movie/episode detail page, or the series Episode Focus View for episodes) rather than starting playback; a long-press starts "play now" after a confirm; an episode detail/focus page links back to its parent series and season (see [ux-flows.md §5B.5](ux-flows.md) and [§5B.1](ux-flows.md)) | Medium | Done |
|
||||
| UR-059 | Skipping to the next episode records the episode left behind as **fully watched** rather than saving a mid-episode resume point — skipping means "done with this one", not "stopped here" — and Continue Watching hides episodes the viewer has already moved past (a partial position behind that series' next-up episode), so the row only ever offers genuinely unfinished media | Medium | Done |
|
||||
| UR-060 | Search results are ordered by how well they match: a name that *starts* with the query outranks one matching mid-word (typing "parks" finds "Parks and Recreation" before "Sparks of Love"), and at equal match quality a container outranks its contents (a series before its episodes). Results are grouped into distinct categories — TV Shows, Episodes, Movies, Songs, Albums, Artists and People — so a show never competes with its own episodes for the same slot, and searching an actor's name reaches their bio | High | Done |
|
||||
| UR-061 | Double tapping the video skips within it — right half jumps **forward 30 seconds**, left half jumps **back 10 seconds** — with an on-screen indicator naming the amount. A double tap leaves the play state unchanged — playing jumps and keeps playing, paused jumps and stays paused — because the second tap re-toggles what the first tap toggled (see DR-098); the skip lands relative to the position the player actually reports, and repeated double taps accumulate rather than all skipping from the same spot | Medium | Done |
|
||||
| UR-062 | Opening a TV series lands the viewer **where they are in it**, not at season 1: the series page scrolls the current season into view and highlights the current episode, and the hero button opens that episode (labelled `Resume S2E4` / `Play S1E1`). "Current" means the episode in progress, else the server's Next Up for that series, else the first unwatched episode, else the first — resolved by the backend so it also works offline. A season is **never a page of its own**: every route that names a season lands on the series with that season in view, so the episodes of all seasons are always one continuous scrollable list | High | Done |
|
||||
| UR-063 | Each video library is **one page**, not three. Browsing (hero, Continue Watching, Next Up, Recently Added, genre rows), the full title grid, and the genre browser are tabs of `/library/tv` and `/library/movies` rather than separate routes with inconsistent names (`/library/tv/shows` vs `/library/movies/all`, `/library/shows/genres` vs `/library/movies/genres`). The old routes redirect so existing links keep working | Medium | Done |
|
||||
| UR-064 | Watch history can be **erased**, per series and per season, from the series page. Clearing marks every episode inside unwatched and clears resume positions, so the show returns to "never watched" and reopens on its premiere. It asks for confirmation first (it cannot be undone) and requires a connection to the server, since history cleared only locally would be undone by the next sync | Medium | Done |
|
||||
|
||||
---
|
||||
|
||||
@@ -99,7 +106,7 @@ External system integrations and platform-specific implementations.
|
||||
| IR-017 | Jellyfin API client for transcoding parameters | API | UR-022 | Planned |
|
||||
| IR-018 | libmpv subtitle rendering and selection | Playback | UR-020 | Planned |
|
||||
| IR-019 | libmpv audio track selection | Playback | UR-021 | Planned |
|
||||
| IR-020 | libmpv/ExoPlayer equalizer integration | Playback | UR-027 | Planned |
|
||||
| IR-020 | libmpv/ExoPlayer equalizer integration | Playback | UR-027 | Done (Linux/MPV; Android parity pending) |
|
||||
| IR-022 | Jellyfin API client for person/cast data | API | UR-035, UR-036 | Done |
|
||||
| IR-023 | Database schema for person/cast caching | Storage | UR-035, UR-036 | Done |
|
||||
| IR-024 | Jellyfin API client for home screen data (featured, continue watching) | API | UR-034 | Done |
|
||||
@@ -185,11 +192,11 @@ Internal architecture, components, and application logic.
|
||||
| DR-029 | Sleep timer with roller UI, time/track/episode modes, and auto-stop (audio + video players) | Player | UR-026 | Done |
|
||||
| DR-049 | Auto-play episode limit (configurable max episodes per session) | Player | UR-023 | Done |
|
||||
| DR-050 | Reusable scroll picker (roller) component | UI | UR-026 | Done |
|
||||
| DR-030 | Equalizer UI with presets and custom bands | UI | UR-027 | Planned |
|
||||
| DR-030 | Equalizer UI with presets and custom bands | UI | UR-027 | Done |
|
||||
| DR-031 | Clickable artist/album links in now playing view | UI | UR-028 | Done |
|
||||
| DR-032 | List view option for library browsing (albums, artists) | UI | UR-029 | Done |
|
||||
| DR-033 | Genre browsing screen with quick filters | UI | UR-030 | Done |
|
||||
| DR-034 | Crossfade engine with configurable duration (0-12s) | Player | UR-031 | Done (Linux only) |
|
||||
| DR-034 | Crossfade engine with configurable duration (0-12s) | Player | UR-031 | Not implemented (blocked on MPV: single-stream audio chain; `acrossfade` needs 2 inputs — see docs/specs/playback-backend-unification.md) |
|
||||
| DR-035 | Gapless playback between sequential tracks | Player | UR-032 | Done (Linux only) |
|
||||
| DR-036 | Volume normalization with preset levels (Loud/Normal/Quiet) | Player | UR-033 | Done (Linux only) |
|
||||
| DR-037 | Remote session browser and control UI | UI | UR-010 | Done |
|
||||
@@ -216,10 +223,10 @@ Internal architecture, components, and application logic.
|
||||
| DR-060 | Multi-server store and active-account selection: save/get/delete server, save/get user, set/get active user (per-server), active-session resolution | Storage | UR-047 | Partial (store done; server-switcher UI pending) |
|
||||
| DR-061 | Episode Focus View: episode hero followed *immediately* by the "More Episodes" strip — a forward-biased window (~3 before / ~6 after) around the current episode, spanning season boundaries in series order, with the current episode present and badged, per-card resume progress and watched state, and click-to-swap focus (no playback) | UI | UR-048 | Done |
|
||||
| DR-062 | Detail-page section ordering: continuation content precedes discovery content — Episode Focus View renders hero → episode strip → cast → similar; Series renders hero → seasons/episodes → cast → similar | UI | UR-048 | Done |
|
||||
| DR-063 | Search scope resolver mapping the originating route to an `includeItemTypes` set (All / Music / Movies / TV), defaulting to All for Home, `/library`, and the search tab | UI | UR-049 | Implemented |
|
||||
| DR-063 | Search scope taxonomy owned by Rust: `SearchScope` (All / Music / Movies / TV) crosses IPC as an opaque enum and `SearchScope::item_types()` expands it to Jellyfin item types, resolved once in `repository_search` before the cache and server paths diverge so online and offline filter identically; `All` expands to *no* filter rather than the union of the other scopes (which would drop People and folders). The frontend maps the originating route to a scope (`resolveSearchScope`, presentation) and never names an item type for search | Backend | UR-049 | Implemented |
|
||||
| DR-064 | Scope chip row rendered under the search bar on both the search page and the in-library header search: preselected from context, horizontally scrollable, re-runs the search preserving the query on change | UI | UR-049 | Implemented |
|
||||
| DR-065 | Thread `SearchOptions.includeItemTypes` through `library.search()` so the global/header search honours scope (backend online + offline paths already support it) | UI | UR-049 | Implemented |
|
||||
| DR-066 | Persisted search result group order with a drag-and-drop settings list, keyboard-accessible reordering, a shipped default (Songs → Albums → Artists → Movies → TV Shows), and empty-group omission | Settings | UR-050 | Implemented |
|
||||
| DR-066 | Persisted search result group order with a drag-and-drop settings list, keyboard-accessible reordering, a shipped default (see DR-091 for the current group set and order), and empty-group omission | Settings | UR-050 | Implemented |
|
||||
| DR-067 | `SearchResults` renders groups in the user-configured order rather than hardcoded markup order, without altering intra-group ranking | UI | UR-050 | Implemented |
|
||||
| DR-068 | Library card shape by media type: 1:1 square for music (circular mask for artists), 2:3 poster for movies/series/seasons, 16:9 for episodes and collection folders | UI | UR-051 | Done |
|
||||
| DR-069 | Responsive library grid (2/3/4/5/6 columns across base→xl) with two-line truncated card text and artwork-overlay progress/watched state | UI | UR-051 | Done |
|
||||
@@ -227,16 +234,37 @@ Internal architecture, components, and application logic.
|
||||
| DR-075 | Shared `AccountMenu` component: identity header (user + server), Downloads / Settings / Display entries, divider, Sign out last; anchored to the username/avatar trigger and identical on desktop and mobile | UI | UR-054 | Done |
|
||||
| DR-076 | App shell exposes the header (and therefore the account menu) on every authenticated non-immersive route, including `/`, `/search`, and `/downloads`; only `/player/*` and `/login` remain chrome-free | UI | UR-054 | Done |
|
||||
| DR-077 | Display section in Settings binding the existing persisted grid/list `viewMode` store, giving the preference a discoverable home | Settings | UR-054, UR-029 | Done |
|
||||
| DR-078 | Catalog-visibility gate spanning the "Show all server media" toggle → `set_show_server_catalog` → `INCLUDE_CATALOG_BROWSE` → the synced-catalog UNION branch of offline `get_items`. Visibility resolves to `serverReachable \|\| showServerCatalog`, so offline with the toggle off lists downloaded/local media only | Storage | UR-052, UR-002 | Partial (gate implemented and unit-tested; defeated upstream by DR-079 and by the repository fallback in DR-080) |
|
||||
| DR-079 | `isConnected` derives from backend-reported server reachability alone; `navigator.onLine` is advisory and may only trigger a recheck, never force or clear the offline state (a reachable LAN server while the browser reports offline, and an unreachable server on a live link, must both resolve correctly) | Connectivity | UR-052, UR-043 | Broken (`isConnected` ANDs in `navigator.onLine`, so a live link with an unreachable server never enters offline listing) |
|
||||
| DR-080 | With the catalog-browse gate off, an empty offline `get_items` result is authoritative "no downloads here" and must be returned as-is; the hybrid repository must not treat it as a cache miss and fall through to the server | Storage | UR-052, UR-013 | Broken (`has_content()` cache-hit test in `HybridRepository::get_items`/`parallel_race` falls through to the server on an intentionally empty result) |
|
||||
| DR-078 | Catalog-visibility gate spanning the "Show all server media" toggle → `set_show_server_catalog` → `INCLUDE_CATALOG_BROWSE` → the synced-catalog UNION branch of offline `get_items`. Visibility resolves to `serverReachable \|\| showServerCatalog`, so offline with the toggle off lists downloaded/local media only | Storage | UR-052, UR-002 | Done |
|
||||
| DR-079 | `isConnected` derives from backend-reported server reachability alone; `navigator.onLine` is advisory and may only trigger a recheck, never force or clear the offline state (a reachable LAN server while the browser reports offline, and an unreachable server on a live link, must both resolve correctly) | Connectivity | UR-052, UR-043 | Done |
|
||||
| DR-080 | With the catalog-browse gate off, an empty offline `get_items` result is authoritative "no downloads here" and must be returned as-is; the hybrid repository must not treat it as a cache miss and fall through to the server | Storage | UR-052, UR-013 | Done |
|
||||
| DR-074 | WiFi-only download gate: `NetworkState`/`NetworkType` transport model reported from the platform via `set_network_state`, checked in `pump_download_queue` before starting any pending row (cellular/metered/unknown fail closed, WiFi and Ethernet require `NOT_METERED`); blocked rows stay `pending` and re-pump on network change, with a `waitingForNetwork` event driving the "Waiting for WiFi" notice. Also wires the previously inert Smart Caching / Queue Pre-caching / WiFi Only settings toggles to `CacheConfig` | Downloads | UR-053 | Done (pending device verification) |
|
||||
| DR-081 | `/downloads` split into a default **Downloaded** browse view and a secondary **Transfers** activity view, with a view switch and a Transfers badge shown only while transfers are active | UI | UR-055 | Planned |
|
||||
| DR-082 | Offline-scoped browse entry point in the repository client: browse downloaded content only (offline repository `get_items`/`get_libraries` — downloaded items plus their containers) independent of server reachability, without merging server catalog | Storage | UR-055 | Planned |
|
||||
| DR-083 | Downloaded browse reuses library grids, cards, and detail pages via the offline-scoped source; omits libraries/containers with no downloaded content; badges partially- vs fully-downloaded containers; play uses the local file; remove available at item/album/season/series level | UI | UR-055 | Planned |
|
||||
| DR-084 | Transfers view renders only in-flight rows (downloading/queued/paused/failed/waiting-for-WiFi) with Pause/Resume/Cancel/Retry; completed transfers leave the view and appear in Downloaded | UI | UR-055 | Planned |
|
||||
| DR-085 | Per-item on-disk size: stat downloaded files, aggregate to album/season/series subtotals and a device total, format in consistent rounded human units; surface size on cards and detail pages, the device total on the Downloaded surface, and a reclaim figure in the remove confirmation | Downloads | UR-056 | Planned |
|
||||
| DR-081 | `/downloads` split into a default **Downloaded** browse view and a secondary **Transfers** activity view, with a view switch and a Transfers badge shown only while transfers are active | UI | UR-055 | Done |
|
||||
| DR-082 | Offline-scoped browse entry point in the repository client: browse downloaded content only (offline repository `get_items`/`get_libraries` — downloaded items plus their containers) independent of server reachability, without merging server catalog | Storage | UR-055 | Done |
|
||||
| DR-083 | Downloaded browse reuses library grids, cards, and detail pages via the offline-scoped source; omits libraries/containers with no downloaded content; badges partially- vs fully-downloaded containers; play uses the local file; remove available at item/album/season/series level | UI | UR-055 | Done |
|
||||
| DR-084 | Transfers view renders only in-flight rows (downloading/queued/paused/failed/waiting-for-WiFi) with Pause/Resume/Cancel/Retry; completed transfers leave the view and appear in Downloaded | UI | UR-055 | Done |
|
||||
| DR-085 | Per-item on-disk size: stat downloaded files, aggregate to album/season/series subtotals and a device total, format in consistent rounded human units; surface size on cards and detail pages, the device total on the Downloaded surface, and a reclaim figure in the remove confirmation | Downloads | UR-056 | Done |
|
||||
| DR-086 | Settings page persists each control on change via per-group writers (`playerSetAudioSettings` / `playerSetVideoSettings` / `updateCacheConfig`) rather than a batch Save action; slider controls persist on `change` (pointer release) not each `input` tick; no Save button, `saving`, or `saveMessage` state | Settings | UR-057 | Done |
|
||||
| DR-087 | `MediaCard` gains an `onLongPress` prop with pointer-based long-press detection (~500 ms hold, cancelled on >10 px move so carousel scroll is unaffected, trailing click suppressed); home carousels wire tap→detail/focus routing and long-press→confirm→player; episode taps route to `/library/<seriesId>?episode=<id>`; the bare-episode detail page links to its parent series/season | UI | UR-058 | Done |
|
||||
| DR-088 | Skip-to-next-episode marks the outgoing episode played (`markAsPlayed`) instead of reporting a stop position, and arms a one-shot suppression consumed by the player's stop handler so `VideoPlayer`'s post-navigation unmount stop report cannot overwrite the 100% progress with the partial position | UI | UR-059 | Done |
|
||||
| DR-089 | Continue Watching suppresses resume entries superseded by Next Up: an in-progress episode whose series has a next-up entry strictly later in series order (season, then episode) is dropped from the Home and TV rows; movies, series without a next-up entry, and items with unknown/mixed episode ordering are always kept | UI | UR-059 | Done |
|
||||
| DR-090 | Relevance ranking in Rust (`domain/search_rank.rs`): results sort by match position (prefix → word-start → mid-word substring → no name match) then by media kind (containers before their contents), stably so the backend's own relevance breaks ties. Applied in `repository_search` to both the instant cache result and the merged cache+server union, so the list does not reshuffle when server results land | Backend | UR-060 | Done |
|
||||
| DR-091 | Search result groups split TV into separate Shows and Episodes groups and add a People group (default order: Shows → Episodes → Movies → Songs → Albums → Artists → People); a stored `tvShows` order from before the split expands in place to shows+episodes so an upgrading user keeps their arrangement | UI | UR-060 | Done |
|
||||
| DR-092 | Video tap gestures resolve in `tapGestures.ts` (pure, unit-tested) rather than inline in `VideoPlayer.svelte`: `registerTap` classifies each tap and the component acts on it immediately — `togglePlayPause` for a first tap, or `seek` (+30 s right / −10 s left) plus a re-toggle for a second tap inside `DOUBLE_TAP_WINDOW_MS` (300 ms). A consumed pair resets the state, and a swipe forgets the tap. The deferral this originally used was removed in DR-098, which also covers suppressing the compatibility `click` the browser synthesizes after a touch tap. `resolveSeekTarget` converts the delta to the absolute position the facade requires, clamped per DR-095 and chained off a still-in-flight `pendingSeekTarget` so back-to-back skips accumulate instead of all resolving against a not-yet-updated position | UI | UR-061 | Done |
|
||||
| DR-094 | Frontend boundary tripwire (`scripts/check-frontend-boundary.sh`) detects Jellyfin item-type array literals **anywhere** in `src/` rather than only inline at an `includeItemTypes:` query site, so a category→type mapping cannot evade the check by being assigned to a named const (the evasion that let the `scoped-search` leak pass CI); requires two adjacent type literals so single-type presentation and `item.type ===` inspection stay legal, and caps the allowlist to force taxonomy into Rust instead of accumulating exceptions | Tooling | - | Done |
|
||||
| DR-098 | Video tap gestures act **immediately** — no deferral, no timer, and only first/second taps exist. A first tap toggles play/pause; a second tap inside `DOUBLE_TAP_WINDOW_MS` seeks *and* toggles again, so the two toggles cancel and a double tap preserves the play state (playing → jump and keep playing; paused → jump and stay paused). This replaces a design that deferred the first tap behind a 300 ms timer so a second tap could cancel it: the timer cleared its own handle *before* invoking the toggle, which reopened the `tapTimeout !== null` guard in `handleVideoClick` meant to suppress the compatibility `click` Android's WebView synthesizes after a touch — the late click then toggled a second time, producing a pause/unpause loop (long-press was unaffected, which is what identified the tap path). Click suppression no longer depends on the timer: `handleVideoClick` ignores `detail === 0` *and* any click within `TOUCH_CLICK_SUPPRESS_MS` of a touch tap. A swipe undoes the touchstart toggle exactly once (latched on `swipeGestureActive`) so brightness swipes never change play state. Click suppression is shared by **every** click target layered over the video via `isSynthesizedTouchClick`, not just the `<video>`: pausing renders a full-screen play-overlay button, so the synthesized click lands on *that* and an unguarded handler there resumed immediately — pausing appeared impossible while unpausing worked, because unpausing removes the overlay | UI | UR-061 | Done |
|
||||
| DR-099 | The video seek bar is usable by touch. Two Android-only defects made dragging or tapping it move the thumb without moving playback. (a) *Gesture hijack*: the container-level gesture layer skips `touchstart` on a control (DR-098) but kept handling `touchmove`, so a seek-bar drag was measured against the **previous** gesture's start point — a huge bogus vertical delta that read as a brightness swipe, dimmed the screen to the 0.3 floor, and fired a spurious play/pause "correction" mid-drag. A gesture is now latched at `touchstart` (`playerGestureActive`) and `touchmove` ignores anything not latched, since re-checking the move target cannot recover a start point that was never recorded. (b) *Commit signal*: the seek was committed **only** from `change`, which Android's WebView does not reliably fire for a touch interaction on a range input — the thumb moved to the tapped position and no seek ever ran. `touchend`/`mouseup` now commit as well; `input` arms a one-shot latch so whichever release signal arrives first commits and the other is a no-op. `seekRelative` shares the same `commitSeek` entry point instead of fabricating a synthetic `change` event | UI | UR-005, UR-061 | Done |
|
||||
| DR-097 | Transport authority (play/pause/toggle) lives in Rust for **webview-rendered** media, not just native. The controller tracks the state the HTML5 element reports (`html5_playing`, fed by `report_html5_state`, which now *stores* rather than only re-emitting); `play`/`pause`/`toggle_playback` consult it and drive the element by emitting a `ControlCommand` that `playerEvents.handleControlCommand` executes against the active adapter. A `stopped`/`idle` report clears it so the native backend (MPV/ExoPlayer) regains authority for music. The frontend facade no longer short-circuits transport into the adapter: `adapter.toggle()` previously decided play-vs-pause by reading `el.paused` off the DOM, a value that flips transiently while an element buffers or settles a seek — so two intents ~150 ms apart read *different* values, performed *opposing* actions, and self-sustained a play/pause loop needing no further input (observed on Android with a fully-buffered `readyState=4 networkState=1` element). Same "backend decides, adapter executes the primitive" split as `player_seek_video` | Player | UR-005 | Done |
|
||||
| DR-096 | `Html5PlayerAdapter.play()` is resilient to stall recovery: an in-flight attempt is memoised so concurrent callers (UI plus hls.js gap-controller recovery) share one `element.play()` instead of stacking calls, and an `AbortError` ("play() request was interrupted by a call to pause()") is logged at debug rather than pushed to `host.onError`. The browser raises it whenever a pending play promise is superseded by a pause/seek/source change, which hls.js does routinely while nudging past a stall — reporting it surfaced a player error roughly once per second for the whole stall and left the UI stuck showing paused | Player | UR-005 | Done |
|
||||
| DR-095 | Seek targets clamp strictly *inside* the media (`clampSeekTarget`, `END_SEEK_MARGIN_SECONDS` = 6 s ≈ one HLS segment) instead of to the exact `duration`. Landing on the duration makes hls.js request the segment whose start time lies past the end of the media (e.g. a 6330.324 s item → segment 1055 starting at 6336.33 s), which Jellyfin never produces; the fetch times out and hls.js' gap-controller stalls at the last buffered position, presenting as "unpausing or skipping bounces straight back to paused". Applied on both seek paths — the relative-skip `resolveSeekTarget` and the seek-bar drag, whose range input `max` is the duration itself — and floored at 0 so media shorter than the margin still seeks to the start | UI | UR-061 | Done |
|
||||
| DR-100 | Leaving a video and re-entering it renders the **video** player, never the audio one. Both halves of the `/player/[id]` decision are pure and unit-tested in `playerSurface.ts`. (a) `shouldReuseActivePlayback` excludes video: the "already playing, just show the UI" shortcut (added for expanding the audio mini player) returns *before* a stream URL is fetched, which is fine for audio — the backend owns the stream and the route only mirrors it — but leaves `<VideoPlayer>` with nothing to render. Closing a webview-rendered video deliberately emits no `stopped` state (that would break the autoplay handoff, see DR-047), so the Rust controller still reports that movie/episode as its loaded media and re-entering the same item hit the shortcut. (b) `resolvePlayerSurface` maps video-without-a-stream-URL to `pending` (spinner) instead of falling through to `<AudioPlayer>`, so no future path can put video content in the audio surface. Video now always takes the full load path, which fetches the stream URL and applies the stored resume position | UI | UR-005 | Done |
|
||||
| DR-101 | "Where is this viewer in this series" is resolved in **Rust**, not the frontend. `repository_get_series_episodes` performs the season fan-out (`get_items(series_id)` → seasons → `get_items(season_id)`, plus the flat-series fallback for shows whose children are episodes rather than season folders) and returns them in series order — season index ascending, episode index ascending, specials (season 0) after every numbered season. `repository_get_series_current_episode` layers the pure policy `pick_current_episode` over that list: an **in-progress** episode wins (earliest in series order on a tie — it is literally where playback stopped, and Next Up would skip past it), then the server's **Next Up** for that series, then the **first unwatched** episode, then the first. The third rung is the offline path, not dead code: `OfflineRepository::get_next_up_episodes` returns an empty vec, so without it the feature would be online-only. A failing Next Up or resume lookup degrades to empty rather than failing the call. `repository_get_next_up_episodes` had accepted a `series_id` since it was written and **no caller had ever passed one** | Repository | UR-062 | Done |
|
||||
| DR-102 | The series detail page anchors on that answer. It calls `repositoryGetSeriesEpisodes` once instead of fanning out over seasons in TypeScript (the fan-out *and* its flat-series fallback were domain knowledge in the presentation layer), groups the returned episodes under season headers by `parentIndexNumber`, and passes the resolved current episode to `SeasonSection` → `EpisodeRow`, which renders a highlight ring and scrolls itself into view. The hero button navigates to `/library/<seriesId>?episode=<currentId>` — the Episode Focus View, where an explicit Play/Resume commits — per ux-flows §5B.5: Play on a *container* is navigation, Play on a *leaf* commits. It previously resolved `$libraryItems[0]`, the first **season** by `SortName`, and navigated to `/player/<seasonId>`, which the player route bounced back to `/library/<seasonId>` — so Play on a series played nothing and landed on the season-1 page | UI | UR-062 | Done |
|
||||
| DR-103 | A season is not a destination. `/library/<seasonId>` redirects to `/library/<seriesId>#season-<indexNumber>`, the anchor `SeasonSection` renders, so a season link scrolls the series' continuous episode list rather than opening a page. Every inbound link follows: the episode breadcrumb, `handleItemClick case "season"`, the TV landing page's `case "Season"`, and `DownloadedBrowse`. A season carrying no `seriesId` (deep link into a stale cache) still renders the generic view so the user is never stranded. This removes a surface that had no route of its own — it fell through the detail page's `kind` chain to the generic "Contents" poster grid, contradicting ux-flows §5A.2 (episodes must be a row list), and clicking an episode there opened a bare Episode page, which §5B.1 forbids | UI | UR-062 | Done |
|
||||
| DR-104 | The "More Episodes" strip spans the **whole series** in series order, per ux-flows §5B.2's cross-season continuity rule: at the end of a season the window runs on into the next season's first episodes instead of dead-ending. `adjacentEpisodes` previously filtered the pool to `parentIndexNumber === current.parentIndexNumber` and sorted by `indexNumber` alone, so the window could never leave the current season — and, when episodes of several seasons did reach it, sorting by episode number alone interleaved them. Cards crossing a season boundary are labelled `SxEy` rather than a bare episode number so the jump is legible | UI | UR-062 | Done |
|
||||
| DR-105 | Video library routes collapse to one per library. `/library/tv` and `/library/movies` render browse / all-titles / genres as in-page tabs driven by `?view=`, omitted for the default `browse` (the convention `searchRouteUrl` already uses for the `all` scope); `resolveLibraryView` is pure and unit-tested. The four legacy routes become redirect-only `+page.ts` loads rather than deletions, because `GenreTags` links to them and users have them in history; `resolveSearchScope` keeps its `/library/shows` branch for the same reason. The "Browse" tile grid at the bottom of both landing pages is removed — it was a second navigation affordance to the same destinations the carousels' "Show all" links already reach | UI | UR-063 | Done |
|
||||
| DR-106 | Erasing watch history goes through the repository, not the local cache: `clear_watch_history(item_id)` maps to Jellyfin's `DELETE /Users/{userId}/PlayedItems/{itemId}`, which clears the played flag *and* zeroes the resume position, and which the server applies recursively to a folder — so one call handles a whole series or season. `OfflineRepository` returns `RepoError::Offline` rather than clearing locally, because history diverged only on the device would be silently undone by the next sync; the button disables itself while the server is unreachable. `ClearHistoryButton` is shared by the series hero and each `SeasonSection` header, confirms before acting (there is no undo), and reloads the page on success so the recomputed current episode — the premiere, for a fully cleared series — is what the viewer sees | Repository | UR-064 | Done |
|
||||
| DR-107 | Seasons on the series page are collapsible, and **only the current season is expanded** on load — the one holding the episode DR-101 resolved. A show with ten seasons otherwise renders every episode of every season at once, burying the one episode the viewer came for under hundreds of rows. Expansion state is per season and pure (`initialExpandedSeasons` in `seriesNavigation.ts`): the current season, or the first season when there is no current episode, so a never-watched show still opens on season 1 rather than fully collapsed. A `?episode=` deep link expands that episode's season too. Toggling is local and not persisted — it is a reading position, not a preference | UI | UR-062 | Done |
|
||||
| DR-093 | Traceability coverage gate derives its requirement denominators from `requirements.md` at run time rather than hardcoded literals: `countDefinedRequirements` counts an ID only where it leads a markdown table row (ignoring the "Traces To" column and prose) and deduplicates IDs listed both in the definition tables and in the §3 traceability matrix; `computeCoverage` reports the *intersection* of traced and defined IDs so an ID traced in code but absent from `requirements.md` is surfaced as `orphaned` instead of inflating the ratio past 100%. UT/IT test identifiers are excluded as a separate taxonomy. CI and `bun run traces:coverage` share this computation and fail on both a sub-threshold and an impossible >100% result | Tooling | - | Done |
|
||||
|
||||
---
|
||||
|
||||
@@ -303,6 +331,12 @@ Internal architecture, components, and application logic.
|
||||
| UR-055 | - | DR-081, DR-082, DR-083, DR-084 |
|
||||
| UR-056 | - | DR-085 |
|
||||
| UR-057 | - | DR-086 |
|
||||
| UR-058 | - | DR-087 |
|
||||
| UR-060 | - | DR-090, DR-091 |
|
||||
| UR-061 | - | DR-092 |
|
||||
| UR-062 | - | DR-101, DR-102, DR-103, DR-104, DR-107 |
|
||||
| UR-063 | - | DR-105 |
|
||||
| UR-064 | - | DR-106 |
|
||||
|
||||
---
|
||||
|
||||
@@ -373,11 +407,35 @@ Internal architecture, components, and application logic.
|
||||
| UT-059 | Audio-only stream URL builder for a video item (selected audio-stream index) | JA-032, DR-052 | Pending |
|
||||
| UT-060 | Background-audio handoff state machine (background→audio, foreground→video; no dual audio) | DR-052 | Pending |
|
||||
| UT-061 | Background-audio Tauri command param naming (camelCase) | DR-052 | Pending |
|
||||
| UT-062 | `setBackgroundAudioEnabled` reports whether the native bridge was actually reached (missing bridge, stale proxy, throwing method) so a dead bridge cannot look armed | UR-040, IR-025, DR-051 | Done |
|
||||
| UT-067 | Offline `get_items` gates the synced-catalog UNION on the catalog-browse flag (downloads only when off, full catalog when on) | DR-078 | Done |
|
||||
| UT-068 | Catalog visibility resolves to `serverReachable \|\| showServerCatalog`, and is pushed to the backend on every change of either input | DR-078, DR-079 | Pending |
|
||||
| UT-069 | `isConnected` follows backend reachability alone: false when the server is unreachable on a live link, true for a reachable server while `navigator.onLine` is false | DR-079 | Pending |
|
||||
| UT-070 | Hybrid `get_items` returns an empty offline result as-is when the catalog-browse gate is off, without querying the server | DR-080 | Pending |
|
||||
| UT-068 | Catalog visibility resolves to `serverReachable \|\| showServerCatalog`, and is pushed to the backend on every change of either input | DR-078, DR-079 | Done |
|
||||
| UT-069 | `isConnected` follows backend reachability alone: false when the server is unreachable on a live link, true for a reachable server while `navigator.onLine` is false | DR-079 | Done |
|
||||
| UT-070 | Hybrid `get_items` returns an empty offline result as-is when the catalog-browse gate is off, without querying the server | DR-080 | Done |
|
||||
| UT-066 | WiFi-only download gate: cellular and metered WiFi blocked, unmetered WiFi/Ethernet allowed, unknown/none fail closed, desktop default ungated; plus the frontend network reporter (transport reporting, change subscription, teardown, fail-open queries) | DR-074 | Done |
|
||||
| UT-071 | Byte-size formatter: zero/negative/non-finite → "0 B"; decimal unit thresholds; 2–3 significant-figure banding; trailing-zero trimming; largest-unit cap | DR-085 | Done |
|
||||
| UT-072 | Downloaded-only browse returns a downloaded leaf and its container, filtered to the requested album parent; a non-downloaded sibling is omitted | DR-082, DR-083 | Done |
|
||||
| UT-073 | An empty downloaded-only browse is authoritative — no rows, no error — regardless of the catalog-browse flag | DR-082 | Done |
|
||||
| UT-074 | Only libraries with downloaded content are listed; an empty one is omitted | DR-082 | Done |
|
||||
| UT-075 | Disk usage reports a leaf's own size, a container's summed descendants, and reconciles the device total with the sum of leaves | DR-085 | Done |
|
||||
| UT-076 | Downloaded library browse lists album containers, not their individual tracks; drilling into the album returns the tracks | DR-082, DR-083 | Done |
|
||||
| UT-077 | Downloaded TV library browse lists the series, not seasons/episodes; drilling returns the season then the episode | DR-082, DR-083 | Done |
|
||||
| UT-078 | A downloaded leaf with no cached container (e.g. a movie) still surfaces at the library level | DR-082, DR-083 | Done |
|
||||
| UT-079 | Each EQ preset returns a 10-band gain curve within range; Flat is all zeros; Bass Boost lifts lows and leaves highs flat | DR-030 | Done |
|
||||
| UT-080 | `with_equalizer_normalised` clamps out-of-range gains and forces the band vector to exactly 10 entries (pad short, truncate long) | DR-030 | Done |
|
||||
| UT-081 | Old persisted AudioSettings JSON without EQ fields loads as disabled + flat | DR-030 | Done |
|
||||
| UT-082 | EQ fields serialize as camelCase (`equalizerEnabled`/`equalizerBands`) and round-trip | DR-030 | Done |
|
||||
| UT-083 | EQ filter entries are empty when disabled or when the curve is flat (clears the `af` filter) | IR-020 | Done |
|
||||
| UT-084 | Enabled EQ builds one peaking `equalizer` per non-zero band at the right frequency and gain inside a single `lavfi` chain | IR-020 | Done |
|
||||
| UT-085 | A first tap resolves to `togglePlayPause` immediately — no deferral and no timer | DR-092, DR-098 | Done |
|
||||
| UT-086 | A second tap inside the window seeks (+30 s right half, −10 s left half) with the matching feedback side **and** re-toggles play/pause, so the two toggles cancel and the play state is unchanged by a double tap | DR-092, DR-098 | Done |
|
||||
| UT-087 | A tap after the window, and the tap following a consumed pair, are each fresh first taps that toggle (there is no third-tap case); repeated double taps keep seeking; `cancel()` makes the next tap a first tap so an interpreted swipe cannot seek | DR-092, DR-098 | Done |
|
||||
| UT-088 | `resolveSeekTarget` applies the delta to the reported position, clamps into `[0, duration - END_SEEK_MARGIN_SECONDS]`, chains off an in-flight pending target so rapid skips accumulate, and ignores that target once the player reports past it | DR-092, DR-095 | Done |
|
||||
| UT-089 | A touch drag on the video seek bar seeks to the dragged position, never toggles play/pause, and never alters brightness — the container gesture layer stays out of a control drag entirely | DR-098, DR-099 | Done |
|
||||
| UT-090 | The seek bar commits its seek on `touchend` even when the engine never fires `change`, and commits exactly once when both signals arrive | DR-099 | Done |
|
||||
| UT-091 | Transport intents (play/pause/toggle) reach the backend even while a video adapter is registered, and never call the adapter's own `play`/`pause`/`toggle` — the webview must not decide play-vs-pause from the DOM | DR-097 | Done |
|
||||
| UT-092 | `shouldReuseActivePlayback` reuses backend playback for an already-loaded audio track but never for video, and never when an explicit start position or a next-episode restart was requested | DR-100 | Done |
|
||||
| UT-093 | `resolvePlayerSurface` returns `video` only with a stream URL, `pending` for video whose stream URL is still missing (never `audio`), and `audio` for audio content | DR-100 | Done |
|
||||
|
||||
### Integration Tests
|
||||
|
||||
@@ -396,8 +454,8 @@ Internal architecture, components, and application logic.
|
||||
| IT-011 | Resume playback from server position | IR-015, UR-019 | Pending |
|
||||
| IT-012 | Equalizer bands via libmpv | IR-020, UR-027 | Pending |
|
||||
| IT-013 | Background-audio handoff on Android: background/lock continues audio via native service and stops video decode; foreground resumes video at position | IR-025, UR-040 | Pending |
|
||||
| IT-016 | Offline library listing end-to-end: with the server unreachable, a library page lists only downloaded media with the toggle off, and additionally reveals greyed-out cached catalog entries with the toggle on | UR-052, DR-078, DR-079, DR-080 | Pending |
|
||||
| IT-017 | A download queued from a greyed-out offline catalog entry persists and is resolved and started on reconnect | UR-052, UR-011 | Pending |
|
||||
| IT-016 | Offline library listing end-to-end: with the server unreachable, a library page lists only downloaded media with the toggle off, and additionally reveals greyed-out cached catalog entries with the toggle on | UR-052, DR-078, DR-079, DR-080 | Done |
|
||||
| IT-017 | A download queued from a greyed-out offline catalog entry persists and is resolved and started on reconnect | UR-052, UR-011 | Done |
|
||||
|
||||
---
|
||||
|
||||
@@ -467,22 +525,36 @@ The `PlayerBackend` trait defines optional audio settings methods with default e
|
||||
| Basic playback | ✅ | ✅ | Parity |
|
||||
| Volume control | ✅ | ✅ | Parity |
|
||||
| Seek | ✅ | ✅ | Parity |
|
||||
| Crossfade | ✅ | ❌ | Gap |
|
||||
| Gapless playback | ✅ | ❌ | Gap |
|
||||
| Volume normalization | ✅ | ❌ | Gap |
|
||||
| Crossfade | ❌ | ❌ | Not implemented (blocked on MPV) |
|
||||
| Gapless playback | ✅ | ⚠️ | Implemented, pending on-device verification |
|
||||
| Volume normalization | ✅ | ⚠️ | Implemented (LoudnessEnhancer — gain stage, approximate vs MPV's dynaudnorm), pending on-device verification |
|
||||
| Equalizer (10-band) | ✅ | ⚠️ | Implemented (resampled onto device bands), pending on-device verification |
|
||||
| Position updates | 250ms | On-demand | Inconsistent |
|
||||
|
||||
**Future Fix**:
|
||||
1. Implement `set_audio_settings()` in `ExoPlayerBackend`
|
||||
2. Add Kotlin-side ExoPlayer configuration for crossfade (using `ConcatenatingMediaSource` or `DefaultMediaSourceFactory`)
|
||||
3. Implement gapless via ExoPlayer's built-in gapless support
|
||||
4. Add volume normalization via ExoPlayer's `LoudnessEnhancer` or audio processor
|
||||
5. Standardize position update frequency across platforms
|
||||
**Status** (see docs/specs/android-audio-settings-parity.md):
|
||||
1. ✅ `set_audio_settings()` implemented in `ExoPlayerBackend` (JSON over JNI)
|
||||
2. ✅ Gapless via ExoPlayer's `pauseAtEndOfMediaItems`
|
||||
3. ✅ Volume normalization via `LoudnessEnhancer`
|
||||
4. ✅ Equalizer via `android.media.audiofx.Equalizer`, canonical 10 bands
|
||||
resampled onto the device's band centres
|
||||
5. ⬜ **Not yet verified on a physical device** — the EQ/normalization effects
|
||||
depend on device-specific `AudioEffect` availability and band layouts
|
||||
6. ⬜ Flip the trait's `set_audio_settings` default from `Ok(())` to
|
||||
`Err(not_implemented())` so a backend that omits it fails loudly instead of
|
||||
silently reporting success. Deferred until (5) confirms the Android path works
|
||||
7. ⬜ Standardize position update frequency across platforms
|
||||
|
||||
Crossfade is deliberately absent: it is unimplemented on every platform and
|
||||
architecturally blocked on MPV, so building it on Android alone would invert the
|
||||
parity gap. (The previously suggested `ConcatenatingMediaSource` is also
|
||||
deprecated in current Media3.)
|
||||
|
||||
**Impact**:
|
||||
- Medium - Android users lack audio enhancement features advertised in requirements
|
||||
- User experience differs between platforms
|
||||
- UR-031 (Crossfade), UR-032 (Gapless), UR-033 (Normalization) only work on Linux
|
||||
- UR-032 (Gapless), UR-033 (Normalization) and UR-027 (Equalizer) are now
|
||||
implemented on Android as well as Linux, pending on-device verification
|
||||
- UR-031 (Crossfade) works nowhere — see DR-034
|
||||
|
||||
**Traces To**: IR-004, UR-031, UR-032, UR-033, DR-034, DR-035, DR-036
|
||||
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
# Spec: Android audio settings parity (EQ, normalization, gapless)
|
||||
|
||||
**Status:** Proposed
|
||||
**Requirements:** UR-031, UR-032, UR-033, UR-027 → DR-034, DR-035, DR-036, DR-030; IR-004
|
||||
**UX spec:** n/a — no UI change; Settings › Audio already renders these controls
|
||||
**Supersedes / revises:** closes the audio half of the parity gap recorded in [playback-backend-unification.md](playback-backend-unification.md)
|
||||
|
||||
## Summary
|
||||
|
||||
Implement `set_audio_settings` / `audio_settings` on `ExoPlayerBackend` so the
|
||||
equalizer, volume normalization, and gapless playback settings actually take
|
||||
effect on Android. Today the Settings › Audio panel renders these controls on
|
||||
Android and they silently do nothing — `ExoPlayerBackend` is the only backend
|
||||
that does not override the trait's no-op defaults.
|
||||
|
||||
Crossfade is explicitly **not** included; see Out of scope.
|
||||
|
||||
## Motivation
|
||||
|
||||
`PlayerBackend` declares `set_audio_settings` with a default `Ok(())` body.
|
||||
`MpvBackend`, `NullBackend`, and `WebviewAudioBackend` all override it;
|
||||
`ExoPlayerBackend` does not. The settings are persisted, pushed to the backend on
|
||||
every track load, and displayed in the UI — and then dropped on the floor.
|
||||
|
||||
This is the single most user-visible platform divergence in the app: a user who
|
||||
sets a "Rock" EQ preset on Android sees the sliders move and hears no change.
|
||||
|
||||
The backend-unification investigation ruled out fixing this by swapping engines
|
||||
(video cannot be unified; see the sibling spec), so the fix is to implement the
|
||||
trait methods where they are missing.
|
||||
|
||||
## Layer assignment
|
||||
|
||||
| Logic / responsibility | Layer | Why it belongs there |
|
||||
|------------------------|-------|----------------------|
|
||||
| Band count, centre frequencies, gain range, preset→curve map | Rust (existing) | Already domain-owned in `settings.rs` per [audio-equalizer.md](audio-equalizer.md). Android must consume the same `AudioSettings`, not define its own bands. Duplicating the band layout in Kotlin would be a taxonomy leak of exactly the kind `check:boundary` guards against. |
|
||||
| Mapping `AudioSettings` → Android audio-effect parameters | Rust → JNI boundary | Platform playback detail, the direct analogue of `build_af_filter` in `mpv_backend.rs`. Belongs with the other `set_audio_settings` code. |
|
||||
| Attaching/detaching `Equalizer` and `LoudnessEnhancer` to the ExoPlayer audio session | Kotlin (`JellyTauPlayer.kt`) | Android platform API mechanics; needs the live `audioSessionId`, which only the Kotlin layer holds. |
|
||||
| Normalization preset (Loud/Normal/Quiet) → target gain | Rust (existing) | `VolumeLevel` is domain vocabulary; the same preset must mean the same loudness on every platform. |
|
||||
| Rendering sliders / preset chips | Frontend (existing) | Pure presentation; unchanged by this spec. |
|
||||
|
||||
Borderline row: attaching the effects could arguably be driven entirely from
|
||||
Rust via JNI property calls. It goes to Kotlin because `AudioEffect` construction
|
||||
requires the audio session id and must be re-attached when ExoPlayer rebuilds its
|
||||
audio sink — lifecycle state that lives in `JellyTauPlayer.kt`. Rust still owns
|
||||
*what* the values are; Kotlin owns *when* the effect objects exist.
|
||||
|
||||
## Design
|
||||
|
||||
### Rust — `ExoPlayerBackend` (`src-tauri/src/player/android/mod.rs`)
|
||||
|
||||
Override the two defaulted methods, mirroring the shape of the existing
|
||||
`set_audio_track` JNI call:
|
||||
|
||||
```rust
|
||||
fn set_audio_settings(&mut self, settings: &AudioSettings) -> Result<(), PlayerError> {
|
||||
let s = settings.clone().with_crossfade_clamped().with_equalizer_normalised();
|
||||
// Serialize as JSON — the same pattern load() already uses for subtitles,
|
||||
// avoiding a 6-arg JNI signature that has to change every time a field lands.
|
||||
let json = serde_json::to_string(&s).map_err(|e| PlayerError { message: e.to_string() })?;
|
||||
// Kotlin: fun setAudioSettings(json: String)
|
||||
self.call_player_method_string("setAudioSettings", &json)?;
|
||||
self.shared_state.lock_safe().audio_settings = s;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn audio_settings(&self) -> AudioSettings {
|
||||
self.shared_state.lock_safe().audio_settings.clone()
|
||||
}
|
||||
```
|
||||
|
||||
`ExoPlayerState` gains an `audio_settings: AudioSettings` field. Note
|
||||
`ExoPlayerBackend` currently holds no such state — `position`/`state`/`volume` are
|
||||
all pushed in by JNI callbacks — so this is the first *pull*-side field. That is
|
||||
correct: audio settings are commanded downward, never reported upward.
|
||||
|
||||
### Kotlin — `JellyTauPlayer.kt`
|
||||
|
||||
```kotlin
|
||||
fun setAudioSettings(json: String) {
|
||||
val s = JSONObject(json)
|
||||
applyEqualizer(s.getBoolean("equalizerEnabled"), s.getJSONArray("equalizerBands"))
|
||||
applyNormalization(s.getBoolean("normalizeVolume"), s.getString("volumeLevel"))
|
||||
exoPlayer.pauseAtEndOfMediaItems = !s.getBoolean("gaplessPlayback")
|
||||
}
|
||||
```
|
||||
|
||||
Three independent mechanisms:
|
||||
|
||||
- **Gapless** — nearly free. ExoPlayer is gapless by default for compatible
|
||||
formats; honouring the setting means *disabling* it when the user turns it off,
|
||||
via `pauseAtEndOfMediaItems`. Note this only applies within a loaded playlist;
|
||||
our queue loads one item at a time, so verify behaviour before claiming DR-035
|
||||
on Android (see Testing).
|
||||
- **Equalizer** — `android.media.audiofx.Equalizer` bound to
|
||||
`exoPlayer.audioSessionId`. Android's EQ exposes a device-dependent band count
|
||||
(commonly 5) at fixed centre frequencies, which will **not** match our 10-band
|
||||
ISO layout. Rust owns the canonical 10 bands; Kotlin resamples them onto the
|
||||
device's bands by nearest-centre-frequency interpolation. Gains are in
|
||||
millibels (`setBandLevel` takes mB, we store dB → ×100), clamped to the
|
||||
device's reported `getBandLevelRange()`.
|
||||
- **Normalization** — `android.media.audiofx.LoudnessEnhancer`, also bound to the
|
||||
audio session, `setTargetGain(mB)` derived from `VolumeLevel`. This is a gain
|
||||
booster, not a true EBU R128 normalizer like MPV's `dynaudnorm`; parity is
|
||||
approximate and should be documented as such rather than overclaimed.
|
||||
|
||||
Lifecycle: build the effects lazily on first use, release them in `release()`,
|
||||
and re-attach on `onAudioSessionIdChanged` — ExoPlayer can rebuild its audio sink
|
||||
(e.g. on a format change), which invalidates effects bound to the old session.
|
||||
|
||||
### Make the silent-failure mode impossible
|
||||
|
||||
The trait's default is the root cause of this whole class of bug:
|
||||
|
||||
```rust
|
||||
// backend.rs:85 — reports success while doing nothing
|
||||
fn set_audio_settings(&mut self, _settings: &AudioSettings) -> Result<(), PlayerError> {
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
Android inherits this, so every EQ/normalization change on Android returns `Ok`
|
||||
and silently does nothing — the UI ships and has no effect, with no error anywhere.
|
||||
|
||||
Once `ExoPlayerBackend` implements the methods, **change the trait default to
|
||||
`Err(PlayerError::not_implemented())`**, matching how `set_audio_track` /
|
||||
`set_subtitle_track` already behave. Any future backend that forgets to implement
|
||||
audio settings then fails loudly instead of lying.
|
||||
|
||||
Check the call sites before flipping it: `NullBackend` overrides both methods, so
|
||||
the graceful-degradation path is unaffected, but confirm nothing treats a
|
||||
`set_audio_settings` error as fatal to playback.
|
||||
|
||||
### Re-application on track load
|
||||
|
||||
`PlayerController` already re-pushes `AudioSettings` per track on the platforms
|
||||
that implement it; the Android path inherits that for free once the trait methods
|
||||
exist. No controller change.
|
||||
|
||||
### 🔴 Threading note
|
||||
|
||||
`setAudioSettings` is invoked from Rust on whatever thread the command lands on.
|
||||
`AudioEffect` construction must not happen on the ExoPlayer application thread
|
||||
from inside a player callback — that is the re-entrancy hazard CLAUDE.md warns
|
||||
about, and the same shape as the `AutoplayDecision` deadlock. Post the work to
|
||||
the player's handler rather than doing it inline in a listener.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- **Crossfade (UR-031 / DR-034).** Not implemented on *any* platform today, and
|
||||
architecturally blocked on MPV (single-stream audio chain; `acrossfade` needs
|
||||
two inputs). Implementing it on Android alone would invert the parity gap. It
|
||||
needs its own spec and probably two player instances.
|
||||
- True EBU R128 normalization. `LoudnessEnhancer` is a gain stage; matching
|
||||
`dynaudnorm` exactly is out of reach without a custom `AudioProcessor`.
|
||||
- Windows audio settings — see [windows-native-audio-backend.md](windows-native-audio-backend.md).
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] `ExoPlayerBackend` overrides `set_audio_settings` and `audio_settings`.
|
||||
- [ ] EQ preset change on Android audibly changes playback; setting persists across track changes and app restart.
|
||||
- [ ] Normalization toggle audibly changes level; the three presets are ordered Loud > Normal > Quiet.
|
||||
- [ ] Disabling gapless produces a gap between consecutive tracks; enabling it does not.
|
||||
- [ ] Effects are released on `release()` and survive an audio-session rebuild.
|
||||
- [ ] `requirements.md` parity matrix updated: EQ and normalization ✅ Android.
|
||||
- [ ] `bun run check` and `bun run test` pass.
|
||||
- [ ] `cargo fmt` clean, `cargo clippy` clean, `bun run test:rust` passes.
|
||||
- [ ] `bun run check:boundary` passes.
|
||||
- [ ] New requirement-implementing code carries `// TRACES:` comments.
|
||||
- [ ] `bindings.ts` regenerated if Rust types changed.
|
||||
|
||||
## Testing
|
||||
|
||||
**Rust** (`cargo test`): `set_audio_settings` stores the sanitized settings and
|
||||
`audio_settings()` returns them — assert clamping/normalisation is applied
|
||||
(crossfade clamped to 12s, band vector normalised to `EQ_BANDS.len()`). The JNI
|
||||
call itself is not unit-testable; extract the JSON serialization into a pure
|
||||
function and test that its shape matches what the Kotlin parser expects. That
|
||||
serialization contract is the part most likely to silently break.
|
||||
|
||||
**Kotlin**: the band-resampling function (10 canonical bands → N device bands) is
|
||||
pure arithmetic — extract it and unit-test it, including the degenerate cases of
|
||||
a 5-band device and a device reporting 10 bands.
|
||||
|
||||
**Manual, on device** (these are the ones that actually prove it):
|
||||
1. Set Bass Boost, play a track, confirm audible change.
|
||||
2. Toggle normalization mid-track; confirm level change without a playback stall.
|
||||
3. Queue two gapless-encoded tracks, toggle the setting, confirm the gap appears/disappears.
|
||||
4. Force a format change (44.1kHz → 48kHz track) and confirm the EQ still applies afterwards — this exercises the session-rebuild re-attach.
|
||||
|
||||
## TRACES
|
||||
|
||||
- `ExoPlayerBackend::set_audio_settings` → `// TRACES: UR-027, UR-032, UR-033 | DR-030, DR-035, DR-036`
|
||||
- Kotlin `setAudioSettings` / `applyEqualizer` / `applyNormalization` → same IDs
|
||||
- Band-resampling helper + its tests → `DR-030 | UT-xxx`
|
||||
|
||||
## Notes for the implementer
|
||||
|
||||
- Read [audio-equalizer.md](audio-equalizer.md) first — it defines the canonical
|
||||
band layout and the preset→curve rule this spec consumes. Do not redefine bands
|
||||
in Kotlin.
|
||||
- Android source edits go in `src-tauri/android/src` (canonical tree), then run
|
||||
`scripts/sync-android-sources.sh`. Never edit the `gen/` tree.
|
||||
- There is a **stale duplicate** `JellyTauPlayer.kt` (285 lines) at
|
||||
`src-tauri/android/app/src/main/java/com/dtourolle/jellytau/player/` alongside
|
||||
the real 1103-line file at `src-tauri/android/src/main/java/...`. Edit the
|
||||
latter. Consider deleting the former as a separate change.
|
||||
- A parallel Claude session may be active — `git diff` before "repairing"
|
||||
unexpected changes.
|
||||
@@ -0,0 +1,196 @@
|
||||
# Spec: Android native video — transparent-webview spike
|
||||
|
||||
**Status:** Proposed (spike — timeboxed, may conclude "not viable")
|
||||
**Requirements:** IR-004, UR-003, UR-004 → DR-001, DR-023, DR-024
|
||||
**UX spec:** n/a — no intended visual change; the video surface must land exactly where the `<video>` element is today
|
||||
**Supersedes / revises:** acts on finding 2 of [playback-backend-unification.md](playback-backend-unification.md)
|
||||
|
||||
## Summary
|
||||
|
||||
Test whether ExoPlayer's existing `SurfaceView` video path can be composited
|
||||
behind a transparent Tauri WebView on Android. If it works, Android regains
|
||||
hardware video decoding (MediaCodec) and libass-quality ASS/SSA subtitles, both
|
||||
of which the current webview path lacks. If it does not, we document why and
|
||||
delete the dead code.
|
||||
|
||||
This is a **spike**, not a feature commitment. The deliverable is a yes/no answer
|
||||
with evidence, plus either a working path behind a flag or a removal.
|
||||
|
||||
## Motivation
|
||||
|
||||
`createAdapter()` hardcodes `const effectiveKind = "html5"` and does
|
||||
`void backendKind`, discarding the `use_html5_element` value Rust computes in
|
||||
`get_player_status`. As a result:
|
||||
|
||||
- `NativePlayerAdapter` is dead code.
|
||||
- `JellyTauPlayer.kt`'s `getOrCreateSurfaceView()` — which already calls
|
||||
`setZOrderMediaOverlay(false)` and wires `setVideoSurfaceHolder` — is
|
||||
unreachable.
|
||||
- Android video decodes in the WebView instead of via MediaCodec, despite
|
||||
`CodecDetector.kt` going to the trouble of reporting hardware codec
|
||||
capabilities back to Rust for DeviceProfile generation.
|
||||
|
||||
The code comment in `nativeAdapter.ts:11-14` justifies this by citing
|
||||
tauri#10152 as an upstream blocker. **That justification is stale.**
|
||||
|
||||
### Why the blocker no longer holds
|
||||
|
||||
- tauri#10152 is open but **dead since 2024-07-01**, and it is a *feature
|
||||
request* ("Support transparent webviews on mobile"), not a bug report about
|
||||
compositing.
|
||||
- The capability shipped in tauri commit `27d01834` (2024-09-02) — a clippy
|
||||
cleanup that moved `transparent()` out of the desktop-gated impl block, fencing
|
||||
only the tao call behind `#[cfg(desktop)]`. Because it landed as unrelated
|
||||
cleanup, nobody closed the issue.
|
||||
- The black/white-screen reports (tauri#8381, tauri#9408) were a real but
|
||||
*different* bug: a broken JNI signature for `setBackgroundColor`, fixed in
|
||||
**wry 0.39.4** (PR #1237). We ship wry 0.55.x.
|
||||
- Current wry calls `setBackgroundColor(0)` unconditionally on Android when
|
||||
transparency is requested.
|
||||
|
||||
### The honest caveat
|
||||
|
||||
**Nobody has demonstrated SurfaceView-behind-WebView on Tauri Android.** A search
|
||||
of both `tauri-apps/tauri` and `tauri-apps/wry` issues for `surfaceview` returns
|
||||
zero results, and the one native-video Tauri plugin
|
||||
(`YeonV/tauri-plugin-videoplayer`) sidesteps compositing by launching a separate
|
||||
fullscreen Activity. Nothing upstream blocks this; nothing upstream proves it.
|
||||
Hence: spike, not feature.
|
||||
|
||||
Note this is the *Android* question only. The equivalent Linux compositing
|
||||
problem is maintainer-declared unfixable and is **not** in scope — see the
|
||||
unification spec.
|
||||
|
||||
## Layer assignment
|
||||
|
||||
| Logic / responsibility | Layer | Why it belongs there |
|
||||
|------------------------|-------|----------------------|
|
||||
| Which video backend this platform uses | Rust (existing) | `get_player_status` already computes `use_html5_element`. The frontend must *consume* it, not decide it. Restoring that is the point of the spike. |
|
||||
| Surface creation, z-ordering, `setVideoSurfaceHolder` lifecycle | Kotlin | Android platform mechanics; already written in `JellyTauPlayer.kt`. |
|
||||
| Seek/audio-track *strategy* | Rust (existing) | Already returned by `player_seek_video` / `player_switch_audio_track`; `NativePlayerAdapter` executes the chosen primitive. Unchanged — this is exactly what the `PlayerAdapter` contract was built for. |
|
||||
| Positioning the surface under the video viewport | Frontend | Pure presentation/layout. **This is the risk area** — see Design. |
|
||||
|
||||
## Design
|
||||
|
||||
### Phase 1 — prove compositing (no app changes)
|
||||
|
||||
Before touching the adapter factory, verify the primitive works at all:
|
||||
|
||||
1. Set `"transparent": true` in `tauri.conf.json` for the Android build, plus
|
||||
`html, body { background: transparent; }`.
|
||||
2. Confirm the WebView is genuinely transparent (a native view behind it is
|
||||
visible) and that the app does not regress to a black/white screen.
|
||||
|
||||
If this fails, stop — everything downstream is moot, and the finding is that
|
||||
Tauri Android transparency is still broken in practice despite the shipped fix.
|
||||
|
||||
### Phase 2 — un-hardcode the factory
|
||||
|
||||
```ts
|
||||
// src/lib/player/adapters/index.ts
|
||||
export function createAdapter({ backendKind, host, bridge }: CreateAdapterArgs): PlayerAdapter {
|
||||
return backendKind === "native"
|
||||
? new NativePlayerAdapter(host)
|
||||
: new Html5PlayerAdapter(host, bridge);
|
||||
}
|
||||
```
|
||||
|
||||
`backendKind` comes from `get_player_status` (`VideoBackend::Native` on Android).
|
||||
Gate behind a setting — `experimentalNativeVideo`, default **off** — so a broken
|
||||
spike cannot ship as a regression. Rust already owns this decision; the flag only
|
||||
suppresses it.
|
||||
|
||||
**Also in scope: remove the user-agent sniffing in
|
||||
`src/lib/services/webviewAudio.ts:30-41`.** It re-derives which audio backend the
|
||||
platform has from `navigator.userAgent` ("matching the Rust cfg gate", per its own
|
||||
comment) — the frontend deciding a backend fact it should be told. Same root cause
|
||||
as the hardcode above, same fix: consume the value Rust already computes. Fold it
|
||||
in here rather than leaving a second, subtler copy of the bug behind. If
|
||||
`get_player_status` does not currently expose enough to cover the audio case, add
|
||||
the field — that is backend work, and correct.
|
||||
|
||||
### Phase 3 — surface positioning
|
||||
|
||||
The hard part, and where this most likely fails. The webview's `<video>` element
|
||||
occupies a laid-out box; the `SurfaceView` must be positioned to match it, and
|
||||
kept matched through scroll, rotation, and mini-player transitions.
|
||||
|
||||
Approach: the video view reports its `getBoundingClientRect()` to Rust, which
|
||||
forwards the rect to Kotlin to position the `SurfaceView`. This is the same
|
||||
"faking it" technique the ecosystem uses on desktop — acceptable here *only if*
|
||||
the video is effectively fullscreen on Android, which it is in the player route.
|
||||
|
||||
**Explicit failure criterion**: if the surface cannot be kept aligned during
|
||||
rotation or the mini-player transition without visible artefacts, the spike fails
|
||||
and we keep HTML5. Do not ship a janky native path for a codec win.
|
||||
|
||||
### What we gain if it works
|
||||
|
||||
- **Hardware decode via MediaCodec** — `CodecDetector.kt` already reports
|
||||
capabilities; the DeviceProfile would finally match what actually plays.
|
||||
- **ASS/SSA subtitles** are *not* automatic. ExoPlayer cannot render them; that
|
||||
would require libmpv, which is a separate and much larger decision (see the
|
||||
unification spec's engine comparison). Scope this spike to hardware decode
|
||||
only, and do not claim subtitle improvements from it.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- Linux native video. Maintainer-declared unfixable on WebKitGTK/Wayland.
|
||||
- Replacing ExoPlayer with libmpv on Android.
|
||||
- Windows native video.
|
||||
- Removing the HTML5 path. It stays as the default and the fallback.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
The spike is **complete** when one of these is true:
|
||||
|
||||
**Success path**
|
||||
- [ ] Transparent WebView confirmed working on a physical device.
|
||||
- [ ] `experimentalNativeVideo` off → behaviour byte-identical to today.
|
||||
- [ ] `webviewAudio.ts` no longer inspects `navigator.userAgent`; the platform's audio backend is read from Rust.
|
||||
- [ ] `experimentalNativeVideo` on → video plays via ExoPlayer/MediaCodec, correctly positioned, with working seek, audio-track switch, and subtitle selection through the existing `PlayerAdapter` contract.
|
||||
- [ ] No artefacts on rotation, background/foreground, or mini-player transition.
|
||||
- [ ] `adb shell dumpsys media.metrics` (or logcat) confirms a hardware decoder is in use.
|
||||
- [ ] Measured battery/thermal or CPU improvement over the HTML5 path on the same clip.
|
||||
|
||||
**Failure path**
|
||||
- [ ] The blocking behaviour is documented in this spec with evidence.
|
||||
- [ ] `NativePlayerAdapter` and the unreachable `SurfaceView` code are deleted, or explicitly retained with a *correct* comment.
|
||||
- [ ] `nativeAdapter.ts:11-14` no longer cites tauri#10152.
|
||||
|
||||
Either way:
|
||||
- [ ] `bun run check`, `bun run test`, `bun run check:boundary` pass.
|
||||
- [ ] `cargo fmt` / `cargo clippy` clean; `bun run test:rust` passes.
|
||||
|
||||
## Testing
|
||||
|
||||
Adapter-selection logic is pure and testable without a device: assert
|
||||
`createAdapter` returns `NativePlayerAdapter` for `backendKind: "native"` with
|
||||
the flag on, and `Html5PlayerAdapter` in every other combination — including that
|
||||
the flag off forces HTML5 even when Rust says native. That last case is the
|
||||
regression guard.
|
||||
|
||||
Everything else is manual on-device; there is no meaningful way to unit-test
|
||||
surface compositing. Test on at least two devices — compositing behaviour varies
|
||||
by OEM and Android version.
|
||||
|
||||
Per CLAUDE.md, if the spike turns into a bug fix (e.g. seek breaks under the
|
||||
native adapter), write the failing test first.
|
||||
|
||||
## TRACES
|
||||
|
||||
- `createAdapter` → `// TRACES: UR-003, UR-004 | DR-023, DR-024`
|
||||
- Adapter-selection tests → `UT-xxx`
|
||||
- No new requirement IDs; this spike either satisfies existing IR-004 expectations or documents why it cannot.
|
||||
|
||||
## Notes for the implementer
|
||||
|
||||
- **Do not skip Phase 1.** If transparency does not work, phases 2 and 3 are
|
||||
wasted effort.
|
||||
- `VideoPlayer.svelte` has a documented hazard: no lifecycle calls after an
|
||||
`await` in `onMount` — it flips to HTML5 mode and breaks Android seek. The
|
||||
adapter swap touches exactly this code path.
|
||||
- tauri-specta tagged responses keep Rust field names (`new_url`, not `newUrl`).
|
||||
- Android source edits go in `src-tauri/android/src`, then run
|
||||
`scripts/sync-android-sources.sh`.
|
||||
- A parallel Claude session may be active — `git diff` first.
|
||||
@@ -0,0 +1,176 @@
|
||||
# Spec: Audio equalizer
|
||||
|
||||
**Status:** Accepted
|
||||
**Requirements:** UR-027 → DR-030 (EQ UI), IR-020 (MPV EQ integration).
|
||||
**UX spec:** n/a (extends the Settings › Audio section, ux-flows §8.1 instant-apply).
|
||||
**Supersedes / revises:** —
|
||||
**Revised by:** [android-audio-settings-parity.md](android-audio-settings-parity.md) — lifts the "Android is a no-op" limitation below.
|
||||
|
||||
## Summary
|
||||
|
||||
Add a graphic audio equalizer to playback. Users pick a preset (Flat, Rock,
|
||||
Pop, Jazz, Classical, Bass Boost, Treble Boost, Vocal) or set custom per-band
|
||||
gains, from a new block in Settings › Audio. On Linux the gains apply live via
|
||||
MPV's audio-filter chain; the settings persist and re-apply on the next track
|
||||
and at startup, exactly like crossfade/gapless/normalize do today. Android is a
|
||||
no-op for now (documented parity gap, same as those three features).
|
||||
|
||||
## Motivation
|
||||
|
||||
UR-027 is one of the few still-unbuilt audio features. The audio-settings
|
||||
pipeline it needs already exists — `AudioSettings` + `set_audio_settings` on the
|
||||
`PlayerBackend` trait, the `player_set_audio_settings` command, and the Settings
|
||||
› Audio UI with instant-apply. Crossfade, gapless, and volume normalization all
|
||||
ride that pipeline. The equalizer is the same shape: N more fields on
|
||||
`AudioSettings`, an `af` filter on the MPV backend, one more block in the
|
||||
settings panel. No new command, no new state machine.
|
||||
|
||||
## Layer assignment
|
||||
|
||||
| Logic / responsibility | Layer | Why it belongs there |
|
||||
|------------------------|-------|----------------------|
|
||||
| EQ band count, centre frequencies, gain range/clamping | Rust | Domain of the audio engine; the bands must match what the MPV filter expects. Changing the DSP must not require a frontend change. |
|
||||
| Preset name → per-band gain curve | Rust | A preset *is* a domain gain curve, not a label. It changes with the audio engine's band layout, never with the UI. Placing it in the frontend would be the scoped-search taxonomy mistake again (values that look like config but are domain data). |
|
||||
| Translating gains → MPV `af` filter string | Rust | Platform playback detail; lives with the other `set_audio_settings` filter code in `mpv_backend.rs`. |
|
||||
| Persisting the chosen settings, re-pushing on load | Rust/existing | Same path crossfade/etc. already use; the controller re-applies `AudioSettings` per track. |
|
||||
| Rendering band sliders, the preset chips, live readouts | Frontend | Pure presentation; changes only if the settings UI is redesigned. |
|
||||
| Which preset chip is highlighted; instant-apply on change | Frontend | Presentation/input handling (UR-057), the same as the normalize preset picker. |
|
||||
|
||||
Tie-breaker note: the preset→curve map is the one tempting boundary leak. It goes
|
||||
in Rust because a preset is a set of band gains defined *by the band layout*,
|
||||
which is an engine property. The frontend only ever names a preset and renders
|
||||
the resulting gains; it never defines them.
|
||||
|
||||
## Design
|
||||
|
||||
### `AudioSettings` (Rust, `settings.rs`)
|
||||
|
||||
Add two fields (both `#[serde(rename_all = "camelCase")]` via the existing
|
||||
struct attribute):
|
||||
|
||||
```rust
|
||||
/// Equalizer enabled. When false, no `af` EQ filter is applied.
|
||||
pub equalizer_enabled: bool,
|
||||
/// Per-band gains in dB, one per FIXED band (see EQ_BANDS). Length is
|
||||
/// validated/normalised to EQ_BANDS.len(); clamped to [-12, +12] dB.
|
||||
pub equalizer_bands: Vec<f32>,
|
||||
```
|
||||
|
||||
Fixed 10-band ISO layout (domain constant in `settings.rs`):
|
||||
|
||||
```rust
|
||||
pub const EQ_BANDS: [f32; 10] =
|
||||
[31.0, 62.0, 125.0, 250.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0, 16000.0];
|
||||
pub const EQ_GAIN_MIN: f32 = -12.0;
|
||||
pub const EQ_GAIN_MAX: f32 = 12.0;
|
||||
```
|
||||
|
||||
- `Default`: `equalizer_enabled: false`, `equalizer_bands: vec![0.0; 10]` (flat).
|
||||
- New `with_equalizer_normalised(self)` clamps each gain to `[EQ_GAIN_MIN,
|
||||
EQ_GAIN_MAX]` and pads/truncates the vec to 10 bands. Applied in the command
|
||||
alongside `with_crossfade_clamped` (add that call too — it's currently missing).
|
||||
- Backward compat: both fields `#[serde(default)]` so old persisted JSON loads.
|
||||
|
||||
### Presets (Rust, `settings.rs`)
|
||||
|
||||
```rust
|
||||
#[derive(specta::Type, Serialize, Deserialize, Clone, Copy, PartialEq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum EqPreset { Flat, Rock, Pop, Jazz, Classical, BassBoost, TrebleBoost, Vocal }
|
||||
|
||||
impl EqPreset {
|
||||
/// The 10-band gain curve (dB) for this preset.
|
||||
pub fn gains(&self) -> [f32; 10] { /* table */ }
|
||||
}
|
||||
```
|
||||
|
||||
Preset selection is a *frontend* convenience: tapping a chip sets
|
||||
`equalizer_bands = preset.gains()` and pushes settings. The curve tables live in
|
||||
Rust; the frontend reads them via a tiny `player_get_eq_presets` command
|
||||
returning `Vec<(EqPreset, Vec<f32>)>` (or a map), so the frontend never encodes
|
||||
the numbers. (If exposing the whole table is awkward through specta, expose
|
||||
`player_eq_preset_gains(preset) -> Vec<f32>` instead — pick at implement time.)
|
||||
|
||||
### MPV application (Rust, `mpv_backend.rs::set_audio_settings`)
|
||||
|
||||
Build an `equalizer` / `anequalizer` filter from the bands and set the `af`
|
||||
property. When `equalizer_enabled` is false or all gains are 0, clear the EQ
|
||||
filter (leave any other `af` entries intact). Use `af add`/`af remove` or a
|
||||
rebuilt `af` string; keep it isolated so it doesn't stomp a future crossfade
|
||||
filter. Errors map to `PlayerError` like the gapless code.
|
||||
|
||||
### No new persistence table
|
||||
|
||||
`AudioSettings` is already round-tripped by the frontend settings store and
|
||||
re-pushed via `player_set_audio_settings` on change and on load. The two new
|
||||
fields ride along. `NullBackend`/Android inherit the trait default (no-op).
|
||||
|
||||
### Wire summary
|
||||
|
||||
- Command names unchanged: `player_set_audio_settings`,
|
||||
`player_get_audio_settings` (now carry the EQ fields).
|
||||
- New (optional) read-only command for preset curves — kebab n/a (it's a
|
||||
command): `player_get_eq_presets` (or `player_eq_preset_gains`).
|
||||
- Regenerate `bindings.ts` from the Rust types; never hand-edit.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- Android/ExoPlayer EQ (parity gap tracked with crossfade/gapless/normalize).
|
||||
**Now specified in [android-audio-settings-parity.md](android-audio-settings-parity.md)**,
|
||||
which implements `set_audio_settings` on `ExoPlayerBackend`. The canonical band
|
||||
layout and preset→curve map defined here remain authoritative; the Android side
|
||||
resamples those bands onto the device equalizer rather than defining its own.
|
||||
- Per-track or per-library EQ profiles — one global profile only.
|
||||
- Automatic loudness/room correction; only manual bands + presets.
|
||||
- Changing the crossfade/normalize TODOs in `set_audio_settings` beyond wiring
|
||||
the missing `with_crossfade_clamped` call.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] Settings › Audio has an Equalizer block: enable toggle, preset chips, 10
|
||||
band sliders with live dB readouts, instant-apply (no Save button).
|
||||
- [ ] Choosing a preset sets the bands from the Rust-defined curve; editing a
|
||||
band switches the highlighted preset to "Custom" (frontend-only label).
|
||||
- [ ] Gains clamp to [-12, +12] dB; the band vector always normalises to 10.
|
||||
- [ ] On Linux, enabling EQ audibly changes output and persists across tracks
|
||||
and app restart; disabling clears the filter without affecting other audio.
|
||||
- [ ] Old persisted settings (no EQ fields) load without error, defaulting flat.
|
||||
- [ ] `bun run check` and `bun run test` pass.
|
||||
- [ ] `cargo fmt` clean, `cargo clippy` clean, `bun run test:rust` passes.
|
||||
- [ ] `bun run check:boundary` passes (no preset curve numbers in the frontend).
|
||||
- [ ] New requirement-implementing code carries `// TRACES:` comments.
|
||||
- [ ] `bindings.ts` regenerated.
|
||||
|
||||
## Testing
|
||||
|
||||
- Rust (`settings.rs`): default is flat + disabled; `with_equalizer_normalised`
|
||||
clamps out-of-range gains and pads/truncates band length; serialization
|
||||
round-trips the camelCase fields; backward-compat load of pre-EQ JSON; each
|
||||
preset returns a 10-length curve; Flat is all zeros.
|
||||
- Rust IPC param naming for any new command (camelCase rule per CLAUDE.md).
|
||||
- Frontend (`settings` page or an extracted helper): selecting a preset sets the
|
||||
expected band array; editing a band flips the label to Custom; enable toggle
|
||||
gates the sliders. Keep DSP untested on the frontend (it's Rust's).
|
||||
|
||||
## TRACES
|
||||
|
||||
- `AudioSettings` EQ fields + normalise + presets: `UR-027 | DR-030` (+ unit tests)
|
||||
- MPV EQ filter application: `UR-027 | IR-020`
|
||||
- Settings EQ UI block: `UR-027 | DR-030`
|
||||
- Preset-curve command: `UR-027 | DR-030`
|
||||
|
||||
## Notes for the implementer
|
||||
|
||||
- A parallel Claude session is active in this repo (it has touched
|
||||
`tauri.conf.json`, `Dockerfile`, `package.json`, home components, and added
|
||||
build scripts, and the Rust build is currently broken by its
|
||||
`tauri.conf.json` bundle-target change). `git diff` before "repairing"
|
||||
anything you didn't write; keep EQ changes isolated to `settings.rs`,
|
||||
`mpv_backend.rs`, `backend.rs` (trait default already covers it),
|
||||
`commands/player/settings.rs`, and the settings page.
|
||||
- Mirror the volume-normalization block in the settings page for the toggle +
|
||||
preset-picker pattern; mirror the gapless code in `set_audio_settings` for the
|
||||
MPV property handling.
|
||||
- Confirm the exact MPV filter name available in the linked libmpv
|
||||
(`equalizer` vs `anequalizer`/`superequalizer`) before committing the filter
|
||||
string; gate cleanly if unavailable.
|
||||
@@ -0,0 +1,215 @@
|
||||
# Spec: Harden the frontend boundary tripwire
|
||||
|
||||
**Status:** Implemented
|
||||
**Requirements:** DR-094
|
||||
**UX spec:** n/a — developer tooling.
|
||||
**Supersedes / revises:** revises the detection rule in
|
||||
[scripts/check-frontend-boundary.sh](../../scripts/check-frontend-boundary.sh);
|
||||
the boundary *policy* in [scoped-search-boundary.md](scoped-search-boundary.md)
|
||||
is unchanged.
|
||||
|
||||
## Summary
|
||||
|
||||
`bun run check:boundary` passes on a tree that contains the exact leak it was
|
||||
built to catch. It matches a multi-type array only when written **inline at the
|
||||
query site**, so assigning the same array to a named const evades it entirely —
|
||||
which is how [searchScope.ts](../../src/lib/utils/searchScope.ts) has kept a
|
||||
category→item-type mapping through every green CI run. This spec broadens the
|
||||
match to item-type array literals anywhere in `src/`, and resolves the handful
|
||||
of legitimate hits that broadening surfaces.
|
||||
|
||||
## Motivation
|
||||
|
||||
The current pattern is anchored to the `includeItemTypes:` key:
|
||||
|
||||
```sh
|
||||
PATTERN='includeItemTypes:[[:space:]]*\[[^]]*,[^]]*\]'
|
||||
```
|
||||
|
||||
The live leak is not written that way:
|
||||
|
||||
```ts
|
||||
// src/lib/utils/searchScope.ts:29 — invisible to the tripwire
|
||||
const SCOPE_ITEM_TYPES = { music: ["MusicAlbum", "MusicArtist", "Audio", "Playlist"], … };
|
||||
```
|
||||
|
||||
The taxonomy and the query are one indirection apart, and the grep only sees the
|
||||
query. The script's own header is admirably honest that it is "a TRIPWIRE, NOT A
|
||||
PROOF" — but the gap here is not a subtle judgment call it was designed to
|
||||
defer to human review. It is the *crudest form* of the violation, one `const`
|
||||
away from the shape it does match, in the very file the founding incident was
|
||||
written about.
|
||||
|
||||
Broadening the pattern to any item-type array literal finds it, with a
|
||||
manageable number of other hits (measured, not estimated):
|
||||
|
||||
| Site | Verdict |
|
||||
|------|---------|
|
||||
| `searchScope.ts:30,32` | 🔴 The leak. Removed by [scoped-search-boundary-implementation.md](scoped-search-boundary-implementation.md). |
|
||||
| `PersonDetailView.svelte:30` | Already allowlisted, with a recorded reason. |
|
||||
| `DownloadedBrowse.svelte:95` | Borderline — `["MusicAlbum","Series","Season","BoxSet"].includes(item.type)` as an "is this a container?" predicate. |
|
||||
| `GenericMediaListPage.svelte:298` | Borderline — `["MusicAlbum","MusicArtist","Audio","Playlist"].includes(config.itemType)` as a music-styling predicate. |
|
||||
| 6 hits in `*.test.ts` | Excluded; tests legitimately name types. |
|
||||
|
||||
Four non-test sites total. This is a tractable change, not a boil-the-ocean one.
|
||||
|
||||
## Layer assignment
|
||||
|
||||
Tooling only — no application logic, nothing crosses IPC. The two borderline
|
||||
*application* sites do get a layer decision, below.
|
||||
|
||||
| Logic / responsibility | Layer | Why it belongs there |
|
||||
|------------------------|-------|----------------------|
|
||||
| Detecting item-type array literals in `src/` | Build tooling (`scripts/`) | Static analysis of repo source; belongs beside the existing check. |
|
||||
| "Is this item a container?" (`DownloadedBrowse`) | **Rust** (recommended) | Containers-vs-leaves is Jellyfin structure, and the set grows when Jellyfin adds a container type — the litmus test's "yes". Prefer a `MediaItem.isContainer` boolean from the backend over a type-set predicate in a component. |
|
||||
| "Is this music content?" (`GenericMediaListPage`) | **Frontend, allowlisted** | Selects a grid *style*. It reads `config.itemType`, a value the page already declares about itself, and changes only if the UI is redesigned — the litmus test's "no". Single-type presentation is explicitly not the target of the rule. |
|
||||
|
||||
`DownloadedBrowse` defaults to Rust per the checklist's borderline rule; see
|
||||
Out of scope for why the migration itself is deferred rather than bundled.
|
||||
|
||||
## Design
|
||||
|
||||
### 1. Broaden the pattern
|
||||
|
||||
Replace the key-anchored pattern with one matching an array literal of two or
|
||||
more known Jellyfin item types, wherever it appears:
|
||||
|
||||
```sh
|
||||
# Two or more adjacent item-type string literals inside a bracket.
|
||||
TYPES='Movie|Series|Episode|Audio|MusicAlbum|MusicArtist|MusicVideo|Season|BoxSet|Playlist|Book|AudioBook|Video|Person|Folder|CollectionFolder|TvChannel|LiveTvChannel'
|
||||
PATTERN="\[[[:space:]]*\"($TYPES)\"[[:space:]]*,[[:space:]]*\"($TYPES)\""
|
||||
```
|
||||
|
||||
Properties worth stating, because each is a deliberate trade:
|
||||
|
||||
- **Not anchored to any key**, so a named const, a function return, a `Record`
|
||||
value, or an inline query all match equally.
|
||||
- **Requires two adjacent type literals**, preserving the existing and correct
|
||||
carve-out that single-type presentation (`itemType: "Movie"`) is legitimate.
|
||||
- **Requires string literals**, so `item.type === "Audio"` (display inspection)
|
||||
still does not match.
|
||||
- **Explicit type list**, not `[A-Z][a-z]+`, so arbitrary string arrays
|
||||
(`["High","Low"]`, `["Songs","Albums"]`) do not produce noise.
|
||||
|
||||
Keep `grep -rInE`, the `*.test.*` exclusion, and the allowlist mechanism as they
|
||||
are — all three work.
|
||||
|
||||
### 2. Resolve the surfaced sites
|
||||
|
||||
- `PersonDetailView.svelte` — already allowlisted; entry unchanged.
|
||||
- `GenericMediaListPage.svelte` — **add to the allowlist** with the reason from
|
||||
the layer table (grid styling over a self-declared `itemType`).
|
||||
- `DownloadedBrowse.svelte` — **add to the allowlist with a `TODO` naming the
|
||||
preferred fix** (backend `isContainer`). An allowlist entry that records a
|
||||
known-borderline decision is honest; silently broadening the pattern to miss
|
||||
it would not be.
|
||||
- `searchScope.ts` — **not allowlisted.** It is the leak, and
|
||||
[scoped-search-boundary-implementation.md](scoped-search-boundary-implementation.md)
|
||||
deletes it.
|
||||
|
||||
### 3. 🔴 Sequencing
|
||||
|
||||
**This spec must land after Stage 1 of
|
||||
[scoped-search-boundary-implementation.md](scoped-search-boundary-implementation.md).**
|
||||
Hardening the tripwire first turns `master` red on a violation with no fix
|
||||
available, and the only ways out are reverting the hardening or allowlisting the
|
||||
leak — the second of which is exactly how a boundary rule dies.
|
||||
|
||||
### 4. Keep the allowlist honest
|
||||
|
||||
The script already warns that a growing allowlist means the boundary is eroding.
|
||||
This change takes it from 1 entry to 3, which is close to that line. Add a hard
|
||||
cap so drift is caught mechanically rather than by whoever notices:
|
||||
|
||||
```sh
|
||||
MAX_ALLOWLIST=4
|
||||
if [ "${#ALLOWLIST[@]}" -gt "$MAX_ALLOWLIST" ]; then
|
||||
echo "❌ Allowlist has ${#ALLOWLIST[@]} entries (max $MAX_ALLOWLIST)."
|
||||
echo " Push taxonomy into Rust instead of appending here."
|
||||
exit 1
|
||||
fi
|
||||
```
|
||||
|
||||
The cap is deliberately just above the current count: the next exception forces
|
||||
a conversation instead of a one-line append.
|
||||
|
||||
### 5. Restate the limits
|
||||
|
||||
The header's "tripwire, not a proof" caveat stays and gets sharper. The broadened
|
||||
pattern still cannot see:
|
||||
|
||||
- a type set built at run time (`[...musicTypes, "Playlist"]`),
|
||||
- types split across variables (`const A = "Audio"; [A, B]`),
|
||||
- taxonomy expressed as a `switch` or chained `||` rather than an array.
|
||||
|
||||
The spec-review checklist remains the real gate. This raises the floor; it does
|
||||
not close the class.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- **Migrating `DownloadedBrowse` to a backend `isContainer` flag.** It touches
|
||||
`MediaItem`, `bindings.ts`, and the offline path — its own spec. Allowlisted
|
||||
with a TODO here so it is recorded, not forgotten.
|
||||
- The scoped-search fix itself — [scoped-search-boundary-implementation.md](scoped-search-boundary-implementation.md).
|
||||
- Detecting the run-time-construction cases listed above.
|
||||
- Extending the check to Rust or Kotlin (the rule is about `src/`).
|
||||
- Changing the boundary *policy* in CLAUDE.md.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] With `searchScope.ts` reverted to its leaking form, `bun run check:boundary`
|
||||
**fails** and names `src/lib/utils/searchScope.ts`. This is the criterion
|
||||
that proves the fix — verify it explicitly before landing.
|
||||
- [ ] On the post-fix tree, `bun run check:boundary` passes.
|
||||
- [ ] A newly introduced `const X = ["Movie", "Series"]` in any non-test `src/`
|
||||
file fails the check (regression test for the const-indirection evasion).
|
||||
- [ ] `itemType: "Movie"` and `item.type === "Audio"` do **not** trip the check.
|
||||
- [ ] `["High", "Low"]` and other non-item-type arrays do **not** trip it.
|
||||
- [ ] Test files are still excluded (the 6 known test hits stay silent).
|
||||
- [ ] The allowlist has exactly 3 entries, each with a written reason; a 5th
|
||||
entry fails the check via `MAX_ALLOWLIST`.
|
||||
- [ ] The script header still states it is a tripwire, not a proof, and names the
|
||||
evasions it cannot see.
|
||||
- [ ] `bun run check` and `bun run test` pass.
|
||||
- [ ] `bun run test:all` passes.
|
||||
|
||||
## Testing
|
||||
|
||||
The script is bash and has no test harness. Verify by construction — each is a
|
||||
temporary edit, run, revert:
|
||||
|
||||
1. Reintroduce the `SCOPE_ITEM_TYPES` const → **must fail**.
|
||||
2. Add `const T = ["Movie","Series"]` to a scratch `.svelte` file → **must fail**.
|
||||
3. Add the same to a `.test.ts` file → **must pass** (exclusion holds).
|
||||
4. Add `itemType: "Movie"` → **must pass**.
|
||||
5. Add a 5th allowlist entry → **must fail** on the cap.
|
||||
|
||||
Record the five results in the PR description. A grep-based gate that has never
|
||||
been observed failing is indistinguishable from one that cannot fail — which is
|
||||
the precise condition this whole spec exists to correct.
|
||||
|
||||
## TRACES
|
||||
|
||||
Allocate in `requirements.md`:
|
||||
|
||||
- **DR-094** — "Frontend boundary tripwire detects Jellyfin item-type array
|
||||
literals anywhere in `src/` (not only inline at an `includeItemTypes:` query
|
||||
site), so a category→type mapping cannot evade the check via a named const;
|
||||
allowlist is capped to force taxonomy into Rust rather than accumulating
|
||||
exceptions." Category: Tooling. Status: Done on merge.
|
||||
|
||||
Shell scripts carry no `TRACES:` comment convention in this repo; reference
|
||||
DR-094 in the script header comment instead.
|
||||
|
||||
## Notes for the implementer
|
||||
|
||||
- A parallel Claude session may be active in this repo — `git diff` before
|
||||
"repairing" unexpected changes (CLAUDE.md §Gotchas).
|
||||
- **Land after Stage 1 of the scoped-search fix** — see §3. This is the one
|
||||
ordering constraint that will break `master` if ignored.
|
||||
- Test the regex against the current tree *before* committing:
|
||||
`grep -rInE "$PATTERN" src/ | grep -v '\.test\.'` should return exactly the
|
||||
four sites in the Motivation table.
|
||||
- The `TYPES` list will need occasional extension as Jellyfin adds types.
|
||||
That is acceptable for a tripwire — an unlisted type produces a false
|
||||
negative, never a false positive, so the check degrades safely.
|
||||
@@ -0,0 +1,250 @@
|
||||
# Spec: Build provenance (git describe + build profile)
|
||||
|
||||
**Status:** Proposed
|
||||
**Requirements:** new DR-093 (build provenance surfaced in-app and in logs); no UR — this is a diagnostic capability, not a user feature
|
||||
**UX spec:** n/a — adds an About block to Settings; no new flow
|
||||
**Supersedes / revises:** —
|
||||
|
||||
## Summary
|
||||
|
||||
Make every build say exactly what it is. Today a running JellyTau reports no
|
||||
version at all — not in the UI, not in the logs — and the only version string in
|
||||
the tree is the hand-maintained `0.2.0` duplicated across three files.
|
||||
|
||||
This adds a `build.rs`-generated provenance string (`git describe` + short SHA +
|
||||
dirty flag + debug/release profile), exposes it over IPC, and renders it in a new
|
||||
Settings › About block. It also removes one of the three hand-bumped version
|
||||
files.
|
||||
|
||||
## Motivation
|
||||
|
||||
The concrete problem: when a user reports "the equalizer does nothing on my
|
||||
device" — which is a live risk for v0.2.0, whose Android audio settings are not
|
||||
yet device-verified — there is currently no way to tell which build they are
|
||||
running. Tag? Master? A local debug build from three weeks ago? The bug report
|
||||
cannot distinguish them.
|
||||
|
||||
Two smaller irritations this also fixes:
|
||||
|
||||
- **Debug builds masquerade as releases.** `0.2.0` is `0.2.0` whether it came
|
||||
from a tagged release or `bun run tauri dev`.
|
||||
- **Three files carry the version.** `package.json`, `src-tauri/Cargo.toml` and
|
||||
`src-tauri/tauri.conf.json` must be bumped in lockstep; the release checklist
|
||||
exists partly to stop them drifting.
|
||||
|
||||
### What this deliberately does *not* do
|
||||
|
||||
**The canonical version stays hand-bumped in `Cargo.toml`.** Cargo requires a
|
||||
literal semver string at manifest-parse time and cannot derive it from git. The
|
||||
same is true of `tauri.conf.json`. Attempting to source the *release* version
|
||||
from a tag trades a scripted, reviewable bump for a fragile build-time
|
||||
dependency that breaks in exactly the environment we care most about (CI, in
|
||||
Docker, from a shallow clone).
|
||||
|
||||
So: **the release version is authored; the build provenance is derived.** They
|
||||
answer different questions — "what release is this?" versus "what commit is this
|
||||
binary actually built from?" — and only the second benefits from git.
|
||||
|
||||
## Layer assignment
|
||||
|
||||
| Logic / responsibility | Layer | Why it belongs there |
|
||||
|------------------------|-------|----------------------|
|
||||
| Capturing git describe / SHA / dirty state at compile time | Rust (`build.rs`) | Only the Rust build has a compile step that can shell out to git and bake the result into the binary. A frontend equivalent would report the *dev server's* state, not the shipped binary's. |
|
||||
| Degrading to a sentinel when git is unavailable | Rust (`build.rs`) | Build-environment concern. Must never fail the build — CI runs in Docker from a shallow clone. |
|
||||
| Release version (`0.2.0`) | Rust (`Cargo.toml`, authored) | Domain fact about the product, not derivable from the environment. |
|
||||
| Deciding *what a build is* (release / dev / dirty) | Rust | Domain classification. The frontend must not infer "this is a dev build" from a string shape — it renders what it is told. |
|
||||
| Rendering the About block, copy-to-clipboard | Frontend | Pure presentation. |
|
||||
|
||||
Borderline row: the release/dev/dirty classification could be done in the
|
||||
frontend by pattern-matching the describe string. It goes to Rust because that is
|
||||
a *rule about what constitutes a release build*, and it would have to change if
|
||||
the tagging scheme changed — the litmus test in the template puts that in Rust.
|
||||
Send a typed enum, not a string for the frontend to parse.
|
||||
|
||||
## Design
|
||||
|
||||
### `build.rs`
|
||||
|
||||
```rust
|
||||
fn main() {
|
||||
emit_build_provenance();
|
||||
tauri_build::build()
|
||||
}
|
||||
|
||||
fn emit_build_provenance() {
|
||||
let describe = std::process::Command::new("git")
|
||||
.args(["describe", "--tags", "--always", "--dirty"])
|
||||
.output()
|
||||
.ok()
|
||||
.filter(|o| o.status.success())
|
||||
.and_then(|o| String::from_utf8(o.stdout).ok())
|
||||
.map(|s| s.trim().to_string())
|
||||
.unwrap_or_else(|| "unknown".to_string());
|
||||
|
||||
println!("cargo:rustc-env=JELLYTAU_GIT_DESCRIBE={describe}");
|
||||
|
||||
// Rebuild when HEAD moves or a ref is written, so the string does not go
|
||||
// stale across commits. Guarded: these paths do not exist in a git-less
|
||||
// source tarball, and emitting rerun-if-changed for a missing path would
|
||||
// force a rebuild every time.
|
||||
for p in [".git/HEAD", ".git/refs"] {
|
||||
if std::path::Path::new("../").join(p).exists() {
|
||||
println!("cargo:rerun-if-changed=../{p}");
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
🔴 **`build.rs` must never fail the build.** Every git call is
|
||||
`.ok()`-swallowed; a missing git binary, a shallow clone, or a source tarball all
|
||||
yield `"unknown"`. A build that breaks because git is absent would be a worse bug
|
||||
than the one this fixes.
|
||||
|
||||
Note the `../` prefixes: `build.rs` runs with CWD at `src-tauri/`, so the repo's
|
||||
`.git` is one level up.
|
||||
|
||||
### The provenance type
|
||||
|
||||
```rust
|
||||
/// TRACES: DR-093
|
||||
#[derive(specta::Type, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct BuildInfo {
|
||||
/// Authored release version (Cargo.toml).
|
||||
pub version: String,
|
||||
/// `git describe --tags --always --dirty`, or "unknown".
|
||||
pub git_describe: String,
|
||||
/// What kind of build this is — classified in Rust, not inferred by the UI.
|
||||
pub kind: BuildKind,
|
||||
}
|
||||
|
||||
/// TRACES: DR-093
|
||||
#[derive(specta::Type, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum BuildKind {
|
||||
/// Built from a clean, exactly-tagged commit in release mode.
|
||||
Release,
|
||||
/// Release-mode build that is not on a clean tag (e.g. master, or dirty).
|
||||
Untagged,
|
||||
/// debug_assertions build.
|
||||
Development,
|
||||
/// Git state unavailable at build time.
|
||||
Unknown,
|
||||
}
|
||||
```
|
||||
|
||||
Classification:
|
||||
|
||||
```rust
|
||||
let kind = if cfg!(debug_assertions) {
|
||||
BuildKind::Development
|
||||
} else if describe == "unknown" {
|
||||
BuildKind::Unknown
|
||||
} else if describe.contains('-') { // "v0.2.0-3-gcb79a37" or "...-dirty"
|
||||
BuildKind::Untagged
|
||||
} else {
|
||||
BuildKind::Release
|
||||
};
|
||||
```
|
||||
|
||||
### Command
|
||||
|
||||
```rust
|
||||
/// TRACES: DR-093
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn get_build_info() -> BuildInfo { … }
|
||||
```
|
||||
|
||||
No parameters, so the camelCase param rule does not apply; the struct fields do
|
||||
need `#[serde(rename_all = "camelCase")]` (above). Regenerate `bindings.ts`.
|
||||
|
||||
Also log the provenance once at startup, next to the existing init logging —
|
||||
that is what makes a user-submitted log file self-identifying, which is most of
|
||||
the value.
|
||||
|
||||
### Settings › About
|
||||
|
||||
A new block at the bottom of `src/routes/settings/+page.svelte`, rendering
|
||||
version, describe string, and a badge for non-release builds. One
|
||||
copy-to-clipboard button that yields a paste-ready block for bug reports:
|
||||
|
||||
```
|
||||
JellyTau 0.2.0 (v0.2.0-3-gcb79a37-dirty, development)
|
||||
linux x86_64
|
||||
```
|
||||
|
||||
Platform/arch come from the existing Tauri APIs; do not shell out.
|
||||
|
||||
### Removing one version file
|
||||
|
||||
`tauri.conf.json`'s `"version"` field can be omitted, in which case Tauri falls
|
||||
back to the Cargo version. That takes the bump from three files to two.
|
||||
|
||||
**Verify before adopting**: confirm the Android `versionName`/`versionCode` and
|
||||
the NSIS installer version still resolve correctly with the field absent —
|
||||
Android packaging in particular reads the Tauri config. If either regresses,
|
||||
keep the field and drop this part; it is a convenience, not the point of the
|
||||
spec.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- Deriving the *release* version from git tags (see Motivation).
|
||||
- A build-time timestamp. It defeats reproducible builds and adds little over
|
||||
the commit SHA.
|
||||
- CI provenance/attestation, SBOM, signing.
|
||||
- Displaying the Jellyfin server version (separate concern, already available
|
||||
from `/System/Info`).
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] `cargo build` succeeds with git absent, from a shallow clone, and from a source tarball with no `.git` — yielding `"unknown"` in each case, never a build failure.
|
||||
- [ ] A tagged clean release build reports `BuildKind::Release`; `bun run tauri dev` reports `Development`; a dirty tree reports `Untagged` (release mode) with `-dirty` in the describe string.
|
||||
- [ ] The describe string changes after a new commit without a manual `cargo clean` (rerun-if-changed works).
|
||||
- [ ] Provenance is logged once at startup.
|
||||
- [ ] Settings › About renders version + describe + build-kind badge, with working copy-to-clipboard.
|
||||
- [ ] 🔴 CI checkouts that build a shippable artifact set `fetch-depth: 0`, or their artifacts are knowingly stamped `unknown`. Currently only `publish-docs.yml` sets it; `build-release.yml` has five checkouts and `build-and-test.yml` two, all of which would report `unknown` as-is.
|
||||
- [ ] **No toolchain installed in CI** — git is already present in the builder image; nothing new is added.
|
||||
- [ ] `bun run check`, `bun run test`, `bun run check:boundary` pass.
|
||||
- [ ] `cargo fmt` clean, `cargo clippy` clean, `bun run test:rust` passes.
|
||||
- [ ] `bindings.ts` regenerated.
|
||||
- [ ] DR-093 allocated in `requirements.md`; new code carries `// TRACES:`.
|
||||
|
||||
## Testing
|
||||
|
||||
**Rust**: the classification is pure and must be extracted from the command as
|
||||
`classify_build(describe: &str, debug: bool) -> BuildKind` so it can be tested
|
||||
directly. Cover: `"v0.2.0"` → `Release`; `"v0.2.0-3-gcb79a37"` → `Untagged`;
|
||||
`"v0.2.0-dirty"` → `Untagged`; `"unknown"` → `Unknown`; `debug = true` → always
|
||||
`Development` regardless of describe.
|
||||
|
||||
`build.rs` itself is not unit-testable. Verify its failure path manually by
|
||||
building with `PATH` stripped of git, and from a `git archive` tarball — both
|
||||
must succeed with `"unknown"`.
|
||||
|
||||
**Frontend**: assert the About block renders each `BuildKind` correctly, and that
|
||||
it renders the backend-supplied kind rather than re-deriving it from the string
|
||||
(a test that passes a `Release` kind with a `-dirty` describe and asserts the
|
||||
badge follows the *kind* would catch that regression).
|
||||
|
||||
## TRACES
|
||||
|
||||
- `build.rs` provenance emission → `// TRACES: | DR-093`
|
||||
- `BuildInfo` / `BuildKind` / `classify_build` → `// TRACES: | DR-093`
|
||||
- `get_build_info` command → `// TRACES: | DR-093`
|
||||
- Settings About block → `// TRACES: | DR-093`
|
||||
- `classify_build` tests → `UT-BUILD-1`
|
||||
- Allocate **DR-093** in `requirements.md` ("Build provenance: git describe and
|
||||
build profile surfaced in-app and in logs"). Next free DR at time of writing
|
||||
is DR-093.
|
||||
|
||||
## Notes for the implementer
|
||||
|
||||
- Do the `build.rs` + command + logging first; the About UI is the smaller half
|
||||
and the logging alone delivers most of the diagnostic value.
|
||||
- The `fetch-depth: 0` change is the easiest part to forget and the one that
|
||||
makes CI artifacts useless if missed — it is why that acceptance box is
|
||||
flagged. Weigh it per workflow: test-only jobs do not need it.
|
||||
- Do not add a build timestamp "while you are in there" — see Out of scope.
|
||||
- A parallel Claude session may be active — `git diff` before "repairing"
|
||||
unexpected changes.
|
||||
@@ -0,0 +1,169 @@
|
||||
# Spec: Migrate to libmpv2 and declare the project licence
|
||||
|
||||
**Status:** Proposed
|
||||
**Requirements:** UR-003 → IR-003 (revises the MPV integration); no new user-facing behaviour
|
||||
**UX spec:** n/a
|
||||
**Supersedes / revises:** dependency and licensing housekeeping identified in [playback-backend-unification.md](playback-backend-unification.md)
|
||||
|
||||
## Summary
|
||||
|
||||
Two related pieces of housekeeping that block or complicate later work:
|
||||
|
||||
1. Replace the abandoned `libmpv` crate (pinned to a git branch) with the
|
||||
maintained `libmpv2`.
|
||||
2. Add a `LICENSE` file. The project has none, which leaves its legal status
|
||||
undefined while it links GPL-licensed libmpv.
|
||||
|
||||
Neither changes user-visible behaviour. Both are prerequisites for
|
||||
[windows-native-audio-backend.md](windows-native-audio-backend.md).
|
||||
|
||||
## Motivation
|
||||
|
||||
### The dependency is dead
|
||||
|
||||
```toml
|
||||
# src-tauri/Cargo.toml
|
||||
libmpv = { git = "https://github.com/ParadoxSpiral/libmpv-rs.git", branch = "master" }
|
||||
```
|
||||
|
||||
- crates.io `libmpv` 2.0.1 was published **2020-09-29**.
|
||||
- The upstream repo's last commit was **2023-01-08**; nothing since was released.
|
||||
- We pin a git *branch*, so builds are not reproducible — the same lockfile-less
|
||||
checkout can resolve differently over time, and CI has no protection if the
|
||||
branch moves or the repo disappears.
|
||||
|
||||
`libmpv2` (kohsine/libmpv2-rs) is a maintained fork of exactly this crate:
|
||||
6.0.0 released **2026-05-12**, ~23.5k recent downloads against the original's
|
||||
~1.1k, releases roughly quarterly since 2024.
|
||||
|
||||
### The project has no licence
|
||||
|
||||
There is no `LICENSE`/`COPYING` file and `src-tauri/Cargo.toml` has no `license`
|
||||
field. The project is open source and will never be commercial, so this is purely
|
||||
an omission — but it matters because we link libmpv, and "no licence" defaults to
|
||||
*all rights reserved*, which is incompatible with distributing a GPL-derived
|
||||
work.
|
||||
|
||||
## Design
|
||||
|
||||
### Part 1 — licence
|
||||
|
||||
**Use GPLv3.** This is forced, not chosen:
|
||||
|
||||
- mpv's default build is **GPLv2-or-later**, so the combined work must be
|
||||
GPL-compatible.
|
||||
- Apache-2.0 is **GPLv2-incompatible** (patent-termination and indemnification
|
||||
clauses) but GPLv3-compatible.
|
||||
- A scan of the dependency tree found Apache-2.0-**only** crates with no
|
||||
alternative arm — most importantly **`tao`** (Tauri's own windowing crate),
|
||||
plus `sync_wrapper`, `gethostname`, and `ring` (Apache-2.0 AND ISC).
|
||||
|
||||
`tao` is unavoidable in a Tauri app, so GPLv2 is unavailable. Exercising mpv's
|
||||
"or later" option puts the combination at **GPLv3**.
|
||||
|
||||
Actions:
|
||||
- Add `LICENSE` containing the GPLv3 text.
|
||||
- Add `license = "GPL-3.0-or-later"` to `src-tauri/Cargo.toml` and `license` to
|
||||
`package.json`.
|
||||
- Note in the README that the binary links libmpv (GPLv2+) and FFmpeg.
|
||||
|
||||
Because the project is open source, we use mpv's **default GPL build** — no
|
||||
`-Dgpl=false`, no LGPL FFmpeg build, and none of the LGPL §6 relinking analysis
|
||||
that a proprietary app would need. We keep VAAPI/VDPAU/X11 and every GPL FFmpeg
|
||||
filter.
|
||||
|
||||
🔴 Never build FFmpeg with `--enable-nonfree` — that produces a binary that is
|
||||
**unredistributable under any licence**, open source or not.
|
||||
|
||||
### Part 2 — libmpv → libmpv2
|
||||
|
||||
```toml
|
||||
# Linux (and later Windows, per the Windows audio spec)
|
||||
libmpv2 = "=6.0.0"
|
||||
```
|
||||
|
||||
Pin exactly: `libmpv2` has broken its API in **every** major release.
|
||||
|
||||
Breaking changes to expect, from the changelog:
|
||||
|
||||
| Version | Change | Impact here |
|
||||
|---|---|---|
|
||||
| 4.0.0 | Removed command helper methods — call `mpv.command(...)` directly | Low; we already use `command`/`set_property` |
|
||||
| 5.0.0 | Removed `mpv_node` support entirely (properties return strings; parse JSON yourself); `EventContext` folded into `Mpv`; `ProtocolContext` → `Protocol` | **Medium** — `start_event_loop` uses `create_event_context()`; check whether that call still exists |
|
||||
| 6.0.0 | `RenderContext::new()` → `Mpv::create_render_context()`; `'static` bound on `OpenGLInitParams`; render context now borrows `Mpv` (fixes a use-after-free) | **None** — we do not use the render API |
|
||||
|
||||
The last row matters: we run mpv audio-only (`video = no`), so the entire render
|
||||
surface is irrelevant to us. Consider disabling the default `render` feature to
|
||||
reduce build surface.
|
||||
|
||||
The main porting work is the event loop in `mpv_backend.rs` — `wait_event`,
|
||||
`disable_deprecated_events`, and the `FileLoaded` / `PlaybackRestart` /
|
||||
`PropertyChange` / `EndFile` handling, given 5.0.0 folded `EventContext` into
|
||||
`Mpv`.
|
||||
|
||||
Everything else — `set_property` calls, the `af` filter graph, the 250ms position
|
||||
thread, the seek-suppression window — should port unchanged.
|
||||
|
||||
## Layer assignment
|
||||
|
||||
No logic moves. This is a dependency swap plus a licence file; the
|
||||
`PlayerBackend` trait boundary is untouched.
|
||||
|
||||
| Logic / responsibility | Layer | Why it belongs there |
|
||||
|------------------------|-------|----------------------|
|
||||
| mpv event → `PlayerStatusEvent` mapping | Rust (unchanged) | Already correct; only the binding API beneath it changes. |
|
||||
|
||||
## Out of scope
|
||||
|
||||
- Any behaviour change. If playback behaves differently after this, that is a bug.
|
||||
- Windows support — separate spec, but this must land first.
|
||||
- Adopting the render API. We are audio-only on mpv.
|
||||
- Re-licensing decisions beyond adding the file the project already implies.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] `LICENSE` (GPLv3) present; `license` field set in `Cargo.toml` and `package.json`.
|
||||
- [ ] A full dependency-licence audit has been run (`cargo install cargo-license && cargo license`) and confirms no GPLv3-incompatible dependency. *(The scan behind this spec resolved 441 of 575 crates from the local registry cache; the remaining 134 are unverified.)*
|
||||
- [ ] `libmpv` git dependency removed; `libmpv2` pinned to an exact version.
|
||||
- [ ] Linux audio playback works identically: play/pause/seek/volume, queue advance, gapless, EQ, normalization, sleep timer.
|
||||
- [ ] Position updates still arrive at 250ms; the 150ms post-seek suppression still prevents the jump-to-zero glitch.
|
||||
- [ ] `EndFile` still emits `PlaybackEnded` only for EOF (not STOP/QUIT/ERROR) — autoplay depends on this.
|
||||
- [ ] Builder image updated if the libmpv dev package requirement changed; **no toolchain install added to any CI step**.
|
||||
- [ ] `bun run check`, `bun run test`, `bun run check:boundary` pass.
|
||||
- [ ] `cargo fmt` clean, `cargo clippy` clean, `bun run test:rust` passes.
|
||||
|
||||
## Testing
|
||||
|
||||
The existing `mpv_backend_test.rs` plus the `build_af_filter`,
|
||||
`eq_filter_entries`, and `normalize_filter_entry` tests are the regression net —
|
||||
they must pass unchanged, since none of them touch the binding API.
|
||||
|
||||
The event loop has no unit tests and is where the risk concentrates. Verify
|
||||
manually on Linux:
|
||||
|
||||
1. Play → pause → play; confirm position does not flash to 0:00 (the known
|
||||
playing-event regression).
|
||||
2. Seek mid-track; confirm no jump-to-zero within 150ms.
|
||||
3. Let a track end naturally; confirm autoplay advances (exercises `EndFile` EOF).
|
||||
4. Press stop; confirm autoplay does **not** advance.
|
||||
5. Sleep-timer expiry; confirm it stops without triggering autoplay.
|
||||
|
||||
Cases 3–5 are the ones most likely to break silently, and each corresponds to a
|
||||
bug already fixed once in this codebase.
|
||||
|
||||
## TRACES
|
||||
|
||||
- `MpvBackend` construction / event loop → existing `// TRACES: UR-003 | IR-003`, unchanged
|
||||
- No new requirement IDs; this is a dependency migration.
|
||||
|
||||
## Notes for the implementer
|
||||
|
||||
- Do this **before** the Windows audio backend.
|
||||
- Read the 4.0/5.0/6.0 changelogs before writing code — the crate has broken API
|
||||
in every major release, most recently two months before this spec.
|
||||
- The crates.io `repository` field for `libmpv2` points at `kohsine/libmpv-rs`,
|
||||
but the repo was renamed to **`libmpv2-rs`**; the old raw URLs 404.
|
||||
- `libmpv2-sys` ships pregenerated bindings and vendored headers, so no libclang
|
||||
is needed at build time — relevant to keeping the builder image thin.
|
||||
- A parallel Claude session may be active — `git diff` before "repairing"
|
||||
unexpected changes.
|
||||
@@ -0,0 +1,226 @@
|
||||
# Spec: Playback backend unification — findings and strategy
|
||||
|
||||
**Status:** Accepted (analysis; no code changes)
|
||||
**Requirements:** IR-004, UR-031, UR-032, UR-033 — revises the "Platform Playback Backend Parity" issue in requirements.md
|
||||
**UX spec:** n/a
|
||||
**Supersedes / revises:** informs [android-native-video-spike.md](android-native-video-spike.md), [android-audio-settings-parity.md](android-audio-settings-parity.md), [windows-native-audio-backend.md](windows-native-audio-backend.md)
|
||||
|
||||
## Summary
|
||||
|
||||
This spec records the outcome of an investigation into unifying JellyTau's
|
||||
playback backends (Linux/MPV, Android/ExoPlayer, Windows/webview) onto a single
|
||||
engine with hardware acceleration everywhere. **The conclusion is that video
|
||||
cannot be unified onto a native engine, and should not be attempted.** Audio
|
||||
*can* be, and that is where the remaining specs direct effort.
|
||||
|
||||
No code changes follow from this spec directly. It exists so the decision is
|
||||
written down with its evidence, and so a future session does not re-run the same
|
||||
investigation.
|
||||
|
||||
## Motivation
|
||||
|
||||
The requirements doc carries a "Platform Playback Backend Parity" issue noting
|
||||
that audio settings work on Linux but not Android, and proposing eventual
|
||||
convergence. The natural next question — "should we just run one engine
|
||||
everywhere?" — needed answering before spending effort on per-backend patches.
|
||||
|
||||
The investigation also surfaced that several statements in requirements.md and in
|
||||
code comments are factually wrong. Those corrections are part of the deliverable.
|
||||
|
||||
## Findings
|
||||
|
||||
### 1. The current architecture is not what the docs describe
|
||||
|
||||
| Platform | Audio | Video |
|
||||
|----------|-------|-------|
|
||||
| Linux | MPV (native, **audio-only**) | webview `<video>` + hls.js |
|
||||
| Android | ExoPlayer (native) | **webview `<video>` + hls.js** |
|
||||
| Windows | webview `<audio>` | webview `<video>` + hls.js |
|
||||
|
||||
Two surprises:
|
||||
|
||||
- **MPV never decodes video.** `mpv_backend.rs` sets `video = no` and
|
||||
`audio-display = no` at construction. Linux video has always been the webview.
|
||||
Correspondingly, `player_play_item` deliberately does *not* load into MPV on
|
||||
Linux (it calls `set_current_item`, which only updates the queue).
|
||||
- **Android video is also the webview.** `createAdapter()` in
|
||||
`src/lib/player/adapters/index.ts` hardcodes `const effectiveKind = "html5"`
|
||||
and does `void backendKind`, discarding the `use_html5_element` signal that
|
||||
`get_player_status` computes in Rust. `NativePlayerAdapter` is dead code, and
|
||||
ExoPlayer's `SurfaceView` path in `JellyTauPlayer.kt` is unreachable.
|
||||
|
||||
So video is *already* unified — on HTML5, everywhere, by accident of that
|
||||
hardcode — and on the path without hardware decoding on Android.
|
||||
|
||||
### 2. Native video cannot be composited with a Tauri webview
|
||||
|
||||
This is the load-bearing finding. It is **not** an mpv limitation; it defeats
|
||||
every candidate engine identically:
|
||||
|
||||
- **mpv**: `tauri-plugin-libmpv`'s own platform table reads Linux ⚠️
|
||||
*"Experimental. Window embedding is not working."*
|
||||
- **GStreamer** (wry discussion #284, 2024): *"Gstreamer was rendering above the
|
||||
surface and covering all html elements."*
|
||||
- **libVLC** (tauri discussion #6343, 2024): *"I had to render the webview in a
|
||||
child window though because vlc kept rendering on top of it."*
|
||||
|
||||
Root cause, from Tauri maintainer amrbashir (tauri#9220, 2024-03-30):
|
||||
|
||||
> "we are limited to using Webkit2GTK on Linux and that requires a GTK window.
|
||||
> While possible to add a GTK widget as a child X11 window inside raw X11 window,
|
||||
> this is however a bit hacky and **it is not possible on Wayland at all**."
|
||||
|
||||
WebKitGTK, WebView2, and Android WebView each draw into their own compositor
|
||||
surface. A native video surface is either entirely above or entirely below the
|
||||
webview; it cannot interleave with HTML. Every working example in the ecosystem
|
||||
is the same hack — a separate child window position-synced to a
|
||||
`getBoundingClientRect()` div — which breaks on resize, scroll, and any UI drawn
|
||||
over the video. For JellyTau that means the controls, subtitle overlay, and
|
||||
mini-player.
|
||||
|
||||
The most recent comment on tauri#6343 (2026-05-23) confirms it is still unsolved:
|
||||
|
||||
> "I'm faking it and the window is not truly embedded, basically when the parent
|
||||
> moves or resizes I reset the position and size of the libmpv window to align it
|
||||
> with an HTML div."
|
||||
|
||||
**The principle to carry forward: audio can unify on a native engine; video
|
||||
cannot, because video needs a surface and the webview owns the surface.**
|
||||
|
||||
### 3. mpv would regress streaming quality
|
||||
|
||||
mpv has **no adaptive bitrate**. It delegates HLS to FFmpeg's demuxer, which
|
||||
selects one variant at open time and never adapts; mpv#3548 (2016) requested ABR
|
||||
and it never landed. `--hls-bitrate` is a static picker defaulting to `max`.
|
||||
|
||||
The webview path already has real ABR via hls.js. Moving video to mpv would be a
|
||||
**downgrade** on every platform — no graceful degradation on weak networks, and
|
||||
quality changes requiring teardown and reload.
|
||||
|
||||
### 4. Crossfade is architecturally blocked on mpv
|
||||
|
||||
mpv's audio chain is single-stream. FFmpeg's `acrossfade` is an `N→A` filter
|
||||
requiring two input streams, so there is no second input to feed it. Real
|
||||
crossfade needs **two libmpv instances** with manually ramped volumes. Upstream
|
||||
maintainer response (mpv#4512, closed three minutes after opening):
|
||||
|
||||
> "No. I also find crossfading stupid and complex, so the likeliness of that
|
||||
> happening is low."
|
||||
|
||||
GStreamer *could* do it via `audiomixer`. mpv cannot, at any reasonable cost.
|
||||
|
||||
### 5. Engine comparison summary
|
||||
|
||||
| Criterion | mpv | GStreamer | libVLC |
|
||||
|-----------|-----|-----------|--------|
|
||||
| Webview compositing | ❌ Linux broken | ❌ same wall | ❌ same wall |
|
||||
| Adaptive bitrate HLS | ❌ none | ✅ adaptivedemux2 | ✅ adaptive module |
|
||||
| Rust bindings | ⚠️ `libmpv2` active; our pin is dead | ✅ `gstreamer-rs` excellent | ❌ `vlc-rs` abandoned (2018) |
|
||||
| Windows cross-MSVC | ⚠️ prebuilt DLL | ❌ pkg-config vs cargo-xwin | ❌ no better |
|
||||
| Android packaging | ✅ Maven AAR (used by Findroid) | ⚠️ Cerbero/NDK, painful | ✅ mature AAR |
|
||||
| ASS/SSA subtitles | ✅ libass built in | ✅ libass | ✅ libass |
|
||||
| Crossfade | ❌ impossible | ✅ `audiomixer` | ⚠️ unclear |
|
||||
|
||||
Every candidate fails the first row, which is the disqualifying one.
|
||||
|
||||
### 6. Two further options ruled out
|
||||
|
||||
**Webview `<audio>`/`<video>` everywhere** (i.e. delete the native audio backends
|
||||
too) is dead on Android: `navigator.mediaSession` is *deliberately compiled out*
|
||||
of Android WebView (Chromium CL 2613133003), so lockscreen/media-notification
|
||||
control would be impossible. Chromium has also never shipped `audioTracks`. It
|
||||
remains fine for Windows *video*, which is what we already do.
|
||||
|
||||
**FFmpeg-direct / Rust-native** (`ffmpeg-next`, `rsmpeg`, Symphonia) is not
|
||||
close: the safe bindings do not expose hardware decode at all, `ffmpeg-next` is
|
||||
self-declared maintenance-only, and Symphonia lacks HE-AAC and gapless AAC. This
|
||||
is a multi-person-year path to reach parity with what we already have.
|
||||
|
||||
### 7. If libmpv is ever revisited on Android
|
||||
|
||||
Recorded so the next investigation starts from evidence rather than repeating the
|
||||
search. The `dev.jdtech.mpv:libmpv` AAR — maintained by Findroid's author, i.e.
|
||||
another Jellyfin Android client — was inspected directly:
|
||||
|
||||
- `libmpv.so` exports the full 54-function `mpv_*` C API with **zero `Java_`
|
||||
symbols**; JNI is a separate optional ~19 KB `libplayer.so`. So it is drivable
|
||||
from Rust without a Java shim. (This is precisely what disqualifies libVLC,
|
||||
whose Android video path hard-requires a Java `AWindow` jobject.)
|
||||
- ~23 MB/ABI, versus libVLC's ~46 MB/ABI.
|
||||
- 🔴 **The published AAR is built `--enable-gpl --enable-version3` — it is
|
||||
GPLv3**, not LGPL. Fine for us (see [libmpv2-migration.md](libmpv2-migration.md)),
|
||||
but it would be a hard constraint for anyone shipping closed source, and an
|
||||
LGPL rebuild would be your own build to own.
|
||||
- Top unverified risk if anyone tries this: whether `libmpv2-sys` can
|
||||
cross-compile for `aarch64-linux-android` against that prebuilt `.so`. No
|
||||
working example of `libmpv2` on Android was found.
|
||||
|
||||
None of this changes the verdict — the cost is the MediaSession/foreground-service
|
||||
rewrite, not the bindings.
|
||||
|
||||
## Decision
|
||||
|
||||
1. **Do not unify video onto a native engine.** Video stays in the webview with
|
||||
hls.js on all platforms. This is not a compromise — it is the configuration
|
||||
that falls out of the compositing constraint, and it is the only one that
|
||||
gives us ABR for free.
|
||||
2. **Android native video is worth a bounded spike anyway** — not for
|
||||
unification, but because ExoPlayer's `SurfaceView` path already exists and
|
||||
would restore hardware decode plus ASS/SSA subtitles. See
|
||||
[android-native-video-spike.md](android-native-video-spike.md).
|
||||
3. **Audio parity is the real gap** and is achievable without touching any of the
|
||||
above. See [android-audio-settings-parity.md](android-audio-settings-parity.md)
|
||||
and [windows-native-audio-backend.md](windows-native-audio-backend.md).
|
||||
4. **Migrate the dead libmpv pin** regardless of any of this. See
|
||||
[libmpv2-migration.md](libmpv2-migration.md).
|
||||
|
||||
## Corrections to existing docs
|
||||
|
||||
These are factual errors found during the investigation. Fixing them is in scope
|
||||
for this spec.
|
||||
|
||||
| Location | Says | Actually |
|
||||
|----------|------|----------|
|
||||
| `requirements.md` UR-031 (line ~44) | "Done (Linux only)" | Not implemented on any platform. |
|
||||
| `requirements.md` DR-034 (line ~196) | "Done (Linux only)" | Not implemented anywhere — `mpv_backend.rs` has a bare `// TODO: Implement crossfade via MPV audio filters if needed`. Architecturally blocked on mpv (finding 4). |
|
||||
| `requirements.md` parity matrix | Crossfade ✅ Linux / ❌ Android | ❌ / ❌ |
|
||||
| `requirements.md` parity matrix | (no EQ row) | EQ is also Linux-only — `build_af_filter`/`eq_filter_entries` exist only in `mpv_backend.rs`. Same root cause, same fix. |
|
||||
| `nativeAdapter.ts:11-14` | Native Android video "blocked upstream by tauri#10152" | tauri#10152 is a stale *feature request*, dead since 2024-07-01. The capability shipped in tauri commit `27d01834` (2024-09-02). Not a blocker. |
|
||||
|
||||
## Layer assignment
|
||||
|
||||
No new logic. The one boundary observation worth recording:
|
||||
|
||||
| Logic / responsibility | Layer | Why it belongs there |
|
||||
|------------------------|-------|----------------------|
|
||||
| Which video backend a platform uses (`use_html5_element`) | Rust | Already correctly computed in `get_player_status`. The frontend currently *discards* it — that is the bug, not the design. Restoring it means the frontend consumes a backend decision rather than making its own. |
|
||||
|
||||
## Out of scope
|
||||
|
||||
- Any code change. This spec is analysis; the sibling specs carry the work.
|
||||
- iOS/macOS. Not current targets.
|
||||
- Replacing hls.js.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] `requirements.md` DR-034 status corrected; parity matrix updated (crossfade ❌/❌, EQ row added).
|
||||
- [ ] Stale tauri#10152 comment in `nativeAdapter.ts` corrected.
|
||||
- [ ] The four sibling specs exist and are linked from here.
|
||||
|
||||
## Testing
|
||||
|
||||
n/a — documentation only.
|
||||
|
||||
## TRACES
|
||||
|
||||
No new code. Requirement text changes only; DR-034's status line is the one
|
||||
substantive edit.
|
||||
|
||||
## Notes for the implementer
|
||||
|
||||
- The evidence above was gathered in July 2026. The compositing constraint has
|
||||
been stable since 2021 (wry#284) and is maintainer-declared unfixable, so it is
|
||||
unlikely to change soon — but if someone revisits this, tauri#6343 and wry#284
|
||||
are the threads to re-read first.
|
||||
- A parallel Claude session may be active in this repo — `git diff` before
|
||||
"repairing" unexpected changes.
|
||||
@@ -0,0 +1,198 @@
|
||||
# Spec: Playback documentation corrections
|
||||
|
||||
**Status:** Proposed
|
||||
**Requirements:** revises the status of DR-034; corrects the parity matrix in [requirements.md](../requirements.md)
|
||||
**UX spec:** n/a
|
||||
**Supersedes / revises:** implements the "Corrections to existing docs" section of [playback-backend-unification.md](playback-backend-unification.md)
|
||||
|
||||
## Summary
|
||||
|
||||
Fix four factual errors in the requirements doc and the player source comments,
|
||||
all found while investigating backend unification. Each claims something the code
|
||||
does not do. Small change, but they are actively misleading: two of them assert a
|
||||
feature is implemented when it is implemented nowhere, and one cites an upstream
|
||||
blocker that no longer exists.
|
||||
|
||||
Documentation and comments only — no behaviour change.
|
||||
|
||||
## Motivation
|
||||
|
||||
These errors compound. DR-034 reads "Done (Linux only)", so a future session
|
||||
planning Android parity would reasonably assume crossfade exists on Linux and
|
||||
only needs porting — when in fact it is unimplemented everywhere *and*
|
||||
architecturally blocked on the engine it supposedly runs on. Likewise the
|
||||
tauri#10152 comment has been discouraging work on Android native video since the
|
||||
upstream capability shipped in September 2024.
|
||||
|
||||
## The corrections
|
||||
|
||||
### 1. DR-034 status is wrong
|
||||
|
||||
`requirements.md` line ~196:
|
||||
|
||||
```
|
||||
| DR-034 | Crossfade engine with configurable duration (0-12s) | Player | UR-031 | Done (Linux only) |
|
||||
```
|
||||
|
||||
The code:
|
||||
|
||||
```rust
|
||||
// src-tauri/src/player/mpv_backend.rs, in set_audio_settings
|
||||
// TODO: Implement crossfade via MPV audio filters if needed
|
||||
```
|
||||
|
||||
That is the entire crossfade implementation. `crossfade_duration` is plumbed
|
||||
through `AudioSettings` and clamped to 0–12s, but no backend ever acts on it.
|
||||
|
||||
**Change to:** `Not implemented (blocked on MPV — see playback-backend-unification.md)`
|
||||
|
||||
Worth stating *why* in the requirements entry, because it is not a scheduling
|
||||
gap: mpv's audio chain is single-stream, and FFmpeg's `acrossfade` is an `N→A`
|
||||
filter needing two inputs. Real crossfade requires two libmpv instances with
|
||||
manually ramped volumes. Upstream declined the feature (mpv#4512).
|
||||
|
||||
### 1b. UR-031 status is wrong for the same reason
|
||||
|
||||
`requirements.md` line ~44:
|
||||
|
||||
```
|
||||
| UR-031 | Crossfade between audio tracks | Low | Done (Linux only) |
|
||||
```
|
||||
|
||||
Same error one level up: the *user* requirement is also marked done. Since no
|
||||
backend implements crossfade, UR-031 is not satisfied on any platform.
|
||||
|
||||
**Change to:** `Not implemented (blocked — see DR-034)`
|
||||
|
||||
Note line ~517 of the same file (`UR-031 (Crossfade), UR-032 (Gapless),
|
||||
UR-033 (Normalization) only work on Linux`) inherits the error — crossfade works
|
||||
nowhere, so it should read UR-032/UR-033 only.
|
||||
|
||||
### 2. Parity matrix crossfade row is wrong
|
||||
|
||||
```
|
||||
| Crossfade | ✅ | ❌ | Gap |
|
||||
```
|
||||
|
||||
**Change to** `| Crossfade | ❌ | ❌ | Not implemented |` — it is not a
|
||||
platform-parity gap, it is an unbuilt feature.
|
||||
|
||||
### 3. Parity matrix is missing the equalizer
|
||||
|
||||
The matrix lists crossfade, gapless, and normalization but omits the EQ, which
|
||||
has the same Linux-only shape and the same root cause (`ExoPlayerBackend` not
|
||||
overriding `set_audio_settings`). `build_af_filter` and `eq_filter_entries` exist
|
||||
only in `mpv_backend.rs`; there is no equalizer code in the Android tree.
|
||||
|
||||
**Add:** `| Equalizer (10-band) | ✅ | ❌ | Gap |`
|
||||
|
||||
### 4. `nativeAdapter.ts` cites a stale blocker
|
||||
|
||||
`src/lib/player/adapters/nativeAdapter.ts:11-14` states native Android video is
|
||||
blocked upstream by tauri#10152 (transparent webview / SurfaceView compositing).
|
||||
|
||||
tauri#10152 is open but **dead since 2024-07-01**, and it is a *feature request*
|
||||
that `WebviewWindowBuilder::transparent` was desktop-only — not a report that
|
||||
compositing is broken. The capability shipped in tauri commit `27d01834`
|
||||
(2024-09-02), which moved `transparent()` into the cross-platform impl block with
|
||||
only the tao call `#[cfg(desktop)]`-fenced. It landed as a clippy cleanup, so the
|
||||
issue was never closed. Separately, the black/white-screen bug (tauri#8381,
|
||||
tauri#9408) was a broken JNI signature for `setBackgroundColor`, fixed in wry
|
||||
0.39.4; we ship wry 0.55.x.
|
||||
|
||||
**Change to:** a comment stating the adapter is currently unreachable because
|
||||
`createAdapter` hardcodes the HTML5 kind, that transparency is no longer an
|
||||
upstream blocker, and that
|
||||
[android-native-video-spike.md](android-native-video-spike.md) tracks whether
|
||||
SurfaceView compositing actually works. Be explicit that *nobody has
|
||||
demonstrated* SurfaceView-behind-WebView on Tauri Android — nothing upstream
|
||||
blocks it, and nothing upstream proves it.
|
||||
|
||||
### 5. Platform capability is signalled three incompatible ways
|
||||
|
||||
Not a doc error — a real inconsistency found during the same investigation, worth
|
||||
recording here even though fixing it needs its own change.
|
||||
|
||||
Which backend a platform uses is currently expressed three ways:
|
||||
|
||||
1. Rust `#[cfg]` gates in `player/mod.rs` and `create_player_backend` — the truth.
|
||||
2. The `useHtml5Element` / `VideoBackend` value from `get_player_status` — which
|
||||
the frontend discards (see the spike spec).
|
||||
3. **Frontend user-agent sniffing** in `src/lib/services/webviewAudio.ts:30-41`:
|
||||
|
||||
```ts
|
||||
const ua = navigator.userAgent.toLowerCase();
|
||||
const isAndroid = ua.includes("android");
|
||||
const isLinux = ua.includes("linux") && !isAndroid;
|
||||
return !isAndroid && !isLinux;
|
||||
```
|
||||
|
||||
The comment says it is "matching the Rust cfg gate" — i.e. the frontend
|
||||
re-derives a backend decision from the user-agent string and hopes it stays in
|
||||
sync. That is the frontend deciding *which backend exists*, which is domain
|
||||
knowledge, not presentation. It also breaks silently the moment a new target is
|
||||
added or a webview's UA changes.
|
||||
|
||||
**This is a boundary leak of the same family the spec-review checklist exists to
|
||||
catch**, even though `check:boundary`'s tripwire (item-type arrays) does not
|
||||
match it. Rust already computes the answer; the frontend should consume it.
|
||||
|
||||
Not fixed by this spec — it is behavioural, not documentation. It should be
|
||||
folded into the spike spec's factory rework, where the same
|
||||
"consume Rust's decision instead of re-deriving it" change is already in scope.
|
||||
|
||||
### Also worth fixing while here
|
||||
|
||||
`requirements.md` IR-004 reads "In Progress (basic playback works, audio settings
|
||||
missing)". That stays accurate until
|
||||
[android-audio-settings-parity.md](android-audio-settings-parity.md) lands, but
|
||||
the "Future Fix" list in the parity issue proposes
|
||||
`ConcatenatingMediaSource` for crossfade — **deprecated in current Media3**. Drop
|
||||
that suggestion; the modern approach is a custom `AudioProcessor`.
|
||||
|
||||
## Layer assignment
|
||||
|
||||
No logic. Documentation and comments only.
|
||||
|
||||
| Logic / responsibility | Layer | Why it belongs there |
|
||||
|------------------------|-------|----------------------|
|
||||
| — | — | No logic introduced or moved by this spec. |
|
||||
|
||||
## Out of scope
|
||||
|
||||
- Implementing crossfade. This spec only stops claiming it exists.
|
||||
- Implementing Android audio settings — see the parity spec.
|
||||
- Running the Android video spike — see that spec.
|
||||
- Rewriting the architecture docs. `docs/architecture/05-platform-backends.md`
|
||||
should be re-read for the same class of error, but that is a larger pass.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] DR-034 status corrected, with the blocking reason stated.
|
||||
- [ ] UR-031 status corrected (line ~44), and the "only work on Linux" line (~517) no longer lists crossfade.
|
||||
- [ ] Parity matrix: crossfade ❌/❌; equalizer row added.
|
||||
- [ ] `ConcatenatingMediaSource` suggestion removed from the "Future Fix" list.
|
||||
- [ ] `nativeAdapter.ts` comment corrected and pointing at the spike spec.
|
||||
- [ ] `bun run check` and `bun run test` pass (a comment change still touches TS).
|
||||
- [ ] `bun run traces:markdown` re-run if requirement text changed.
|
||||
|
||||
No Rust changes, so the `cargo` gates do not apply.
|
||||
|
||||
## Testing
|
||||
|
||||
None beyond the standard gates — no behaviour changes. Confirm
|
||||
`bun run traces:markdown` regenerates cleanly, since DR-034's row is referenced
|
||||
by the traceability matrix.
|
||||
|
||||
## TRACES
|
||||
|
||||
No code implementing requirements changes; no TRACES comments to add or update.
|
||||
The DR-034 row in `docs/traceability.md` will regenerate with the corrected text.
|
||||
|
||||
## Notes for the implementer
|
||||
|
||||
- Do **not** silently delete DR-034. The requirement (UR-031 crossfade) is still
|
||||
wanted; it is the *status* that is wrong. Keeping the row with an honest status
|
||||
and a reason is the point.
|
||||
- A parallel Claude session may be active — `git diff` before "repairing"
|
||||
unexpected changes.
|
||||
@@ -0,0 +1,258 @@
|
||||
# Spec: Enforce the unified player boundary
|
||||
|
||||
**Status:** Proposed
|
||||
**Requirements:** DR-095 (new); relates to UR-005 and the unified-player-boundary
|
||||
principle in CLAUDE.md and [02-svelte-frontend.md](../architecture/02-svelte-frontend.md)
|
||||
**UX spec:** n/a — refactor, no user-visible change.
|
||||
**Supersedes / revises:** n/a
|
||||
|
||||
## Summary
|
||||
|
||||
The stated principle is that UI controls playback **only** through
|
||||
`playerController` ([src/lib/player/index.ts](../../src/lib/player/index.ts)),
|
||||
never by calling `commands.player*` directly. There are **52 direct call sites
|
||||
outside** that facade. This spec routes the genuine playback-control calls
|
||||
through the facade, narrows the principle's wording so it stops forbidding
|
||||
things it never meant to forbid, and adds the lint rule that keeps it true —
|
||||
because this rule is the one design principle in the audit with **no automated
|
||||
check at all**, and it is also the one that drifted furthest.
|
||||
|
||||
## Motivation
|
||||
|
||||
Direct `commands.player*` usage outside `src/lib/player/`, by file:
|
||||
|
||||
| File | Sites |
|
||||
|---|---|
|
||||
| [queue.ts](../../src/lib/stores/queue.ts) | 10 |
|
||||
| [player/[id]/+page.svelte](../../src/routes/player/[id]/+page.svelte) | 9 |
|
||||
| [VideoPlayer.svelte](../../src/lib/components/player/VideoPlayer.svelte) | 8 |
|
||||
| [settings/+page.svelte](../../src/routes/settings/+page.svelte) | 5 |
|
||||
| [sleepTimer.ts](../../src/lib/stores/sleepTimer.ts) / [auth.ts](../../src/lib/stores/auth.ts) / [autoplay.ts](../../src/lib/api/autoplay.ts) | 4 each |
|
||||
| [preload.ts](../../src/lib/services/preload.ts) | 3 |
|
||||
| [library/[id]](../../src/routes/library/[id]/+page.svelte), [playerEvents.ts](../../src/lib/services/playerEvents.ts), [playbackMode.ts](../../src/lib/stores/playbackMode.ts) | 1–2 each |
|
||||
|
||||
These are **not** equivalent violations, and treating them as one number is why
|
||||
the rule has been easy to ignore. Three distinct groups:
|
||||
|
||||
**(a) Genuine violations — playback control with a facade method that already
|
||||
exists.** `playerStop` ×6, `playerPlayTracks` ×4, `playerSeek` ×2,
|
||||
`playerPlayAlbumTrack` ×2, `playerNext`, `playerPrevious`, `playerSkipTo`,
|
||||
`playerToggleShuffle`, `playerCycleRepeat`, `playerRemoveFromQueue`,
|
||||
`playerMoveInQueue`, `playerAddTrackById`, `playerAddTracksByIds`,
|
||||
`playerSetSubtitleTrack`, `playerPlayItem`. The facade exposes `stop()`,
|
||||
`seek()`, `next()`, `previous()`, `skipTo()`, `toggleShuffle()`,
|
||||
`cycleRepeat()`, `removeFromQueue()`, `moveInQueue()`, `addTrackById()`,
|
||||
`addTracksByIds()`, `setSubtitleTrack()`, `playTracks()`, `playAlbumTrack()`,
|
||||
`playItem()` — every one of these has a facade equivalent that is simply not
|
||||
being called. `queue.ts` is the starkest case: it imports `commands` directly
|
||||
and re-implements ten methods the facade already provides.
|
||||
|
||||
**(b) Playback control with no facade method.** `playerPlayQueue`,
|
||||
`playerGetQueue`, `playerGetStatus`, `playerEnterBackgroundAudio`,
|
||||
`playerExitBackgroundAudio`, `playerSetSleepTimer`, `playerCancelSleepTimer`,
|
||||
`playerPlayNextEpisode`, `playerCancelAutoplayCountdown`. In scope for the
|
||||
principle, but currently *impossible* to comply with — the facade has no surface
|
||||
for them. A rule that cannot be followed is not being broken so much as it is
|
||||
unfinished.
|
||||
|
||||
**(c) Not playback control.** `playerConfigureJellyfin` ×3,
|
||||
`playerDisableJellyfin`, `playerGet/SetAudioSettings`,
|
||||
`playerGet/SetVideoSettings`, `playerGetEqPresets`,
|
||||
`playerGet/SetAutoplaySettings`, `playerGet/SetCacheConfig`,
|
||||
`playerPreloadUpcoming`. These are configuration and lifecycle calls that happen
|
||||
to live under the `player_` command prefix. The principle is about *who is
|
||||
authoritative for playback state* — settings CRUD isn't that.
|
||||
|
||||
The audit's read: the rule as written is violated 52 times, which makes real
|
||||
drift indistinguishable from acceptable usage, and that ambiguity is what lets
|
||||
group (a) persist. Note also that the principle **is** well-honoured where it
|
||||
matters most — the read side is clean, with UI reading state exclusively from
|
||||
the facade's re-exported stores. The write side is what drifted.
|
||||
|
||||
## Layer assignment
|
||||
|
||||
Frontend-internal refactor. No domain logic moves and nothing new crosses IPC —
|
||||
the same Rust commands are called, through one module instead of many.
|
||||
|
||||
| Logic / responsibility | Layer | Why it belongs there |
|
||||
|------------------------|-------|----------------------|
|
||||
| Playback command dispatch (adapter routing: native vs HTML5) | Frontend — `src/lib/player/` **only** | Presentation-layer plumbing, but must be centralised: the facade picks between the native backend and the HTML5 `<video>` adapter. A caller bypassing it silently skips that routing. |
|
||||
| Playback *authority* (position, pause, rate, track changes) | **Rust / the player** | Unchanged. The player is authoritative; UI is a consumer. This spec does not touch that direction. |
|
||||
| Queue mutation commands | Frontend facade → Rust | Rust owns queue state; the facade is the single call path to it. |
|
||||
| Player settings CRUD (EQ, video, autoplay, cache) | Frontend, **outside** the facade | Configuration, not playback control — read/written on a settings page with no adapter routing. Explicitly carved out below. |
|
||||
| Backend→frontend event handling | `playerEvents.ts` | Already correct. It is the facade's own plumbing, not a bypassing consumer. |
|
||||
|
||||
No Jellyfin taxonomy is involved, so no boundary-leak risk.
|
||||
|
||||
## Design
|
||||
|
||||
### 1. Narrow the principle to what it actually means
|
||||
|
||||
Amend CLAUDE.md and [02-svelte-frontend.md](../architecture/02-svelte-frontend.md):
|
||||
|
||||
> **Unified player boundary.** UI controls **playback** — transport, queue
|
||||
> mutation, track selection, playback initiation — *only* through
|
||||
> `playerController`. Player **configuration** commands (`player_*_settings`,
|
||||
> `player_configure_jellyfin`, `player_*_cache_config`, `player_preload_upcoming`)
|
||||
> are ordinary IPC and may be called directly from settings surfaces.
|
||||
|
||||
This is a clarification, not a relaxation: it makes group (c) explicitly fine so
|
||||
that a violation count means something. A rule with 52 nominal violations, most
|
||||
of them acceptable, provides no signal.
|
||||
|
||||
### 2. Fill the facade gaps (group b)
|
||||
|
||||
Add to `playerController`, each a thin pass-through preserving current
|
||||
behaviour:
|
||||
|
||||
```ts
|
||||
playQueue, getQueue, getStatus,
|
||||
enterBackgroundAudio, exitBackgroundAudio,
|
||||
setSleepTimer, cancelSleepTimer,
|
||||
playNextEpisode, cancelAutoplayCountdown,
|
||||
```
|
||||
|
||||
Do this **first** — group (a) cannot be fully migrated while callers still need
|
||||
a direct import for a neighbouring call, and a file that imports `commands` for
|
||||
one reason will keep using it for others.
|
||||
|
||||
### 3. Migrate group (a)
|
||||
|
||||
Mechanical: replace `commands.playerX(...)` with `playerController.x(...)`.
|
||||
Highest-value first: `queue.ts` (10 sites, all direct facade equivalents), then
|
||||
`player/[id]/+page.svelte`, `VideoPlayer.svelte`, `sleepTimer.ts`,
|
||||
`playbackMode.ts`, `library/[id]/+page.svelte`.
|
||||
|
||||
Two sites need care rather than substitution:
|
||||
|
||||
- **`playerEvents.ts`** (`playerOnPlaybackEnded`, `playerStop` in the error
|
||||
path). This module *is* the facade's event plumbing — the counterpart to
|
||||
`index.ts`, inside the boundary conceptually though not by directory. Treat
|
||||
`src/lib/services/playerEvents.ts` as **inside** the boundary and exempt it,
|
||||
rather than making it call the facade that calls back into it. Record this in
|
||||
the lint config with the reason.
|
||||
- **`VideoPlayer.svelte`** — registers its own adapter via `setActiveAdapter`.
|
||||
Its `playerStop`/`playerPlayItem` calls interact with adapter lifecycle, and
|
||||
CLAUDE.md's gotcha ("no lifecycle calls after an `await` in `onMount`") applies.
|
||||
Migrate this file **last and on its own**, so an Android seek regression is
|
||||
bisectable to one commit.
|
||||
|
||||
### 4. Add the lint rule (the part that makes it stick)
|
||||
|
||||
The audit's finding was that principles with working checks held up and
|
||||
principles without them drifted. This principle has no check. Add
|
||||
`scripts/check-player-boundary.sh`, wired as `bun run check:player-boundary` and
|
||||
into `test-all.sh`:
|
||||
|
||||
```sh
|
||||
# Playback-control commands that MUST go through the facade.
|
||||
CONTROL='player(Play|Pause|Toggle|Stop|Seek|Next|Previous|SkipTo|ToggleShuffle|CycleRepeat|RemoveFromQueue|MoveInQueue|SetVolume|ToggleMute|SetSubtitleTrack|SeekVideo|SwitchAudioTrack|PlayTracks|PlayAlbumTrack|PlayItem|PlayQueue|AddTrackById|AddTracksByIds|GetQueue|GetStatus|EnterBackgroundAudio|ExitBackgroundAudio|SetSleepTimer|CancelSleepTimer|PlayNextEpisode|CancelAutoplayCountdown|OnPlaybackEnded)'
|
||||
|
||||
# Inside the boundary: the facade and its event plumbing.
|
||||
EXEMPT='^src/lib/player/|^src/lib/services/playerEvents\.ts$'
|
||||
```
|
||||
|
||||
Flag `commands.$CONTROL` in non-test `src/` files outside `EXEMPT`. Config
|
||||
commands are deliberately absent from the list, matching §1 — so the check
|
||||
encodes the narrowed rule rather than the aspirational one.
|
||||
|
||||
An ESLint `no-restricted-syntax` rule would give better editor feedback, but the
|
||||
project has no ESLint config; a shell check matches the existing
|
||||
`check:boundary` precedent and adds no dependency.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- Changing playback *behaviour* — pure refactor.
|
||||
- The one-directional state principle (audited clean; UI reads from facade
|
||||
stores only).
|
||||
- Moving settings CRUD behind the facade (§1 explicitly carves it out).
|
||||
- Introducing ESLint.
|
||||
- Refactoring `VideoPlayer.svelte`'s 2079 lines generally, beyond its facade
|
||||
call sites.
|
||||
- The `commands.player*` calls **inside** `src/lib/player/` — that is the
|
||||
facade doing its job.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] `playerController` exposes the group-(b) methods listed in §2.
|
||||
- [ ] `grep -rn "commands\.player" src/ --include='*.ts' --include='*.svelte' | grep -v '^src/lib/player/' | grep -v 'playerEvents\.ts' | grep -v '\.test\.' | grep -v bindings.ts`
|
||||
returns **only** configuration commands per §1 — no transport, queue, or
|
||||
playback-initiation call.
|
||||
- [ ] `queue.ts` no longer imports `commands` from bindings.
|
||||
- [ ] `bun run check:player-boundary` exists, is wired into `test-all.sh`, and
|
||||
passes.
|
||||
- [ ] The check **fails** when a `commands.playerStop()` is added to a non-exempt
|
||||
file — verify explicitly, as with the other gates in this batch.
|
||||
- [ ] The check does **not** fail on `commands.playerSetAudioSettings()` in
|
||||
`settings/+page.svelte` (the §1 carve-out works).
|
||||
- [ ] CLAUDE.md and `02-svelte-frontend.md` carry the narrowed wording, including
|
||||
the config carve-out and the `playerEvents.ts` exemption with its reason.
|
||||
- [ ] **No behavioural change**: audio and video playback, queue reorder,
|
||||
shuffle/repeat, sleep timer, background audio, and autoplay all behave as
|
||||
before on **both Linux and Android**.
|
||||
- [ ] Android seek and `onMount` lifecycle still correct after the
|
||||
`VideoPlayer.svelte` migration (the known-fragile path).
|
||||
- [ ] `bun run check` and `bun run test` pass.
|
||||
- [ ] `bun run check:boundary` passes.
|
||||
- [ ] Changed code carries `// TRACES:` comments.
|
||||
- [ ] No Rust change, so no `bindings.ts` regeneration.
|
||||
|
||||
## Testing
|
||||
|
||||
**Frontend** (`bun run test`):
|
||||
- Extend the existing facade tests to cover each new group-(b) method: it
|
||||
forwards to the right command with the right arguments, and routes to the
|
||||
active adapter where applicable.
|
||||
- `queue.ts` tests: assert calls land on `playerController`, not `commands`. Mock
|
||||
the facade — a test that mocks `commands` would pass either way and guard
|
||||
nothing.
|
||||
- Keep `tauriIntegration.test.ts` and the other IPC param-naming tests green;
|
||||
they cover the camelCase rule this refactor must not disturb.
|
||||
|
||||
**Manual** (no automated coverage for these paths):
|
||||
- Linux: play/pause/seek/next/prev, queue reorder, shuffle, repeat, sleep timer,
|
||||
transcoded video (HLS), background audio enter/exit.
|
||||
- Android: the same, plus lockscreen/MediaSession controls, and **seek after
|
||||
entering the player** — the specific regression CLAUDE.md warns about.
|
||||
|
||||
Because this is a pure refactor, the strongest signal is that no test *changes
|
||||
expectation*. A test needing its assertions rewritten means behaviour moved —
|
||||
investigate rather than update it.
|
||||
|
||||
## TRACES
|
||||
|
||||
Allocate in `requirements.md`:
|
||||
|
||||
- **DR-095** — "UI playback control is routed exclusively through the
|
||||
`playerController` facade (`src/lib/player/`), with `playerEvents.ts` inside
|
||||
the boundary as its event plumbing and player *configuration* commands
|
||||
explicitly outside it; enforced by `scripts/check-player-boundary.sh`."
|
||||
Category: Player. Traces to UR-005. Status: Done on merge.
|
||||
|
||||
```typescript
|
||||
// src/lib/player/index.ts
|
||||
// TRACES: UR-005 | DR-095
|
||||
```
|
||||
|
||||
New facade tests take `@req-test: UT-089` onward (next free UT is **UT-089**;
|
||||
coordinate if landing alongside the sibling specs, which draw from the same
|
||||
pool).
|
||||
|
||||
## Notes for the implementer
|
||||
|
||||
- A parallel Claude session may be active in this repo — `git diff` before
|
||||
"repairing" unexpected changes (CLAUDE.md §Gotchas).
|
||||
- **Order matters**: §2 (fill gaps) → §3 (migrate, `VideoPlayer.svelte` last and
|
||||
alone) → §4 (add the check). Adding the check first turns `master` red.
|
||||
- 🔴 **`VideoPlayer.svelte`**: no lifecycle calls after an `await` in `onMount` —
|
||||
it flips to HTML5 mode and breaks Android seek. Do not let a mechanical
|
||||
substitution introduce an `await` before a lifecycle call.
|
||||
- The facade's `requireHandle()` may throw where a raw `commands` call did not.
|
||||
Check each migrated call site's error handling rather than assuming the
|
||||
try/catch still covers the same cases.
|
||||
- `playbackMode.ts` interacts with remote-mode routing (`play_on_session` vs
|
||||
local MPV). Verify remote casting still works after migrating its
|
||||
`playerPlayTracks` call.
|
||||
- This spec is deliberately the *lowest* priority of the audit batch: it is the
|
||||
largest diff and the only one carrying real regression risk, while the
|
||||
traceability gate is a few lines and restores a dead safety net.
|
||||
@@ -0,0 +1,161 @@
|
||||
# Spec: Remove the broken `check-req-coverage.sh`
|
||||
|
||||
**Status:** Implemented
|
||||
**Requirements:** supports DR-093 (see [traceability-gate-repair.md](traceability-gate-repair.md))
|
||||
**UX spec:** n/a — developer tooling.
|
||||
**Supersedes / revises:** n/a
|
||||
|
||||
## Summary
|
||||
|
||||
`scripts/check-req-coverage.sh` is broken, orphaned, and actively misleading: it
|
||||
reports `Total Requirements: 1`, zeros in every category, and then prints
|
||||
**"✨ All requirements have implementations!"**. Nothing references it — not CI,
|
||||
not `package.json`, not the docs. This spec deletes it, with a narrowly-scoped
|
||||
alternative (repair it) documented and rejected below.
|
||||
|
||||
## Motivation
|
||||
|
||||
Running it today produces:
|
||||
|
||||
```
|
||||
Category Breakdown:
|
||||
UR: 0 requirements
|
||||
IR: 0 requirements
|
||||
DR: 0 requirements
|
||||
JA: 0 requirements
|
||||
|
||||
Summary:
|
||||
Total Requirements: 1
|
||||
✅ Fully Implemented: 0 (0%)
|
||||
|
||||
✨ All requirements have implementations!
|
||||
```
|
||||
|
||||
Every number is wrong (the real totals are UR 61, IR 29, DR 89, JA 32), and the
|
||||
concluding message is the *opposite* of a warning — a developer running this to
|
||||
sanity-check coverage is told everything is fine.
|
||||
|
||||
This is worse than having no script. It is a trap, and it sits in `scripts/`
|
||||
next to tools that do work, with nothing marking it as dead.
|
||||
|
||||
Verification that it is genuinely orphaned:
|
||||
|
||||
```console
|
||||
$ grep -rn "check-req-coverage" . --include='*.yml' --include='*.json' \
|
||||
--include='*.sh' --include='*.md' | grep -v node_modules
|
||||
(no output)
|
||||
```
|
||||
|
||||
## Layer assignment
|
||||
|
||||
Developer tooling only; no application logic and nothing crosses the IPC
|
||||
boundary.
|
||||
|
||||
| Logic / responsibility | Layer | Why it belongs there |
|
||||
|------------------------|-------|----------------------|
|
||||
| Requirement-coverage reporting | Build tooling — `extract-traces.ts` | One tool should own coverage analysis. A second, divergent implementation is how the two answers ("1 requirement" vs "211") came to disagree unnoticed. |
|
||||
|
||||
## Design
|
||||
|
||||
**Delete `scripts/check-req-coverage.sh`.**
|
||||
|
||||
Coverage reporting is owned by [scripts/extract-traces.ts](../../scripts/extract-traces.ts),
|
||||
which is correct, is what CI runs, and gains a first-class local coverage mode
|
||||
in [traceability-gate-repair.md](traceability-gate-repair.md):
|
||||
|
||||
```bash
|
||||
bun run traces:coverage # the supported way to check coverage locally
|
||||
```
|
||||
|
||||
Then check the sibling scripts for the same rot. `scripts/` also contains
|
||||
`check-test-coverage.sh` and `find-req-implementations.sh`, neither of which is
|
||||
referenced from `package.json`. An unreferenced script is never run and so rots
|
||||
silently — that is the actual failure mode being fixed here, and fixing only the
|
||||
one instance found by audit leaves the others to be rediscovered later.
|
||||
|
||||
### Findings (investigation, 2026-07)
|
||||
|
||||
All three scripts turned out to share a **single root cause**, and all three are
|
||||
deleted:
|
||||
|
||||
| Script | Defect |
|
||||
|---|---|
|
||||
| `check-req-coverage.sh` | Reads `README.md`, which has held **zero** requirement rows since they moved to `docs/requirements.md` → `total_reqs=1`, every category 0, "✨ All requirements have implementations!" Also greps `src-tauri/` unscoped. |
|
||||
| `check-test-coverage.sh` | Greps `src-tauri/` unscoped — including **40 GB** of `target/` build artifacts. Hangs indefinitely; produces no output at all. |
|
||||
| `find-req-implementations.sh` | Same unscoped `src-tauri/` grep. Same hang. |
|
||||
|
||||
So none of them were subtly wrong — two could never terminate, and the third
|
||||
inverted its own conclusion.
|
||||
|
||||
They were nonetheless *salvageable*: scoping the greps to `src-tauri/src` and
|
||||
repointing at `docs/requirements.md` would be a few lines, and the `@req:` /
|
||||
`@req-test:` tags they read are still present in the tree (**146** and **76**
|
||||
occurrences).
|
||||
|
||||
**Decision: delete all three anyway.** The tags are an undocumented parallel
|
||||
convention — `@req:` appears in no doc, and CLAUDE.md describes only `TRACES:`.
|
||||
Repairing the scripts would re-establish a second traceability system to keep in
|
||||
sync with the first, which is the same two-sources-of-truth condition that let
|
||||
"1 requirement" and "211 requirements" coexist unnoticed. `TRACES:` plus the
|
||||
repaired coverage engine ([traceability-gate-repair.md](traceability-gate-repair.md))
|
||||
already cover this ground.
|
||||
|
||||
The existing `@req:` / `@req-test:` comments are left in place: they are
|
||||
harmless as prose, several encode genuinely useful test intent, and stripping
|
||||
222 comments across the tree is a large diff with no functional gain. They are
|
||||
simply no longer read by any tool.
|
||||
|
||||
### Alternative considered: repair rather than delete
|
||||
|
||||
Rejected. The script's output format duplicates what `traces:markdown` already
|
||||
generates, it has no tests, no caller, and no documented purpose distinct from
|
||||
`extract-traces.ts`. Repairing it recreates the two-sources-of-truth condition
|
||||
that produced the contradiction. If a shell-based coverage check is ever wanted,
|
||||
it should shell out to `traces:json` and `jq` rather than re-parse
|
||||
`requirements.md` independently.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- The CI workflow denominators — [traceability-gate-repair.md](traceability-gate-repair.md).
|
||||
- Any change to `extract-traces.ts`'s output (that spec owns it).
|
||||
- Auditing scripts that *are* referenced from `package.json` — they run
|
||||
regularly and would fail visibly.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] `scripts/check-req-coverage.sh` no longer exists.
|
||||
- [ ] `grep -rn "check-req-coverage" .` (excluding `node_modules` and this spec)
|
||||
returns nothing — no dangling reference in CI, docs, or `package.json`.
|
||||
- [ ] `scripts/check-test-coverage.sh` and `find-req-implementations.sh` have each
|
||||
been run and either wired into `package.json` or deleted; the decision and
|
||||
reason are recorded in `scripts/README.md`. **Outcome: all three deleted —
|
||||
see Findings.**
|
||||
- [ ] `scripts/README.md` documents `bun run traces:coverage` as the supported
|
||||
way to check requirement coverage locally.
|
||||
- [ ] `bun run test:all` passes (confirms nothing invoked the deleted script).
|
||||
- [ ] `bun run check` and `bun run test` pass.
|
||||
- [ ] `bun run check:boundary` passes.
|
||||
|
||||
## Testing
|
||||
|
||||
No unit tests — this is a deletion. Verification is the grep in the acceptance
|
||||
criteria plus a green `bun run test:all`, which exercises the script paths that
|
||||
actually run.
|
||||
|
||||
## TRACES
|
||||
|
||||
No new requirement. The deletion is covered by **DR-093**
|
||||
([traceability-gate-repair.md](traceability-gate-repair.md)), which establishes
|
||||
`extract-traces.ts` as the single owner of coverage reporting. Note the removal
|
||||
in that DR's text when both land.
|
||||
|
||||
## Notes for the implementer
|
||||
|
||||
- A parallel Claude session may be active in this repo — `git diff` before
|
||||
"repairing" unexpected changes (CLAUDE.md §Gotchas).
|
||||
- Land this **after** or alongside [traceability-gate-repair.md](traceability-gate-repair.md),
|
||||
so `bun run traces:coverage` exists before the broken script is removed and
|
||||
developers are never left without a coverage command.
|
||||
- Check `docs/traceability-ci.md` and `docs/traces-quick-ref.md` for prose
|
||||
references to the deleted script; the grep above covers `.md`, but read the
|
||||
surrounding sentence rather than deleting the line mechanically.
|
||||
@@ -0,0 +1,254 @@
|
||||
# Spec: Land the scoped-search boundary fix (implementation)
|
||||
|
||||
**Status:** Stage 1 Implemented — Stage 2 (result-side grouping) outstanding
|
||||
**Requirements:** UR-049, UR-050 | DR-063, DR-066, DR-067 (existing — no new IDs)
|
||||
**UX spec:** n/a — zero user-visible change is the point (see Acceptance criteria).
|
||||
**Supersedes / revises:** implements [scoped-search-boundary.md](scoped-search-boundary.md),
|
||||
which specified this fix but was never built. That spec remains the **design
|
||||
authority**; this one is the delivery plan and status correction.
|
||||
|
||||
## Summary
|
||||
|
||||
[scoped-search-boundary.md](scoped-search-boundary.md) diagnosed a domain-taxonomy
|
||||
leak, specified the fix in full detail, and became the justification for the
|
||||
project's boundary rule in CLAUDE.md, the `check:boundary` tripwire, and the
|
||||
spec-review checklist. **The fix was never implemented.** The leak it describes
|
||||
is still live in `main`. This spec exists to close that gap and to correct the
|
||||
record — the codebase currently enforces a rule against a violation it still
|
||||
contains.
|
||||
|
||||
## Motivation
|
||||
|
||||
The mapping the rule forbids is present and in use:
|
||||
|
||||
```ts
|
||||
// src/lib/utils/searchScope.ts:29-32
|
||||
const SCOPE_ITEM_TYPES: Record<Exclude<SearchScope, "all">, string[]> = {
|
||||
music: ["MusicAlbum", "MusicArtist", "Audio", "Playlist"],
|
||||
movies: ["Movie"],
|
||||
tv: ["Series", "Episode"],
|
||||
};
|
||||
```
|
||||
|
||||
This is not dead code. [library.ts:262](../../src/lib/stores/library.ts#L262)
|
||||
calls `scopeItemTypes(scope)` and puts the result straight into
|
||||
`options.includeItemTypes`. Meanwhile there is **no `SearchScope` anywhere in
|
||||
`src-tauri/`**:
|
||||
|
||||
```console
|
||||
$ grep -rn "SearchScope" src-tauri/src --include='*.rs'
|
||||
(no output)
|
||||
```
|
||||
|
||||
Three things make this the highest-value item found in the design-principles
|
||||
audit:
|
||||
|
||||
1. **The rule's own founding incident is unremediated.** CLAUDE.md cites this
|
||||
spec as "the incident this rule came from." A rule whose originating
|
||||
violation is still shipping is not credible.
|
||||
2. **The tripwire cannot see it.** `bun run check:boundary` passes — it greps for
|
||||
a multi-type array literal *at the query site*, and this one is assigned to a
|
||||
named const and dereferenced elsewhere. Broadening the tripwire is specified
|
||||
separately in [boundary-tripwire-hardening.md](boundary-tripwire-hardening.md);
|
||||
note that hardening it **without** landing this fix would turn `master` red.
|
||||
3. **The spec's own acceptance criterion fails today.** "Adding a hypothetical
|
||||
new type to a scope requires editing only Rust" — adding a type to the Music
|
||||
scope right now requires editing `searchScope.ts`.
|
||||
|
||||
## Layer assignment
|
||||
|
||||
Unchanged from [scoped-search-boundary.md](scoped-search-boundary.md) §Design;
|
||||
restated so this spec is reviewable on its own.
|
||||
|
||||
| Logic / responsibility | Layer | Why it belongs there |
|
||||
|------------------------|-------|----------------------|
|
||||
| Scope → Jellyfin item types (`music` → `MusicAlbum`, `MusicArtist`, `Audio`, `Playlist`) | **Rust** | Domain vocabulary. Changes if Jellyfin adds/renames an item type — the litmus test's "yes" case. This is the leak being fixed. |
|
||||
| Result item → search group bucketing | **Rust** | Same taxonomy, result side. Classifying a `MediaItem` as a Song vs Album is Jellyfin vocabulary, not layout. |
|
||||
| `All` sends no filter at all (≠ union of enumerated types) | **Rust** | A query-shaping rule with a correctness consequence (Person/folder results would be silently dropped). Belongs with the expansion it qualifies. |
|
||||
| Group display order, labels, reordering, persistence | Frontend | Pure presentation — changes only if the UI is redesigned. Explicitly retained frontend-side. |
|
||||
| `resolveSearchScope(pathname)` — route → initial scope | Frontend | Routing/navigation, no Jellyfin vocabulary. Stays exactly as-is. |
|
||||
| Chip labels (`SCOPE_LABELS`), scope order (`SEARCH_SCOPES`) | Frontend | Display strings over an opaque enum. |
|
||||
| `GROUP_SCOPE` (which group belongs to which scope) | **Delete** | Borderline taxonomy, made redundant: once Rust filters by scope, out-of-scope groups arrive empty and drop via the empty-omit rule. Borderline defaults to Rust; here it defaults to *gone*. |
|
||||
|
||||
The `SearchScope` and `SearchGroupId` **types** come to the frontend from
|
||||
generated `bindings.ts`. Naming an opaque enum variant is not taxonomy; knowing
|
||||
what item types it expands to is.
|
||||
|
||||
## Design
|
||||
|
||||
**Follow [scoped-search-boundary.md](scoped-search-boundary.md) §Design as
|
||||
written** — `SearchScope` enum + `item_types()` in `repository/types.rs`,
|
||||
`SearchOptions.scope`, `SearchGroupId`/`SearchGroup`/`GroupedSearchResult`,
|
||||
scope-wins precedence, `All` → `None` → no filter. It is not restated here;
|
||||
duplicating it would create two drifting copies of the same design.
|
||||
|
||||
This spec adds only the delivery sequencing that the original left implicit.
|
||||
|
||||
### Staging: land it in two reviewable pieces
|
||||
|
||||
The original bundles the query side and the result side into one change. That is
|
||||
a large diff touching Rust types, `bindings.ts`, the store, and a component, with
|
||||
the `search-event` dual-payload hazard in the middle. Split it:
|
||||
|
||||
**Stage 1 — query side (closes the leak).**
|
||||
`SearchScope` enum, `SearchOptions.scope`, command resolves scope →
|
||||
`include_item_types` in Rust, `library.ts` sends `{ scope }`, delete
|
||||
`SCOPE_ITEM_TYPES` and `scopeItemTypes()`. Result grouping stays as it is.
|
||||
|
||||
After Stage 1 the actual boundary violation is gone and
|
||||
[boundary-tripwire-hardening.md](boundary-tripwire-hardening.md) can land safely.
|
||||
|
||||
**Stage 2 — result side.** `SearchGroupId`/`SearchGroup`/`GroupedSearchResult`,
|
||||
Rust bucketing, both payloads converted, `composeSearchGroups()` shrunk,
|
||||
`GROUP_ITEM_TYPES`/`groupItemTypes()`/`GROUP_SCOPE` deleted.
|
||||
|
||||
Both stages are required for the original spec's acceptance criteria to pass;
|
||||
Stage 1 alone leaves `GROUP_ITEM_TYPES` in the frontend. **Stage 1 is not a
|
||||
stopping point** — it is a review boundary. Do not mark the parent spec
|
||||
Implemented until Stage 2 lands.
|
||||
|
||||
### Stage 1 — delivered (July 2026)
|
||||
|
||||
- `SearchScope` enum + `item_types()` in [repository/types.rs](../../src-tauri/src/repository/types.rs);
|
||||
`All` → `None` → no filter.
|
||||
- `SearchOptions.scope` with `resolve_scope()`; scope wins over
|
||||
`include_item_types`, which stays for the non-search `get_items` callers.
|
||||
- `repository_search` resolves the scope **once, before** the cache/server split,
|
||||
so both phases filter identically.
|
||||
- `SCOPE_ITEM_TYPES` and `scopeItemTypes()` deleted; `searchScope.ts` now
|
||||
re-exports `SearchScope` from the generated bindings instead of a hand-written
|
||||
union.
|
||||
- [library.ts](../../src/lib/stores/library.ts) sends `{ scope }`.
|
||||
- 8 Rust tests (`search_scope_tests`); the frontend suite now asserts the
|
||||
*opaque scope* is sent rather than an item-type list.
|
||||
|
||||
Verified: adding `"AudioBook"` to the Music scope changed **zero** files under
|
||||
`src/` — the criterion that failed before this work.
|
||||
|
||||
**Stage 2 remains open**: `GROUP_ITEM_TYPES` / `groupItemTypes()` (result-side
|
||||
bucketing, single-type-per-group) are still in `searchScope.ts`, and both search
|
||||
payloads still carry a flat `MediaItem[]` rather than `GroupedSearchResult`.
|
||||
|
||||
### 🔴 The `search-event` dual payload (Stage 2)
|
||||
|
||||
The original flags this as "the single largest part of the change and the
|
||||
easiest to half-do." Restating because it is the one thing that silently breaks:
|
||||
search resolves **twice** — the command returns instant cache results, then the
|
||||
merged cache+server union arrives via `search-event`. Both payloads must carry
|
||||
`GroupedSearchResult`. Convert one and the UI flickers between shapes as server
|
||||
results land.
|
||||
|
||||
Write the failing test for the *event* payload first — the command return is the
|
||||
obvious half, the event is the half that gets forgotten.
|
||||
|
||||
### Note on `SearchOptions.scope` and specta
|
||||
|
||||
`SearchOptions` is already `#[serde(rename_all = "camelCase")]` with
|
||||
`skip_serializing_if = "Option::is_none"`. Add `scope: Option<SearchScope>`
|
||||
following that pattern so `All`/absent omits the key. Regenerate `bindings.ts`
|
||||
— `SearchOptions` there is currently
|
||||
`{ limit?, includeItemTypes?, searchTerm? }` and must gain `scope?`. Never
|
||||
hand-edit it.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- Redesigning anything in [scoped-search-boundary.md](scoped-search-boundary.md).
|
||||
If implementation shows the design wrong, revise **that** spec, don't fork it.
|
||||
- Online/offline `include_item_types` **filtering** — already correct; only the
|
||||
source of the type list moves.
|
||||
- Ranking within or across groups (DR-090 territory).
|
||||
- Chip UX, scope persistence, group-order persistence — unchanged.
|
||||
- The two lesser type-set sites in `DownloadedBrowse.svelte` and
|
||||
`GenericMediaListPage.svelte`, handled in
|
||||
[boundary-tripwire-hardening.md](boundary-tripwire-hardening.md).
|
||||
- Broadening the tripwire itself — same sibling spec.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
Inherits every criterion from [scoped-search-boundary.md](scoped-search-boundary.md)
|
||||
§Acceptance criteria. Additionally:
|
||||
|
||||
- [ ] `grep -rn "SearchScope" src-tauri/src --include='*.rs'` returns matches —
|
||||
the enum exists in Rust (it does not today).
|
||||
- [ ] `grep -n "SCOPE_ITEM_TYPES\|scopeItemTypes\|GROUP_ITEM_TYPES\|groupItemTypes" src/lib/utils/searchScope.ts`
|
||||
returns nothing.
|
||||
- [ ] `grep -rn "scopeItemTypes" src/` returns nothing — including the
|
||||
`library.ts` import and call site.
|
||||
- [ ] `SearchOptions` in `bindings.ts` includes `scope`; regenerated, not
|
||||
hand-edited.
|
||||
- [ ] **Behaviour is byte-identical for the user**: same scoping, same groups,
|
||||
same order, same empty-group omission, offline included. This spec is a
|
||||
pure refactor — any visible change is a defect.
|
||||
- [ ] `All` scope sends no `includeItemTypes` (asserted in a Rust test, not by
|
||||
inspection).
|
||||
- [ ] Adding a type to the Music scope requires editing **only** Rust —
|
||||
demonstrate by making the edit and confirming no `src/` file changes.
|
||||
- [ ] `scoped-search-boundary.md` status flips to **Implemented**, and
|
||||
`scoped-search.md`'s "frontend only, no Rust changes" framing gets a
|
||||
banner pointing at the corrected design.
|
||||
- [ ] `bun run check` and `bun run test` pass.
|
||||
- [ ] `cargo fmt` clean, `cargo clippy` clean, `bun run test:rust` passes.
|
||||
- [ ] `bun run check:boundary` passes.
|
||||
- [ ] Changed code carries `// TRACES:` comments (IDs below).
|
||||
|
||||
## Testing
|
||||
|
||||
Follow [scoped-search-boundary.md](scoped-search-boundary.md) §Testing. Emphases:
|
||||
|
||||
**Rust** (`cargo test`):
|
||||
- `SearchScope::item_types()` per scope; `All` → `None`.
|
||||
- Scope resolution happens **before** the online/offline split, so both paths
|
||||
get the same filter — a regression here is invisible until someone searches
|
||||
offline.
|
||||
- `scope` set + `include_item_types` set → scope wins (the documented
|
||||
precedence; assert it rather than trusting the doc).
|
||||
- Stage 2: mixed `Vec<MediaItem>` buckets correctly; unknown types dropped;
|
||||
canonical group order; **the `search-event` payload is the grouped shape**.
|
||||
|
||||
**Frontend** (`bun run test`):
|
||||
- `resolveSearchScope()` tests in `searchScope.test.ts` must pass **unchanged** —
|
||||
they cover the part that is not moving, and are the regression net proving the
|
||||
refactor didn't disturb routing.
|
||||
- `library.ts` sends `{ scope }` and never `includeItemTypes` for search.
|
||||
- `composeSearchGroups()` over fixture `SearchGroup[]` with no `.type`
|
||||
inspection in the implementation.
|
||||
|
||||
**Offline parity:** run a scoped search with the server unreachable and confirm
|
||||
identical grouping. The offline repository path honours `include_item_types`
|
||||
independently, and this is the case most likely to be missed.
|
||||
|
||||
## TRACES
|
||||
|
||||
No new requirement IDs — this implements existing ones. Retag as the code moves:
|
||||
|
||||
```rust
|
||||
// src-tauri/src/repository/types.rs
|
||||
/// TRACES: UR-049 | DR-063
|
||||
pub enum SearchScope { … }
|
||||
```
|
||||
|
||||
```typescript
|
||||
// src/lib/utils/searchScope.ts — keep the file header; it retains
|
||||
// resolveSearchScope + group-order presentation logic.
|
||||
// TRACES: UR-049, UR-050 | DR-063, DR-066, DR-067
|
||||
```
|
||||
|
||||
Update DR-063's text in `requirements.md` to state that scope expansion is owned
|
||||
by Rust, so the requirement stops describing the leaked design. New Rust tests
|
||||
take `@req-test: UT-089` onward (next free UT is **UT-089**).
|
||||
|
||||
## Notes for the implementer
|
||||
|
||||
- A parallel Claude session may be active in this repo — `git diff` before
|
||||
"repairing" unexpected changes (CLAUDE.md §Gotchas).
|
||||
- **Read [scoped-search-boundary.md](scoped-search-boundary.md) first.** This
|
||||
spec is deliberately thin on design; that one is the authority.
|
||||
- Sequence with the sibling specs: **Stage 1 here → then
|
||||
[boundary-tripwire-hardening.md](boundary-tripwire-hardening.md)**. Hardening
|
||||
the tripwire first turns `master` red on a known-unfixed violation.
|
||||
- `git log --oneline -- docs/specs/scoped-search-boundary.md` is worth a look
|
||||
before starting — understanding why the fix stalled may surface a constraint
|
||||
the spec didn't record.
|
||||
- The user-visible-change count for this spec is zero. If QA reports a
|
||||
difference in search results, that is a bug in the refactor, not an
|
||||
improvement.
|
||||
@@ -8,8 +8,14 @@
|
||||
> is being moved into Rust. The **user-facing behaviour and UX in this spec are
|
||||
> unchanged**; only where the scope→item-type mapping and result bucketing live
|
||||
> changes. Read the boundary spec before touching search code.
|
||||
>
|
||||
> **Progress:** the scope→item-type mapping now lives in Rust
|
||||
> (`SearchScope::item_types()`); the frontend sends an opaque scope. Result-side
|
||||
> bucketing (`GROUP_ITEM_TYPES`) is still frontend-side — see
|
||||
> [scoped-search-boundary-implementation.md](scoped-search-boundary-implementation.md)
|
||||
> §Stage 2.
|
||||
|
||||
**Status:** Implemented (boundary revision pending — see banner above)
|
||||
**Status:** Implemented (boundary revision: query side done, result side pending)
|
||||
**Scope:** Frontend only. No Rust changes required. *(Revised — see banner.)*
|
||||
**Requirements:** UR-049 → DR-063, DR-064, DR-065; UR-050 → DR-066, DR-067
|
||||
(see [requirements.md](../requirements.md)).
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
# Spec: series navigation lands on the current episode
|
||||
|
||||
**Status:** Accepted
|
||||
**Requirements:** UR-062 → DR-101, DR-102, DR-103, DR-104, DR-107; UR-063 → DR-105; UR-064 → DR-106
|
||||
**UX spec:** [ux-flows.md §5B.1](../ux-flows.md), [§5B.2](../ux-flows.md), [§5B.4](../ux-flows.md), [§5B.5](../ux-flows.md)
|
||||
|
||||
## Summary
|
||||
|
||||
Opening a TV series lands you where you actually are in it: the seasons render
|
||||
as collapsible sections with **only the current season expanded**, the current
|
||||
episode highlighted and scrolled into view, and the hero button opens that
|
||||
episode's focus view (labelled `Resume S2E4` / `Play S1E1`) instead of the first
|
||||
season. A season stops being a destination of its own — every route that used to
|
||||
land on `/library/<seasonId>` now lands on the series with that season in view,
|
||||
so the full cross-season episode list is always reachable in one place. Watch
|
||||
history can be erased per series and per season. Separately, each video library
|
||||
collapses from three routes (landing, all-titles, genres) to one route with
|
||||
in-page tabs.
|
||||
|
||||
## Motivation
|
||||
|
||||
Two problems, reported together.
|
||||
|
||||
**1. Series navigation dead-ends at season 1.** The series detail page's Play
|
||||
button resolved its target as `$libraryItems[0]` — the first *season* child,
|
||||
ordered by `SortName` — and navigated to `/player/<seasonId>`. The player route
|
||||
classifies `season` as a container kind and bounces it back to
|
||||
`/library/<seasonId>`. So Play on a series played nothing; it navigated you to
|
||||
the season-1 page. Opening a series without pressing Play rendered every season
|
||||
stacked but scrolled to the top, so a viewer 4 seasons deep had to scroll past
|
||||
everything they had already watched.
|
||||
|
||||
The backend has been able to answer "where is this viewer in this show" the
|
||||
whole time: `repository_get_next_up_episodes(handle, series_id, limit)` is wired
|
||||
end-to-end to `/Shows/NextUp?SeriesId=`. **Both frontend call sites pass
|
||||
`undefined` for `series_id`** — the per-series capability existed and was never
|
||||
used.
|
||||
|
||||
**2. Seasons are an accidental page.** There is no season route. `/library/
|
||||
<seasonId>` falls through the detail page's `kind` chain into the generic
|
||||
"Contents" poster grid, which contradicts ux-flows §5A.2 (episodes in a season
|
||||
must render as a row list). Worse, clicking an episode from that grid opens a
|
||||
*bare* Episode page, which §5B.1 explicitly forbids. Four call sites fed it: the
|
||||
episode breadcrumb, `handleItemClick case "season"`, the TV landing page, and
|
||||
the broken Play button above.
|
||||
|
||||
**3. Too many video library routes.** Seven routes serve two media types, and the
|
||||
naming does not even agree with itself: `/library/tv` + `/library/tv/shows` +
|
||||
`/library/shows/genres` versus `/library/movies` + `/library/movies/all` +
|
||||
`/library/movies/genres`. The genre routes do not share a prefix, which
|
||||
`searchScope.ts:45` carries an apologetic comment about. The two "all" pages are
|
||||
27-line config wrappers over the same `GenericMediaListPage`.
|
||||
|
||||
## Layer assignment
|
||||
|
||||
| Logic / responsibility | Layer | Why it belongs there |
|
||||
|------------------------|-------|----------------------|
|
||||
| Which episode is "current" for a series (resume → next-up → first unwatched → first) | **Rust** | Domain policy over Jellyfin user-data semantics. It changes if Jellyfin changes what `UserData.is_played` means, if Next Up's rules change, or if we decide a 98%-watched episode counts as finished. It does not change if the UI is redesigned. |
|
||||
| Gathering a series' episodes across all seasons in broadcast order | **Rust** | Jellyfin's shape (episodes hang off season folders, except when a series is flat and they hang off the series) is provider vocabulary. The frontend already reimplemented this fan-out *and* its flat-series fallback; that is domain knowledge that leaked. |
|
||||
| Ordering rule for "series order" (season index, then episode index, specials last) | **Rust** | Season 0 = specials is a Jellyfin convention, not a layout choice. |
|
||||
| Scrolling the current episode into view; the highlight ring and `Up next` badge | Frontend | Pure presentation. Changes only if the page is redesigned. |
|
||||
| Which seasons start expanded | Frontend | Consumes the backend's answer (`currentEpisode`) to decide layout. The *decision* about where the viewer is stays in Rust; only "and therefore this section opens" is here. |
|
||||
| What "erase watch history" means (played flag + resume position, recursive over a container) | **Rust** | Jellyfin user-data semantics. Changes if the server's mark-unplayed behaviour changes; unaffected by any UI redesign. |
|
||||
| Refusing to clear history while offline | **Rust** | A data-integrity rule, not a disabled button: history cleared only locally would be undone by the next sync. The UI disabling the button is a courtesy on top. |
|
||||
| Play button *label* (`Resume S2E4` vs `Play S1E1`) | Frontend | Rendering a decision the backend already made (the returned episode plus its resume position). |
|
||||
| Which route Play navigates to | Frontend | Navigation is presentation. |
|
||||
| Redirecting `/library/<seasonId>` to the series anchor | Frontend | Route topology. |
|
||||
| Episode-strip window size (3 before / 6 after) | Frontend | A layout constant; §5B.2 owns it. |
|
||||
| Library page tabs and the `?view=` param | Frontend | View preference and route topology. |
|
||||
|
||||
Borderline row — **the strip's cross-season *ordering*** is Rust (it is series
|
||||
order, above), but the *window* taken from that ordered list is frontend. The
|
||||
tie-breaker: the list handed to the frontend is already correct and complete;
|
||||
choosing how much of it fits on screen is layout.
|
||||
|
||||
## Design
|
||||
|
||||
### Rust: the current-episode policy
|
||||
|
||||
Two new pieces, split so the policy is unit-testable without a repository.
|
||||
|
||||
**Pure policy** — `src-tauri/src/repository/series_progress.rs`:
|
||||
|
||||
```rust
|
||||
/// Series order: season index asc, then episode index asc. Specials (season 0)
|
||||
/// sort after every numbered season rather than before season 1.
|
||||
pub fn sort_series_order(episodes: &mut [MediaItem]);
|
||||
|
||||
/// The episode a viewer should land on, given everything already fetched.
|
||||
/// Order: in-progress episode → Next Up → first unwatched → first episode.
|
||||
pub fn pick_current_episode(
|
||||
episodes: &[MediaItem], // series order
|
||||
next_up: &[MediaItem],
|
||||
resume: &[MediaItem],
|
||||
) -> Option<MediaItem>;
|
||||
```
|
||||
|
||||
Why that order:
|
||||
|
||||
- **In-progress wins** because a partially-watched episode is literally where
|
||||
the viewer stopped; Next Up would skip past it. Ties break toward the earliest
|
||||
in series order, so a viewer who dipped into a later episode still resumes the
|
||||
one they are actually working through.
|
||||
- **Next Up second** because it is the server's own answer, and it accounts for
|
||||
history we do not cache.
|
||||
- **First unwatched third** — the offline repository returns an empty vec for
|
||||
Next Up (`offline.rs:1247`), so without this fallback the whole feature would
|
||||
be online-only. This is the offline path, not dead code.
|
||||
- **First episode last** so a never-watched series lands on S1E1 rather than
|
||||
nothing.
|
||||
|
||||
A `resume`/`next_up` entry that is not among `episodes` is still honoured — it
|
||||
comes from the same server and may carry an id the season fan-out missed — but
|
||||
it must belong to this series.
|
||||
|
||||
**Fetch + command** — `src-tauri/src/commands/repository.rs`:
|
||||
|
||||
```rust
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn repository_get_series_episodes(
|
||||
manager: State<'_, RepositoryManagerWrapper>,
|
||||
handle: String,
|
||||
series_id: String,
|
||||
) -> Result<Vec<MediaItem>, String>
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn repository_get_series_current_episode(
|
||||
manager: State<'_, RepositoryManagerWrapper>,
|
||||
handle: String,
|
||||
series_id: String,
|
||||
) -> Result<Option<MediaItem>, String>
|
||||
```
|
||||
|
||||
Frontend params are camelCase (`{ handle, seriesId }`) per the Tauri v2 rule.
|
||||
|
||||
`repository_get_series_episodes` performs the fan-out the frontend used to do:
|
||||
`get_items(series_id)` → seasons → `get_items(season_id)` per season, plus the
|
||||
flat-series fallback (a series whose children are episodes, not seasons), then
|
||||
`sort_series_order`. `repository_get_series_current_episode` calls it, adds
|
||||
`get_next_up_episodes(Some(series_id), Some(1))` and
|
||||
`get_resume_items(Some(series_id), Some(10))`, and applies `pick_current_episode`.
|
||||
Both tolerate a failing Next Up (offline) by treating it as empty rather than
|
||||
failing the whole call.
|
||||
|
||||
### Frontend: series page
|
||||
|
||||
- `loadItem()` calls `repositoryGetSeriesEpisodes` once instead of fanning out
|
||||
over seasons itself, and `repositoryGetSeriesCurrentEpisode` for the anchor.
|
||||
Season *headers* still come from `get_items(seriesId)`; the page groups the
|
||||
returned episodes under them by `parentIndexNumber`.
|
||||
- No `?episode=` param → series view, `SeasonSection` receives
|
||||
`currentEpisodeId`, `EpisodeRow` renders the highlight and scrolls itself into
|
||||
view (`scrollIntoView({ block: "center" })`, the existing `focused` mechanism,
|
||||
now distinguishing *focused* from *current*).
|
||||
- Seasons are collapsible and **only the current season is expanded**
|
||||
(`initialExpandedSeasons`). Without this a ten-season show renders every
|
||||
episode of every season at once and buries the one the viewer came for. A
|
||||
collapsed season still shows its episode count and watched count, so progress
|
||||
is legible without expanding. Toggle state is local and not persisted — it is
|
||||
a reading position, not a preference.
|
||||
- Hero Play → `goto(/library/<seriesId>?episode=<currentId>)`, i.e. the Episode
|
||||
Focus View, where an explicit Play/Resume starts playback. This follows
|
||||
ux-flows §5B.5's "tap opens, never commits" rule: Play on a *container* is
|
||||
navigation; Play on a *leaf* (the focus view, a movie) commits.
|
||||
- Clicking an episode in a season section → `?episode=` swap, not
|
||||
`/player/<id>`. §5B.1.
|
||||
|
||||
### Frontend: seasons are not a destination
|
||||
|
||||
`/library/<seasonId>` resolves the season's `seriesId` and redirects to
|
||||
`/library/<seriesId>#season-<indexNumber>`; `SeasonSection` renders that anchor
|
||||
id. A season with no `seriesId` (deep link into a stale cache) keeps the old
|
||||
generic rendering as a fallback so the user is never stranded. Inbound links
|
||||
updated: episode breadcrumb, `handleItemClick case "season"`, the TV landing
|
||||
page's `case "Season"`, and `DownloadedBrowse`.
|
||||
|
||||
### Erasing watch history
|
||||
|
||||
```rust
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn repository_clear_watch_history(
|
||||
manager: State<'_, RepositoryManagerWrapper>,
|
||||
handle: String,
|
||||
item_id: String,
|
||||
) -> Result<(), String>
|
||||
```
|
||||
|
||||
`OnlineRepository` maps it to `DELETE /Users/{userId}/PlayedItems/{itemId}` —
|
||||
Jellyfin's mark-unplayed, which clears the played flag *and* zeroes the resume
|
||||
position, and which the server applies recursively to a folder. One call
|
||||
therefore handles a whole series or a single season; no per-episode fan-out.
|
||||
`OfflineRepository` returns `RepoError::Offline` rather than clearing locally,
|
||||
because divergent local history is undone by the next sync.
|
||||
|
||||
`ClearHistoryButton` is shared by the series hero (`scope="series"`) and each
|
||||
`SeasonSection` header (`scope="season"`). It confirms first — there is no undo —
|
||||
disables itself while the server is unreachable, and reloads the page on success
|
||||
so the recomputed current episode is what the viewer sees. Clearing a whole
|
||||
series therefore returns it to S1E1, which is the same path a never-watched
|
||||
series takes through `pick_current_episode`.
|
||||
|
||||
### Frontend: one route per video library
|
||||
|
||||
`/library/tv` and `/library/movies` each gain `?view=browse|all|genres` tabs,
|
||||
rendering the existing `GenericMediaListPage` / `GenericGenreBrowser` components
|
||||
inline. `?view=` is omitted for `browse` (the default) to keep URLs clean —
|
||||
the same convention `searchRouteUrl` uses for the `all` scope.
|
||||
|
||||
The four legacy routes become redirect-only `+page.ts` loads:
|
||||
|
||||
| Legacy | Redirects to |
|
||||
|--------|--------------|
|
||||
| `/library/tv/shows` | `/library/tv?view=all` |
|
||||
| `/library/shows/genres` | `/library/tv?view=genres` |
|
||||
| `/library/movies/all` | `/library/movies?view=all` |
|
||||
| `/library/movies/genres` | `/library/movies?view=genres` |
|
||||
|
||||
They are kept (rather than deleted) because `GenreTags` builds links to them and
|
||||
users may have them in history. `resolveSearchScope` keeps its `/library/shows`
|
||||
branch for the same reason.
|
||||
|
||||
The "Browse" tile grid at the bottom of both landing pages is removed — the tabs
|
||||
replace it, and the tiles were a second navigation affordance to the same two
|
||||
destinations the carousels' "Show all" links already reach.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- **Cross-season autoplay.** `player/mod.rs:fetch_next_episode_for_item` is
|
||||
still season-bounded, so autoplay stops at a season boundary. Fixing it should
|
||||
reuse `repository_get_series_episodes`, but it touches the playback state
|
||||
machine and the Android JNI advance path (see the `AutoplayDecision` deadlock
|
||||
note in CLAUDE.md) and belongs in its own change.
|
||||
- **Music library routes.** `/library/music/*` has five sub-routes with the same
|
||||
shape; the same consolidation applies but is not done here.
|
||||
- **Marking a series' progress** (mark-watched / mark-unwatched from the series
|
||||
page).
|
||||
@@ -0,0 +1,238 @@
|
||||
# Spec: Repair the traceability coverage gate
|
||||
|
||||
**Status:** Implemented
|
||||
**Requirements:** DR-093 → supports the traceability practice described in CLAUDE.md
|
||||
**UX spec:** n/a — developer tooling, no user-facing surface.
|
||||
**Supersedes / revises:** n/a
|
||||
|
||||
## Summary
|
||||
|
||||
The CI traceability gate has been passing unconditionally for an unknown length
|
||||
of time because it divides traced-requirement counts by **hardcoded denominators
|
||||
that no longer match [requirements.md](../requirements.md)**. It currently
|
||||
reports **158% overall coverage** (and `JA 24 / 3 = 800%`), so the 50% threshold
|
||||
is mathematically unreachable and the job cannot fail. This spec makes the gate
|
||||
derive its denominators from `requirements.md` at run time, so it reports the
|
||||
real number (**85%** today) and can actually fail again.
|
||||
|
||||
## Motivation
|
||||
|
||||
`.gitea/workflows/traceability-check.yml` hardcodes `UR/39, IR/24, DR/48, JA/3`
|
||||
and `TOTAL_REQS=114`. The real counts are **UR 61, IR 29, DR 89, JA 32 — 211
|
||||
total**. Requirements were added over time; the divisors were never updated.
|
||||
|
||||
The consequence is not a cosmetic reporting bug. The gate is the *only*
|
||||
automated defence for the traceability practice, and it is dead:
|
||||
|
||||
```
|
||||
CI today: 181 / 114 = 158% → threshold 50% can never trip
|
||||
Reality: 181 / 211 = 85% → healthy, but unguarded
|
||||
```
|
||||
|
||||
Coverage could collapse to 30% and CI would still print a green
|
||||
"✅ Coverage is acceptable". An audit of the design principles found that every
|
||||
principle with a *working* automated check is in good shape, and the ones that
|
||||
drifted are exactly the ones whose checks were broken or too narrow — this is
|
||||
the clearest instance.
|
||||
|
||||
A second, related defect is handled in a sibling spec: `scripts/check-req-coverage.sh`
|
||||
is separately broken and orphaned (see
|
||||
[req-coverage-script-removal.md](req-coverage-script-removal.md)).
|
||||
|
||||
## Layer assignment
|
||||
|
||||
This spec touches only CI/build tooling — no application logic crosses the
|
||||
Rust/Svelte boundary. The table is filled in for completeness.
|
||||
|
||||
| Logic / responsibility | Layer | Why it belongs there |
|
||||
|------------------------|-------|----------------------|
|
||||
| Counting requirement IDs defined in `requirements.md` | Build tooling (`scripts/`) | Neither runtime layer; it is repo metadata analysis. Belongs beside `extract-traces.ts`, not in the workflow YAML, so it is runnable and testable locally. |
|
||||
| Counting *traced* requirement IDs | Build tooling — existing `extract-traces.ts` | Already implemented and correct; this spec consumes it rather than duplicating it. |
|
||||
| Threshold policy (the 50% number) | CI workflow | Deployment policy, not analysis. Keeping it in YAML lets it be tuned without touching the script. |
|
||||
|
||||
No frontend or Rust logic is added, so no taxonomy leak is possible.
|
||||
|
||||
## Design
|
||||
|
||||
### 1. Denominators come from `requirements.md`, not literals
|
||||
|
||||
`requirements.md` defines requirements in markdown tables with a stable leading
|
||||
cell, e.g.:
|
||||
|
||||
```
|
||||
| DR-001 | Player state machine (idle, loading, …) | Player | UR-005 | Done |
|
||||
| UR-002 | Access media when online or offline | High | Done |
|
||||
```
|
||||
|
||||
Extend [scripts/extract-traces.ts](../../scripts/extract-traces.ts) to also emit
|
||||
the *defined* counts, so one tool owns both sides of the fraction and CI does no
|
||||
arithmetic on stale literals. Add a `defined` key to the JSON report:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"byType": { "UR": [...], "IR": [...], "DR": [...], "JA": [...] }, // traced (existing)
|
||||
"defined": { "UR": 61, "IR": 29, "DR": 89, "JA": 32 }, // NEW
|
||||
"coverage": { "covered": 181, "total": 211, "percent": 85 }, // NEW
|
||||
"requirements": { ... }, // existing
|
||||
"totalTraces": 318, "totalFiles": …, "timestamp": "…" // existing
|
||||
}
|
||||
```
|
||||
|
||||
Parsing rule for a *defined* requirement: a line in `docs/requirements.md`
|
||||
matching `^\|\s*(UR|IR|DR|JA)-\d{3}\s*\|` — the ID must be the table's first
|
||||
cell. This deliberately does **not** count IDs mentioned in the `Traces To`
|
||||
column or in prose, which is why a naive `grep -o` over the whole file
|
||||
overcounts.
|
||||
|
||||
`defined` counts IDs that exist in the spec; `byType` counts IDs that appear in
|
||||
a `TRACES:` comment somewhere in the source. Coverage is
|
||||
`|byType ∩ defined| / |defined|`.
|
||||
|
||||
> **Intersection, not raw length.** A `TRACES:` comment naming an ID that
|
||||
> `requirements.md` does not define (a typo, or a requirement later deleted)
|
||||
> must **not** inflate the numerator — that is how a ratio exceeds 100% in the
|
||||
> first place. Such IDs are reported separately as `orphaned` so they get fixed
|
||||
> rather than silently counted or silently dropped.
|
||||
|
||||
```jsonc
|
||||
"orphaned": ["DR-097"] // traced in code but not defined in requirements.md
|
||||
```
|
||||
|
||||
### 2. The workflow consumes the computed number
|
||||
|
||||
Replace the arithmetic in `.gitea/workflows/traceability-check.yml` (lines
|
||||
46–76) with reads of the precomputed fields:
|
||||
|
||||
```sh
|
||||
COVERAGE=$(jq '.coverage.percent' traces-report.json)
|
||||
COVERED=$(jq '.coverage.covered' traces-report.json)
|
||||
TOTAL_REQS=$(jq '.coverage.total' traces-report.json)
|
||||
|
||||
for T in UR IR DR JA; do
|
||||
TRACED=$(jq --arg t "$T" '.byType[$t] | length' traces-report.json)
|
||||
DEFINED=$(jq --arg t "$T" '.defined[$t]' traces-report.json)
|
||||
echo " $T: $TRACED / $DEFINED"
|
||||
done
|
||||
|
||||
MIN_THRESHOLD=50
|
||||
[ "$COVERAGE" -lt "$MIN_THRESHOLD" ] && { echo "❌ …"; exit 1; }
|
||||
```
|
||||
|
||||
No hardcoded denominator survives anywhere in the workflow.
|
||||
|
||||
### 3. A self-check so this cannot silently rot again
|
||||
|
||||
The root cause was a number that drifted with nothing watching it. Add a
|
||||
guard that fails the job on an arithmetically impossible result:
|
||||
|
||||
```sh
|
||||
if [ "$COVERAGE" -gt 100 ]; then
|
||||
echo "❌ Coverage > 100% — the gate is miscomputing; orphaned IDs: $(jq -c '.orphaned' traces-report.json)"
|
||||
exit 1
|
||||
fi
|
||||
```
|
||||
|
||||
A >100% reading is now a hard failure rather than a green tick.
|
||||
|
||||
### 4. Local parity
|
||||
|
||||
Add a script so the gate is runnable outside CI:
|
||||
|
||||
```jsonc
|
||||
"traces:coverage": "bun run scripts/extract-traces.ts --format coverage"
|
||||
```
|
||||
|
||||
Prints the same table CI prints and exits non-zero below threshold.
|
||||
|
||||
### Threshold
|
||||
|
||||
Keep `MIN_THRESHOLD=50` in this spec. Real coverage is 85%, so raising the bar
|
||||
is tempting, but doing it in the same change that repairs the gate conflates
|
||||
"restore the safety net" with "tighten the policy" — if the build then fails, it
|
||||
is ambiguous which change caused it. Ratcheting is deliberately deferred to
|
||||
follow-up work once the honest number has been observed on `master` for a few
|
||||
builds.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- Raising `MIN_THRESHOLD` above 50 (see above).
|
||||
- Fixing/removing `scripts/check-req-coverage.sh` — [req-coverage-script-removal.md](req-coverage-script-removal.md).
|
||||
- Adding TRACES comments to raise the actual coverage number.
|
||||
- Changing the `TRACES:` comment format or the extractor's parsing of it.
|
||||
- The PR "modified files missing TRACES" step (lines 78–126), which is advisory
|
||||
by design and stays advisory.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] `bun run traces:json` emits `defined`, `coverage`, and `orphaned` keys.
|
||||
- [ ] `coverage.total` equals the count of requirement IDs defined in
|
||||
`requirements.md` (**211** at time of writing), not a literal.
|
||||
- [ ] `coverage.percent` reports **85** (±1 for rounding) on the current tree —
|
||||
i.e. the honest number, not 158.
|
||||
- [ ] No hardcoded requirement denominator (`39`, `24`, `48`, `3`, `114`) remains
|
||||
in `.gitea/workflows/traceability-check.yml`. Verify:
|
||||
`grep -nE '/ *(39|24|48|3|114)\b' .gitea/workflows/traceability-check.yml`
|
||||
returns nothing.
|
||||
- [ ] Adding a new requirement row to `requirements.md` **lowers** reported
|
||||
coverage until it is traced (proves the denominator is live).
|
||||
- [ ] A `TRACES:` comment naming an undefined ID appears in `orphaned` and does
|
||||
**not** raise `coverage.percent`.
|
||||
- [ ] The job fails if coverage is forced below 50% (test by temporarily raising
|
||||
`MIN_THRESHOLD` to 99 locally) — proving the gate can fail again.
|
||||
- [ ] The job fails if coverage computes >100%.
|
||||
- [ ] `bun run check` and `bun run test` pass.
|
||||
- [ ] `bun run check:boundary` passes.
|
||||
- [ ] New requirement-implementing code carries `// TRACES:` comments.
|
||||
- [ ] No Rust types changed, so no `bindings.ts` regeneration needed.
|
||||
|
||||
## Testing
|
||||
|
||||
`extract-traces.ts` currently has no test coverage. Add
|
||||
`scripts/extract-traces.test.ts` (vitest) over fixture strings rather than the
|
||||
live `requirements.md`, so the tests do not change meaning as requirements are
|
||||
added:
|
||||
|
||||
- **UT:** counts a well-formed table row as a defined requirement.
|
||||
- **UT:** does **not** count an ID appearing only in the `Traces To` column or
|
||||
in prose — the specific overcounting bug this parse rule avoids.
|
||||
- **UT:** coverage is the intersection — a traced-but-undefined ID lands in
|
||||
`orphaned` and does not inflate the numerator.
|
||||
- **UT:** coverage of an empty trace set is 0%, not a divide-by-zero.
|
||||
- **UT:** all-traced fixture reports exactly 100%, never above.
|
||||
|
||||
CI behaviour is verified by the acceptance criteria above (the forced-failure
|
||||
check is the important one — a gate nobody has watched fail is not known to
|
||||
work).
|
||||
|
||||
## TRACES
|
||||
|
||||
Allocate in `requirements.md`:
|
||||
|
||||
- **DR-093** — "Traceability coverage gate derives requirement denominators from
|
||||
`requirements.md` at run time (not hardcoded literals), computes coverage as
|
||||
the intersection of traced and defined IDs, reports IDs traced but undefined
|
||||
as orphaned, and fails on an impossible >100% result." Category: Tooling.
|
||||
Status: Done on merge.
|
||||
|
||||
Tag:
|
||||
|
||||
```typescript
|
||||
// scripts/extract-traces.ts
|
||||
// TRACES: | DR-093
|
||||
```
|
||||
|
||||
Tests carry `@req-test: UT-089 …` onward (next free UT is **UT-089**).
|
||||
|
||||
## Notes for the implementer
|
||||
|
||||
- A parallel Claude session may be active in this repo — run `git diff` before
|
||||
"repairing" unexpected changes (CLAUDE.md §Gotchas).
|
||||
- **Do not add tooling to the CI image for this.** `jq` and `bun` are already in
|
||||
`jellytau-builder`; this spec needs nothing else. Installing a system package
|
||||
in a workflow step violates the hard CI rule in CLAUDE.md.
|
||||
- Keep `traces:json`'s existing keys intact — `release-notes.ts` and
|
||||
`traces:markdown` consume the same report, and the CI workflow uploads it as
|
||||
an artifact. This is an additive change.
|
||||
- The `head -50 docs/traceability.md` and artifact-upload steps are unaffected.
|
||||
- Expect the first green build after this change to print a *lower* number than
|
||||
before (85% vs 158%). That is the fix working, not a regression.
|
||||
@@ -0,0 +1,209 @@
|
||||
# Spec: Windows native audio backend
|
||||
|
||||
**Status:** Proposed
|
||||
**Requirements:** UR-003, UR-027, UR-032, UR-033 → DR-030, DR-035, DR-036; new IR-030
|
||||
**UX spec:** n/a — Settings › Audio already renders the controls
|
||||
**Supersedes / revises:** acts on the "audio can unify, video cannot" conclusion in [playback-backend-unification.md](playback-backend-unification.md)
|
||||
|
||||
## Summary
|
||||
|
||||
Give Windows a real native audio backend instead of the current webview
|
||||
`<audio>` shim. Windows is the only platform where audio playback has no decoder
|
||||
of its own: `WebviewAudioBackend` hands a URL to a frontend `<audio>` element and
|
||||
relays transport commands. It cannot set volume, cannot apply any audio setting,
|
||||
and reports state only via DOM events.
|
||||
|
||||
Audio needs no rendering surface, so **none of the webview-compositing problems
|
||||
that block unified video apply here.** This is the cleanest available win.
|
||||
|
||||
## Motivation
|
||||
|
||||
`WebviewAudioBackend` was a deliberate stopgap ("audio-only playback for
|
||||
platforms without a native audio backend"), and it works — but it has a hard
|
||||
functional gap. From `webview_audio_backend.rs`:
|
||||
|
||||
```rust
|
||||
fn set_volume(&mut self, volume: f32) -> Result<(), PlayerError> {
|
||||
// ...stores locally only; there is no ControlCommand action for volume
|
||||
}
|
||||
```
|
||||
|
||||
So volume changes never reach the element; the frontend has to observe the player
|
||||
store and apply volume itself. `set_audio_settings` likewise stores values that
|
||||
nothing consumes — EQ, normalization, and gapless are all inert on Windows.
|
||||
|
||||
Meanwhile the backend-unification investigation established that a native *audio*
|
||||
engine is unproblematic on Windows specifically: `tauri-plugin-libmpv` lists
|
||||
Windows as its **fully tested** platform (in contrast to Linux, where embedding
|
||||
is broken — but that is a *video surface* problem, which audio does not have).
|
||||
|
||||
## Layer assignment
|
||||
|
||||
| Logic / responsibility | Layer | Why it belongs there |
|
||||
|------------------------|-------|----------------------|
|
||||
| Decoding and playing the audio stream | Rust | Playback is domain logic; every other platform already decodes in Rust or a native player. The webview shim is the anomaly. |
|
||||
| Applying `AudioSettings` (EQ/normalize/gapless) | Rust | Same `AudioSettings` contract as MPV/ExoPlayer; band layout and presets stay canonical in `settings.rs`. |
|
||||
| Position/state reporting | Rust | Restores the project's core principle — the player is the authoritative source of state. Today Windows inverts this: the DOM element is authoritative and Rust mirrors it. |
|
||||
| Volume | Rust | Currently broken precisely because it is split across the boundary. |
|
||||
| Rendering the player UI | Frontend | Unchanged. |
|
||||
|
||||
The strongest argument for this change is the third row. CLAUDE.md states
|
||||
playback state is one-directional with the player authoritative; on Windows that
|
||||
is currently false, and the `player_report_*` round-trip exists to paper over it.
|
||||
|
||||
## Design
|
||||
|
||||
### Engine choice
|
||||
|
||||
Two viable options; **libmpv is recommended** for consistency with the Linux
|
||||
audio backend.
|
||||
|
||||
| | libmpv | GStreamer |
|
||||
|---|---|---|
|
||||
| Windows status | ✅ `tauri-plugin-libmpv` reports fully tested | ✅ works, but… |
|
||||
| Rust bindings | `libmpv2` 6.0.0, active | `gstreamer-rs` 0.25.x, excellent |
|
||||
| Cross-MSVC from Linux | ⚠️ needs prebuilt DLL + import lib | ❌ `gstreamer-sys` uses pkg-config, fights `cargo-xwin` |
|
||||
| Code reuse | ✅ `MpvBackend` logic is directly reusable | ❌ a second engine to learn |
|
||||
| Crossfade capable | ❌ single-stream chain | ✅ `audiomixer` |
|
||||
|
||||
libmpv wins on reuse: `MpvBackend`'s `set_audio_settings` — the `af` lavfi graph
|
||||
built by `build_af_filter`, `eq_filter_entries`, `normalize_filter_entry` — is
|
||||
platform-independent and would apply unchanged.
|
||||
|
||||
The one reason to prefer GStreamer is crossfade (UR-031), which mpv structurally
|
||||
cannot do. If crossfade becomes a priority, revisit; it would then argue for
|
||||
GStreamer on *both* Linux and Windows, which is a much larger change.
|
||||
|
||||
### Structure
|
||||
|
||||
Rename the cfg gate so `MpvBackend` is no longer Linux-only:
|
||||
|
||||
```rust
|
||||
// src-tauri/src/player/mod.rs
|
||||
#[cfg(any(target_os = "linux", target_os = "windows"))]
|
||||
pub mod mpv_backend;
|
||||
```
|
||||
|
||||
`MpvBackend::new` needs one platform-specific branch: `detect_audio_system()`
|
||||
currently probes `pactl`/`pw-cli`/`/proc/asound/cards` to pick an `ao`. On
|
||||
Windows the equivalent is `wasapi` (mpv's default), so the detection is a
|
||||
`#[cfg]` returning `"wasapi"` — no probing needed.
|
||||
|
||||
Everything else — the event loop, the 250ms position thread, the seek-suppression
|
||||
window, the `af` filter graph — is unchanged.
|
||||
|
||||
`WebviewAudioBackend` stays for other targets (macOS and anything else hitting
|
||||
the `not(any(...))` arm) and as the fallback if libmpv fails to initialize. The
|
||||
existing `emit_backend_init_failed` path already handles that gracefully.
|
||||
|
||||
### Build
|
||||
|
||||
`libmpv2-sys` is well-suited to cross-compilation: no pkg-config, vendored
|
||||
headers, pregenerated bindings (no libclang). It emits `cargo:rustc-link-lib=mpv`
|
||||
unconditionally, so the build must supply a linkable import library for
|
||||
`x86_64-pc-windows-msvc`.
|
||||
|
||||
Keep the `build_libmpv` feature **off** — its Unix path shells out to mpv-build
|
||||
and explicitly rejects cross-compilation.
|
||||
|
||||
🔴 Per CLAUDE.md, the prebuilt libmpv **must be added to the builder image**
|
||||
(`Dockerfile.builder` → rebuild + push via `scripts/build-builder-image.sh`), not
|
||||
installed at CI job time. `libmpv-2.dll` must also be bundled into the NSIS
|
||||
installer via `tauri.conf.json`'s resources.
|
||||
|
||||
### Verified build mechanics
|
||||
|
||||
The cross-compile path was tested hands-on from Linux (July 2026), not inferred:
|
||||
|
||||
- Neither shinchiro nor zhongfly ships an `mpv.def` or MSVC `mpv.lib` — only a
|
||||
MinGW `libmpv.dll.a`. (Several online sources claim otherwise; they are wrong.)
|
||||
- An MSVC-style import lib can be generated locally with LLVM tools only:
|
||||
`llvm-readobj --coff-exports libmpv-2.dll` → synthesize `mpv.def` →
|
||||
`llvm-dlltool -m i386:x86-64 -d mpv.def -l mpv.lib`. `llvm-lib /def:` produces a
|
||||
byte-identical result.
|
||||
- A real `lld-link` link against that import lib **succeeds**, and the resulting
|
||||
import table resolves `mpv_client_api_version` from `libmpv-2.dll`. `lld-link`
|
||||
is the linker `cargo-xwin` uses, so this is the load-bearing step.
|
||||
- Linking directly against the shipped MinGW `libmpv.dll.a` **also** succeeds, so
|
||||
def-generation may be skippable — but that relies on lld's GNU-archive
|
||||
tolerance rather than a documented contract. Keep `llvm-dlltool` as the
|
||||
fallback.
|
||||
- MinGW origin is not an ABI problem: libmpv exports a pure C ABI, and the x86-64
|
||||
Windows calling convention is platform-defined. The upstream note that MSVC
|
||||
cannot *build* mpv is frequently misread as "MSVC cannot *link* libmpv" — that
|
||||
is not what it says.
|
||||
- 🔴 Never free/realloc across the DLL boundary — use `mpv_free`.
|
||||
|
||||
Build wiring is ordinary: `cargo:rustc-link-lib=dylib=mpv` plus
|
||||
`cargo:rustc-link-search`. Nothing about libmpv conflicts with `cargo-xwin`.
|
||||
|
||||
### Size and shipping
|
||||
|
||||
Measured uncompressed: **93 MiB** (zhongfly `mpv-dev-lgpl-x86_64`) vs **112 MiB**
|
||||
(shinchiro, full GPL build); ~26–30 MB compressed in the `.7z`.
|
||||
|
||||
**Ship the zhongfly LGPL build** — smaller, and there is no reason to pull the
|
||||
GPL variant in for an audio-only use.
|
||||
|
||||
Import-table inspection confirms **no companion DLLs are needed**: every
|
||||
dependency is a system DLL (`KERNEL32`, `USER32`, `d2d1`, `DWrite`, `OPENGL32`,
|
||||
`vulkan-1`, UCRT `api-ms-win-*`). One file to bundle.
|
||||
|
||||
93 MiB is still substantial against a Tauri app's usual few MB. Since we use mpv
|
||||
audio-only, investigate whether a pruned build (no video decoders, no libplacebo)
|
||||
is worth producing for the builder image — but treat that as an optimization,
|
||||
not a blocker.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- Windows *video*. Stays in WebView2 + hls.js — it works and has ABR.
|
||||
- Crossfade (UR-031/DR-034) — not implemented anywhere; needs its own spec.
|
||||
- Replacing `WebviewAudioBackend` for macOS.
|
||||
- MPRIS/SMTC media-key integration — worth a follow-up, not this spec.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [ ] Windows build produces a `MpvBackend`-backed player; `backend-init-failed` is emitted (not a crash) if libmpv is unavailable.
|
||||
- [ ] Volume control works from the UI — the current hard gap.
|
||||
- [ ] EQ, normalization, and gapless audibly take effect on Windows.
|
||||
- [ ] Position/state originate in Rust; the `<audio>` element is no longer in the audio path.
|
||||
- [ ] Seek, next/previous, and queue advance work; sleep timer stops playback.
|
||||
- [ ] `libmpv-2.dll` ships in the NSIS installer and the app runs on a clean Windows VM with no mpv installed.
|
||||
- [ ] Builder image carries the Windows libmpv artefacts; **no toolchain install added to any CI step**.
|
||||
- [ ] `bun run check`, `bun run test`, `bun run check:boundary` pass.
|
||||
- [ ] `cargo fmt` clean, `cargo clippy` clean, `bun run test:rust` passes.
|
||||
- [ ] New requirement-implementing code carries `// TRACES:` comments.
|
||||
|
||||
## Testing
|
||||
|
||||
**Rust**: the existing `mpv_backend_test.rs` and the `build_af_filter` /
|
||||
`normalize_filter_entry` / `eq_filter_entries` unit tests already cover the
|
||||
filter-graph logic and are platform-independent — they should pass unchanged
|
||||
under a Windows `cargo check`/test. Add a test asserting `detect_audio_system()`
|
||||
returns `wasapi` under `cfg(windows)`.
|
||||
|
||||
**Manual, on Windows**: volume, EQ preset change, normalization toggle, gapless
|
||||
between two tracks, seek, queue advance, sleep timer. Then the packaging test —
|
||||
install the NSIS output on a clean VM and confirm it launches and plays.
|
||||
|
||||
Per CLAUDE.md, the volume gap is a *bug fix*: write a failing test for
|
||||
"`set_volume` reaches the backend" before implementing.
|
||||
|
||||
## TRACES
|
||||
|
||||
- Windows `MpvBackend` construction in `create_player_backend` → `// TRACES: UR-003 | IR-030`
|
||||
- `detect_audio_system` Windows branch → `IR-030`
|
||||
- Existing `set_audio_settings` gains Windows coverage → `UR-027, UR-032, UR-033 | DR-030, DR-035, DR-036`
|
||||
- Allocate **IR-030** in `requirements.md` ("libmpv integration for Windows audio playback").
|
||||
|
||||
## Notes for the implementer
|
||||
|
||||
- Do this **after** [libmpv2-migration.md](libmpv2-migration.md) — porting the
|
||||
current dead `libmpv` git pin to a second platform would double the migration
|
||||
work.
|
||||
- `libmpv2` has broken its API in every major release (4.0 removed command
|
||||
helpers, 5.0 removed `mpv_node`, 6.0 changed `RenderContext` ownership). Pin an
|
||||
exact version.
|
||||
- Only the `render`-feature parts of `libmpv2` concern video; audio-only use does
|
||||
not need it, and disabling the default `render` feature may shrink the build.
|
||||
- A parallel Claude session may be active — `git diff` first.
|
||||
+26
-12
@@ -43,14 +43,26 @@ Extracts all TRACES comments from:
|
||||
|
||||
### 2. Coverage Thresholds
|
||||
The workflow checks:
|
||||
- **Minimum overall coverage:** 50% (57+ requirements traced)
|
||||
- **Requirements by type:**
|
||||
- UR (User): 23+ of 39
|
||||
- IR (Integration): 5+ of 24
|
||||
- DR (Development): 28+ of 48
|
||||
- JA (Jellyfin API): 0+ of 3
|
||||
- **Minimum overall coverage:** 50%
|
||||
|
||||
If coverage drops below threshold, the workflow **fails** and blocks merge.
|
||||
Denominators are **derived from `docs/requirements.md` at run time** — they are
|
||||
never hardcoded here or in the workflow. Run `bun run traces:coverage` for the
|
||||
current per-type breakdown; any number written into this document is a snapshot
|
||||
that will drift.
|
||||
|
||||
> **Why this matters.** The workflow used to divide by frozen literals
|
||||
> (UR/39, IR/24, DR/48, JA/3, total 114) while `requirements.md` had grown past
|
||||
> 200. It reported **158%** coverage, so the 50% threshold was unreachable and
|
||||
> the job could not fail regardless of how far coverage dropped. See
|
||||
> [specs/traceability-gate-repair.md](specs/traceability-gate-repair.md).
|
||||
|
||||
Coverage is the *intersection* of traced and defined IDs: an ID that appears in
|
||||
a `TRACES:` comment but is not defined in `requirements.md` is reported as
|
||||
**orphaned** and does not count toward coverage. UT/IT test identifiers are a
|
||||
separate taxonomy and are excluded entirely.
|
||||
|
||||
The workflow **fails** and blocks merge if coverage drops below 50% — or if it
|
||||
computes above 100%, which can only mean the gate is miscounting.
|
||||
|
||||
### 3. Modified File Checking
|
||||
On pull requests, the workflow:
|
||||
@@ -153,11 +165,13 @@ cat docs/traceability.md
|
||||
## Coverage Goals
|
||||
|
||||
### Current Status
|
||||
- Overall: 51% (56/114)
|
||||
- UR: 59% (23/39)
|
||||
- IR: 21% (5/24)
|
||||
- DR: 58% (28/48)
|
||||
- JA: 0% (0/3)
|
||||
|
||||
Run `bun run traces:coverage` — it prints the live figure and exits non-zero
|
||||
below threshold. Numbers are deliberately not pinned here; the previous snapshot
|
||||
in this section (51%, 56/114) was stale by roughly 100 requirements and was what
|
||||
made the broken CI arithmetic look plausible for so long.
|
||||
|
||||
As of July 2026 overall coverage is ~86% (182/212).
|
||||
|
||||
### Targets
|
||||
- **Short term** (Sprint): Maintain ≥50% overall
|
||||
|
||||
+2858
-1632
File diff suppressed because it is too large
Load Diff
+67
-7
@@ -346,10 +346,12 @@ flowchart TB
|
||||
**User Interaction:**
|
||||
- **Tap screen:** Controls reappear for 3 seconds
|
||||
- **Double tap left side:** Rewind 10 seconds (shows animated feedback with "-10" indicator)
|
||||
- **Double tap right side:** Forward 10 seconds (shows animated feedback with "+10" indicator)
|
||||
- **Double tap right side:** Forward 30 seconds (shows animated feedback with "+30" indicator)
|
||||
- **Single tap play/pause is deferred** by the 300 ms double-tap window, so a double tap
|
||||
skips without also toggling pause (UR-061)
|
||||
- **Swipe up/down on left side:** Adjust brightness (0.3-1.7x, shows brightness indicator with progress bar)
|
||||
- **Swipe up/down on right side:** Adjust volume (0-100%, shows volume indicator with progress bar)
|
||||
- **Keyboard arrows:** ← rewind 10s, → forward 10s (desktop/external keyboard)
|
||||
- **Keyboard arrows:** ← rewind 10s, → forward 30s (desktop/external keyboard)
|
||||
- **Keyboard space/K:** Toggle play/pause
|
||||
- **Keyboard F:** Toggle fullscreen
|
||||
- **Pinch:** Zoom (planned)
|
||||
@@ -609,9 +611,12 @@ flowchart TB
|
||||
```
|
||||
|
||||
An episode is **never** browsed as a bare `Episode` item page. Clicking an
|
||||
episode anywhere navigates to `/library/<seriesId>?episode=<episodeId>`, so the
|
||||
episode is always shown in the context of its series and the series' full
|
||||
episode list is already loaded.
|
||||
episode anywhere — a series' season list, a Home carousel (§5B.5), etc. —
|
||||
navigates to `/library/<seriesId>?episode=<episodeId>`, so the episode is always
|
||||
shown in the context of its series and the series' full episode list is already
|
||||
loaded. Should an episode ever arrive without a `seriesId` (deep link, stale
|
||||
cache), the bare Episode page renders as a fallback and links back to its parent
|
||||
series and season by title so the user is never stranded.
|
||||
|
||||
### 5B.2 Episode Focus View — section order
|
||||
|
||||
@@ -683,10 +688,10 @@ A movie has no continuation set, so cast follows the hero directly.
|
||||
### 5B.4 Series detail — section order
|
||||
|
||||
```
|
||||
Hero (poster, title, metadata, Play / Download)
|
||||
Hero (poster, title, metadata, Resume SxEy / Download / Clear history)
|
||||
→ Crew links
|
||||
→ Genre tags
|
||||
→ Seasons + episodes (per-season sections)
|
||||
→ Seasons (collapsible; only the current season expanded)
|
||||
→ Cast
|
||||
→ More Like This
|
||||
```
|
||||
@@ -695,6 +700,61 @@ The same principle as §5B.2: **episodes come before cast and similar shows.**
|
||||
The reason a user opens a series page is to pick an episode; discovery content
|
||||
is secondary and sits underneath.
|
||||
|
||||
**Rules for the seasons block** *(UR-062, UR-064)*:
|
||||
|
||||
- **The page opens where the viewer is.** The backend resolves the current
|
||||
episode — in progress, else Next Up, else first unwatched, else the premiere —
|
||||
and the page scrolls it into view with an `Up next` badge and a highlight ring.
|
||||
Never season 1 by default, unless season 1 *is* where the viewer is.
|
||||
- **Seasons collapse; only the current one is expanded.** A ten-season show
|
||||
otherwise renders hundreds of rows and buries the episode the viewer came for.
|
||||
A collapsed season still names its episode count and watched count, so
|
||||
progress is readable without expanding it.
|
||||
- **The hero button opens, it does not play.** It reads `Resume S2E4` /
|
||||
`Play S1E1` — naming its target — and navigates to that episode's Focus View,
|
||||
where Play commits. Play on a *container* is navigation (§5B.5); Play on a
|
||||
*leaf* is the commitment.
|
||||
- **A season is never its own page.** `/library/<seasonId>` redirects to
|
||||
`/library/<seriesId>#season-N`. Every affordance that names a season — the
|
||||
episode breadcrumb, a season card in a grid, a Downloads drill-in — lands on
|
||||
the series with that season in view, so the episodes of all seasons stay one
|
||||
browsable list.
|
||||
- **Watch history is erasable** per series (hero) and per season (season
|
||||
header). It confirms first, cannot be undone, and needs the server. Clearing a
|
||||
whole series returns it to S1E1 by the same path a never-watched show takes.
|
||||
|
||||
### 5B.5 Home-card interaction — tap opens, long-press plays
|
||||
|
||||
Cards on the Home screen carousels (Next Movie, Next Episode, Continue
|
||||
Watching, Recently Added, …) **do not play on tap.** A plain tap opens the
|
||||
item; playback is the deliberate, second gesture.
|
||||
|
||||
| Card kind | Tap (short) | Long-press (~500 ms hold) |
|
||||
|-----------|-------------|---------------------------|
|
||||
| Movie | Movie detail page (`/library/<id>`) | Confirm → play now (`/player/<id>`) |
|
||||
| Episode | Series Episode Focus View (`/library/<seriesId>?episode=<id>`, per §5B.1) | Confirm → play now (`/player/<id>`) |
|
||||
| Series / Season / Album / Artist / Playlist / Folder | Detail page (`/library/<id>`) | Same as tap (no single "play now" target) |
|
||||
| Channel / live leaf | Player (`/player/<id>`) — no detail page exists | Confirm → play now |
|
||||
|
||||
Rationale and rules:
|
||||
|
||||
- **Tap is navigation, not commitment.** Previously a tap on a movie/episode
|
||||
jumped straight into the player, which made it easy to lose your place in a
|
||||
half-watched item or start a stream you only meant to inspect. Tap now lands
|
||||
on the detail/focus page, where Play is an explicit button.
|
||||
- **Long-press is the shortcut for "just play it."** It surfaces a native
|
||||
confirm (`Play "<name>" now?`) before starting playback, so an accidental
|
||||
hold never blows away a resume position silently.
|
||||
- **The long-press must not fight the carousel.** Detection cancels if the
|
||||
pointer moves more than ~10 px (a horizontal scroll of the row), so holding
|
||||
to scroll never triggers play.
|
||||
- **Episodes still obey §5B.1** — a home tap on an episode opens the series
|
||||
Focus View, never a bare Episode page, so the series context loads.
|
||||
|
||||
This behavior lives in `MediaCard` (`onLongPress` prop + pointer-based
|
||||
detection) so any surface can opt in; today the Home carousels are the only
|
||||
opt-in. Grids and other surfaces keep tap-to-open with no long-press.
|
||||
|
||||
---
|
||||
|
||||
## 6. Search Flow
|
||||
|
||||
+10
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "jellytau",
|
||||
"version": "0.0.16",
|
||||
"version": "0.3.0",
|
||||
"description": "",
|
||||
"type": "module",
|
||||
"packageManager": "bun@1.3.5",
|
||||
@@ -20,16 +20,25 @@
|
||||
"check:boundary": "bash scripts/check-frontend-boundary.sh",
|
||||
"android:build": "./scripts/build-android.sh",
|
||||
"android:build:release": "./scripts/build-android.sh release",
|
||||
"android:build:device": "./scripts/build-android.sh --device",
|
||||
"android:build:release:device": "./scripts/build-android.sh release --device",
|
||||
"android:build:clean": "rm -rf node_modules/.vite dist .svelte-kit .next build target src-tauri/target && bun install && bun run build",
|
||||
"android:deploy": "./scripts/deploy-android.sh",
|
||||
"android:dev": "./scripts/build-and-deploy.sh",
|
||||
"android:check": "./scripts/check-android.sh",
|
||||
"android:logs": "./scripts/logcat.sh",
|
||||
"desktop:build:linux": "./scripts/build-desktop-linux.sh",
|
||||
"desktop:build:arch": "./scripts/build-arch.sh",
|
||||
"desktop:build:windows": "./scripts/build-windows-cross.sh",
|
||||
"docker:build:linux": "docker compose run --rm desktop-linux-build",
|
||||
"docker:build:arch": "docker compose run --rm arch-build",
|
||||
"docker:build:windows": "docker compose run --rm windows-cross",
|
||||
"clean": "./scripts/clean.sh",
|
||||
"tauri": "tauri",
|
||||
"traces": "bun run scripts/extract-traces.ts",
|
||||
"traces:json": "bun run scripts/extract-traces.ts --format json",
|
||||
"traces:markdown": "bun run scripts/extract-traces.ts --format markdown > docs/traceability.md",
|
||||
"traces:coverage": "bun run scripts/extract-traces.ts --format coverage",
|
||||
"release:notes": "bun run scripts/release-notes.ts"
|
||||
},
|
||||
"license": "MIT",
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
# Maintainer: Duncan Tourolle <duncan@tourolle.paris>
|
||||
#
|
||||
# JellyTau — a cross-platform Jellyfin client (Tauri + SvelteKit).
|
||||
#
|
||||
# This PKGBUILD builds from the local source tree by default (see the `dev`
|
||||
# convenience below), which is what scripts/build-arch.sh uses inside the Arch
|
||||
# Docker stage. For AUR distribution, replace the `source=()` line with a release
|
||||
# tarball/VCS URL and drop the local-copy prepare() step.
|
||||
|
||||
pkgname=jellytau
|
||||
pkgver=0.0.18
|
||||
pkgrel=1
|
||||
pkgdesc="A cross-platform Jellyfin client"
|
||||
arch=('x86_64')
|
||||
url="https://gitea.tourolle.paris/dtourolle/jellytau"
|
||||
license=('MIT')
|
||||
# Runtime: libmpv for audio, webkit2gtk for the webview + HTML5 transcoded video.
|
||||
depends=('webkit2gtk-4.1' 'mpv' 'gtk3' 'libayatana-appindicator')
|
||||
makedepends=('rust' 'cargo' 'bun' 'nodejs' 'pkgconf' 'libsoup3')
|
||||
options=('!strip' '!lto')
|
||||
|
||||
# Populated from the working tree by scripts/build-arch.sh (SRC env var).
|
||||
_srcdir="${JELLYTAU_SRC:-$startdir/../..}"
|
||||
|
||||
build() {
|
||||
cd "$_srcdir"
|
||||
export CARGO_HOME="${CARGO_HOME:-$srcdir/cargo-home}"
|
||||
bun install --frozen-lockfile || bun install
|
||||
bun run build
|
||||
# Only the raw binary is needed; packaging is done in package() below so we
|
||||
# control the Arch filesystem layout ourselves rather than via tauri-bundler.
|
||||
(cd src-tauri && cargo build --release --locked)
|
||||
}
|
||||
|
||||
package() {
|
||||
cd "$_srcdir"
|
||||
|
||||
install -Dm755 "src-tauri/target/release/jellytau" \
|
||||
"$pkgdir/usr/bin/jellytau"
|
||||
|
||||
# Desktop entry
|
||||
install -Dm644 "packaging/arch/jellytau.desktop" \
|
||||
"$pkgdir/usr/share/applications/jellytau.desktop"
|
||||
|
||||
# Icons (hicolor)
|
||||
install -Dm644 "src-tauri/icons/32x32.png" \
|
||||
"$pkgdir/usr/share/icons/hicolor/32x32/apps/jellytau.png"
|
||||
install -Dm644 "src-tauri/icons/128x128.png" \
|
||||
"$pkgdir/usr/share/icons/hicolor/128x128/apps/jellytau.png"
|
||||
install -Dm644 "src-tauri/icons/128x128@2x.png" \
|
||||
"$pkgdir/usr/share/icons/hicolor/256x256/apps/jellytau.png"
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=JellyTau
|
||||
Comment=A cross-platform Jellyfin client
|
||||
Exec=jellytau
|
||||
Icon=jellytau
|
||||
Terminal=false
|
||||
Categories=AudioVideo;Player;Audio;Video;
|
||||
StartupWMClass=jellytau
|
||||
+17
-1
@@ -69,13 +69,29 @@ Extract requirement IDs (TRACES) from source code and generate a traceability ma
|
||||
bun run traces # Generate markdown report
|
||||
bun run traces:json # Generate JSON report
|
||||
bun run traces:markdown # Save to docs/traceability.md
|
||||
bun run traces:coverage # Coverage gate — exits non-zero below 50%
|
||||
```
|
||||
|
||||
The script scans all TypeScript, Svelte, and Rust files looking for `TRACES:` comments and generates a comprehensive mapping of:
|
||||
The script scans all TypeScript, Svelte, and Rust files (plus `scripts/`)
|
||||
looking for `TRACES:` comments and generates a comprehensive mapping of:
|
||||
- Which code files implement which requirements
|
||||
- Line numbers and code context
|
||||
- Coverage summary by requirement type (UR, IR, DR, JA)
|
||||
|
||||
**`bun run traces:coverage` is the supported way to check requirement coverage
|
||||
locally** — it runs the same computation CI does. Coverage denominators are
|
||||
derived from `docs/requirements.md` at run time; they are never hardcoded. An ID
|
||||
that appears in a `TRACES:` comment but is not defined in `requirements.md` is
|
||||
reported as *orphaned* and does not count toward coverage (see DR-093).
|
||||
|
||||
> **Removed:** `check-req-coverage.sh`, `check-test-coverage.sh`, and
|
||||
> `find-req-implementations.sh` were deleted in July 2026. They read an
|
||||
> undocumented `@req:` tag convention parallel to `TRACES:`, grepped `src-tauri/`
|
||||
> unscoped (hanging on ~40 GB of `target/` artifacts), and in one case reported
|
||||
> "all requirements implemented" from an empty result set. `extract-traces.ts` is
|
||||
> the single source of truth for requirement coverage. See
|
||||
> [docs/specs/req-coverage-script-removal.md](../docs/specs/req-coverage-script-removal.md).
|
||||
|
||||
Example TRACES comment in code:
|
||||
```typescript
|
||||
// TRACES: UR-005, UR-026 | DR-029
|
||||
|
||||
@@ -18,15 +18,50 @@ echo ""
|
||||
# Parse args: build type (debug/release) and optional --clean flag.
|
||||
# By default the build is INCREMENTAL — Cargo and Vite reuse their caches.
|
||||
# Pass --clean (or CLEAN=1) to wipe all caches for a from-scratch build.
|
||||
#
|
||||
# ABI selection: by default Tauri builds all four ABIs (arm64/arm/x86/x86_64),
|
||||
# which is what a distributable universal APK needs — but for an on-device test
|
||||
# it means three wasted Rust compiles. Pass --device (or ABI=aarch64) to build
|
||||
# only the connected device's architecture; --abi <t> targets one explicitly.
|
||||
BUILD_TYPE="debug"
|
||||
CLEAN="${CLEAN:-0}"
|
||||
ABI="${ABI:-}"
|
||||
next_is_abi=0
|
||||
for arg in "$@"; do
|
||||
if [ "$next_is_abi" = "1" ]; then
|
||||
ABI="$arg"
|
||||
next_is_abi=0
|
||||
continue
|
||||
fi
|
||||
case "$arg" in
|
||||
--clean) CLEAN=1 ;;
|
||||
--abi) next_is_abi=1 ;;
|
||||
--device) ABI="device" ;;
|
||||
debug|release) BUILD_TYPE="$arg" ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# Resolve --device to the attached device's Rust target triple.
|
||||
if [ "$ABI" = "device" ]; then
|
||||
device_abi="$(adb shell getprop ro.product.cpu.abi 2>/dev/null | tr -d '\r\n')"
|
||||
case "$device_abi" in
|
||||
arm64-v8a) ABI="aarch64" ;;
|
||||
armeabi-v7a) ABI="armv7" ;;
|
||||
x86_64) ABI="x86_64" ;;
|
||||
x86) ABI="i686" ;;
|
||||
*)
|
||||
echo "⚠️ Could not detect device ABI (got '${device_abi:-none}') — building all targets."
|
||||
ABI=""
|
||||
;;
|
||||
esac
|
||||
[ -n "$ABI" ] && echo "🎯 Device ABI $device_abi → building only '$ABI'"
|
||||
fi
|
||||
|
||||
TARGET_ARGS=()
|
||||
if [ -n "$ABI" ]; then
|
||||
TARGET_ARGS=(--target "$ABI")
|
||||
fi
|
||||
|
||||
# Step 0: Optionally clear build caches for a fully fresh build.
|
||||
if [ "$CLEAN" = "1" ]; then
|
||||
echo "🧹 Clearing build caches (clean build)..."
|
||||
@@ -48,10 +83,10 @@ if [ "$BUILD_TYPE" = "release" ]; then
|
||||
# after sync-android-sources.sh, since gen/android is (re)generated there.
|
||||
./scripts/write-keystore-properties.sh
|
||||
echo "📦 Building release APK..."
|
||||
bun run tauri android build --apk true
|
||||
bun run tauri android build --apk true "${TARGET_ARGS[@]}"
|
||||
else
|
||||
echo "📦 Building debug APK..."
|
||||
bun run tauri android build --apk true --debug
|
||||
bun run tauri android build --apk true --debug "${TARGET_ARGS[@]}"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
|
||||
Executable
+36
@@ -0,0 +1,36 @@
|
||||
#!/bin/bash
|
||||
# Build an Arch Linux package (.pkg.tar.zst) for JellyTau via makepkg.
|
||||
#
|
||||
# Tauri's bundler has no pacman target (as of tauri-cli 2.9.x), so we ship a
|
||||
# hand-written PKGBUILD in packaging/arch/ and build it with makepkg. This must
|
||||
# run on an Arch host / the `arch-build` Docker stage — makepkg is Arch-specific
|
||||
# and refuses to run as root, so run it as a non-root user with sudo for deps.
|
||||
#
|
||||
# Usage (typically inside the arch-build Docker stage as a non-root user):
|
||||
# scripts/build-arch.sh
|
||||
# OUTPUT_DIR=/app/dist scripts/build-arch.sh
|
||||
set -euo pipefail
|
||||
|
||||
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
cd "$REPO_ROOT/packaging/arch"
|
||||
|
||||
echo "🏛️ Building JellyTau Arch package"
|
||||
echo "=================================="
|
||||
|
||||
# Point the PKGBUILD at the working tree and give cargo/bun a writable home.
|
||||
export JELLYTAU_SRC="$REPO_ROOT"
|
||||
export CARGO_HOME="${CARGO_HOME:-$REPO_ROOT/.cargo-arch}"
|
||||
|
||||
# -s installs missing deps (needs sudo/root privileges for pacman), -f overwrites.
|
||||
makepkg -sf --noconfirm
|
||||
|
||||
echo ""
|
||||
echo "✅ Built Arch package(s):"
|
||||
ls -1 ./*.pkg.tar.zst
|
||||
|
||||
if [[ -n "${OUTPUT_DIR:-}" ]]; then
|
||||
mkdir -p "$OUTPUT_DIR"
|
||||
cp -v ./*.pkg.tar.zst "$OUTPUT_DIR/"
|
||||
echo ""
|
||||
echo "📦 Copied Arch package(s) to $OUTPUT_DIR"
|
||||
fi
|
||||
Executable
+44
@@ -0,0 +1,44 @@
|
||||
#!/bin/bash
|
||||
# Build Linux desktop packages (deb + rpm) for JellyTau.
|
||||
#
|
||||
# Produces bundles under src-tauri/target/release/bundle/{deb,rpm}.
|
||||
# Runs on the existing Ubuntu builder image. NOTE: Tauri has no pacman bundle
|
||||
# target — the Arch package is built separately with makepkg (scripts/build-arch.sh
|
||||
# / Dockerfile.arch). `appimage` is also available if you want a portable bundle.
|
||||
#
|
||||
# Usage:
|
||||
# scripts/build-desktop-linux.sh # deb + rpm
|
||||
# BUNDLES="deb,appimage" scripts/build-desktop-linux.sh # subset / add appimage
|
||||
# OUTPUT_DIR=/app/dist scripts/build-desktop-linux.sh # copy bundles out
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
BUNDLES="${BUNDLES:-deb,rpm}"
|
||||
|
||||
echo "🐧 Building JellyTau Linux desktop packages"
|
||||
echo "==========================================="
|
||||
echo "Bundles: $BUNDLES"
|
||||
echo ""
|
||||
|
||||
bun install --frozen-lockfile 2>/dev/null || bun install
|
||||
bun run build
|
||||
|
||||
# --bundles overrides tauri.conf.json bundle.targets so this script controls
|
||||
# exactly which Linux formats are produced (never NSIS here).
|
||||
bun run tauri build --bundles "$BUNDLES"
|
||||
|
||||
BUNDLE_ROOT="src-tauri/target/release/bundle"
|
||||
echo ""
|
||||
echo "✅ Built packages:"
|
||||
find "$BUNDLE_ROOT" -maxdepth 2 -type f \
|
||||
\( -name '*.deb' -o -name '*.rpm' -o -name '*.AppImage' \) -print
|
||||
|
||||
if [[ -n "${OUTPUT_DIR:-}" ]]; then
|
||||
mkdir -p "$OUTPUT_DIR"
|
||||
find "$BUNDLE_ROOT" -maxdepth 2 -type f \
|
||||
\( -name '*.deb' -o -name '*.rpm' -o -name '*.AppImage' \) \
|
||||
-exec cp -v {} "$OUTPUT_DIR/" \;
|
||||
echo ""
|
||||
echo "📦 Copied bundles to $OUTPUT_DIR"
|
||||
fi
|
||||
Executable
+69
@@ -0,0 +1,69 @@
|
||||
#!/bin/bash
|
||||
# Cross-compile JellyTau for Windows from Linux, producing an NSIS installer.
|
||||
#
|
||||
# Uses the OFFICIAL Tauri cross-compile path (https://v2.tauri.app/distribute/
|
||||
# windows-installer/): the MSVC target driven by cargo-xwin, which downloads the
|
||||
# MSVC CRT/Windows SDK headers and links with lld. This is the target Tauri
|
||||
# officially supports for Windows (the mingw/GNU target is not), and unlike GNU
|
||||
# it can bundle the NSIS installer from a Linux host.
|
||||
#
|
||||
# Playback on Windows: video renders via WebView2 and audio via the webview
|
||||
# <audio> backend (WebviewAudioBackend) — see docs/build-windows.md.
|
||||
#
|
||||
# Requirements (present in the Docker windows-cross target / unified builder):
|
||||
# - rustup target x86_64-pc-windows-msvc
|
||||
# - cargo-xwin (cargo install --locked cargo-xwin)
|
||||
# - lld, llvm (linker + llvm-lib used by cargo-xwin)
|
||||
# - nsis (makensis) (installer generator)
|
||||
#
|
||||
# Usage:
|
||||
# scripts/build-windows-cross.sh # exe + NSIS installer
|
||||
# WIN_BUNDLES=none scripts/build-windows-cross.sh # exe only, skip bundling
|
||||
# OUTPUT_DIR=/app/dist scripts/build-windows-cross.sh
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
TARGET="x86_64-pc-windows-msvc"
|
||||
WIN_BUNDLES="${WIN_BUNDLES:-nsis}"
|
||||
|
||||
echo "🪟 Cross-compiling JellyTau for Windows ($TARGET, via cargo-xwin)"
|
||||
echo "================================================================"
|
||||
echo "Video plays via WebView2; audio via the webview <audio> backend."
|
||||
echo "Bundles: $WIN_BUNDLES"
|
||||
echo ""
|
||||
|
||||
bun install --frozen-lockfile 2>/dev/null || bun install
|
||||
bun run build
|
||||
|
||||
# --runner cargo-xwin + the MSVC target is what makes the Tauri CLI treat this as
|
||||
# a real Windows build and enable the nsis/msi bundlers on a Linux host.
|
||||
#
|
||||
# IMPORTANT: do NOT pass `--bundles nsis` here. tauri-cli 2.9.x validates the
|
||||
# `--bundles` flag against a static clap enum gated by the HOST OS (Linux allows
|
||||
# only deb/rpm/appimage) *before* it considers --target/--runner, so `--bundles
|
||||
# nsis` is rejected at arg-parse time. Instead the Windows bundle targets come
|
||||
# from tauri.conf.json (bundle.targets includes "nsis"), which is not subject to
|
||||
# that CLI validation — the bundler then picks nsis once it knows the target is
|
||||
# Windows.
|
||||
if [[ "$WIN_BUNDLES" == "none" ]]; then
|
||||
bun run tauri build --runner cargo-xwin --target "$TARGET" --no-bundle
|
||||
else
|
||||
bun run tauri build --runner cargo-xwin --target "$TARGET"
|
||||
fi
|
||||
|
||||
BIN_DIR="src-tauri/target/$TARGET/release"
|
||||
echo ""
|
||||
echo "✅ Built Windows artifacts:"
|
||||
find "$BIN_DIR" -maxdepth 1 -name '*.exe' -print
|
||||
find "$BIN_DIR/bundle" -type f \( -name '*.exe' -o -name '*.msi' \) -print 2>/dev/null || true
|
||||
|
||||
if [[ -n "${OUTPUT_DIR:-}" ]]; then
|
||||
mkdir -p "$OUTPUT_DIR"
|
||||
find "$BIN_DIR" -maxdepth 1 -name 'jellytau.exe' -exec cp -v {} "$OUTPUT_DIR/" \;
|
||||
# NSIS setup installers land in bundle/nsis/*-setup.exe; MSI in bundle/msi/*.msi.
|
||||
find "$BIN_DIR/bundle" -type f \( -name '*-setup.exe' -o -name '*.msi' \) \
|
||||
-exec cp -v {} "$OUTPUT_DIR/" \; 2>/dev/null || true
|
||||
echo ""
|
||||
echo "📦 Copied Windows artifacts to $OUTPUT_DIR"
|
||||
fi
|
||||
@@ -1,6 +1,8 @@
|
||||
#!/usr/bin/env bash
|
||||
# Boundary tripwire: flag domain-taxonomy leaks in the Svelte frontend.
|
||||
#
|
||||
# Implements DR-094 (see docs/requirements.md).
|
||||
#
|
||||
# The project rule (CLAUDE.md, docs/architecture/02-svelte-frontend.md) is that
|
||||
# the frontend is presentation-only and the Rust backend owns domain logic —
|
||||
# including Jellyfin's item-type *taxonomy* (what the category "Music" means as a
|
||||
@@ -9,18 +11,29 @@
|
||||
#
|
||||
# ⚠️ This is a TRIPWIRE, NOT A PROOF. A grep cannot distinguish taxonomy-as-policy
|
||||
# (a leak) from taxonomy-as-display (legitimate: "is this a music card?"). It
|
||||
# targets the one machine-detectable signature of the leak class — a *query* that
|
||||
# names a multi-type category — and defers everything subtler to the human
|
||||
# spec-review checklist (docs/specs/SPEC-REVIEW-CHECKLIST.md). A clean run here
|
||||
# does not mean the boundary is respected; it means the crudest violation isn't
|
||||
# present.
|
||||
# targets the machine-detectable signature of the leak class and defers
|
||||
# everything subtler to the human spec-review checklist
|
||||
# (docs/specs/SPEC-REVIEW-CHECKLIST.md). A clean run here does not mean the
|
||||
# boundary is respected; it means the crudest violation isn't present.
|
||||
#
|
||||
# What it flags: an `includeItemTypes: [ ... , ... ]` array literal with two or
|
||||
# more types — i.e. the frontend deciding that a *category* maps to a *set* of
|
||||
# Jellyfin types, which is domain knowledge the backend should own. Single-type
|
||||
# query arrays (`includeItemTypes: ["Movie"]`) are a page saying "I show movies"
|
||||
# and are allowed. Type *inspection* (`item.type === "Audio"`) is display logic
|
||||
# and is not matched.
|
||||
# What it flags: an array literal naming two or more Jellyfin item types,
|
||||
# ANYWHERE in src/ — i.e. the frontend deciding that a *category* maps to a *set*
|
||||
# of Jellyfin types, which is domain knowledge the backend should own.
|
||||
# Single-type arrays (`includeItemTypes: ["Movie"]`) are a page saying "I show
|
||||
# movies" and are allowed. Type *inspection* (`item.type === "Audio"`) is display
|
||||
# logic and is not matched.
|
||||
#
|
||||
# 🔴 What it still CANNOT see (do not read a green run as proof):
|
||||
# - a type set built at run time: [...musicTypes, "Playlist"]
|
||||
# - types split across variables: const A = "Audio"; [A, B]
|
||||
# - taxonomy as control flow: switch (t) { case "Audio": … }
|
||||
# t === "Audio" || t === "MusicAlbum"
|
||||
# - an item type absent from ITEM_TYPES below (false negative by design)
|
||||
#
|
||||
# This check was hardened in July 2026 after the audit found it passing on the
|
||||
# very leak it was written for: the original pattern was anchored to
|
||||
# `includeItemTypes:` at the query site, so assigning the same array to a named
|
||||
# const evaded it entirely. See docs/specs/boundary-tripwire-hardening.md (DR-094).
|
||||
#
|
||||
# Escaping a genuine exception: add the file+reason to the ALLOWLIST below.
|
||||
|
||||
@@ -28,7 +41,7 @@ set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
# Files permitted to contain a multi-type includeItemTypes query, with the reason.
|
||||
# Files permitted to contain a multi-type item-type array, with the reason.
|
||||
# Keep this SHORT. A growing allowlist means the boundary is eroding — that is a
|
||||
# signal to push taxonomy into Rust, not to keep appending here.
|
||||
ALLOWLIST=(
|
||||
@@ -36,8 +49,31 @@ ALLOWLIST=(
|
||||
# two-type filmography query with no category-configuration behind it. Tracked
|
||||
# as acceptable pending any person-scope work; revisit if it grows.
|
||||
"src/lib/components/library/PersonDetailView.svelte"
|
||||
|
||||
# Grid styling predicate over `config.itemType`, a value the page already
|
||||
# declares about itself. Selects a *look*, issues no query, and would only
|
||||
# change if the UI were redesigned — presentation, not taxonomy-as-policy.
|
||||
"src/lib/components/library/GenericMediaListPage.svelte"
|
||||
|
||||
# "Is this item a container?" predicate for downloads browsing.
|
||||
# BORDERLINE — leans domain: the container set grows when Jellyfin adds a
|
||||
# container type. TODO: replace with a backend-supplied `MediaItem.isContainer`
|
||||
# flag and remove this entry. Tracked in
|
||||
# docs/specs/boundary-tripwire-hardening.md §Out of scope.
|
||||
"src/lib/components/downloads/DownloadedBrowse.svelte"
|
||||
)
|
||||
|
||||
# Hard cap so erosion is caught mechanically rather than by whoever notices.
|
||||
# Deliberately just above the current count: the next exception forces a
|
||||
# conversation instead of a one-line append.
|
||||
MAX_ALLOWLIST=4
|
||||
|
||||
if [[ "${#ALLOWLIST[@]}" -gt "$MAX_ALLOWLIST" ]]; then
|
||||
echo "❌ Allowlist has ${#ALLOWLIST[@]} entries (max $MAX_ALLOWLIST)."
|
||||
echo " Push taxonomy into Rust instead of appending here."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
is_allowed() {
|
||||
local file="$1"
|
||||
for allowed in "${ALLOWLIST[@]}"; do
|
||||
@@ -46,11 +82,28 @@ is_allowed() {
|
||||
return 1
|
||||
}
|
||||
|
||||
# Multi-element includeItemTypes array: `includeItemTypes: [ <x> , <y> ... ]`.
|
||||
# The comma inside the brackets is what makes it multi-type.
|
||||
PATTERN='includeItemTypes:[[:space:]]*\[[^]]*,[^]]*\]'
|
||||
# Two or more adjacent Jellyfin item-type string literals inside a bracket.
|
||||
#
|
||||
# NOT anchored to `includeItemTypes:` — that was the original rule, and it missed
|
||||
# the real leak: `searchScope.ts` assigned the same array to a named const and
|
||||
# dereferenced it one indirection away from the query, so the grep never saw it
|
||||
# while CI stayed green. Matching the array literal itself catches a const, a
|
||||
# Record value, a function return, and an inline query alike.
|
||||
#
|
||||
# Deliberate limits:
|
||||
# - requires TWO adjacent types, so single-type presentation
|
||||
# (`itemType: "Movie"`) stays legal — the rule targets *category* taxonomy;
|
||||
# - requires string literals, so `item.type === "Audio"` (display inspection)
|
||||
# does not match;
|
||||
# - uses an explicit type list rather than a generic capitalised-word pattern,
|
||||
# so unrelated string arrays (`["High","Low"]`) produce no noise.
|
||||
#
|
||||
# An item type missing from this list is a false *negative*, never a false
|
||||
# positive — the check degrades safely as Jellyfin adds types.
|
||||
ITEM_TYPES='Movie|Series|Episode|Audio|MusicAlbum|MusicArtist|MusicVideo|Season|BoxSet|Playlist|Book|AudioBook|Video|Person|Folder|CollectionFolder|TvChannel|LiveTvChannel'
|
||||
PATTERN="\[[[:space:]]*\"($ITEM_TYPES)\"[[:space:]]*,[[:space:]]*\"($ITEM_TYPES)\""
|
||||
|
||||
echo "🔎 Checking frontend for domain-taxonomy leaks (multi-type query arrays)…"
|
||||
echo "🔎 Checking frontend for domain-taxonomy leaks (item-type array literals)…"
|
||||
|
||||
# Collect hits, excluding tests and the allowlist.
|
||||
violations=""
|
||||
@@ -69,9 +122,11 @@ done < <(grep -rInE "$PATTERN" src/ 2>/dev/null || true)
|
||||
|
||||
if [[ -n "$violations" ]]; then
|
||||
echo ""
|
||||
echo "❌ Frontend boundary violation: a multi-type includeItemTypes query defines"
|
||||
echo " a category in the presentation layer. That taxonomy belongs in Rust —"
|
||||
echo " send an opaque scope and let the backend expand it to item types."
|
||||
echo "❌ Frontend boundary violation: an item-type array literal defines a"
|
||||
echo " category in the presentation layer. That taxonomy belongs in Rust —"
|
||||
echo " send an opaque scope/enum and let the backend expand it to item types"
|
||||
echo " (see SearchScope::item_types() in src-tauri/src/repository/types.rs)."
|
||||
echo " Assigning the array to a const does not make it presentation."
|
||||
echo " See docs/specs/scoped-search-boundary.md and CLAUDE.md."
|
||||
echo ""
|
||||
echo "$violations" | sed 's/^/ /'
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# Requirements Coverage Checker
|
||||
# Extracts @req tags from codebase and compares with README.md
|
||||
#
|
||||
|
||||
set -e
|
||||
|
||||
REQUIREMENTS_FILE="README.md"
|
||||
SOURCE_DIRS="src-tauri/ src/"
|
||||
|
||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||
echo " Requirements Coverage Report"
|
||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||
echo ""
|
||||
|
||||
# Extract requirement IDs from README.md (UR-, IR-, DR-, JA-)
|
||||
echo "📊 Scanning requirements from $REQUIREMENTS_FILE..."
|
||||
requirements=$(grep -E "^\| (UR|IR|DR|JA)-[0-9]+" "$REQUIREMENTS_FILE" | \
|
||||
sed -E 's/^\| ([A-Z]+-[0-9]+).*/\1/' | \
|
||||
sort -u)
|
||||
|
||||
total_reqs=$(echo "$requirements" | wc -l)
|
||||
implemented=0
|
||||
partial=0
|
||||
planned=0
|
||||
missing=0
|
||||
|
||||
echo ""
|
||||
echo "Category Breakdown:"
|
||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||
|
||||
for category in UR IR DR JA; do
|
||||
cat_count=$(echo "$requirements" | grep "^$category-" | wc -l)
|
||||
printf "%-4s %3d requirements\n" "$category:" "$cat_count"
|
||||
done
|
||||
|
||||
echo ""
|
||||
echo "Implementation Status:"
|
||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||
|
||||
for req in $requirements; do
|
||||
# Count full implementations
|
||||
full_count=$(grep -r "@req: $req" $SOURCE_DIRS 2>/dev/null | grep -v "@req-partial" | grep -v "@req-planned" | wc -l)
|
||||
|
||||
# Count partial implementations
|
||||
partial_count=$(grep -r "@req-partial: $req" $SOURCE_DIRS 2>/dev/null | wc -l)
|
||||
|
||||
# Count planned
|
||||
planned_count=$(grep -r "@req-planned: $req" $SOURCE_DIRS 2>/dev/null | wc -l)
|
||||
|
||||
if [ "$full_count" -gt 0 ]; then
|
||||
echo "✅ $req: $full_count implementation(s)"
|
||||
((implemented++))
|
||||
elif [ "$partial_count" -gt 0 ]; then
|
||||
echo "🔶 $req: $partial_count partial implementation(s)"
|
||||
((partial++))
|
||||
elif [ "$planned_count" -gt 0 ]; then
|
||||
echo "📋 $req: Planned (not yet implemented)"
|
||||
((planned++))
|
||||
else
|
||||
echo "❌ $req: No implementation found"
|
||||
((missing++))
|
||||
fi
|
||||
done
|
||||
|
||||
echo ""
|
||||
echo "Summary:"
|
||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||
printf "Total Requirements: %3d\n" "$total_reqs"
|
||||
printf "✅ Fully Implemented: %3d (%.0f%%)\n" "$implemented" "$(echo "scale=0; $implemented * 100 / $total_reqs" | bc)"
|
||||
printf "🔶 Partially Implemented: %3d (%.0f%%)\n" "$partial" "$(echo "scale=0; $partial * 100 / $total_reqs" | bc)"
|
||||
printf "📋 Planned: %3d (%.0f%%)\n" "$planned" "$(echo "scale=0; $planned * 100 / $total_reqs" | bc)"
|
||||
printf "❌ Missing: %3d (%.0f%%)\n" "$missing" "$(echo "scale=0; $missing * 100 / $total_reqs" | bc)"
|
||||
echo ""
|
||||
|
||||
# Exit code based on missing critical requirements
|
||||
if [ "$missing" -gt 0 ]; then
|
||||
echo "⚠️ Warning: $missing requirements have no implementation"
|
||||
exit 1
|
||||
else
|
||||
echo "✨ All requirements have implementations!"
|
||||
exit 0
|
||||
fi
|
||||
@@ -1,40 +0,0 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# Test Coverage Report
|
||||
# Links test requirements to implementations
|
||||
#
|
||||
|
||||
echo "Test Coverage Report"
|
||||
echo "===================="
|
||||
echo ""
|
||||
|
||||
test_reqs=$(grep -rh "@req-test:" src-tauri/ 2>/dev/null | \
|
||||
sed 's/.*@req-test: \([A-Z][A-Z]-[0-9]*\).*/\1/' | \
|
||||
sort -u)
|
||||
|
||||
total_tests=0
|
||||
covered=0
|
||||
uncovered=0
|
||||
|
||||
for req in $test_reqs; do
|
||||
test_count=$(grep -r "@req-test: $req" src-tauri/ 2>/dev/null | wc -l)
|
||||
impl_count=$(grep -r "@req: $req" src-tauri/ src/ 2>/dev/null | wc -l)
|
||||
|
||||
((total_tests++))
|
||||
|
||||
if [ "$test_count" -gt 0 ] && [ "$impl_count" -gt 0 ]; then
|
||||
echo "✅ $req: $test_count test(s), $impl_count implementation(s)"
|
||||
((covered++))
|
||||
elif [ "$impl_count" -eq 0 ]; then
|
||||
echo "⚠️ $req: $test_count test(s) but no implementation"
|
||||
((uncovered++))
|
||||
fi
|
||||
done
|
||||
|
||||
echo ""
|
||||
echo "Summary:"
|
||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||
printf "Total Test Requirements: %3d\n" "$total_tests"
|
||||
printf "✅ With Implementation: %3d (%.0f%%)\n" "$covered" "$(echo "scale=0; $covered * 100 / $total_tests" | bc)"
|
||||
printf "⚠️ No Implementation: %3d (%.0f%%)\n" "$uncovered" "$(echo "scale=0; $uncovered * 100 / $total_tests" | bc)"
|
||||
echo ""
|
||||
@@ -0,0 +1,182 @@
|
||||
/**
|
||||
* Tests for the traceability coverage computation.
|
||||
*
|
||||
* These run over fixture strings rather than the live docs/requirements.md, so
|
||||
* their meaning does not drift as requirements are added.
|
||||
*
|
||||
* Background: the CI gate divided traced-requirement counts by hardcoded
|
||||
* denominators (UR/39, IR/24, DR/48, JA/3, total 114) that had fallen out of
|
||||
* date, reporting 158% coverage and making the 50% threshold unreachable. These
|
||||
* tests pin the parsing and arithmetic that replace those literals.
|
||||
*
|
||||
* @req-test: UT-089 - Requirement definitions parsed from requirements.md
|
||||
* @req-test: UT-090 - Coverage is the intersection of traced and defined IDs
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { countDefinedRequirements, computeCoverage } from "./extract-traces";
|
||||
|
||||
describe("countDefinedRequirements", () => {
|
||||
it("counts a well-formed table row as a defined requirement", () => {
|
||||
const md = `
|
||||
| ID | Requirement | Priority | Status |
|
||||
|----|-------------|----------|--------|
|
||||
| UR-001 | Run the app on multiple platforms | High | In Progress |
|
||||
| UR-002 | Access media when online or offline | High | Done |
|
||||
`;
|
||||
const defined = countDefinedRequirements(md);
|
||||
expect(defined.UR).toBe(2);
|
||||
expect(defined.DR).toBe(0);
|
||||
});
|
||||
|
||||
it("does not count IDs that appear only in the Traces To column", () => {
|
||||
// The bug this rule avoids: a naive grep for /DR-\d{3}/ over the whole file
|
||||
// counts DR-001 here as "defined", inflating the denominator with IDs that
|
||||
// are merely referenced.
|
||||
const md = `
|
||||
| DR-001 | Player state machine | Player | UR-005 | Done |
|
||||
| DR-002 | MediaItem struct | Player | UR-003, UR-004 | Done |
|
||||
`;
|
||||
const defined = countDefinedRequirements(md);
|
||||
expect(defined.DR).toBe(2);
|
||||
// UR-005/UR-003/UR-004 are referenced, never defined here.
|
||||
expect(defined.UR).toBe(0);
|
||||
});
|
||||
|
||||
it("does not count IDs mentioned in prose", () => {
|
||||
const md = `
|
||||
Some prose explaining that UR-005 relates to DR-001 and JA-002.
|
||||
|
||||
| UR-005 | Control media playback | High | Done |
|
||||
`;
|
||||
const defined = countDefinedRequirements(md);
|
||||
expect(defined.UR).toBe(1);
|
||||
expect(defined.DR).toBe(0);
|
||||
expect(defined.JA).toBe(0);
|
||||
});
|
||||
|
||||
it("deduplicates an ID listed in both the spec table and the traceability matrix", () => {
|
||||
// requirements.md lists every UR twice: once in §1 (definition) and again in
|
||||
// §3 (traceability matrix), both as a leading table cell. Counting rows
|
||||
// instead of unique IDs double-counts the UR denominator (121 vs 61).
|
||||
const md = `
|
||||
| UR-005 | Control media playback | High | Done |
|
||||
| UR-006 | Browse the library | High | Done |
|
||||
|
||||
### Traceability Matrix
|
||||
|
||||
| UR-005 | - | DR-001, DR-005, DR-009 |
|
||||
| UR-006 | - | DR-012 |
|
||||
`;
|
||||
const defined = countDefinedRequirements(md);
|
||||
expect(defined.UR).toBe(2);
|
||||
});
|
||||
|
||||
it("collects the defined ID set, not just counts", () => {
|
||||
const md = `
|
||||
| UR-001 | A | High | Done |
|
||||
| DR-050 | B | Player | UR-001 | Done |
|
||||
`;
|
||||
const defined = countDefinedRequirements(md);
|
||||
expect(defined.ids.has("UR-001")).toBe(true);
|
||||
expect(defined.ids.has("DR-050")).toBe(true);
|
||||
expect(defined.ids.has("UR-999")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("computeCoverage", () => {
|
||||
const defined = {
|
||||
UR: 2,
|
||||
IR: 0,
|
||||
DR: 2,
|
||||
JA: 0,
|
||||
total: 4,
|
||||
ids: new Set(["UR-001", "UR-002", "DR-001", "DR-002"]),
|
||||
};
|
||||
|
||||
it("computes coverage as traced ∩ defined over defined", () => {
|
||||
const traced = ["UR-001", "DR-001"];
|
||||
const cov = computeCoverage(traced, defined);
|
||||
expect(cov.covered).toBe(2);
|
||||
expect(cov.total).toBe(4);
|
||||
expect(cov.percent).toBe(50);
|
||||
});
|
||||
|
||||
it("does not let a traced-but-undefined ID inflate the numerator", () => {
|
||||
// This is how a ratio exceeds 100%: a TRACES comment naming a typo'd or
|
||||
// deleted requirement counted as covered.
|
||||
const traced = ["UR-001", "DR-001", "DR-097"];
|
||||
const cov = computeCoverage(traced, defined);
|
||||
expect(cov.covered).toBe(2);
|
||||
expect(cov.percent).toBe(50);
|
||||
});
|
||||
|
||||
it("reports traced-but-undefined IDs as orphaned so they get fixed", () => {
|
||||
const traced = ["UR-001", "DR-097", "JA-404"];
|
||||
const cov = computeCoverage(traced, defined);
|
||||
expect(cov.orphaned).toEqual(["DR-097", "JA-404"]);
|
||||
});
|
||||
|
||||
it("has no orphans when every traced ID is defined", () => {
|
||||
const cov = computeCoverage(["UR-001", "UR-002"], defined);
|
||||
expect(cov.orphaned).toEqual([]);
|
||||
});
|
||||
|
||||
it("ignores UT/IT test IDs entirely — they are a separate taxonomy", () => {
|
||||
// UT/IT are defined in §4 of requirements.md, not among the four
|
||||
// requirement types. Treating them as orphans buries real typos in ~60
|
||||
// lines of noise, and counting them would corrupt the ratio.
|
||||
const cov = computeCoverage(["UR-001", "UT-088", "IT-017"], defined);
|
||||
expect(cov.orphaned).toEqual([]);
|
||||
expect(cov.covered).toBe(1);
|
||||
});
|
||||
|
||||
it("reports 0% rather than dividing by zero for an empty trace set", () => {
|
||||
const cov = computeCoverage([], defined);
|
||||
expect(cov.covered).toBe(0);
|
||||
expect(cov.percent).toBe(0);
|
||||
});
|
||||
|
||||
it("reports 0% rather than NaN when nothing is defined", () => {
|
||||
const empty = { UR: 0, IR: 0, DR: 0, JA: 0, total: 0, ids: new Set<string>() };
|
||||
const cov = computeCoverage([], empty);
|
||||
expect(cov.percent).toBe(0);
|
||||
expect(Number.isNaN(cov.percent)).toBe(false);
|
||||
});
|
||||
|
||||
it("reports exactly 100% when all defined requirements are traced, never above", () => {
|
||||
const traced = ["UR-001", "UR-002", "DR-001", "DR-002"];
|
||||
const cov = computeCoverage(traced, defined);
|
||||
expect(cov.percent).toBe(100);
|
||||
});
|
||||
|
||||
it("ignores duplicate traced IDs", () => {
|
||||
const traced = ["UR-001", "UR-001", "UR-001"];
|
||||
const cov = computeCoverage(traced, defined);
|
||||
expect(cov.covered).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("live requirements.md", () => {
|
||||
it("parses the real file to the counts the CI gate must use", () => {
|
||||
// Guards the specific regression: CI hardcoded UR/39, IR/24, DR/48, JA/3
|
||||
// (total 114) while the real file had grown to 211. Update these numbers
|
||||
// deliberately when requirements are added — that edit is the signal the
|
||||
// denominator is live rather than frozen.
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
// import.meta.dir is Bun-only; derive from import.meta.url under vitest.
|
||||
const here = path.dirname(new URL(import.meta.url).pathname);
|
||||
const md = fs.readFileSync(
|
||||
path.resolve(here, "../docs/requirements.md"),
|
||||
"utf-8"
|
||||
);
|
||||
const defined = countDefinedRequirements(md);
|
||||
|
||||
expect(defined.UR).toBe(64);
|
||||
expect(defined.IR).toBe(29);
|
||||
expect(defined.DR).toBe(104);
|
||||
expect(defined.JA).toBe(32);
|
||||
expect(defined.total).toBe(229);
|
||||
});
|
||||
});
|
||||
+193
-16
@@ -34,11 +34,20 @@ interface TracesData {
|
||||
DR: string[];
|
||||
JA: string[];
|
||||
};
|
||||
/** Requirements *defined* in requirements.md — the coverage denominators. */
|
||||
defined?: { UR: number; IR: number; DR: number; JA: number; total: number };
|
||||
coverage?: CoverageResult;
|
||||
}
|
||||
|
||||
// Repo root, derived from this script's location (scripts/ -> repo root).
|
||||
// Must NOT be hardcoded to a developer's machine, or CI checkouts see no files.
|
||||
const BASE_DIR = path.resolve(import.meta.dir, "..");
|
||||
//
|
||||
// `import.meta.dir` is a Bun extension and is undefined when this module is
|
||||
// imported by vitest (which runs it as an ordinary ESM module), so fall back to
|
||||
// import.meta.url — this file must stay importable for extract-traces.test.ts.
|
||||
const SCRIPT_DIR =
|
||||
import.meta.dir ?? path.dirname(new URL(import.meta.url).pathname);
|
||||
const BASE_DIR = path.resolve(SCRIPT_DIR, "..");
|
||||
|
||||
const TRACES_PATTERN = /TRACES:\s*([^\n]+)/gi;
|
||||
const REQ_ID_PATTERN = /([A-Z]{2})-(\d{3})/g;
|
||||
@@ -50,7 +59,10 @@ function extractRequirementIds(tracesString: string): string[] {
|
||||
|
||||
function getAllSourceFiles(): string[] {
|
||||
const baseDir = BASE_DIR;
|
||||
const patterns = ["src", "src-tauri/src"];
|
||||
// `scripts` is scanned too: build tooling implements requirements (e.g.
|
||||
// DR-093, the coverage engine itself) and would otherwise be invisible to the
|
||||
// very matrix it generates.
|
||||
const patterns = ["src", "src-tauri/src", "scripts"];
|
||||
const files: string[] = [];
|
||||
|
||||
function walkDir(dir: string) {
|
||||
@@ -192,6 +204,109 @@ function extractTraces(): TracesData {
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Coverage: how many *defined* requirements are actually traced.
|
||||
//
|
||||
// The denominators MUST be derived from requirements.md, never hardcoded. The
|
||||
// CI gate previously divided by frozen literals (UR/39, IR/24, DR/48, JA/3,
|
||||
// total 114) while the real file had grown to 211 requirements, so it reported
|
||||
// 158% coverage and the 50% threshold became unreachable — the gate could not
|
||||
// fail. See docs/specs/traceability-gate-repair.md.
|
||||
//
|
||||
// TRACES: | DR-093
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface DefinedRequirements {
|
||||
UR: number;
|
||||
IR: number;
|
||||
DR: number;
|
||||
JA: number;
|
||||
total: number;
|
||||
ids: Set<string>;
|
||||
}
|
||||
|
||||
export interface CoverageResult {
|
||||
covered: number;
|
||||
total: number;
|
||||
percent: number;
|
||||
/** Traced in code but not defined in requirements.md (typo, or deleted req). */
|
||||
orphaned: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* A requirement is *defined* only where its ID is the leading cell of a markdown
|
||||
* table row: `| DR-001 | … |`.
|
||||
*
|
||||
* This deliberately ignores IDs in the "Traces To" column and in prose — a
|
||||
* naive scan for /DR-\d{3}/ counts those as definitions and inflates the
|
||||
* denominator. IDs are deduplicated because requirements.md lists each UR twice
|
||||
* (once in §1 as a definition, again in §3's traceability matrix), which would
|
||||
* otherwise double the UR count from 61 to 121.
|
||||
*
|
||||
* TRACES: | DR-093
|
||||
*/
|
||||
export function countDefinedRequirements(markdown: string): DefinedRequirements {
|
||||
const ids = new Set<string>();
|
||||
const ROW_ID = /^\|\s*(UR|IR|DR|JA)-(\d{3})\s*\|/;
|
||||
|
||||
for (const line of markdown.split("\n")) {
|
||||
const match = line.match(ROW_ID);
|
||||
if (match) ids.add(`${match[1]}-${match[2]}`);
|
||||
}
|
||||
|
||||
const countOf = (type: string) =>
|
||||
[...ids].filter((id) => id.startsWith(`${type}-`)).length;
|
||||
|
||||
return {
|
||||
UR: countOf("UR"),
|
||||
IR: countOf("IR"),
|
||||
DR: countOf("DR"),
|
||||
JA: countOf("JA"),
|
||||
total: ids.size,
|
||||
ids,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Coverage is the *intersection* of traced and defined IDs over defined IDs.
|
||||
*
|
||||
* Using the raw traced count as the numerator is what lets a ratio exceed 100%:
|
||||
* a TRACES comment naming a requirement that no longer exists would count as
|
||||
* covered. Those IDs are reported as `orphaned` so they get fixed rather than
|
||||
* silently counted or silently dropped.
|
||||
*
|
||||
* TRACES: | DR-093
|
||||
*/
|
||||
export function computeCoverage(
|
||||
tracedIds: string[],
|
||||
defined: DefinedRequirements
|
||||
): CoverageResult {
|
||||
// Only the four *requirement* types participate in coverage. UT/IT are test
|
||||
// identifiers defined in §4 of requirements.md — a different taxonomy, and
|
||||
// flagging them as orphans would bury real typos in ~60 lines of noise.
|
||||
const isRequirement = (id: string) => /^(UR|IR|DR|JA)-\d{3}$/.test(id);
|
||||
|
||||
const traced = new Set(tracedIds.filter(isRequirement));
|
||||
const covered = [...traced].filter((id) => defined.ids.has(id));
|
||||
const orphaned = [...traced].filter((id) => !defined.ids.has(id)).sort();
|
||||
|
||||
return {
|
||||
covered: covered.length,
|
||||
total: defined.total,
|
||||
percent:
|
||||
defined.total === 0
|
||||
? 0
|
||||
: Math.round((covered.length / defined.total) * 100),
|
||||
orphaned,
|
||||
};
|
||||
}
|
||||
|
||||
/** Read requirements.md from the repo and count what it defines. */
|
||||
export function readDefinedRequirements(): DefinedRequirements {
|
||||
const reqPath = path.join(BASE_DIR, "docs", "requirements.md");
|
||||
return countDefinedRequirements(fs.readFileSync(reqPath, "utf-8"));
|
||||
}
|
||||
|
||||
function generateMarkdown(data: TracesData): string {
|
||||
let md = `# Code Traceability Matrix
|
||||
|
||||
@@ -265,21 +380,83 @@ function generateJson(data: TracesData): string {
|
||||
return JSON.stringify(data, null, 2);
|
||||
}
|
||||
|
||||
// Main
|
||||
const args = Bun.argv.slice(2);
|
||||
const format = args.includes("--format")
|
||||
? args[args.indexOf("--format") + 1]
|
||||
: "markdown";
|
||||
/**
|
||||
* Human-readable coverage report; exits non-zero below the threshold so this is
|
||||
* runnable as a local gate (`bun run traces:coverage`), not just in CI.
|
||||
*
|
||||
* TRACES: | DR-093
|
||||
*/
|
||||
function reportCoverage(data: TracesData, minThreshold: number): number {
|
||||
const defined = data.defined!;
|
||||
const cov = data.coverage!;
|
||||
|
||||
console.error("🔍 Extracting TRACES from codebase...");
|
||||
const data = extractTraces();
|
||||
const definedIds = readDefinedRequirements().ids;
|
||||
|
||||
if (format === "json") {
|
||||
console.log(generateJson(data));
|
||||
} else {
|
||||
console.log(generateMarkdown(data));
|
||||
console.log("📋 Requirement coverage (traced / defined):");
|
||||
for (const type of ["UR", "IR", "DR", "JA"] as const) {
|
||||
const traced = data.byType[type].filter((id) => definedIds.has(id)).length;
|
||||
console.log(` ${type}: ${traced} / ${defined[type]}`);
|
||||
}
|
||||
console.log("");
|
||||
console.log(`📈 Overall: ${cov.covered} / ${cov.total} (${cov.percent}%)`);
|
||||
|
||||
if (cov.orphaned.length > 0) {
|
||||
console.log("");
|
||||
console.log(
|
||||
`⚠️ Traced but not defined in requirements.md: ${cov.orphaned.join(", ")}`
|
||||
);
|
||||
console.log(" Fix the TRACES comment or add the requirement.");
|
||||
}
|
||||
|
||||
// A ratio above 100% means the computation is broken (the condition that hid
|
||||
// the stale-denominator bug for so long). Fail loudly rather than report it.
|
||||
if (cov.percent > 100) {
|
||||
console.log("");
|
||||
console.log(`❌ Coverage > 100% — the gate is miscomputing.`);
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (cov.percent < minThreshold) {
|
||||
console.log("");
|
||||
console.log(`❌ Coverage (${cov.percent}%) is below minimum (${minThreshold}%)`);
|
||||
return 1;
|
||||
}
|
||||
|
||||
console.log("");
|
||||
console.log(`✅ Coverage is acceptable (${cov.percent}% >= ${minThreshold}%)`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
console.error(
|
||||
`\n✅ Complete! Found ${data.totalTraces} TRACES across ${data.totalFiles} files`
|
||||
);
|
||||
// Main — guarded so this module stays importable from extract-traces.test.ts.
|
||||
if (import.meta.main) {
|
||||
const args = process.argv.slice(2);
|
||||
const format = args.includes("--format")
|
||||
? args[args.indexOf("--format") + 1]
|
||||
: "markdown";
|
||||
|
||||
console.error("🔍 Extracting TRACES from codebase...");
|
||||
const data = extractTraces();
|
||||
|
||||
const defined = readDefinedRequirements();
|
||||
const allTraced = Object.keys(data.requirements);
|
||||
data.defined = {
|
||||
UR: defined.UR,
|
||||
IR: defined.IR,
|
||||
DR: defined.DR,
|
||||
JA: defined.JA,
|
||||
total: defined.total,
|
||||
};
|
||||
data.coverage = computeCoverage(allTraced, defined);
|
||||
|
||||
if (format === "json") {
|
||||
console.log(generateJson(data));
|
||||
} else if (format === "coverage") {
|
||||
process.exit(reportCoverage(data, 50));
|
||||
} else {
|
||||
console.log(generateMarkdown(data));
|
||||
}
|
||||
|
||||
console.error(
|
||||
`\n✅ Complete! Found ${data.totalTraces} TRACES across ${data.totalFiles} files`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
#!/bin/bash
|
||||
#
|
||||
# Find all files implementing a specific requirement
|
||||
#
|
||||
# Usage: ./find-req-implementations.sh UR-004
|
||||
#
|
||||
|
||||
if [ $# -eq 0 ]; then
|
||||
echo "Usage: $0 <REQUIREMENT_ID>"
|
||||
echo "Example: $0 UR-004"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
REQ_ID=$1
|
||||
|
||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||
echo " Implementations of $REQ_ID"
|
||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||
echo ""
|
||||
|
||||
# Full implementations
|
||||
echo "Full Implementations:"
|
||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||
grep -rn "@req: $REQ_ID" src-tauri/ src/ 2>/dev/null | \
|
||||
grep -v "@req-partial" | \
|
||||
grep -v "@req-planned" | \
|
||||
sed 's/src-tauri\/src\///' | \
|
||||
sed 's/src\///' || echo " (none)"
|
||||
|
||||
echo ""
|
||||
|
||||
# Partial implementations
|
||||
echo "Partial Implementations:"
|
||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||
grep -rn "@req-partial: $REQ_ID" src-tauri/ src/ 2>/dev/null | \
|
||||
sed 's/src-tauri\/src\///' | \
|
||||
sed 's/src\///' || echo " (none)"
|
||||
|
||||
echo ""
|
||||
|
||||
# Planned
|
||||
echo "Planned Implementations:"
|
||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||
grep -rn "@req-planned: $REQ_ID" src-tauri/ src/ 2>/dev/null | \
|
||||
sed 's/src-tauri\/src\///' | \
|
||||
sed 's/src\///' || echo " (none)"
|
||||
|
||||
echo ""
|
||||
|
||||
# Tests
|
||||
echo "Test Cases:"
|
||||
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||
grep -rn "@req-test: $REQ_ID" src-tauri/ 2>/dev/null | \
|
||||
sed 's/src-tauri\/src\///' || echo " (none)"
|
||||
|
||||
echo ""
|
||||
+8
-1
@@ -7,7 +7,7 @@ echo "🧪 Running all tests..."
|
||||
echo ""
|
||||
|
||||
echo "📦 Running frontend tests..."
|
||||
bun run test
|
||||
bun run test --run
|
||||
|
||||
echo ""
|
||||
echo "🦀 Running Rust tests..."
|
||||
@@ -15,5 +15,12 @@ cd src-tauri
|
||||
cargo test
|
||||
cd ..
|
||||
|
||||
echo ""
|
||||
echo "🚧 Checking architectural gates..."
|
||||
# Boundary tripwire (DR-094): no Jellyfin taxonomy in the presentation layer.
|
||||
bun run check:boundary
|
||||
# Traceability coverage (DR-093): fails below 50%, or above 100% (miscount).
|
||||
bun run traces:coverage
|
||||
|
||||
echo ""
|
||||
echo "✅ All tests passed!"
|
||||
|
||||
Generated
+1
-1
@@ -1994,7 +1994,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "jellytau"
|
||||
version = "0.1.0"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"async-trait",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "jellytau"
|
||||
version = "0.1.0"
|
||||
version = "0.3.0"
|
||||
description = "A Tauri App"
|
||||
authors = ["you"]
|
||||
edition = "2021"
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
package com.dtourolle.jellytau
|
||||
|
||||
import android.content.Context
|
||||
import android.media.AudioAttributes
|
||||
import android.media.AudioFocusRequest
|
||||
import android.media.AudioManager
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
@@ -19,8 +14,6 @@ class MainActivity : TauriActivity() {
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private var configAttempts = 0
|
||||
private val maxConfigAttempts = 10
|
||||
private var audioFocusRequest: AudioFocusRequest? = null
|
||||
private val audioManager by lazy { getSystemService(Context.AUDIO_SERVICE) as AudioManager }
|
||||
|
||||
/**
|
||||
* Coarse override for whether backgrounding the app should auto-enter PiP.
|
||||
@@ -50,6 +43,15 @@ class MainActivity : TauriActivity() {
|
||||
*/
|
||||
private var mediaWebView: WebView? = null
|
||||
|
||||
/**
|
||||
* The WebView the @JavascriptInterface bridges have been injected into.
|
||||
*
|
||||
* addJavascriptInterface must run once per WebView instance: re-injecting
|
||||
* over an already-loaded page hands JS a stale proxy whose methods are gone.
|
||||
* Compared by identity so a genuinely new WebView still gets its bridges.
|
||||
*/
|
||||
private var bridgesInstalledOn: WebView? = null
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
enableEdgeToEdge()
|
||||
super.onCreate(savedInstanceState)
|
||||
@@ -159,19 +161,36 @@ class MainActivity : TauriActivity() {
|
||||
android.util.Log.d("MainActivity", "WebView found! Configuring settings...")
|
||||
mediaWebView = webView
|
||||
|
||||
// Add JavaScript interface for audio focus control
|
||||
webView.addJavascriptInterface(object : Any() {
|
||||
@JavascriptInterface
|
||||
fun requestAudioFocus() {
|
||||
handler.post { this@MainActivity.requestAudioFocus() }
|
||||
}
|
||||
// Register the @JavascriptInterface bridges EXACTLY ONCE per WebView.
|
||||
//
|
||||
// configureWebViewForMedia() runs from onCreate's delayed post AND from
|
||||
// every onResume (plus each WebView re-find), so this used to re-inject
|
||||
// all four bridges repeatedly - 5 times in a 45s session. WebView binds
|
||||
// injected objects at page-load time; re-injecting over a live page
|
||||
// leaves JS holding a stale proxy. The object stays truthy while its
|
||||
// methods vanish, which surfaced as a flood of
|
||||
// "WebView: Unknown object" chromium errors and, in JS,
|
||||
// "TypeError: setEnabled is not a function".
|
||||
//
|
||||
// The visible bug: the background-audio toggle turned blue but never
|
||||
// reached native, so backgroundAudioEnabled stayed false, onStop never
|
||||
// dispatched 'jellytau-background', and a locked screen killed audio
|
||||
// instantly (UR-040). Audio focus and PiP broke the same way.
|
||||
//
|
||||
// The settings/WebChromeClient work below is idempotent and must keep
|
||||
// running on resume; only the bridge injection is one-shot.
|
||||
if (webView === bridgesInstalledOn) {
|
||||
android.util.Log.d("MainActivity", "JS bridges already installed on this WebView - skipping re-injection")
|
||||
configureWebViewSettings(webView)
|
||||
return
|
||||
}
|
||||
bridgesInstalledOn = webView
|
||||
|
||||
@JavascriptInterface
|
||||
fun abandonAudioFocus() {
|
||||
handler.post { this@MainActivity.abandonAudioFocus() }
|
||||
}
|
||||
}, "AndroidAudioFocus")
|
||||
android.util.Log.d("MainActivity", "JavaScript interface 'AndroidAudioFocus' added")
|
||||
// NOTE: there is deliberately no "AndroidAudioFocus" bridge. Manual focus
|
||||
// requests from the WebView competed with Chromium's own
|
||||
// AudioFocusDelegate and with ExoPlayer, and the resulting
|
||||
// AUDIOFOCUS_LOSS paused playback. See the comment on the video listeners
|
||||
// in configureWebViewSettings().
|
||||
|
||||
// Add JavaScript interface for picture-in-picture control.
|
||||
// enterPip/canEnterPip must run on the main thread; @JavascriptInterface
|
||||
@@ -212,10 +231,6 @@ class MainActivity : TauriActivity() {
|
||||
backgroundAudioEnabled = enabled
|
||||
android.util.Log.d("MainActivity", "backgroundAudioEnabled = $enabled")
|
||||
}
|
||||
|
||||
/** Whether background audio is available on this device (needs PiP-era APIs unnecessary; audio service always present on Android). */
|
||||
@JavascriptInterface
|
||||
fun isSupported(): Boolean = true
|
||||
}, "AndroidBackgroundAudio")
|
||||
android.util.Log.d("MainActivity", "JavaScript interface 'AndroidBackgroundAudio' added")
|
||||
|
||||
@@ -248,6 +263,21 @@ class MainActivity : TauriActivity() {
|
||||
dispatchWebEvent("jellytau-network-changed")
|
||||
}
|
||||
|
||||
configureWebViewSettings(webView)
|
||||
|
||||
} catch (e: Exception) {
|
||||
android.util.Log.e("MainActivity", "Failed to configure WebView for media", e)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* WebView settings, chrome client and the video-unmute script.
|
||||
*
|
||||
* Split out from the bridge injection because this half is idempotent and
|
||||
* must re-run on every resume, whereas addJavascriptInterface must not.
|
||||
*/
|
||||
private fun configureWebViewSettings(webView: WebView) {
|
||||
try {
|
||||
// Set WebChromeClient to handle video playback and audio focus
|
||||
webView.webChromeClient = object : WebChromeClient() {
|
||||
override fun onShowCustomView(view: View?, callback: CustomViewCallback?) {
|
||||
@@ -259,6 +289,21 @@ class MainActivity : TauriActivity() {
|
||||
super.onHideCustomView()
|
||||
android.util.Log.d("MainActivity", "Video exited fullscreen")
|
||||
}
|
||||
|
||||
/**
|
||||
* Forward WebView console output to logcat under the "JellyTauWeb" tag.
|
||||
*
|
||||
* Without this the frontend is invisible to `adb logcat`, which makes
|
||||
* diagnosing anything that spans the JS/native boundary (the
|
||||
* background-audio handoff in particular) guesswork.
|
||||
*/
|
||||
override fun onConsoleMessage(msg: android.webkit.ConsoleMessage): Boolean {
|
||||
android.util.Log.d(
|
||||
"JellyTauWeb",
|
||||
"${msg.message()} (${msg.sourceId()}:${msg.lineNumber()})"
|
||||
)
|
||||
return true
|
||||
}
|
||||
}
|
||||
android.util.Log.d("MainActivity", "WebChromeClient configured")
|
||||
|
||||
@@ -287,29 +332,18 @@ class MainActivity : TauriActivity() {
|
||||
video.volume = 1.0;
|
||||
console.log('[Android] Video unmuted, volume:', video.volume, 'muted:', video.muted);
|
||||
|
||||
// Add event listeners to manage audio focus
|
||||
video.addEventListener('play', function() {
|
||||
console.log('[Android] Video play event - requesting audio focus');
|
||||
if (typeof AndroidAudioFocus !== 'undefined') {
|
||||
AndroidAudioFocus.requestAudioFocus();
|
||||
}
|
||||
console.log('[Android] Video state - muted:', this.muted, 'volume:', this.volume);
|
||||
});
|
||||
|
||||
video.addEventListener('pause', function() {
|
||||
console.log('[Android] Video pause event - abandoning audio focus');
|
||||
if (typeof AndroidAudioFocus !== 'undefined') {
|
||||
AndroidAudioFocus.abandonAudioFocus();
|
||||
}
|
||||
});
|
||||
|
||||
video.addEventListener('ended', function() {
|
||||
console.log('[Android] Video ended event - abandoning audio focus');
|
||||
if (typeof AndroidAudioFocus !== 'undefined') {
|
||||
AndroidAudioFocus.abandonAudioFocus();
|
||||
}
|
||||
});
|
||||
|
||||
// NOTE: deliberately no audio-focus calls here.
|
||||
//
|
||||
// WebView already manages audio focus for <video> through
|
||||
// Chromium's own AudioFocusDelegate. Requesting AUDIOFOCUS_GAIN
|
||||
// again from MainActivity made two requesters compete inside one
|
||||
// uid: the grant was immediately followed by AUDIOFOCUS_LOSS
|
||||
// (~45ms), whose handler paused playback - so arming background
|
||||
// audio, or simply pressing play, paused the video in a loop.
|
||||
//
|
||||
// ExoPlayer is the third potential owner and stays authoritative
|
||||
// for native playback (JellyTauPlayer manages its own focus).
|
||||
// Leave focus to whichever engine is actually rendering.
|
||||
video.addEventListener('volumechange', function() {
|
||||
console.log('[Android] Video volume changed - volume:', this.volume, 'muted:', this.muted);
|
||||
});
|
||||
@@ -356,48 +390,4 @@ class MainActivity : TauriActivity() {
|
||||
return null
|
||||
}
|
||||
|
||||
private fun requestAudioFocus() {
|
||||
android.util.Log.d("MainActivity", "Requesting audio focus for video playback")
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
val audioAttributes = AudioAttributes.Builder()
|
||||
.setUsage(AudioAttributes.USAGE_MEDIA)
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_MOVIE)
|
||||
.build()
|
||||
|
||||
audioFocusRequest = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
|
||||
.setAudioAttributes(audioAttributes)
|
||||
.setAcceptsDelayedFocusGain(true)
|
||||
.setOnAudioFocusChangeListener { focusChange ->
|
||||
android.util.Log.d("MainActivity", "Audio focus changed: $focusChange")
|
||||
}
|
||||
.build()
|
||||
|
||||
val result = audioManager.requestAudioFocus(audioFocusRequest!!)
|
||||
android.util.Log.d("MainActivity", "Audio focus request result: $result")
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
val result = audioManager.requestAudioFocus(
|
||||
{ focusChange ->
|
||||
android.util.Log.d("MainActivity", "Audio focus changed: $focusChange")
|
||||
},
|
||||
AudioManager.STREAM_MUSIC,
|
||||
AudioManager.AUDIOFOCUS_GAIN
|
||||
)
|
||||
android.util.Log.d("MainActivity", "Audio focus request result (legacy): $result")
|
||||
}
|
||||
}
|
||||
|
||||
private fun abandonAudioFocus() {
|
||||
android.util.Log.d("MainActivity", "Abandoning audio focus")
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
audioFocusRequest?.let {
|
||||
audioManager.abandonAudioFocusRequest(it)
|
||||
}
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
audioManager.abandonAudioFocus { }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,6 +36,53 @@ class JellyTauPlayer(private val appContext: Context) {
|
||||
/** Position update interval in milliseconds */
|
||||
private const val POSITION_UPDATE_INTERVAL_MS = 250L
|
||||
|
||||
/** AudioEffect priority. Positive = higher priority than the default. */
|
||||
private const val EFFECT_PRIORITY = 1000
|
||||
|
||||
/**
|
||||
* Canonical 10-band ISO centre frequencies (Hz), mirroring EQ_BANDS in
|
||||
* settings.rs. Kept in sync deliberately: Rust owns the band layout, this
|
||||
* is only the lookup table used to map those gains onto whatever bands
|
||||
* the device's equalizer actually has.
|
||||
*/
|
||||
private val CANONICAL_BAND_CENTRES_HZ =
|
||||
intArrayOf(31, 62, 125, 250, 500, 1000, 2000, 4000, 8000, 16000)
|
||||
|
||||
/**
|
||||
* Map canonical band gains onto a device's band centres by nearest
|
||||
* centre frequency.
|
||||
*
|
||||
* Pure function so it can be unit-tested without a device — device band
|
||||
* counts vary (commonly 5) and getting this wrong silently mis-shapes the
|
||||
* EQ curve rather than failing.
|
||||
*
|
||||
* TRACES: UR-027 | DR-030
|
||||
*/
|
||||
@JvmStatic
|
||||
fun resampleBands(
|
||||
canonicalGains: FloatArray,
|
||||
canonicalCentresHz: IntArray,
|
||||
deviceCentresHz: IntArray
|
||||
): FloatArray {
|
||||
if (canonicalGains.isEmpty() || deviceCentresHz.isEmpty()) {
|
||||
return FloatArray(deviceCentresHz.size)
|
||||
}
|
||||
val usable = minOf(canonicalGains.size, canonicalCentresHz.size)
|
||||
return FloatArray(deviceCentresHz.size) { d ->
|
||||
val target = deviceCentresHz[d]
|
||||
var nearest = 0
|
||||
var bestDelta = Int.MAX_VALUE
|
||||
for (c in 0 until usable) {
|
||||
val delta = kotlin.math.abs(canonicalCentresHz[c] - target)
|
||||
if (delta < bestDelta) {
|
||||
bestDelta = delta
|
||||
nearest = c
|
||||
}
|
||||
}
|
||||
canonicalGains[nearest]
|
||||
}
|
||||
}
|
||||
|
||||
/** Singleton instance for JNI access */
|
||||
@Volatile
|
||||
private var instance: JellyTauPlayer? = null
|
||||
@@ -135,6 +182,18 @@ class JellyTauPlayer(private val appContext: Context) {
|
||||
private val coroutineScope = CoroutineScope(Dispatchers.Main + SupervisorJob())
|
||||
private var positionUpdateJob: Job? = null
|
||||
|
||||
/** Graphic EQ bound to the current audio session, or null if not attached. */
|
||||
private var equalizer: android.media.audiofx.Equalizer? = null
|
||||
|
||||
/** Loudness/normalization effect bound to the current audio session. */
|
||||
private var loudnessEnhancer: android.media.audiofx.LoudnessEnhancer? = null
|
||||
|
||||
/**
|
||||
* Last settings pushed from Rust, replayed when the audio session is rebuilt.
|
||||
* Held as the raw payload so re-application needs no second parse contract.
|
||||
*/
|
||||
private var lastAudioSettings: org.json.JSONObject? = null
|
||||
|
||||
/** Current media ID being played */
|
||||
private var currentMediaId: String? = null
|
||||
|
||||
@@ -334,6 +393,11 @@ class JellyTauPlayer(private val appContext: Context) {
|
||||
|
||||
override fun onAudioSessionIdChanged(audioSessionId: Int) {
|
||||
android.util.Log.d("JellyTauPlayer", "▶▶▶ AUDIO SESSION ID CHANGED: $audioSessionId")
|
||||
// ExoPlayer rebuilt its audio sink (e.g. on a format change), so
|
||||
// effects bound to the old session are dead. Re-attach, or the EQ
|
||||
// silently stops applying mid-queue.
|
||||
releaseAudioEffects()
|
||||
lastAudioSettings?.let { applyAudioEffects(it) }
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -416,6 +480,133 @@ class JellyTauPlayer(private val appContext: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply audio settings pushed from Rust as JSON.
|
||||
*
|
||||
* Rust owns *what* the values are (band layout, preset curves, normalization
|
||||
* presets); this owns *when* the Android AudioEffect objects exist, since
|
||||
* that needs the live audio session id and must survive a sink rebuild.
|
||||
*
|
||||
* Posted to the main handler rather than run inline: AudioEffect construction
|
||||
* from a player callback can re-enter the player and deadlock.
|
||||
*
|
||||
* TRACES: UR-027, UR-032, UR-033 | DR-030, DR-035, DR-036
|
||||
*/
|
||||
fun setAudioSettings(json: String) {
|
||||
mainHandler.post {
|
||||
try {
|
||||
val settings = org.json.JSONObject(json)
|
||||
lastAudioSettings = settings
|
||||
|
||||
// Gapless: ExoPlayer is gapless by default for compatible
|
||||
// formats, so honouring the setting means disabling it when off.
|
||||
exoPlayer.pauseAtEndOfMediaItems = !settings.optBoolean("gaplessPlayback", true)
|
||||
|
||||
applyAudioEffects(settings)
|
||||
} catch (e: Exception) {
|
||||
android.util.Log.e("JellyTauPlayer", "Failed to apply audio settings", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Attach/update the EQ and loudness effects for the current audio session. */
|
||||
private fun applyAudioEffects(settings: org.json.JSONObject) {
|
||||
val sessionId = exoPlayer.audioSessionId
|
||||
if (sessionId == C.AUDIO_SESSION_ID_UNSET) {
|
||||
// No sink yet; onAudioSessionIdChanged will re-drive this.
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
applyEqualizer(sessionId, settings)
|
||||
} catch (e: Exception) {
|
||||
android.util.Log.e("JellyTauPlayer", "Equalizer unavailable on this device", e)
|
||||
}
|
||||
|
||||
try {
|
||||
applyNormalization(sessionId, settings)
|
||||
} catch (e: Exception) {
|
||||
android.util.Log.e("JellyTauPlayer", "LoudnessEnhancer unavailable on this device", e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun applyEqualizer(sessionId: Int, settings: org.json.JSONObject) {
|
||||
val enabled = settings.optBoolean("equalizerEnabled", false)
|
||||
|
||||
if (!enabled) {
|
||||
equalizer?.enabled = false
|
||||
return
|
||||
}
|
||||
|
||||
val eq = equalizer ?: android.media.audiofx.Equalizer(EFFECT_PRIORITY, sessionId).also {
|
||||
equalizer = it
|
||||
}
|
||||
|
||||
val bandsJson = settings.optJSONArray("equalizerBands")
|
||||
val canonicalGains = FloatArray(bandsJson?.length() ?: 0) { i ->
|
||||
bandsJson!!.optDouble(i, 0.0).toFloat()
|
||||
}
|
||||
if (canonicalGains.isEmpty()) {
|
||||
eq.enabled = false
|
||||
return
|
||||
}
|
||||
|
||||
// The device's band count/centres are device-dependent (commonly 5) and
|
||||
// will not match our canonical 10-band ISO layout, so resample.
|
||||
val deviceBandCount = eq.numberOfBands.toInt()
|
||||
val deviceCentresHz = IntArray(deviceBandCount) { i ->
|
||||
eq.getCenterFreq(i.toShort()) / 1000 // device reports milliHertz
|
||||
}
|
||||
val levelRange = eq.bandLevelRange // millibels, [min, max]
|
||||
|
||||
val resampled = resampleBands(canonicalGains, CANONICAL_BAND_CENTRES_HZ, deviceCentresHz)
|
||||
|
||||
for (i in 0 until deviceBandCount) {
|
||||
val millibels = (resampled[i] * 100f)
|
||||
.coerceIn(levelRange[0].toFloat(), levelRange[1].toFloat())
|
||||
eq.setBandLevel(i.toShort(), millibels.toInt().toShort())
|
||||
}
|
||||
eq.enabled = true
|
||||
}
|
||||
|
||||
private fun applyNormalization(sessionId: Int, settings: org.json.JSONObject) {
|
||||
val enabled = settings.optBoolean("normalizeVolume", false)
|
||||
|
||||
if (!enabled) {
|
||||
loudnessEnhancer?.enabled = false
|
||||
return
|
||||
}
|
||||
|
||||
val enhancer = loudnessEnhancer
|
||||
?: android.media.audiofx.LoudnessEnhancer(sessionId).also { loudnessEnhancer = it }
|
||||
|
||||
// Approximate parity with the Linux dynaudnorm path: LoudnessEnhancer is
|
||||
// a gain stage, not a true EBU R128 normalizer, so these are relative
|
||||
// offsets preserving the Loud > Normal > Quiet ordering.
|
||||
val targetGainMb = when (settings.optString("volumeLevel", "normal")) {
|
||||
"loud" -> 600
|
||||
"quiet" -> -600
|
||||
else -> 0
|
||||
}
|
||||
enhancer.setTargetGain(targetGainMb)
|
||||
enhancer.enabled = true
|
||||
}
|
||||
|
||||
private fun releaseAudioEffects() {
|
||||
try {
|
||||
equalizer?.release()
|
||||
} catch (e: Exception) {
|
||||
android.util.Log.w("JellyTauPlayer", "Equalizer release failed", e)
|
||||
}
|
||||
try {
|
||||
loudnessEnhancer?.release()
|
||||
} catch (e: Exception) {
|
||||
android.util.Log.w("JellyTauPlayer", "LoudnessEnhancer release failed", e)
|
||||
}
|
||||
equalizer = null
|
||||
loudnessEnhancer = null
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current playback position in seconds.
|
||||
*/
|
||||
@@ -756,6 +947,7 @@ class JellyTauPlayer(private val appContext: Context) {
|
||||
mainHandler.post {
|
||||
stopPositionUpdates()
|
||||
coroutineScope.cancel()
|
||||
releaseAudioEffects()
|
||||
exoPlayer.release()
|
||||
instance = null
|
||||
}
|
||||
|
||||
@@ -433,6 +433,12 @@ mod tests {
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// IT-017: a download queued from a greyed-out offline catalog entry
|
||||
/// (pending, `stream_url IS NULL`) persists, and on reconnect its URL is
|
||||
/// resolved and the row is healed (URL + target dir) so the pump can start
|
||||
/// it — while already-resolved rows are left untouched.
|
||||
///
|
||||
/// TRACES: UR-052, UR-011 | IT-017
|
||||
#[tokio::test]
|
||||
async fn resolves_offline_queued_row_and_leaves_resolved_rows_untouched() {
|
||||
let db = test_db();
|
||||
|
||||
@@ -57,18 +57,6 @@ pub struct MediaSessionManagerWrapper(pub Mutex<MediaSessionManager>);
|
||||
/// @req: DR-048 - Video settings (auto-play toggle, countdown duration)
|
||||
pub struct VideoSettingsWrapper(pub Mutex<VideoSettings>);
|
||||
|
||||
/// Base offset (seconds) for the active background-audio handoff.
|
||||
///
|
||||
/// The audio-only stream is requested with `StartTimeTicks` = the handoff
|
||||
/// position, so the server makes that point the stream's zero. ExoPlayer then
|
||||
/// reports position RELATIVE to that zero. To convert back to an absolute
|
||||
/// position on exit (so the video resumes where the audio actually reached), we
|
||||
/// add this stored base to the native player's reported position.
|
||||
///
|
||||
/// TRACES: UR-040 | DR-052
|
||||
#[derive(Default)]
|
||||
pub struct BackgroundAudioOffset(pub Mutex<f64>);
|
||||
|
||||
/// Response for player state queries
|
||||
#[derive(specta::Type, Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -205,6 +193,15 @@ pub struct PlayItemRequest {
|
||||
/// zero-duration session renders no scrubber, even with ACTION_SEEK_TO set.
|
||||
#[serde(default)]
|
||||
pub duration_seconds: Option<f64>,
|
||||
/// Item type (e.g. "Episode", "Movie", "Audio"). Carried through the
|
||||
/// background-audio handoff so an episode played as audio-only is still
|
||||
/// recognised as an episode by autoplay (UR-040) and advances to the next one.
|
||||
#[serde(default)]
|
||||
pub item_type: Option<String>,
|
||||
/// Series ID for TV episodes. Needed alongside `item_type` so the backend can
|
||||
/// look up the next episode when a background-audio track ends.
|
||||
#[serde(default)]
|
||||
pub series_id: Option<String>,
|
||||
}
|
||||
|
||||
/// Queue context for remote transfer - what type of queue is this?
|
||||
@@ -577,7 +574,6 @@ pub async fn player_play_item(
|
||||
pub async fn player_enter_background_audio(
|
||||
player: State<'_, PlayerStateWrapper>,
|
||||
session: State<'_, MediaSessionManagerWrapper>,
|
||||
bg_offset: State<'_, BackgroundAudioOffset>,
|
||||
item: PlayItemRequest,
|
||||
position_seconds: f64,
|
||||
) -> Result<PlayerStatus, String> {
|
||||
@@ -601,7 +597,9 @@ pub async fn player_enter_background_audio(
|
||||
artists: None,
|
||||
primary_image_tag: item.primary_image_tag.clone(),
|
||||
image_id: item.primary_image_tag.clone(),
|
||||
item_type: None,
|
||||
// Carry episode identity so autoplay can advance to the next episode when
|
||||
// this audio-only handoff ends while backgrounded (UR-040).
|
||||
item_type: item.item_type.clone(),
|
||||
playlist_id: None,
|
||||
// Carry the real duration so the lockscreen MediaSession can draw a scrubber.
|
||||
duration: item.duration_seconds,
|
||||
@@ -616,7 +614,7 @@ pub async fn player_enter_background_audio(
|
||||
video_width: None,
|
||||
video_height: None,
|
||||
subtitles: vec![],
|
||||
series_id: None,
|
||||
series_id: item.series_id.clone(),
|
||||
server_id: item.server_id.clone(),
|
||||
};
|
||||
|
||||
@@ -625,17 +623,18 @@ pub async fn player_enter_background_audio(
|
||||
session_mgr.start_audio_session(media_item.clone());
|
||||
}
|
||||
|
||||
// Remember where the video was: the audio stream's zero == this position
|
||||
// (the URL was built with StartTimeTicks=position_seconds), so on exit we add
|
||||
// this base to the native player's relative position to get the absolute one.
|
||||
*bg_offset.0.lock().map_err(|e| e.to_string())? = position_seconds.max(0.0);
|
||||
|
||||
// Same base offset drives the lockscreen scrubber: ExoPlayer reports position
|
||||
// relative to the stream's StartTimeTicks zero, but the metadata duration is
|
||||
// absolute, so shift the reported position back to absolute for the scrubber.
|
||||
let _ = crate::player::set_lockscreen_position_offset(position_seconds.max(0.0));
|
||||
|
||||
let controller = player.0.lock().await;
|
||||
// Remember where the video was: the audio stream's zero == this position
|
||||
// (the URL was built with StartTimeTicks=position_seconds), so on exit we add
|
||||
// this base to the native player's relative position to get the absolute one.
|
||||
// The controller owns it so a backend-driven advance to the next episode
|
||||
// clears it along with the stream it described.
|
||||
controller.set_background_audio_base(position_seconds);
|
||||
controller
|
||||
.play_item(media_item)
|
||||
.map_err(|e| e.to_string())?;
|
||||
@@ -666,21 +665,15 @@ pub async fn player_enter_background_audio(
|
||||
#[specta::specta]
|
||||
pub async fn player_exit_background_audio(
|
||||
player: State<'_, PlayerStateWrapper>,
|
||||
bg_offset: State<'_, BackgroundAudioOffset>,
|
||||
) -> Result<f64, String> {
|
||||
// The base offset (handoff position) + native player's relative position =
|
||||
// the absolute position to resume the video at. Read/reset the base first.
|
||||
let base = {
|
||||
let mut off = bg_offset.0.lock().map_err(|e| e.to_string())?;
|
||||
let b = *off;
|
||||
*off = 0.0;
|
||||
b
|
||||
};
|
||||
|
||||
// Back to foreground playback: the lockscreen scrubber is absolute again.
|
||||
let _ = crate::player::set_lockscreen_position_offset(0.0);
|
||||
|
||||
let controller = player.0.lock().await;
|
||||
// The base offset (handoff position) + native player's relative position =
|
||||
// the absolute position to resume the video at. Zero after a backend-driven
|
||||
// episode advance, whose stream already starts at its own zero.
|
||||
let base = controller.take_background_audio_base();
|
||||
// Capture position into a `let` BEFORE stop() — never hold work across a lock
|
||||
// re-entrant call (deadlock discipline, CLAUDE.md).
|
||||
let relative = controller.position();
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
//! Audio and video playback settings commands.
|
||||
//!
|
||||
//! TRACES: UR-022, UR-031, UR-032, UR-033 | DR-025, DR-034, DR-035, DR-036
|
||||
//! TRACES: UR-022, UR-027, UR-031, UR-032, UR-033 | DR-025, DR-030, DR-034, DR-035, DR-036, IR-020
|
||||
|
||||
use tauri::State;
|
||||
|
||||
use super::{PlayerStateWrapper, VideoSettingsWrapper};
|
||||
use crate::player::AutoplaySettings;
|
||||
use crate::settings::{AudioSettings, VideoSettings};
|
||||
use crate::settings::{AudioSettings, EqPreset, VideoSettings};
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
@@ -14,13 +14,32 @@ pub async fn player_set_audio_settings(
|
||||
player: State<'_, PlayerStateWrapper>,
|
||||
settings: AudioSettings,
|
||||
) -> Result<AudioSettings, String> {
|
||||
// Validate/normalise domain values before applying: clamp crossfade to its
|
||||
// range and normalise the equalizer band vector (length + gain clamps).
|
||||
let validated = settings
|
||||
.with_crossfade_clamped()
|
||||
.with_equalizer_normalised();
|
||||
let mut controller = player.0.lock().await;
|
||||
controller
|
||||
.set_audio_settings(&settings)
|
||||
.set_audio_settings(&validated)
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(controller.audio_settings())
|
||||
}
|
||||
|
||||
/// The built-in equalizer presets and their per-band gain curves (dB), for the
|
||||
/// settings UI. The curve numbers are domain data defined by the band layout,
|
||||
/// so the frontend reads them here rather than encoding them.
|
||||
///
|
||||
/// TRACES: UR-027 | DR-030
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn player_get_eq_presets() -> Result<Vec<(EqPreset, Vec<f32>)>, String> {
|
||||
Ok(EqPreset::ALL
|
||||
.iter()
|
||||
.map(|p| (*p, p.gains().to_vec()))
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn player_get_audio_settings(
|
||||
|
||||
@@ -141,6 +141,8 @@ pub async fn player_play_next_episode(
|
||||
/// - Frontend when HTML5 video ends (Linux/desktop) - passes itemId + repositoryHandle for the video
|
||||
/// - Frontend when audio track ends via backend event - no itemId/repositoryHandle needed
|
||||
/// - Android JNI callback also triggers this logic directly
|
||||
///
|
||||
/// TRACES: UR-023, UR-026, UR-040 | DR-047, DR-052
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn player_on_playback_ended(
|
||||
@@ -242,12 +244,17 @@ pub async fn player_on_playback_ended(
|
||||
});
|
||||
}
|
||||
|
||||
// Start countdown if auto_advance enabled
|
||||
// Advance if auto_advance is enabled. This is the path that actually
|
||||
// runs on Android: the JNI callback's own decision is swallowed by the
|
||||
// NewTrackLoaded end reason set at load, so it returns Stop, emits
|
||||
// PlaybackEnded, and the frontend echoes it back into this command —
|
||||
// which is where the real decision lands.
|
||||
if auto_advance {
|
||||
controller_arc
|
||||
.lock()
|
||||
.await
|
||||
.start_autoplay_countdown(next_episode, countdown_seconds);
|
||||
.auto_advance_to_next_episode(next_episode, countdown_seconds)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,9 +12,11 @@ use serde::{Deserialize, Serialize};
|
||||
use tauri::{AppHandle, Emitter, State};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::domain::rank_search_results;
|
||||
use crate::jellyfin::HttpClient;
|
||||
use crate::repository::{
|
||||
types::*, HybridRepository, MediaRepository, OfflineRepository, OnlineRepository,
|
||||
series_progress, types::*, HybridRepository, MediaRepository, OfflineRepository,
|
||||
OnlineRepository,
|
||||
};
|
||||
|
||||
/// Repository handle manager
|
||||
@@ -319,6 +321,71 @@ pub async fn repository_get_next_up_episodes(
|
||||
.map_err(|e| format!("{:?}", e))
|
||||
}
|
||||
|
||||
/// Every episode of a series, across all seasons, in series order.
|
||||
///
|
||||
/// Jellyfin hangs episodes off season folders — except for "flat" series whose
|
||||
/// children are episodes directly. Both shapes are provider vocabulary, so the
|
||||
/// fan-out and its fallback live in Rust rather than being reimplemented in the
|
||||
/// frontend (which is what it used to do).
|
||||
///
|
||||
/// TRACES: UR-062 | DR-101
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn repository_get_series_episodes(
|
||||
manager: State<'_, RepositoryManagerWrapper>,
|
||||
handle: String,
|
||||
series_id: String,
|
||||
) -> Result<Vec<MediaItem>, String> {
|
||||
let repo = manager.0.get(&handle).ok_or("Repository not found")?;
|
||||
series_progress::fetch_series_episodes(repo.as_ref(), &series_id)
|
||||
.await
|
||||
.map_err(|e| format!("{:?}", e))
|
||||
}
|
||||
|
||||
/// The episode a viewer should land on when they open a series.
|
||||
///
|
||||
/// "Current" is domain policy, not layout: an episode in progress, else the
|
||||
/// server's Next Up for the series, else the first unwatched episode, else the
|
||||
/// first. The third rung is what makes this work offline, where Next Up is
|
||||
/// always empty. Returns `None` only when the series has no episodes at all.
|
||||
///
|
||||
/// TRACES: UR-062 | DR-101
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn repository_get_series_current_episode(
|
||||
manager: State<'_, RepositoryManagerWrapper>,
|
||||
handle: String,
|
||||
series_id: String,
|
||||
) -> Result<Option<MediaItem>, String> {
|
||||
let repo = manager.0.get(&handle).ok_or("Repository not found")?;
|
||||
series_progress::resolve_current_episode(repo.as_ref(), &series_id)
|
||||
.await
|
||||
.map_err(|e| format!("{:?}", e))
|
||||
}
|
||||
|
||||
/// Erase the viewer's watch history for an item.
|
||||
///
|
||||
/// Clears the played flag and the resume position; on a series or season the
|
||||
/// server applies it to everything inside. A series cleared this way is "never
|
||||
/// watched" again, so `repository_get_series_current_episode` returns its
|
||||
/// premiere. Requires the server — offline this fails rather than diverging
|
||||
/// local state the next sync would overwrite.
|
||||
///
|
||||
/// TRACES: UR-064 | DR-106
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn repository_clear_watch_history(
|
||||
manager: State<'_, RepositoryManagerWrapper>,
|
||||
handle: String,
|
||||
item_id: String,
|
||||
) -> Result<(), String> {
|
||||
let repo = manager.0.get(&handle).ok_or("Repository not found")?;
|
||||
repo.as_ref()
|
||||
.clear_watch_history(&item_id)
|
||||
.await
|
||||
.map_err(|e| format!("{:?}", e))
|
||||
}
|
||||
|
||||
/// Get recently played audio
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
@@ -394,7 +461,12 @@ pub struct SearchUpdateEvent {
|
||||
pub result: SearchResult,
|
||||
}
|
||||
|
||||
/// Search for items
|
||||
/// Search for items.
|
||||
///
|
||||
/// Resolves `SearchOptions::scope` into concrete Jellyfin item types before
|
||||
/// dispatching, so scope taxonomy stays in Rust.
|
||||
///
|
||||
/// TRACES: UR-049, UR-050 | DR-063
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn repository_search(
|
||||
@@ -407,9 +479,19 @@ pub async fn repository_search(
|
||||
) -> Result<SearchResult, String> {
|
||||
let repo = manager.0.get(&handle).ok_or("Repository not found")?;
|
||||
|
||||
// Expand the opaque scope into item types HERE — once, before the cache and
|
||||
// server paths diverge — so both phases filter identically. Doing it later
|
||||
// (or in only one path) makes offline results disagree with online ones.
|
||||
// The frontend sends `scope` and never names a Jellyfin item type for
|
||||
// search; see docs/specs/scoped-search-boundary.md.
|
||||
let options = options.map(|mut o| {
|
||||
o.resolve_scope();
|
||||
o
|
||||
});
|
||||
|
||||
// Phase 1: instant local results from the cache (downloaded content) so the
|
||||
// UI can render immediately while the server is still being queried.
|
||||
let cache_result = repo
|
||||
let mut cache_result = repo
|
||||
.search_cache_only(&query, options.clone())
|
||||
.await
|
||||
.unwrap_or_else(|e| {
|
||||
@@ -420,6 +502,12 @@ pub async fn repository_search(
|
||||
}
|
||||
});
|
||||
|
||||
// Neither backend orders by *where* the query matched, so a mid-word hit
|
||||
// ("Sparks" for "parks") can outrank a prefix hit ("Parks and Recreation").
|
||||
// Both phases are ranked with the same rules so the list does not reshuffle
|
||||
// when the server results land.
|
||||
rank_search_results(&mut cache_result.items, &query);
|
||||
|
||||
// Phase 2: query the live server in the background, merge with the cache,
|
||||
// and push the union to the frontend via a `search-event`. Tagged with
|
||||
// `request_id` so the frontend can discard results from superseded queries.
|
||||
@@ -428,7 +516,11 @@ pub async fn repository_search(
|
||||
tauri::async_runtime::spawn(async move {
|
||||
match repo_bg.search_server_only(&query, options).await {
|
||||
Ok(server_result) => {
|
||||
let merged = HybridRepository::merge_search_results(cache_for_merge, server_result);
|
||||
let mut merged =
|
||||
HybridRepository::merge_search_results(cache_for_merge, server_result);
|
||||
// Rank the union, not each half: a server-only prefix match must
|
||||
// be able to outrank a cached mid-word one.
|
||||
rank_search_results(&mut merged.items, &query);
|
||||
let event = SearchUpdateEvent {
|
||||
request_id,
|
||||
result: merged,
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
|
||||
pub mod from_jellyfin;
|
||||
pub mod media;
|
||||
pub mod search_rank;
|
||||
|
||||
pub use from_jellyfin::{kind_from_jellyfin, stream_kind_from_jellyfin, ticks_to_ms};
|
||||
pub use media::{MediaKind, StreamKind};
|
||||
pub use search_rank::rank_search_results;
|
||||
|
||||
@@ -0,0 +1,313 @@
|
||||
//! Relevance ranking for search results.
|
||||
//!
|
||||
//! Both search paths (the SQLite FTS cache and the Jellyfin server) return items
|
||||
//! in an order that ignores *where* in the name the query matched: a server
|
||||
//! substring hit like "Sparks of Love" can outrank "Parks and Recreation" for
|
||||
//! the query "parks". Neither backend is going to change, so the app imposes its
|
||||
//! own ordering on the union.
|
||||
//!
|
||||
//! Ranking is domain logic, not presentation: it encodes what a "better match"
|
||||
//! means and which media kinds outrank which. The frontend only renders the
|
||||
//! order it is given.
|
||||
//!
|
||||
//! Two rules, in priority order:
|
||||
//!
|
||||
//! 1. **Match position** — a prefix match beats a word-start match, which beats
|
||||
//! a mid-word substring match. This is what makes "parks" find
|
||||
//! "Parks and Recreation" before "Sparks of Love".
|
||||
//! 2. **Kind** — containers before their contents at equal match quality, so a
|
||||
//! series outranks its own episodes.
|
||||
//!
|
||||
//! Ties fall back to the input order, so a backend's own relevance signal (FTS
|
||||
//! `rank`) still breaks ties it was never overruled on.
|
||||
|
||||
use crate::domain::MediaKind;
|
||||
use crate::repository::types::MediaItem;
|
||||
|
||||
/// How well a query matched an item's name — better matches sort first.
|
||||
///
|
||||
/// Ordered by discriminant: `Prefix` is the strongest. Derived `Ord` gives the
|
||||
/// comparison for free, so adding a tier in the right position is all it takes.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum MatchQuality {
|
||||
/// The name starts with the query — "parks" in "Parks and Recreation".
|
||||
Prefix,
|
||||
/// Some later *word* starts with the query — "recreation" in "Parks and
|
||||
/// Recreation". Still a deliberate hit: users type whole words.
|
||||
WordStart,
|
||||
/// The query appears mid-word — "parks" in "Sparks of Love". Weakest hit
|
||||
/// that still counts as a match.
|
||||
Substring,
|
||||
/// No match on the name at all. The backend returned it for some other
|
||||
/// reason (overview, artist, album), so it is kept but sorted last.
|
||||
None,
|
||||
}
|
||||
|
||||
/// Rank of a media kind when match quality ties — lower sorts first.
|
||||
///
|
||||
/// Containers outrank the items they contain: searching a show's name should
|
||||
/// surface the show, not an arbitrary episode of it. Within a tier the order is
|
||||
/// arbitrary but stable, and equal ranks fall through to input order.
|
||||
fn kind_rank(kind: MediaKind) -> u8 {
|
||||
match kind {
|
||||
// Top-level containers a user is most likely to be looking for.
|
||||
MediaKind::Series | MediaKind::Movie | MediaKind::Album | MediaKind::Artist => 0,
|
||||
// Sub-containers and standalone collections.
|
||||
MediaKind::Season | MediaKind::Playlist | MediaKind::Channel | MediaKind::Folder => 1,
|
||||
// Leaves — an episode/track is a match *inside* something bigger.
|
||||
MediaKind::Episode | MediaKind::Track | MediaKind::LiveChannel | MediaKind::ChannelItem => {
|
||||
2
|
||||
}
|
||||
// Peripheral matches.
|
||||
MediaKind::Person | MediaKind::Other => 3,
|
||||
}
|
||||
}
|
||||
|
||||
/// Classify how `query` matches `name`, case-insensitively.
|
||||
///
|
||||
/// Both sides are trimmed and lowercased; an empty query matches everything
|
||||
/// equally (`Prefix`), which leaves the input order untouched.
|
||||
pub fn match_quality(name: &str, query: &str) -> MatchQuality {
|
||||
let query = query.trim().to_lowercase();
|
||||
if query.is_empty() {
|
||||
return MatchQuality::Prefix;
|
||||
}
|
||||
let name = name.trim().to_lowercase();
|
||||
|
||||
let Some(index) = name.find(&query) else {
|
||||
return MatchQuality::None;
|
||||
};
|
||||
|
||||
if index == 0 {
|
||||
return MatchQuality::Prefix;
|
||||
}
|
||||
|
||||
// A word start is any match preceded by a non-alphanumeric character, so
|
||||
// "the-office" and "The Office" behave the same. Indexing back one char is
|
||||
// safe on the byte index `find` returned only via `char_indices`, since a
|
||||
// multi-byte char would panic on a raw slice.
|
||||
let preceded_by_boundary = name[..index]
|
||||
.chars()
|
||||
.next_back()
|
||||
.is_some_and(|c| !c.is_alphanumeric());
|
||||
|
||||
if preceded_by_boundary {
|
||||
MatchQuality::WordStart
|
||||
} else {
|
||||
MatchQuality::Substring
|
||||
}
|
||||
}
|
||||
|
||||
/// Sort search results by relevance to `query`, in place.
|
||||
///
|
||||
/// Stable, so items the rules rank equally keep the order the backend supplied
|
||||
/// (FTS `rank` for cache hits, Jellyfin's own ordering for server hits).
|
||||
///
|
||||
/// TRACES: UR-060 | DR-090
|
||||
pub fn rank_search_results(items: &mut [MediaItem], query: &str) {
|
||||
// An empty query carries no relevance signal, so there is nothing to rank
|
||||
// by — reordering on kind alone would shuffle the backend's own ordering
|
||||
// for no reason.
|
||||
if query.trim().is_empty() {
|
||||
return;
|
||||
}
|
||||
items.sort_by_key(|item| (match_quality(&item.name, query), kind_rank(item.kind)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn item(name: &str, kind: MediaKind) -> MediaItem {
|
||||
let mut item = MediaItem::default();
|
||||
item.id = format!("id-{}-{:?}", name, kind);
|
||||
item.name = name.to_string();
|
||||
item.kind = kind;
|
||||
item
|
||||
}
|
||||
|
||||
fn names(items: &[MediaItem]) -> Vec<&str> {
|
||||
items.iter().map(|i| i.name.as_str()).collect()
|
||||
}
|
||||
|
||||
/// UT-085: a prefix match outranks a mid-word substring match.
|
||||
#[test]
|
||||
fn prefix_match_beats_midword_substring() {
|
||||
assert_eq!(
|
||||
match_quality("Parks and Recreation", "parks"),
|
||||
MatchQuality::Prefix
|
||||
);
|
||||
assert_eq!(
|
||||
match_quality("Sparks of Love", "parks"),
|
||||
MatchQuality::Substring
|
||||
);
|
||||
assert!(MatchQuality::Prefix < MatchQuality::Substring);
|
||||
}
|
||||
|
||||
/// UT-085: the reported bug — "parks" must find the show, not "Sparks".
|
||||
#[test]
|
||||
fn ranks_prefix_match_before_substring_match() {
|
||||
let mut items = vec![
|
||||
item("Sparks of Love", MediaKind::Series),
|
||||
item("Parks and Recreation", MediaKind::Series),
|
||||
];
|
||||
|
||||
rank_search_results(&mut items, "parks");
|
||||
|
||||
assert_eq!(
|
||||
names(&items),
|
||||
vec!["Parks and Recreation", "Sparks of Love"]
|
||||
);
|
||||
}
|
||||
|
||||
/// A match at a later word start beats a mid-word one but loses to a prefix.
|
||||
#[test]
|
||||
fn word_start_ranks_between_prefix_and_substring() {
|
||||
assert_eq!(
|
||||
match_quality("The Office", "office"),
|
||||
MatchQuality::WordStart
|
||||
);
|
||||
assert_eq!(match_quality("Bofficer", "office"), MatchQuality::Substring);
|
||||
|
||||
let mut items = vec![
|
||||
item("Bofficer", MediaKind::Series),
|
||||
item("The Office", MediaKind::Series),
|
||||
item("Office Space", MediaKind::Movie),
|
||||
];
|
||||
|
||||
rank_search_results(&mut items, "office");
|
||||
|
||||
assert_eq!(
|
||||
names(&items),
|
||||
vec!["Office Space", "The Office", "Bofficer"]
|
||||
);
|
||||
}
|
||||
|
||||
/// UT-086: at equal match quality a series outranks an episode.
|
||||
#[test]
|
||||
fn series_ranks_before_episode_at_equal_match_quality() {
|
||||
let mut items = vec![
|
||||
item("Parks and Recreation S01E01", MediaKind::Episode),
|
||||
item("Parks and Recreation", MediaKind::Series),
|
||||
];
|
||||
|
||||
rank_search_results(&mut items, "parks");
|
||||
|
||||
assert_eq!(
|
||||
names(&items),
|
||||
vec!["Parks and Recreation", "Parks and Recreation S01E01"]
|
||||
);
|
||||
}
|
||||
|
||||
/// Albums outrank their tracks for the same reason series outrank episodes.
|
||||
#[test]
|
||||
fn album_ranks_before_track_at_equal_match_quality() {
|
||||
let mut items = vec![
|
||||
item("Rumours", MediaKind::Track),
|
||||
item("Rumours", MediaKind::Album),
|
||||
];
|
||||
|
||||
rank_search_results(&mut items, "rumours");
|
||||
|
||||
assert_eq!(items[0].kind, MediaKind::Album);
|
||||
}
|
||||
|
||||
/// Match quality dominates kind: a better-matching episode beats a
|
||||
/// worse-matching series, so kind never drags an irrelevant show to the top.
|
||||
#[test]
|
||||
fn match_quality_outranks_kind() {
|
||||
let mut items = vec![
|
||||
item("Sparks of Love", MediaKind::Series),
|
||||
item("Parks Cleanup", MediaKind::Episode),
|
||||
];
|
||||
|
||||
rank_search_results(&mut items, "parks");
|
||||
|
||||
assert_eq!(names(&items), vec!["Parks Cleanup", "Sparks of Love"]);
|
||||
}
|
||||
|
||||
/// Items the backend returned for a non-name reason (overview, artist) are
|
||||
/// kept, but sort below everything that actually matched the name.
|
||||
#[test]
|
||||
fn non_matching_names_sort_last_without_being_dropped() {
|
||||
let mut items = vec![
|
||||
item("Unrelated Documentary", MediaKind::Movie),
|
||||
item("Parks and Recreation", MediaKind::Series),
|
||||
];
|
||||
|
||||
rank_search_results(&mut items, "parks");
|
||||
|
||||
assert_eq!(
|
||||
names(&items),
|
||||
vec!["Parks and Recreation", "Unrelated Documentary"]
|
||||
);
|
||||
}
|
||||
|
||||
/// Ranking is stable: equally-ranked items keep the backend's order, so the
|
||||
/// FTS/server relevance signal still breaks ties.
|
||||
#[test]
|
||||
fn equal_rank_preserves_input_order() {
|
||||
let mut items = vec![
|
||||
item("Parks A", MediaKind::Series),
|
||||
item("Parks B", MediaKind::Series),
|
||||
item("Parks C", MediaKind::Series),
|
||||
];
|
||||
|
||||
rank_search_results(&mut items, "parks");
|
||||
|
||||
assert_eq!(names(&items), vec!["Parks A", "Parks B", "Parks C"]);
|
||||
}
|
||||
|
||||
/// Case and surrounding whitespace never change the tier.
|
||||
#[test]
|
||||
fn matching_is_case_and_whitespace_insensitive() {
|
||||
assert_eq!(
|
||||
match_quality("PARKS AND RECREATION", " parks "),
|
||||
MatchQuality::Prefix
|
||||
);
|
||||
assert_eq!(
|
||||
match_quality("Parks and Recreation", "PARKS"),
|
||||
MatchQuality::Prefix
|
||||
);
|
||||
}
|
||||
|
||||
/// An empty query leaves the order alone rather than reshuffling on kind.
|
||||
#[test]
|
||||
fn empty_query_preserves_input_order() {
|
||||
let mut items = vec![
|
||||
item("Zebra", MediaKind::Episode),
|
||||
item("Apple", MediaKind::Series),
|
||||
];
|
||||
|
||||
rank_search_results(&mut items, "");
|
||||
|
||||
assert_eq!(names(&items), vec!["Zebra", "Apple"]);
|
||||
}
|
||||
|
||||
/// A multi-byte name must not panic when the match is mid-string — the
|
||||
/// boundary check walks chars rather than slicing raw bytes.
|
||||
#[test]
|
||||
fn handles_multibyte_names_without_panicking() {
|
||||
assert_eq!(
|
||||
match_quality("Pokémon Journeys", "journeys"),
|
||||
MatchQuality::WordStart
|
||||
);
|
||||
assert_eq!(
|
||||
match_quality("Café Parks", "parks"),
|
||||
MatchQuality::WordStart
|
||||
);
|
||||
}
|
||||
|
||||
/// Punctuation counts as a word boundary, so "office" hits "The-Office".
|
||||
#[test]
|
||||
fn punctuation_counts_as_a_word_boundary() {
|
||||
assert_eq!(
|
||||
match_quality("The-Office", "office"),
|
||||
MatchQuality::WordStart
|
||||
);
|
||||
assert_eq!(
|
||||
match_quality("Show: Parks", "parks"),
|
||||
MatchQuality::WordStart
|
||||
);
|
||||
}
|
||||
}
|
||||
+25
-6
@@ -121,6 +121,7 @@ use commands::{
|
||||
player_get_audio_settings,
|
||||
player_get_autoplay_settings,
|
||||
player_get_cache_config,
|
||||
player_get_eq_presets,
|
||||
player_get_queue,
|
||||
// Session management commands
|
||||
player_get_session,
|
||||
@@ -177,6 +178,7 @@ use commands::{
|
||||
remote_session_set_volume,
|
||||
remote_session_toggle_mute,
|
||||
// Repository commands
|
||||
repository_clear_watch_history,
|
||||
repository_create,
|
||||
repository_destroy,
|
||||
repository_get_audio_only_stream_url_for_video,
|
||||
@@ -200,6 +202,8 @@ use commands::{
|
||||
repository_get_rediscover_albums,
|
||||
repository_get_resume_items,
|
||||
repository_get_resume_movies,
|
||||
repository_get_series_current_episode,
|
||||
repository_get_series_episodes,
|
||||
repository_get_similar_items,
|
||||
repository_get_subtitle_url,
|
||||
repository_get_video_download_url,
|
||||
@@ -515,6 +519,12 @@ fn emit_backend_init_failed(app_handle: &tauri::AppHandle, backend: &'static str
|
||||
}
|
||||
|
||||
/// Create the appropriate player backend for the current platform.
|
||||
// playback_reporter/position_throttler are consumed only by the native audio
|
||||
// backends (mpv/exo); on platforms using the webview audio backend they're unused.
|
||||
#[cfg_attr(
|
||||
not(any(target_os = "linux", target_os = "android")),
|
||||
allow(unused_variables)
|
||||
)]
|
||||
fn create_player_backend(
|
||||
app_handle: tauri::AppHandle,
|
||||
playback_reporter: Arc<tokio::sync::Mutex<Option<playback_reporting::PlaybackReporter>>>,
|
||||
@@ -615,11 +625,19 @@ fn create_player_backend(
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback for other platforms
|
||||
// Platforms with no native audio backend (e.g. Windows): render audio-only
|
||||
// playback through a webview <audio> element (all video already renders in
|
||||
// the webview). Falls back to NullBackend only if the backend can't init.
|
||||
#[cfg(not(any(target_os = "linux", target_os = "android")))]
|
||||
{
|
||||
warn!("WARNING: No audio backend available for this platform");
|
||||
Box::new(NullBackend::new())
|
||||
info!("No native audio backend for this platform - using webview <audio> backend");
|
||||
match player::WebviewAudioBackend::new(_event_emitter) {
|
||||
Ok(backend) => Box::new(backend),
|
||||
Err(e) => {
|
||||
emit_backend_init_failed(&app_handle, "webview-audio", e.to_string());
|
||||
Box::new(NullBackend::new())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -666,6 +684,7 @@ fn specta_builder() -> Builder<tauri::Wry> {
|
||||
player_skip_to,
|
||||
player_set_audio_settings,
|
||||
player_get_audio_settings,
|
||||
player_get_eq_presets,
|
||||
player_set_video_settings,
|
||||
player_get_video_settings,
|
||||
// Sleep timer and autoplay commands
|
||||
@@ -853,6 +872,9 @@ fn specta_builder() -> Builder<tauri::Wry> {
|
||||
repository_get_latest_items,
|
||||
repository_get_resume_items,
|
||||
repository_get_next_up_episodes,
|
||||
repository_get_series_episodes,
|
||||
repository_get_series_current_episode,
|
||||
repository_clear_watch_history,
|
||||
repository_get_recently_played_audio,
|
||||
repository_get_resume_movies,
|
||||
repository_get_rediscover_albums,
|
||||
@@ -1180,9 +1202,6 @@ pub fn run() {
|
||||
let video_settings = VideoSettingsWrapper(Mutex::new(VideoSettings::default()));
|
||||
app.manage(video_settings);
|
||||
|
||||
// Background-audio handoff base offset (UR-040).
|
||||
app.manage(commands::player::BackgroundAudioOffset::default());
|
||||
|
||||
// Initialize thumbnail cache
|
||||
info!("[INIT] Initializing thumbnail cache...");
|
||||
let app_data_dir = if let Ok(test_data_dir) = std::env::var("JELLYTAU_DATA_DIR") {
|
||||
|
||||
@@ -18,6 +18,7 @@ use super::events::{PlayerStatusEvent, SharedEventEmitter};
|
||||
use super::media::{MediaItem, MediaType};
|
||||
use super::state::PlayerState;
|
||||
use crate::playback_reporting::{EventThrottler, PlaybackOperation, PlaybackReporter};
|
||||
use crate::settings::{audio_settings_jni_payload, AudioSettings};
|
||||
use crate::utils::conversions::seconds_to_ticks;
|
||||
|
||||
/// Global reference to the JavaVM for JNI callbacks
|
||||
@@ -148,6 +149,10 @@ struct ExoPlayerState {
|
||||
volume: f32,
|
||||
is_loaded: bool,
|
||||
current_media: Option<MediaItem>,
|
||||
/// Last applied audio settings. Unlike the fields above (which JNI callbacks
|
||||
/// push *in*), this is commanded *out* — audio settings are never reported
|
||||
/// by the player, so this is the authoritative copy for `audio_settings()`.
|
||||
audio_settings: AudioSettings,
|
||||
}
|
||||
|
||||
impl ExoPlayerState {
|
||||
@@ -159,6 +164,7 @@ impl ExoPlayerState {
|
||||
volume: 1.0,
|
||||
is_loaded: false,
|
||||
current_media: None,
|
||||
audio_settings: AudioSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -529,6 +535,56 @@ impl PlayerBackend for ExoPlayerBackend {
|
||||
self.shared_state.lock_safe().volume
|
||||
}
|
||||
|
||||
/// Apply audio settings to ExoPlayer (equalizer, normalization, gapless).
|
||||
///
|
||||
/// Sent as JSON rather than a wide JNI signature so new fields do not change
|
||||
/// the method signature — the same approach `load()` uses for subtitles. The
|
||||
/// Kotlin side owns the *mechanics* (attaching AudioEffects to the audio
|
||||
/// session); the canonical band layout and preset curves stay in Rust.
|
||||
///
|
||||
/// TRACES: UR-027, UR-032, UR-033 | DR-030, DR-035, DR-036
|
||||
fn set_audio_settings(&mut self, settings: &AudioSettings) -> Result<(), PlayerError> {
|
||||
let json = audio_settings_jni_payload(settings).map_err(|e| {
|
||||
PlayerError::playback_failed(format!("Failed to serialize audio settings: {}", e))
|
||||
})?;
|
||||
|
||||
let vm = JAVA_VM
|
||||
.get()
|
||||
.ok_or_else(|| PlayerError::playback_failed("JavaVM not initialized"))?;
|
||||
|
||||
let mut env = vm
|
||||
.attach_current_thread()
|
||||
.map_err(|e| PlayerError::playback_failed(format!("Failed to attach thread: {}", e)))?;
|
||||
|
||||
let json_jstring = env.new_string(&json).map_err(|e| {
|
||||
PlayerError::playback_failed(format!("Failed to create settings string: {}", e))
|
||||
})?;
|
||||
|
||||
env.call_method(
|
||||
&self.player_ref,
|
||||
"setAudioSettings",
|
||||
"(Ljava/lang/String;)V",
|
||||
&[JValue::Object(&json_jstring)],
|
||||
)
|
||||
.map_err(|e| {
|
||||
PlayerError::playback_failed(format!("Failed to call setAudioSettings: {}", e))
|
||||
})?;
|
||||
|
||||
// Store the sanitised form so audio_settings() reflects what was applied,
|
||||
// not what was requested.
|
||||
self.shared_state.lock_safe().audio_settings = settings
|
||||
.clone()
|
||||
.with_crossfade_clamped()
|
||||
.with_equalizer_normalised();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// TRACES: UR-027, UR-032, UR-033 | DR-030, DR-035, DR-036
|
||||
fn audio_settings(&self) -> AudioSettings {
|
||||
self.shared_state.lock_safe().audio_settings.clone()
|
||||
}
|
||||
|
||||
fn set_audio_track(&mut self, stream_index: i32) -> Result<(), PlayerError> {
|
||||
let vm = JAVA_VM
|
||||
.get()
|
||||
@@ -858,12 +914,20 @@ pub extern "system" fn Java_com_dtourolle_jellytau_player_JellyTauPlayer_nativeO
|
||||
});
|
||||
}
|
||||
|
||||
// Start countdown if auto_advance enabled
|
||||
if auto_advance {
|
||||
// Shared with the frontend-invoked command path
|
||||
// (player_on_playback_ended) so the two dispatchers cannot
|
||||
// disagree about how a background audio-only episode
|
||||
// advances — they did, and the command's copy was missing
|
||||
// the case entirely. That copy is the one that actually
|
||||
// decides here: the end reason set at load makes this
|
||||
// callback's own decision Stop, and the frontend echoes the
|
||||
// resulting PlaybackEnded back into the command.
|
||||
controller
|
||||
.lock()
|
||||
.await
|
||||
.start_autoplay_countdown(next_episode, countdown_seconds);
|
||||
.auto_advance_to_next_episode(next_episode, countdown_seconds)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
|
||||
@@ -332,6 +332,7 @@ mod tests {
|
||||
gapless_playback: false,
|
||||
normalize_volume: true,
|
||||
volume_level: VolumeLevel::Loud,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
backend.set_audio_settings(&settings).unwrap();
|
||||
|
||||
@@ -156,6 +156,25 @@ pub enum PlayerStatusEvent {
|
||||
/// Target position in seconds (only meaningful for "seek").
|
||||
position: Option<f64>,
|
||||
},
|
||||
/// Ask the frontend webview `<audio>` element to load and play a stream.
|
||||
///
|
||||
/// Emitted by `WebviewAudioBackend` on platforms with no native audio
|
||||
/// backend (e.g. Windows): audio-only playback is rendered by an `<audio>`
|
||||
/// element in the webview, mirroring how all video already renders through
|
||||
/// the webview `<video>`. The element then reports its state/position back
|
||||
/// through the `player_report_*` commands, so the Rust controller stays the
|
||||
/// single source of truth. Subsequent play/pause/seek/stop reach the element
|
||||
/// via `ControlCommand`.
|
||||
WebviewAudioLoad {
|
||||
/// Stream URL for the `<audio>` element to play.
|
||||
url: String,
|
||||
/// Jellyfin item id, used as the media_id when reporting state back.
|
||||
media_id: Option<String>,
|
||||
/// Resume position in seconds (0 = start from the beginning).
|
||||
position: f64,
|
||||
/// Whether to begin playing immediately after loading.
|
||||
autoplay: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// Trait for emitting player events to the frontend.
|
||||
|
||||
+712
-12
@@ -22,6 +22,11 @@ pub mod android;
|
||||
#[cfg(target_os = "linux")]
|
||||
pub mod mpv_backend;
|
||||
|
||||
// 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")))]
|
||||
pub mod webview_audio_backend;
|
||||
|
||||
// Re-export commonly used types
|
||||
pub use autoplay::{AutoplayDecision, AutoplaySettings};
|
||||
pub use backend::{NullBackend, PlayerBackend, PlayerError};
|
||||
@@ -40,6 +45,9 @@ pub use android::ExoPlayerBackend;
|
||||
#[cfg(target_os = "linux")]
|
||||
pub use mpv_backend::MpvBackend;
|
||||
|
||||
#[cfg(not(any(target_os = "linux", target_os = "android")))]
|
||||
pub use webview_audio_backend::WebviewAudioBackend;
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
pub use android::{
|
||||
disable_remote_volume, enable_remote_volume, get_detected_codecs, set_media_command_handler,
|
||||
@@ -97,7 +105,7 @@ pub fn set_lockscreen_position_offset(_offset_seconds: f64) -> Result<(), String
|
||||
}
|
||||
|
||||
use crate::utils::lock::MutexSafe;
|
||||
use log::{debug, error, warn};
|
||||
use log::{debug, error, info, warn};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
use tokio::sync::Mutex as TokioMutex;
|
||||
@@ -144,6 +152,32 @@ pub struct PlayerController {
|
||||
|
||||
// Auto-play episode counter (session-based, resets on manual play)
|
||||
autoplay_episode_count: Arc<Mutex<u32>>,
|
||||
|
||||
// Base offset (seconds) of the active background-audio handoff.
|
||||
//
|
||||
// The audio-only stream is requested with `StartTimeTicks` = the position the
|
||||
// video was handed off at, so the server makes that point the stream's zero
|
||||
// and the native player reports position RELATIVE to it. Adding this base back
|
||||
// yields the absolute position to resume the video at on the way out.
|
||||
//
|
||||
// Lives on the controller (not beside the command) because the queue and this
|
||||
// offset describe the same stream: whenever the controller loads a different
|
||||
// one — notably the backend-driven advance to the next episode — the base has
|
||||
// to move with it.
|
||||
//
|
||||
// TRACES: UR-040 | DR-052
|
||||
background_audio_base: Arc<Mutex<f64>>,
|
||||
|
||||
// Last state reported by a webview-rendered HTML5 <video>/<audio> element.
|
||||
//
|
||||
// Webview-rendered media is played by an element the native backend cannot
|
||||
// reach, so the backend's own state() says nothing about it. Tracking the
|
||||
// REPORTED state here is what lets transport (play/pause/toggle) be decided
|
||||
// in Rust for that media instead of the frontend reading `el.paused` off the
|
||||
// DOM — a value that flips transiently while buffering/seeking and caused
|
||||
// competing intents to take opposing actions. `None` means no webview media
|
||||
// is active and the native backend is authoritative. See DR-097.
|
||||
html5_playing: Arc<Mutex<Option<bool>>>,
|
||||
}
|
||||
|
||||
impl PlayerController {
|
||||
@@ -166,6 +200,8 @@ impl PlayerController {
|
||||
position_throttler,
|
||||
end_reason: Arc::new(Mutex::new(None)),
|
||||
autoplay_episode_count: Arc::new(Mutex::new(0)),
|
||||
background_audio_base: Arc::new(Mutex::new(0.0)),
|
||||
html5_playing: Arc::new(Mutex::new(None)),
|
||||
};
|
||||
|
||||
// Start background timer thread for sleep timer countdown
|
||||
@@ -235,6 +271,23 @@ impl PlayerController {
|
||||
self.end_reason.lock_safe().take()
|
||||
}
|
||||
|
||||
/// Record that playback is being stopped by an expiring sleep timer.
|
||||
///
|
||||
/// Stopping the backend makes it fire its ended callback (ExoPlayer does on
|
||||
/// Android), which lands in `on_playback_ended`. Without an end reason that
|
||||
/// reads as a natural finish and autoplay advances — defeating the timer.
|
||||
/// `UserStop` is the honest label: the stop was user-initiated, just via the
|
||||
/// timer they set rather than the stop button.
|
||||
///
|
||||
/// Takes the shared slot rather than `&self` so the sleep-timer thread —
|
||||
/// which owns clones, not the controller — records it the same way.
|
||||
///
|
||||
/// TRACES: UR-023, UR-026 | DR-029
|
||||
fn note_sleep_timer_stop(end_reason: &Arc<Mutex<Option<EndReason>>>) {
|
||||
log::debug!("[PlayerController] Sleep timer stop: marking end reason UserStop");
|
||||
*end_reason.lock_safe() = Some(EndReason::UserStop);
|
||||
}
|
||||
|
||||
/// Increment autoplay episode counter. Returns true if limit is reached.
|
||||
fn increment_autoplay_count(&self) -> bool {
|
||||
let max = self.autoplay_settings.lock_safe().max_episodes;
|
||||
@@ -451,21 +504,72 @@ impl PlayerController {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// True while webview-rendered media (HTML5 `<video>`/`<audio>`) is the real
|
||||
/// player, so transport must be routed to it rather than the native backend.
|
||||
///
|
||||
/// TRACES: UR-005 | DR-097
|
||||
pub fn is_html5_active(&self) -> bool {
|
||||
self.html5_playing.lock_safe().is_some()
|
||||
}
|
||||
|
||||
/// Whether the webview element last reported itself as playing. Meaningless
|
||||
/// unless [`Self::is_html5_active`] is true.
|
||||
///
|
||||
/// TRACES: UR-005 | DR-097
|
||||
pub fn html5_is_playing(&self) -> bool {
|
||||
self.html5_playing.lock_safe().unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Send a transport intent to the webview element that is rendering media.
|
||||
fn emit_html5_control(&self, action: &str) {
|
||||
if let Some(emitter) = self.event_emitter.lock_safe().as_ref() {
|
||||
emitter.emit(PlayerStatusEvent::ControlCommand {
|
||||
action: action.to_string(),
|
||||
position: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Play/resume playback
|
||||
pub fn play(&self) -> Result<(), PlayerError> {
|
||||
debug!("[PlayerController] play");
|
||||
// Webview-rendered media: the native backend isn't playing it, so drive
|
||||
// the element via a ControlCommand instead (DR-097).
|
||||
if self.is_html5_active() {
|
||||
self.emit_html5_control("play");
|
||||
return Ok(());
|
||||
}
|
||||
let mut backend = self.backend.lock_safe();
|
||||
backend.play()
|
||||
}
|
||||
|
||||
/// Pause playback
|
||||
pub fn pause(&self) -> Result<(), PlayerError> {
|
||||
if self.is_html5_active() {
|
||||
self.emit_html5_control("pause");
|
||||
return Ok(());
|
||||
}
|
||||
let mut backend = self.backend.lock_safe();
|
||||
backend.pause()
|
||||
}
|
||||
|
||||
/// Toggle play/pause
|
||||
/// Toggle play/pause.
|
||||
///
|
||||
/// The decision is made HERE, from authoritative state — the reported webview
|
||||
/// state for HTML5-rendered media, or the native backend's state otherwise.
|
||||
/// The frontend must never decide this from the DOM (see DR-097).
|
||||
///
|
||||
/// TRACES: UR-005 | DR-097
|
||||
pub fn toggle_playback(&self) -> Result<(), PlayerError> {
|
||||
if self.is_html5_active() {
|
||||
let action = if self.html5_is_playing() {
|
||||
"pause"
|
||||
} else {
|
||||
"play"
|
||||
};
|
||||
self.emit_html5_control(action);
|
||||
return Ok(());
|
||||
}
|
||||
let mut backend = self.backend.lock_safe();
|
||||
if backend.state().is_playing() {
|
||||
backend.pause()
|
||||
@@ -650,6 +754,24 @@ impl PlayerController {
|
||||
self.queue.clone()
|
||||
}
|
||||
|
||||
/// True when the current item is a TV episode being played in audio-only
|
||||
/// (background) mode — i.e. an `item_type == "Episode"` item loaded as
|
||||
/// `MediaType::Audio`. Used to decide whether the backend must drive the
|
||||
/// next-episode advance itself (the frontend is suspended in the background).
|
||||
///
|
||||
/// Only *called* from the Android autoplay dispatch (`#[cfg(android)]`), but
|
||||
/// compiled and unit-tested on the host, hence `allow(dead_code)` off-Android.
|
||||
#[cfg_attr(not(target_os = "android"), allow(dead_code))]
|
||||
pub fn current_is_audio_episode(&self) -> bool {
|
||||
self.queue
|
||||
.lock_safe()
|
||||
.current()
|
||||
.map(|item| {
|
||||
item.media_type == MediaType::Audio && item.item_type.as_deref() == Some("Episode")
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Clear the queue entirely (used when playback genuinely stops, e.g. the
|
||||
/// sleep timer fires or the queue ends with repeat off). Pair with
|
||||
/// `emit_queue_changed` so the frontend hides the mini player.
|
||||
@@ -741,6 +863,7 @@ impl PlayerController {
|
||||
let sleep_timer = self.sleep_timer.clone();
|
||||
let event_emitter = self.event_emitter.clone();
|
||||
let backend = self.backend.clone();
|
||||
let end_reason = self.end_reason.clone();
|
||||
|
||||
std::thread::spawn(move || {
|
||||
loop {
|
||||
@@ -757,6 +880,14 @@ impl PlayerController {
|
||||
debug!("[SleepTimer] Time-based timer expired, stopping playback");
|
||||
timer.cancel();
|
||||
|
||||
// Mark the stop *before* it reaches the backend. Stopping
|
||||
// makes the native player fire its ended callback, and
|
||||
// cancelling the timer above means on_playback_ended can no
|
||||
// longer tell this apart from a natural end — without this
|
||||
// it would show the next-episode popup / autoplay right
|
||||
// after the sleep timer fired.
|
||||
Self::note_sleep_timer_stop(&end_reason);
|
||||
|
||||
// Emit cancelled state
|
||||
if let Some(emitter) = event_emitter.lock_safe().as_ref() {
|
||||
emitter.emit(PlayerStatusEvent::SleepTimerChanged {
|
||||
@@ -838,6 +969,23 @@ impl PlayerController {
|
||||
/// Re-emits a `StateChanged` event identical to what MpvBackend/ExoPlayer
|
||||
/// would emit, so `playerEvents.ts` needs no HTML5-specific branch.
|
||||
pub fn report_html5_state(&self, state: String, media_id: Option<String>) {
|
||||
// Track it: this is the authoritative play/pause state for
|
||||
// webview-rendered media, and what transport decisions read (DR-097).
|
||||
// "stopped"/"idle" mean the element is gone, so hand authority back to
|
||||
// the native backend — otherwise music playback would keep emitting
|
||||
// ControlCommands at a element that no longer exists.
|
||||
{
|
||||
let mut tracked = self.html5_playing.lock_safe();
|
||||
*tracked = match state.as_str() {
|
||||
"playing" => Some(true),
|
||||
// "loading" counts as active-but-not-playing so a toggle during
|
||||
// load resolves to "play" rather than falling through to the
|
||||
// native backend.
|
||||
"paused" | "loading" => Some(false),
|
||||
// "stopped"/"idle": element is gone, native backend resumes authority.
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
if let Some(emitter) = self.event_emitter.lock_safe().as_ref() {
|
||||
emitter.emit(PlayerStatusEvent::StateChanged { state, media_id });
|
||||
}
|
||||
@@ -955,9 +1103,11 @@ impl PlayerController {
|
||||
return Ok(AutoplayDecision::Stop);
|
||||
}
|
||||
SleepTimerMode::Episodes { .. } => {
|
||||
// Only count TV episodes (not audio tracks or movies)
|
||||
let is_episode =
|
||||
current.media_type == MediaType::Video && self.is_episode_item(¤t).await;
|
||||
// Only count TV episodes (not audio tracks or movies). Note an
|
||||
// episode played in background-audio mode is MediaType::Audio, so
|
||||
// rely on is_episode_item (which checks item_type) rather than the
|
||||
// media_type alone.
|
||||
let is_episode = self.is_episode_item(¤t).await;
|
||||
|
||||
if is_episode {
|
||||
let should_stop = self.sleep_timer.lock_safe().decrement_episode();
|
||||
@@ -973,10 +1123,12 @@ impl PlayerController {
|
||||
}
|
||||
}
|
||||
|
||||
// For video episodes, fetch next episode and show popup
|
||||
// For episodes, fetch next episode and show popup.
|
||||
// Note: This path is typically not hit for HTML5 video (which uses on_video_playback_ended).
|
||||
// It's here for the Android ExoPlayer path where video items may be in the backend queue.
|
||||
if current.media_type == MediaType::Video && self.is_episode_item(¤t).await {
|
||||
// It's here for the Android ExoPlayer path where episode items sit in the
|
||||
// backend queue — including background-audio mode, where the episode is a
|
||||
// MediaType::Audio item, so gate on is_episode_item (item_type), not media_type.
|
||||
if self.is_episode_item(¤t).await {
|
||||
let repo = self.repository.lock_safe().clone();
|
||||
let jellyfin_id = current.jellyfin_id().unwrap_or(¤t.id);
|
||||
let next_ep_result = if let Some(repo) = &repo {
|
||||
@@ -1034,6 +1186,146 @@ impl PlayerController {
|
||||
}
|
||||
}
|
||||
|
||||
/// Record the base offset of a background-audio handoff (the position the
|
||||
/// video was handed off at, which is the audio stream's zero).
|
||||
///
|
||||
/// TRACES: UR-040 | DR-052
|
||||
pub fn set_background_audio_base(&self, seconds: f64) {
|
||||
*self.background_audio_base.lock_safe() = seconds.max(0.0);
|
||||
}
|
||||
|
||||
/// Read and clear the background-audio base offset.
|
||||
///
|
||||
/// TRACES: UR-040 | DR-052
|
||||
pub fn take_background_audio_base(&self) -> f64 {
|
||||
let mut base = self.background_audio_base.lock_safe();
|
||||
std::mem::replace(&mut *base, 0.0)
|
||||
}
|
||||
|
||||
/// Perform the auto-advance for a `ShowNextEpisodePopup` decision.
|
||||
///
|
||||
/// Single place both end-of-playback dispatchers agree on: the Android JNI
|
||||
/// callback (`nativeOnPlaybackEnded`) and the frontend-invoked command
|
||||
/// (`player_on_playback_ended`). They used to each carry their own copy of
|
||||
/// this branch, and the command's copy was missing the background-audio case
|
||||
/// entirely — so an audio-only episode ending while backgrounded only ever
|
||||
/// started a countdown that nothing could act on.
|
||||
///
|
||||
/// TRACES: UR-040, UR-023 | DR-052
|
||||
pub async fn auto_advance_to_next_episode(
|
||||
&self,
|
||||
next_episode: crate::repository::types::MediaItem,
|
||||
countdown_seconds: u32,
|
||||
) {
|
||||
// Background audio-only episode: the countdown only emits ticks — the
|
||||
// advance itself is a `goto('/player/<id>')` in the webview, which cannot
|
||||
// start audio while the app is backgrounded. Load the next episode's
|
||||
// audio-only stream here instead, or playback stalls at the boundary.
|
||||
if self.current_is_audio_episode() {
|
||||
info!(
|
||||
"[PlayerController] Background audio episode — advancing to {} in backend",
|
||||
next_episode.id
|
||||
);
|
||||
match self
|
||||
.advance_to_next_episode_audio_only(&next_episode.id)
|
||||
.await
|
||||
{
|
||||
Ok(()) => self.emit_queue_changed(),
|
||||
Err(e) => {
|
||||
error!(
|
||||
"[PlayerController] Background audio advance failed: {} — stopping",
|
||||
e
|
||||
);
|
||||
if let Some(emitter) = self.event_emitter() {
|
||||
emitter.emit(PlayerStatusEvent::PlaybackEnded);
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Foreground: the frontend drives the advance off the countdown ticks.
|
||||
self.start_autoplay_countdown(next_episode, countdown_seconds);
|
||||
}
|
||||
|
||||
/// Advance to the next episode while playing audio-only in the background.
|
||||
///
|
||||
/// The normal autoplay-next path navigates the frontend to `/player/<id>`,
|
||||
/// which is unavailable when the app is backgrounded and the WebView is
|
||||
/// suspended. This drives the advance entirely in the backend: build the next
|
||||
/// episode's *audio-only* stream URL and load it into the native audio player,
|
||||
/// so playback continues without any frontend involvement (UR-040).
|
||||
///
|
||||
/// `next_episode_id` is the Jellyfin item ID of the episode to play next.
|
||||
///
|
||||
/// Reached through `auto_advance_to_next_episode`, which gates it on
|
||||
/// `current_is_audio_episode()` — only ever true after a background-audio
|
||||
/// handoff (Android), but compiled and unit-tested on every platform.
|
||||
/// TRACES: UR-040, UR-023 | DR-052
|
||||
pub async fn advance_to_next_episode_audio_only(
|
||||
&self,
|
||||
next_episode_id: &str,
|
||||
) -> Result<(), String> {
|
||||
let repo = self
|
||||
.repository
|
||||
.lock_safe()
|
||||
.clone()
|
||||
.ok_or_else(|| "No repository for background episode advance".to_string())?;
|
||||
|
||||
// Details for session metadata (title/series/artwork) and the stream URL.
|
||||
let next = repo
|
||||
.get_item(next_episode_id)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to fetch next episode {}: {}", next_episode_id, e))?;
|
||||
|
||||
// Audio-only transcode from the start of the episode (no resume offset —
|
||||
// a freshly-started next episode always plays from the beginning).
|
||||
let stream_url = repo
|
||||
.get_audio_only_stream_url_for_video(next_episode_id, None, None, None)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to build audio-only URL for next episode: {}", e))?;
|
||||
|
||||
let media_item = MediaItem {
|
||||
id: next.id.clone(),
|
||||
title: next.name.clone(),
|
||||
name: Some(next.name.clone()),
|
||||
artist: next.series_name.clone(),
|
||||
album: None,
|
||||
album_name: None,
|
||||
album_id: None,
|
||||
artist_items: None,
|
||||
artists: None,
|
||||
primary_image_tag: next.primary_image_tag.clone(),
|
||||
image_id: next.image_id.clone().or(next.primary_image_tag.clone()),
|
||||
// Preserve episode identity so the NEXT end-of-track also advances.
|
||||
item_type: Some("Episode".to_string()),
|
||||
playlist_id: None,
|
||||
duration: next.duration_ms.map(|ms| ms as f64 / 1000.0),
|
||||
artwork_url: None,
|
||||
media_type: MediaType::Audio,
|
||||
source: MediaSource::Remote {
|
||||
stream_url,
|
||||
jellyfin_item_id: next.id.clone(),
|
||||
},
|
||||
video_codec: None,
|
||||
needs_transcoding: false,
|
||||
video_width: None,
|
||||
video_height: None,
|
||||
subtitles: vec![],
|
||||
series_id: next.series_id.clone(),
|
||||
server_id: Some(next.server_id.clone()),
|
||||
};
|
||||
|
||||
// The previous episode's handoff base described the stream we are leaving.
|
||||
// This one is built without StartTimeTicks, so its timeline is already
|
||||
// absolute: clear the base (used to resolve the resume position on the way
|
||||
// back to the foreground) and the lockscreen scrubber's matching shift.
|
||||
self.set_background_audio_base(0.0);
|
||||
let _ = set_lockscreen_position_offset(0.0);
|
||||
|
||||
self.play_item(media_item).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Handle video playback ended from HTML5 video element.
|
||||
///
|
||||
/// HTML5 video plays independently of the Rust backend, so the backend
|
||||
@@ -1127,11 +1419,19 @@ impl PlayerController {
|
||||
Ok(AutoplayDecision::Stop)
|
||||
}
|
||||
|
||||
/// Check if a media item is an episode (has Jellyfin ID to query)
|
||||
/// Check if a media item is an episode (has Jellyfin ID to query).
|
||||
///
|
||||
/// An explicit `item_type == "Episode"` wins so that a TV episode handed off
|
||||
/// to the audio path for background playback (UR-040) is still recognised as
|
||||
/// an episode — otherwise autoplay would fall through to the queue-based
|
||||
/// audio path, find nothing next, and stop at the episode boundary. When the
|
||||
/// type is unknown we fall back to the historical heuristic (video == episode).
|
||||
async fn is_episode_item(&self, item: &MediaItem) -> bool {
|
||||
// For now, assume video items are episodes
|
||||
// In production, we'd check item metadata or query Jellyfin
|
||||
item.media_type == MediaType::Video
|
||||
match item.item_type.as_deref() {
|
||||
Some("Episode") => true,
|
||||
Some(_) => item.media_type == MediaType::Video,
|
||||
None => item.media_type == MediaType::Video,
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch next episode for a series by looking up the season's episodes
|
||||
@@ -1354,6 +1654,156 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
// ===== HTML5 transport authority (DR-097) =====
|
||||
//
|
||||
// Webview-rendered video is played by an element the native backend cannot
|
||||
// reach, so transport for it must be decided from the state the element
|
||||
// REPORTS and executed by emitting a ControlCommand. Previously the frontend
|
||||
// decided play-vs-pause itself by reading `el.paused` off the DOM, which
|
||||
// flips transiently while buffering/seeking — two intents ~150ms apart read
|
||||
// different values, took opposing actions, and self-sustained a pause loop.
|
||||
|
||||
#[test]
|
||||
fn test_html5_state_is_tracked_from_reports() {
|
||||
let controller = PlayerController::default();
|
||||
let emitter = Arc::new(CapturingEmitter::new());
|
||||
controller.set_event_emitter(emitter.clone());
|
||||
|
||||
// No HTML5 media reported yet: the native backend stays authoritative.
|
||||
assert!(!controller.is_html5_active());
|
||||
|
||||
controller.report_html5_state("playing".to_string(), Some("item-1".to_string()));
|
||||
assert!(controller.is_html5_active());
|
||||
assert!(controller.html5_is_playing());
|
||||
|
||||
controller.report_html5_state("paused".to_string(), Some("item-1".to_string()));
|
||||
assert!(controller.is_html5_active());
|
||||
assert!(!controller.html5_is_playing());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_html5_toggle_from_paused_emits_play_control() {
|
||||
let controller = PlayerController::default();
|
||||
let emitter = Arc::new(CapturingEmitter::new());
|
||||
controller.set_event_emitter(emitter.clone());
|
||||
controller.report_html5_state("paused".to_string(), Some("item-1".to_string()));
|
||||
|
||||
controller.toggle_playback().unwrap();
|
||||
|
||||
let controls: Vec<_> = emitter
|
||||
.events()
|
||||
.into_iter()
|
||||
.filter_map(|e| match e {
|
||||
PlayerStatusEvent::ControlCommand { action, .. } => Some(action),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(controls, vec!["play".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_html5_toggle_from_playing_emits_pause_control() {
|
||||
let controller = PlayerController::default();
|
||||
let emitter = Arc::new(CapturingEmitter::new());
|
||||
controller.set_event_emitter(emitter.clone());
|
||||
controller.report_html5_state("playing".to_string(), Some("item-1".to_string()));
|
||||
|
||||
controller.toggle_playback().unwrap();
|
||||
|
||||
let controls: Vec<_> = emitter
|
||||
.events()
|
||||
.into_iter()
|
||||
.filter_map(|e| match e {
|
||||
PlayerStatusEvent::ControlCommand { action, .. } => Some(action),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(controls, vec!["pause".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_html5_repeated_toggles_alternate_and_never_repeat_an_action() {
|
||||
// The loop signature: two intents in quick succession must NOT both
|
||||
// resolve the same way, and must not produce opposing actions from a
|
||||
// stale read. Rust's own tracked state makes the sequence deterministic
|
||||
// as long as the element reports back between intents.
|
||||
let controller = PlayerController::default();
|
||||
let emitter = Arc::new(CapturingEmitter::new());
|
||||
controller.set_event_emitter(emitter.clone());
|
||||
controller.report_html5_state("playing".to_string(), Some("item-1".to_string()));
|
||||
|
||||
controller.toggle_playback().unwrap();
|
||||
// Element confirms the pause it was told to do.
|
||||
controller.report_html5_state("paused".to_string(), Some("item-1".to_string()));
|
||||
controller.toggle_playback().unwrap();
|
||||
|
||||
let controls: Vec<_> = emitter
|
||||
.events()
|
||||
.into_iter()
|
||||
.filter_map(|e| match e {
|
||||
PlayerStatusEvent::ControlCommand { action, .. } => Some(action),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(controls, vec!["pause".to_string(), "play".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_html5_play_and_pause_emit_control_commands() {
|
||||
let controller = PlayerController::default();
|
||||
let emitter = Arc::new(CapturingEmitter::new());
|
||||
controller.set_event_emitter(emitter.clone());
|
||||
controller.report_html5_state("paused".to_string(), Some("item-1".to_string()));
|
||||
|
||||
controller.play().unwrap();
|
||||
controller.pause().unwrap();
|
||||
|
||||
let controls: Vec<_> = emitter
|
||||
.events()
|
||||
.into_iter()
|
||||
.filter_map(|e| match e {
|
||||
PlayerStatusEvent::ControlCommand { action, .. } => Some(action),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(controls, vec!["play".to_string(), "pause".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_html5_stopped_report_releases_transport_to_native_backend() {
|
||||
// When webview video goes away, transport must fall back to the native
|
||||
// backend (music playback must not keep emitting ControlCommands).
|
||||
let controller = PlayerController::default();
|
||||
let emitter = Arc::new(CapturingEmitter::new());
|
||||
controller.set_event_emitter(emitter.clone());
|
||||
|
||||
controller.report_html5_state("playing".to_string(), Some("item-1".to_string()));
|
||||
assert!(controller.is_html5_active());
|
||||
|
||||
controller.report_html5_state("stopped".to_string(), None);
|
||||
assert!(!controller.is_html5_active());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_html5_transport_emits_exactly_one_control_per_intent() {
|
||||
// Guards against a double-drive on platforms where the *backend* is also
|
||||
// webview-based (WebviewAudioBackend on Windows): the html5 short-circuit
|
||||
// must replace the backend call, not run in addition to it.
|
||||
let controller = PlayerController::default();
|
||||
let emitter = Arc::new(CapturingEmitter::new());
|
||||
controller.set_event_emitter(emitter.clone());
|
||||
controller.report_html5_state("playing".to_string(), Some("item-1".to_string()));
|
||||
|
||||
controller.pause().unwrap();
|
||||
|
||||
let controls = emitter
|
||||
.events()
|
||||
.into_iter()
|
||||
.filter(|e| matches!(e, PlayerStatusEvent::ControlCommand { .. }))
|
||||
.count();
|
||||
assert_eq!(controls, 1, "one intent must produce exactly one control");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_controller_volume_default() {
|
||||
let controller = PlayerController::default();
|
||||
@@ -1931,6 +2381,51 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A time-based sleep timer that fires mid-episode must not let the ended
|
||||
/// callback fall through to autoplay.
|
||||
///
|
||||
/// The timer thread stops the backend directly, which makes ExoPlayer emit
|
||||
/// its ended callback. That callback races the thread's own `timer.cancel()`:
|
||||
/// by the time `on_playback_ended` inspects the sleep timer it reads `Off`,
|
||||
/// so the timer branch is skipped and the episode path runs — showing a
|
||||
/// next-episode popup (or advancing) after the user's sleep timer expired.
|
||||
#[tokio::test]
|
||||
async fn test_expired_time_sleep_timer_stops_without_autoplay() {
|
||||
let controller = PlayerController::default();
|
||||
|
||||
let items = create_test_items(3);
|
||||
controller.play_queue(items, 0).unwrap();
|
||||
controller.take_end_reason();
|
||||
|
||||
// Arm a time-based timer that is already due, then let the real timer
|
||||
// thread (started in the constructor, 1s tick) observe the expiry and
|
||||
// run its stop path. Driving the actual thread is the point: the bug was
|
||||
// that this path stopped the backend without recording an end reason.
|
||||
let now = chrono::Utc::now().timestamp_millis();
|
||||
controller.set_sleep_timer(SleepTimerMode::Time { end_time: now });
|
||||
|
||||
// Wait for the timer thread to process the expiry (tick is 1s).
|
||||
for _ in 0..40 {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
if !controller.sleep_timer.lock_safe().is_active() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
!controller.sleep_timer.lock_safe().is_active(),
|
||||
"Timer thread should have expired and cancelled the sleep timer"
|
||||
);
|
||||
|
||||
// The backend stop above makes the native player fire its ended callback.
|
||||
let decision = controller.on_playback_ended().await.unwrap();
|
||||
|
||||
assert!(
|
||||
matches!(decision, AutoplayDecision::Stop),
|
||||
"Expected Stop after an expired time-based sleep timer, got {:?}",
|
||||
decision
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_empty_queue_stops() {
|
||||
let controller = PlayerController::default();
|
||||
@@ -2303,6 +2798,15 @@ mod tests {
|
||||
async fn get_audio_stream_url(&self, _: &str) -> Result<String, repo_types::RepoError> {
|
||||
unimplemented!()
|
||||
}
|
||||
async fn get_audio_only_stream_url_for_video(
|
||||
&self,
|
||||
item_id: &str,
|
||||
_media_source_id: Option<&str>,
|
||||
_start_time_seconds: Option<f64>,
|
||||
_audio_stream_index: Option<i32>,
|
||||
) -> Result<String, repo_types::RepoError> {
|
||||
Ok(format!("http://example.com/{}-audio.mp3", item_id))
|
||||
}
|
||||
async fn get_live_tv_channels(
|
||||
&self,
|
||||
) -> Result<Vec<repo_types::MediaItem>, repo_types::RepoError> {
|
||||
@@ -2358,6 +2862,9 @@ mod tests {
|
||||
async fn unmark_favorite(&self, _: &str) -> Result<(), repo_types::RepoError> {
|
||||
unimplemented!()
|
||||
}
|
||||
async fn clear_watch_history(&self, _: &str) -> Result<(), repo_types::RepoError> {
|
||||
unimplemented!()
|
||||
}
|
||||
async fn get_person(
|
||||
&self,
|
||||
_: &str,
|
||||
@@ -2495,6 +3002,199 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Background audio-only mode (UR-040): a video episode is handed off to the
|
||||
/// native ExoPlayer *audio* path as a `MediaType::Audio` item so it keeps
|
||||
/// playing while the app is backgrounded. When that audio track ends, autoplay
|
||||
/// must STILL recognise it as an episode and offer the next one — otherwise
|
||||
/// playback just pauses at the episode boundary (the reported bug). The item
|
||||
/// carries its episode identity via `item_type: "Episode"` + `series_id`.
|
||||
#[tokio::test]
|
||||
async fn test_playback_ended_background_audio_episode_advances() {
|
||||
let controller = PlayerController::default();
|
||||
controller.set_repository(Arc::new(MockEpisodeRepo::season(3)));
|
||||
|
||||
// Mirrors what player_enter_background_audio builds: the episode as AUDIO.
|
||||
let episode = MediaItem {
|
||||
item_type: Some("Episode".to_string()),
|
||||
media_type: MediaType::Audio, // audio-only handoff, not Video
|
||||
series_id: Some("series1".to_string()),
|
||||
source: MediaSource::Remote {
|
||||
stream_url: "http://example.com/ep2-audio.m3u8".to_string(),
|
||||
jellyfin_item_id: "ep2".to_string(),
|
||||
},
|
||||
..create_test_items(1).remove(0)
|
||||
};
|
||||
controller.play_queue(vec![episode], 0).unwrap();
|
||||
|
||||
// Clear the NewTrackLoaded reason to simulate natural track end.
|
||||
controller.take_end_reason();
|
||||
|
||||
let decision = controller.on_playback_ended().await.unwrap();
|
||||
|
||||
match decision {
|
||||
AutoplayDecision::ShowNextEpisodePopup { next_episode, .. } => {
|
||||
assert_eq!(next_episode.id, "ep3");
|
||||
}
|
||||
other => panic!(
|
||||
"background-audio episode end must advance to the next episode, got {:?}",
|
||||
other
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// The backend-driven advance (used when backgrounded) must load the next
|
||||
/// episode as an AUDIO item carrying its episode identity, so the *following*
|
||||
/// end-of-track also advances rather than stopping.
|
||||
#[tokio::test]
|
||||
async fn test_advance_to_next_episode_audio_only_loads_audio_episode() {
|
||||
let controller = PlayerController::default();
|
||||
controller.set_repository(Arc::new(MockEpisodeRepo::season(3)));
|
||||
|
||||
controller
|
||||
.advance_to_next_episode_audio_only("ep2")
|
||||
.await
|
||||
.expect("advance should succeed");
|
||||
|
||||
let current = controller
|
||||
.queue
|
||||
.lock_safe()
|
||||
.current()
|
||||
.cloned()
|
||||
.expect("an item should be loaded");
|
||||
assert_eq!(current.id, "ep2");
|
||||
assert_eq!(current.media_type, MediaType::Audio);
|
||||
assert_eq!(current.item_type.as_deref(), Some("Episode"));
|
||||
assert_eq!(current.series_id.as_deref(), Some("series1"));
|
||||
// Uses the audio-only URL, not a video stream.
|
||||
match ¤t.source {
|
||||
MediaSource::Remote { stream_url, .. } => {
|
||||
assert!(
|
||||
stream_url.contains("audio"),
|
||||
"expected audio-only URL, got {}",
|
||||
stream_url
|
||||
);
|
||||
}
|
||||
other => panic!("expected Remote source, got {:?}", other),
|
||||
}
|
||||
|
||||
// The controller now considers itself mid background-audio episode, so the
|
||||
// next end-of-track will advance again rather than stop.
|
||||
assert!(controller.current_is_audio_episode());
|
||||
}
|
||||
|
||||
/// The handoff base offset describes ONE stream: the audio-only URL built
|
||||
/// with `StartTimeTicks` = the position the video was handed off at, whose
|
||||
/// timeline therefore starts at that point. The next episode is loaded from
|
||||
/// its own beginning, so its timeline is already absolute and the base must
|
||||
/// be cleared — otherwise returning to the foreground resolves the resume
|
||||
/// position as `old_base + position_in_new_episode` and the video jumps to a
|
||||
/// point that has nothing to do with what was playing.
|
||||
#[tokio::test]
|
||||
async fn test_advance_to_next_episode_audio_only_clears_handoff_base() {
|
||||
let controller = PlayerController::default();
|
||||
controller.set_repository(Arc::new(MockEpisodeRepo::season(3)));
|
||||
|
||||
// Handed off 20 minutes into the previous episode.
|
||||
controller.set_background_audio_base(1200.0);
|
||||
|
||||
controller
|
||||
.advance_to_next_episode_audio_only("ep2")
|
||||
.await
|
||||
.expect("advance should succeed");
|
||||
|
||||
assert_eq!(
|
||||
controller.take_background_audio_base(),
|
||||
0.0,
|
||||
"the next episode starts at its own zero, so the previous handoff \
|
||||
base must not survive the advance"
|
||||
);
|
||||
}
|
||||
|
||||
/// A background audio-only episode must advance IN THE BACKEND when the
|
||||
/// autoplay decision comes back as ShowNextEpisodePopup — never by starting a
|
||||
/// countdown the frontend is supposed to act on.
|
||||
///
|
||||
/// The countdown only emits CountdownTick events; the actual advance is a
|
||||
/// `goto('/player/<id>')` in the webview. While the app is backgrounded that
|
||||
/// navigation cannot start audio, so playback stalls at the episode boundary
|
||||
/// with ExoPlayer parked in STATE_ENDED — and any later play intent
|
||||
/// (lockscreen, headset, Bluetooth reconnect) replays the ended item from the
|
||||
/// start, which is what surfaces to the user as "the episode randomly
|
||||
/// restarted".
|
||||
#[tokio::test]
|
||||
async fn test_auto_advance_background_audio_episode_advances_in_backend() {
|
||||
let controller = PlayerController::default();
|
||||
controller.set_repository(Arc::new(MockEpisodeRepo::season(3)));
|
||||
|
||||
// Currently playing: ep2 handed off to audio-only background playback.
|
||||
let episode = MediaItem {
|
||||
id: "ep2".to_string(),
|
||||
item_type: Some("Episode".to_string()),
|
||||
media_type: MediaType::Audio,
|
||||
series_id: Some("series1".to_string()),
|
||||
source: MediaSource::Remote {
|
||||
stream_url: "http://example.com/ep2-audio.mp3".to_string(),
|
||||
jellyfin_item_id: "ep2".to_string(),
|
||||
},
|
||||
..create_test_items(1).remove(0)
|
||||
};
|
||||
controller.play_queue(vec![episode], 0).unwrap();
|
||||
|
||||
let next = make_repo_episode("ep3", 3);
|
||||
controller.auto_advance_to_next_episode(next, 10).await;
|
||||
|
||||
let current = controller
|
||||
.queue
|
||||
.lock_safe()
|
||||
.current()
|
||||
.cloned()
|
||||
.expect("an item should still be loaded");
|
||||
assert_eq!(
|
||||
current.id, "ep3",
|
||||
"background audio-only episode must advance in the backend, not wait \
|
||||
for a frontend navigation that cannot happen while backgrounded"
|
||||
);
|
||||
assert_eq!(current.media_type, MediaType::Audio);
|
||||
assert!(controller.current_is_audio_episode());
|
||||
}
|
||||
|
||||
/// Foreground video playback keeps the countdown-driven advance: the frontend
|
||||
/// owns the navigation there, so the backend must NOT load the next episode
|
||||
/// itself (that would race the page transition and double-start playback).
|
||||
#[tokio::test]
|
||||
async fn test_auto_advance_foreground_video_episode_uses_countdown() {
|
||||
let controller = PlayerController::default();
|
||||
controller.set_repository(Arc::new(MockEpisodeRepo::season(3)));
|
||||
|
||||
let episode = MediaItem {
|
||||
id: "ep2".to_string(),
|
||||
item_type: Some("Episode".to_string()),
|
||||
media_type: MediaType::Video,
|
||||
series_id: Some("series1".to_string()),
|
||||
source: MediaSource::Remote {
|
||||
stream_url: "http://example.com/ep2.m3u8".to_string(),
|
||||
jellyfin_item_id: "ep2".to_string(),
|
||||
},
|
||||
..create_test_items(1).remove(0)
|
||||
};
|
||||
controller.play_queue(vec![episode], 0).unwrap();
|
||||
|
||||
let next = make_repo_episode("ep3", 3);
|
||||
controller.auto_advance_to_next_episode(next, 10).await;
|
||||
|
||||
let current = controller
|
||||
.queue
|
||||
.lock_safe()
|
||||
.current()
|
||||
.cloned()
|
||||
.expect("an item should still be loaded");
|
||||
assert_eq!(
|
||||
current.id, "ep2",
|
||||
"foreground video advance is frontend-driven; the backend must not \
|
||||
swap the queue item out from under it"
|
||||
);
|
||||
}
|
||||
|
||||
/// Without a controller repository the Android episode path must still
|
||||
/// stop gracefully (previous behavior) rather than error.
|
||||
#[tokio::test]
|
||||
|
||||
@@ -3,7 +3,7 @@ use super::events::{PlayerEventEmitter, PlayerStatusEvent};
|
||||
use super::media::{MediaItem, MediaSource};
|
||||
use super::state::PlayerState;
|
||||
use crate::playback_reporting::{EventThrottler, PlaybackOperation, PlaybackReporter};
|
||||
use crate::settings::AudioSettings;
|
||||
use crate::settings::{AudioSettings, VolumeLevel, EQ_BANDS};
|
||||
use crate::utils::conversions::{seconds_to_ticks, volume_to_percent};
|
||||
use crate::utils::lock::MutexSafe;
|
||||
use libmpv::Mpv;
|
||||
@@ -552,8 +552,19 @@ impl PlayerBackend for MpvBackend {
|
||||
})?;
|
||||
}
|
||||
|
||||
// Audio filter chain: build a single lavfi graph combining the EQ
|
||||
// peaking bands and (optionally) a dynamic loudness normalizer, and
|
||||
// set the `af` property. An empty string clears all filters. Both
|
||||
// features share one `af` graph because MPV exposes a single filter
|
||||
// property. See docs/specs/audio-equalizer.md and IR-020.
|
||||
let af = build_af_filter(settings);
|
||||
self.mpv
|
||||
.set_property("af", af.as_str())
|
||||
.map_err(|e| PlayerError {
|
||||
message: format!("Failed to set audio filters: {:?}", e),
|
||||
})?;
|
||||
|
||||
// TODO: Implement crossfade via MPV audio filters if needed
|
||||
// TODO: Implement volume normalization if needed
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -563,9 +574,200 @@ impl PlayerBackend for MpvBackend {
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the full MPV `af` (audio filter) value from the audio settings.
|
||||
///
|
||||
/// Combines the equalizer peaking bands and the loudness-normalization filter
|
||||
/// into a single `lavfi` graph, because MPV exposes one `af` property. The
|
||||
/// normalizer runs *after* the EQ so it levels the post-EQ signal. Returns an
|
||||
/// empty string when neither feature contributes a filter, which clears `af`.
|
||||
///
|
||||
/// TRACES: UR-027, UR-033 | IR-020, DR-036
|
||||
fn build_af_filter(settings: &AudioSettings) -> String {
|
||||
let mut entries = eq_filter_entries(settings.equalizer_enabled, &settings.equalizer_bands);
|
||||
if let Some(norm) = normalize_filter_entry(settings.normalize_volume, settings.volume_level) {
|
||||
entries.push(norm);
|
||||
}
|
||||
|
||||
if entries.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
format!("lavfi=[{}]", entries.join(","))
|
||||
}
|
||||
|
||||
/// Peaking-EQ filter entries (unwrapped), one ffmpeg `equalizer` (two-pole
|
||||
/// peaking) per band with a non-zero gain, e.g.
|
||||
/// `equalizer=f=31:width_type=o:width=1:g=5`. Returns an empty vec when the EQ
|
||||
/// is disabled or every gain is ~0. Gains are assumed already normalised by
|
||||
/// [`AudioSettings::with_equalizer_normalised`]; bands beyond [`EQ_BANDS`] are
|
||||
/// ignored.
|
||||
///
|
||||
/// TRACES: UR-027 | IR-020
|
||||
fn eq_filter_entries(enabled: bool, bands: &[f32]) -> Vec<String> {
|
||||
if !enabled {
|
||||
return Vec::new();
|
||||
}
|
||||
bands
|
||||
.iter()
|
||||
.zip(EQ_BANDS.iter())
|
||||
.filter(|(gain, _)| gain.abs() >= 0.05) // skip ~0 dB bands
|
||||
.map(|(gain, freq)| {
|
||||
// width_type=o → octave bandwidth; width=1 → one octave per band.
|
||||
format!("equalizer=f={}:width_type=o:width=1:g={}", freq, gain)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Reference peak (`dynaudnorm` `p`, linear amplitude) for the default
|
||||
/// [`VolumeLevel::Normal`] (−14 LUFS) target, leaving −1.2 dB of headroom.
|
||||
const NORMALIZE_REF_PEAK: f32 = 0.87;
|
||||
/// Reference loudness the peak table is anchored at (Normal preset, −14 LUFS).
|
||||
const NORMALIZE_REF_LUFS: f32 = -14.0;
|
||||
|
||||
/// The loudness-normalization filter entry (unwrapped), or `None` when
|
||||
/// normalization is disabled. Uses ffmpeg's `dynaudnorm`, a gentle real-time
|
||||
/// dynamic normalizer that avoids the gain "pumping" `loudnorm`'s single-pass
|
||||
/// mode can produce on very dynamic material.
|
||||
///
|
||||
/// `dynaudnorm` targets a peak amplitude (`p`, linear 0–1), not a LUFS value,
|
||||
/// so the Loud/Normal/Quiet presets become *approximate*: each preset's LUFS
|
||||
/// offset from the Normal reference is applied as a dB offset to the reference
|
||||
/// peak, preserving the Loud > Normal > Quiet ordering. `g=15` (gaussian window
|
||||
/// size) further smooths gain changes; the peak is clamped to a safe (0, 0.99]
|
||||
/// so loud presets never request full-scale.
|
||||
///
|
||||
/// TRACES: UR-033 | DR-036
|
||||
fn normalize_filter_entry(enabled: bool, level: VolumeLevel) -> Option<String> {
|
||||
if !enabled {
|
||||
return None;
|
||||
}
|
||||
// LUFS above the reference → louder → higher peak; each +1 LUFS ≈ +1 dB.
|
||||
let db_offset = level.target_lufs() - NORMALIZE_REF_LUFS;
|
||||
let peak = (NORMALIZE_REF_PEAK * 10f32.powf(db_offset / 20.0)).clamp(0.10, 0.99);
|
||||
// 3 decimals is plenty for a peak target and keeps the filter string stable.
|
||||
Some(format!("dynaudnorm=p={:.3}:g=15", peak))
|
||||
}
|
||||
|
||||
impl Drop for MpvBackend {
|
||||
fn drop(&mut self) {
|
||||
info!("[MpvBackend] Shutting down");
|
||||
// MPV will be automatically cleaned up
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod af_filter_tests {
|
||||
use super::{build_af_filter, eq_filter_entries, normalize_filter_entry};
|
||||
use crate::settings::{AudioSettings, VolumeLevel};
|
||||
|
||||
fn settings() -> AudioSettings {
|
||||
AudioSettings {
|
||||
equalizer_enabled: false,
|
||||
equalizer_bands: vec![0.0; 10],
|
||||
normalize_volume: false,
|
||||
..AudioSettings::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Disabled EQ, or an all-zero curve, produces no EQ entries.
|
||||
///
|
||||
/// TRACES: UR-027 | IR-020 | UT-083
|
||||
#[test]
|
||||
fn test_eq_entries_empty_when_disabled_or_flat() {
|
||||
assert!(eq_filter_entries(false, &[5.0, -3.0, 2.0]).is_empty());
|
||||
assert!(eq_filter_entries(true, &[0.0; 10]).is_empty());
|
||||
// Sub-threshold gains count as flat.
|
||||
assert!(eq_filter_entries(true, &[0.01, -0.02]).is_empty());
|
||||
}
|
||||
|
||||
/// Enabled EQ builds one peaking `equalizer` per non-zero band at the right
|
||||
/// centre frequency and gain, chained inside a single `lavfi` filter.
|
||||
///
|
||||
/// TRACES: UR-027 | IR-020 | UT-084
|
||||
#[test]
|
||||
fn test_eq_filter_builds_lavfi_chain() {
|
||||
// First band (31 Hz) +5 dB, third band (125 Hz) -2 dB, rest flat.
|
||||
let mut s = settings();
|
||||
s.equalizer_enabled = true;
|
||||
s.equalizer_bands = vec![5.0, 0.0, -2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
|
||||
let af = build_af_filter(&s);
|
||||
assert!(af.starts_with("lavfi=["), "wrapped in lavfi: {af}");
|
||||
assert!(af.ends_with("]"));
|
||||
assert!(af.contains("equalizer=f=31:width_type=o:width=1:g=5"));
|
||||
assert!(af.contains("equalizer=f=125:width_type=o:width=1:g=-2"));
|
||||
// Only two bands are non-zero → exactly two peaking filters.
|
||||
assert_eq!(af.matches("equalizer=").count(), 2);
|
||||
}
|
||||
|
||||
/// Disabled normalization yields no filter entry; the combined `af` for a
|
||||
/// fully default (all-off) settings is empty, which clears `af`.
|
||||
///
|
||||
/// TRACES: UR-033 | DR-036 | UT-085
|
||||
#[test]
|
||||
fn test_normalize_disabled_produces_no_filter() {
|
||||
assert!(normalize_filter_entry(false, VolumeLevel::Normal).is_none());
|
||||
assert_eq!(build_af_filter(&settings()), "");
|
||||
}
|
||||
|
||||
/// Enabled normalization emits a `dynaudnorm` filter with a peak target, and
|
||||
/// the peak preserves the Loud > Normal > Quiet ordering.
|
||||
///
|
||||
/// TRACES: UR-033 | DR-036 | UT-086
|
||||
#[test]
|
||||
fn test_normalize_peak_preserves_preset_ordering() {
|
||||
fn peak_of(entry: &str) -> f32 {
|
||||
// "dynaudnorm=p=0.870:g=15" → 0.870
|
||||
entry
|
||||
.split("p=")
|
||||
.nth(1)
|
||||
.and_then(|s| s.split(':').next())
|
||||
.and_then(|s| s.parse().ok())
|
||||
.expect("parseable peak")
|
||||
}
|
||||
|
||||
let loud = normalize_filter_entry(true, VolumeLevel::Loud).unwrap();
|
||||
let normal = normalize_filter_entry(true, VolumeLevel::Normal).unwrap();
|
||||
let quiet = normalize_filter_entry(true, VolumeLevel::Quiet).unwrap();
|
||||
for entry in [&loud, &normal, &quiet] {
|
||||
assert!(
|
||||
entry.starts_with("dynaudnorm="),
|
||||
"dynaudnorm filter: {entry}"
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
peak_of(&loud) > peak_of(&normal) && peak_of(&normal) > peak_of(&quiet),
|
||||
"Loud {} > Normal {} > Quiet {}",
|
||||
peak_of(&loud),
|
||||
peak_of(&normal),
|
||||
peak_of(&quiet),
|
||||
);
|
||||
// Every preset stays within the safe (0, 0.99] clamp.
|
||||
for p in [peak_of(&loud), peak_of(&normal), peak_of(&quiet)] {
|
||||
assert!(p > 0.0 && p <= 0.99, "peak in range: {p}");
|
||||
}
|
||||
|
||||
let mut s = settings();
|
||||
s.normalize_volume = true;
|
||||
s.volume_level = VolumeLevel::Quiet;
|
||||
let af = build_af_filter(&s);
|
||||
assert!(af.starts_with("lavfi=["));
|
||||
assert!(af.contains("dynaudnorm=p="));
|
||||
}
|
||||
|
||||
/// EQ and normalization coexist in one `lavfi` graph, with the normalizer
|
||||
/// placed after the EQ bands so it levels the post-EQ signal.
|
||||
///
|
||||
/// TRACES: UR-027, UR-033 | IR-020, DR-036 | UT-087
|
||||
#[test]
|
||||
fn test_eq_and_normalize_combine_in_order() {
|
||||
let mut s = settings();
|
||||
s.equalizer_enabled = true;
|
||||
s.equalizer_bands = vec![5.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
|
||||
s.normalize_volume = true;
|
||||
s.volume_level = VolumeLevel::Normal;
|
||||
let af = build_af_filter(&s);
|
||||
|
||||
let eq_pos = af.find("equalizer=").expect("has EQ");
|
||||
let norm_pos = af.find("dynaudnorm=").expect("has normalizer");
|
||||
assert!(eq_pos < norm_pos, "normalizer runs after EQ: {af}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
//! Webview audio backend — audio-only playback for platforms without a native
|
||||
//! audio backend (currently Windows).
|
||||
//!
|
||||
//! ## Why this exists
|
||||
//! All *video* already renders through the webview HTML5 `<video>` element on
|
||||
//! every platform (see `VideoPlayer.svelte`); libmpv/ExoPlayer only ever drive
|
||||
//! *audio-only* (music) playback. On Windows there is no native audio backend,
|
||||
//! so `create_player_backend()` used to fall back to `NullBackend` and music was
|
||||
//! silent.
|
||||
//!
|
||||
//! This backend fills that gap without any C dependency (so it still
|
||||
//! cross-compiles from Linux): instead of decoding audio itself, it hands the
|
||||
//! stream URL to a frontend `<audio>` element via a `WebviewAudioLoad` event and
|
||||
//! then drives play/pause/seek/stop through `ControlCommand` events — exactly the
|
||||
//! round-trip the HTML5 video path already uses. The `<audio>` element reports
|
||||
//! its real state/position back through the `player_report_*` commands, so the
|
||||
//! Rust `PlayerController` remains the single source of truth (the controller's
|
||||
//! `report_html5_*` methods fold those reports into the normal event pipeline).
|
||||
//!
|
||||
//! Because the reported state flows through the event pipeline (not through this
|
||||
//! backend's `position()`/`state()` pollers — the timer loop does not poll the
|
||||
//! backend for HTML5-rendered media), this backend only needs to keep a
|
||||
//! best-effort local mirror for direct `player_get_state` queries.
|
||||
//!
|
||||
//! TRACES: UR-003, UR-004, UR-005 | DR-004
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use log::{debug, info};
|
||||
|
||||
use super::backend::{PlayerBackend, PlayerError};
|
||||
use super::events::{PlayerEventEmitter, PlayerStatusEvent};
|
||||
use super::media::{MediaItem, MediaSource};
|
||||
use super::state::PlayerState;
|
||||
use crate::settings::AudioSettings;
|
||||
use crate::utils::lock::MutexSafe;
|
||||
|
||||
/// Extract a webview-playable URL from a media item's source.
|
||||
///
|
||||
/// Remote/DirectUrl are HTTP(S) URLs the `<audio>` element can play directly.
|
||||
/// Local files would need the Tauri asset protocol (`convertFileSrc`) on the
|
||||
/// frontend; for now we pass the path through and let the frontend resolve it.
|
||||
fn stream_url(media: &MediaItem) -> String {
|
||||
match &media.source {
|
||||
MediaSource::Remote { stream_url, .. } => stream_url.clone(),
|
||||
MediaSource::DirectUrl { url } => url.clone(),
|
||||
MediaSource::Local { file_path, .. } => file_path.to_string_lossy().to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
struct InternalState {
|
||||
current_media: Option<MediaItem>,
|
||||
volume: f32,
|
||||
position: f64,
|
||||
duration: Option<f64>,
|
||||
state: PlayerState,
|
||||
audio_settings: AudioSettings,
|
||||
}
|
||||
|
||||
pub struct WebviewAudioBackend {
|
||||
emitter: Arc<dyn PlayerEventEmitter>,
|
||||
state: Arc<std::sync::Mutex<InternalState>>,
|
||||
}
|
||||
|
||||
impl WebviewAudioBackend {
|
||||
pub fn new(emitter: Arc<dyn PlayerEventEmitter>) -> Result<Self, PlayerError> {
|
||||
info!("[WebviewAudioBackend] Initializing (audio renders in webview <audio>)");
|
||||
Ok(Self {
|
||||
emitter,
|
||||
state: Arc::new(std::sync::Mutex::new(InternalState {
|
||||
current_media: None,
|
||||
volume: 1.0,
|
||||
position: 0.0,
|
||||
duration: None,
|
||||
state: PlayerState::Idle,
|
||||
audio_settings: AudioSettings::default(),
|
||||
})),
|
||||
})
|
||||
}
|
||||
|
||||
/// Emit a backend-originated control intent to the active frontend adapter
|
||||
/// (the webview `<audio>` element, via `playerEvents.ts` -> active adapter).
|
||||
fn emit_control(&self, action: &str, position: Option<f64>) {
|
||||
self.emitter.emit(PlayerStatusEvent::ControlCommand {
|
||||
action: action.to_string(),
|
||||
position,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl PlayerBackend for WebviewAudioBackend {
|
||||
fn load(&mut self, media: &MediaItem) -> Result<(), PlayerError> {
|
||||
let url = stream_url(media);
|
||||
info!("[WebviewAudioBackend] load: {} - {}", media.title, url);
|
||||
|
||||
{
|
||||
let mut st = self.state.lock_safe();
|
||||
st.current_media = Some(media.clone());
|
||||
st.position = 0.0;
|
||||
st.duration = media.duration;
|
||||
st.state = PlayerState::Loading {
|
||||
media: media.clone(),
|
||||
};
|
||||
}
|
||||
|
||||
// Hand the URL to the frontend <audio> element. autoplay=true so a plain
|
||||
// load-then-play (the common queue-advance path) starts immediately; an
|
||||
// explicit pause afterwards is still honored via ControlCommand.
|
||||
self.emitter.emit(PlayerStatusEvent::WebviewAudioLoad {
|
||||
url,
|
||||
media_id: media.jellyfin_id().map(|s| s.to_string()),
|
||||
position: 0.0,
|
||||
autoplay: true,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn play(&mut self) -> Result<(), PlayerError> {
|
||||
debug!("[WebviewAudioBackend] play");
|
||||
self.emit_control("play", None);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn pause(&mut self) -> Result<(), PlayerError> {
|
||||
debug!("[WebviewAudioBackend] pause");
|
||||
self.emit_control("pause", None);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn stop(&mut self) -> Result<(), PlayerError> {
|
||||
debug!("[WebviewAudioBackend] stop");
|
||||
{
|
||||
let mut st = self.state.lock_safe();
|
||||
st.current_media = None;
|
||||
st.position = 0.0;
|
||||
st.duration = None;
|
||||
st.state = PlayerState::Idle;
|
||||
}
|
||||
self.emit_control("stop", None);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn seek(&mut self, position: f64) -> Result<(), PlayerError> {
|
||||
debug!("[WebviewAudioBackend] seek: {}", position);
|
||||
self.state.lock_safe().position = position;
|
||||
self.emit_control("seek", Some(position));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_volume(&mut self, volume: f32) -> Result<(), PlayerError> {
|
||||
let clamped = volume.clamp(0.0, 1.0);
|
||||
self.state.lock_safe().volume = clamped;
|
||||
// Volume is applied on the element by the frontend, which observes the
|
||||
// volume via the player store; no dedicated ControlCommand action yet.
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn position(&self) -> f64 {
|
||||
self.state.lock_safe().position
|
||||
}
|
||||
|
||||
fn duration(&self) -> Option<f64> {
|
||||
self.state.lock_safe().duration
|
||||
}
|
||||
|
||||
fn state(&self) -> PlayerState {
|
||||
self.state.lock_safe().state.clone()
|
||||
}
|
||||
|
||||
fn volume(&self) -> f32 {
|
||||
self.state.lock_safe().volume
|
||||
}
|
||||
|
||||
fn set_audio_settings(&mut self, settings: &AudioSettings) -> Result<(), PlayerError> {
|
||||
self.state.lock_safe().audio_settings = settings.clone().with_crossfade_clamped();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn audio_settings(&self) -> AudioSettings {
|
||||
self.state.lock_safe().audio_settings.clone()
|
||||
}
|
||||
}
|
||||
|
||||
// TRACES: UR-003, UR-004, UR-005 | DR-004
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::player::events::PlayerStatusEvent;
|
||||
use crate::player::media::{MediaSource, MediaType};
|
||||
use std::sync::Mutex as StdMutex;
|
||||
|
||||
/// Test emitter that records everything emitted.
|
||||
struct RecordingEmitter {
|
||||
events: Arc<StdMutex<Vec<PlayerStatusEvent>>>,
|
||||
}
|
||||
|
||||
impl PlayerEventEmitter for RecordingEmitter {
|
||||
fn emit(&self, event: PlayerStatusEvent) {
|
||||
self.events.lock().unwrap().push(event);
|
||||
}
|
||||
}
|
||||
|
||||
fn test_media() -> MediaItem {
|
||||
MediaItem {
|
||||
id: "track1".to_string(),
|
||||
title: "Song".to_string(),
|
||||
name: Some("Song".to_string()),
|
||||
artist: Some("Artist".to_string()),
|
||||
album: Some("Album".to_string()),
|
||||
album_name: Some("Album".to_string()),
|
||||
album_id: None,
|
||||
artist_items: None,
|
||||
artists: Some(vec!["Artist".to_string()]),
|
||||
primary_image_tag: None,
|
||||
image_id: None,
|
||||
item_type: Some("Audio".to_string()),
|
||||
playlist_id: None,
|
||||
duration: Some(200.0),
|
||||
artwork_url: None,
|
||||
media_type: MediaType::Audio,
|
||||
source: MediaSource::DirectUrl {
|
||||
url: "http://example.com/song.mp3".to_string(),
|
||||
},
|
||||
video_codec: None,
|
||||
needs_transcoding: false,
|
||||
video_width: None,
|
||||
video_height: None,
|
||||
subtitles: vec![],
|
||||
series_id: None,
|
||||
server_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn backend() -> (WebviewAudioBackend, Arc<StdMutex<Vec<PlayerStatusEvent>>>) {
|
||||
let events = Arc::new(StdMutex::new(Vec::new()));
|
||||
let emitter = Arc::new(RecordingEmitter {
|
||||
events: events.clone(),
|
||||
});
|
||||
(WebviewAudioBackend::new(emitter).unwrap(), events)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_emits_webview_audio_load_with_url() {
|
||||
let (mut b, events) = backend();
|
||||
b.load(&test_media()).unwrap();
|
||||
|
||||
let ev = events.lock().unwrap();
|
||||
let load = ev
|
||||
.iter()
|
||||
.find(|e| matches!(e, PlayerStatusEvent::WebviewAudioLoad { .. }))
|
||||
.expect("WebviewAudioLoad emitted");
|
||||
if let PlayerStatusEvent::WebviewAudioLoad { url, autoplay, .. } = load {
|
||||
assert_eq!(url, "http://example.com/song.mp3");
|
||||
assert!(*autoplay);
|
||||
}
|
||||
assert!(matches!(b.state(), PlayerState::Loading { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pause_and_seek_emit_control_commands() {
|
||||
let (mut b, events) = backend();
|
||||
b.load(&test_media()).unwrap();
|
||||
b.pause().unwrap();
|
||||
b.seek(42.0).unwrap();
|
||||
|
||||
let ev = events.lock().unwrap();
|
||||
assert!(ev.iter().any(|e| matches!(
|
||||
e,
|
||||
PlayerStatusEvent::ControlCommand { action, .. } if action == "pause"
|
||||
)));
|
||||
assert!(ev.iter().any(|e| matches!(
|
||||
e,
|
||||
PlayerStatusEvent::ControlCommand { action, position: Some(p) }
|
||||
if action == "seek" && (*p - 42.0).abs() < f64::EPSILON
|
||||
)));
|
||||
assert_eq!(b.position(), 42.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn volume_is_clamped_and_stored() {
|
||||
let (mut b, _events) = backend();
|
||||
b.set_volume(1.5).unwrap();
|
||||
assert_eq!(b.volume(), 1.0);
|
||||
b.set_volume(-0.2).unwrap();
|
||||
assert_eq!(b.volume(), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stop_resets_to_idle() {
|
||||
let (mut b, _events) = backend();
|
||||
b.load(&test_media()).unwrap();
|
||||
b.stop().unwrap();
|
||||
assert!(matches!(b.state(), PlayerState::Idle));
|
||||
}
|
||||
}
|
||||
@@ -641,6 +641,24 @@ impl MediaRepository for HybridRepository {
|
||||
self.online.get_audio_stream_url(item_id).await
|
||||
}
|
||||
|
||||
async fn get_audio_only_stream_url_for_video(
|
||||
&self,
|
||||
item_id: &str,
|
||||
media_source_id: Option<&str>,
|
||||
start_time_seconds: Option<f64>,
|
||||
audio_stream_index: Option<i32>,
|
||||
) -> Result<String, RepoError> {
|
||||
// Audio-only transcode of a video requires the server - delegate to online.
|
||||
self.online
|
||||
.build_audio_only_stream_url_for_video(
|
||||
item_id,
|
||||
media_source_id,
|
||||
start_time_seconds,
|
||||
audio_stream_index,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn get_live_tv_channels(&self) -> Result<Vec<MediaItem>, RepoError> {
|
||||
// Live TV requires server communication - delegate to online repository
|
||||
self.online.get_live_tv_channels().await
|
||||
@@ -732,6 +750,11 @@ impl MediaRepository for HybridRepository {
|
||||
self.online.unmark_favorite(item_id).await
|
||||
}
|
||||
|
||||
async fn clear_watch_history(&self, item_id: &str) -> Result<(), RepoError> {
|
||||
// Write operations go directly to server
|
||||
self.online.clear_watch_history(item_id).await
|
||||
}
|
||||
|
||||
async fn get_person(&self, person_id: &str) -> Result<MediaItem, RepoError> {
|
||||
let offline = Arc::clone(&self.offline);
|
||||
let online = Arc::clone(&self.online);
|
||||
@@ -1028,6 +1051,16 @@ mod tests {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
async fn get_audio_only_stream_url_for_video(
|
||||
&self,
|
||||
_item_id: &str,
|
||||
_media_source_id: Option<&str>,
|
||||
_start_time_seconds: Option<f64>,
|
||||
_audio_stream_index: Option<i32>,
|
||||
) -> Result<String, RepoError> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
async fn get_live_tv_channels(&self) -> Result<Vec<MediaItem>, RepoError> {
|
||||
unimplemented!()
|
||||
}
|
||||
@@ -1100,6 +1133,10 @@ mod tests {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
async fn clear_watch_history(&self, _item_id: &str) -> Result<(), RepoError> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
async fn get_person(&self, _person_id: &str) -> Result<MediaItem, RepoError> {
|
||||
unimplemented!()
|
||||
}
|
||||
@@ -1276,6 +1313,16 @@ mod tests {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
async fn get_audio_only_stream_url_for_video(
|
||||
&self,
|
||||
_item_id: &str,
|
||||
_media_source_id: Option<&str>,
|
||||
_start_time_seconds: Option<f64>,
|
||||
_audio_stream_index: Option<i32>,
|
||||
) -> Result<String, RepoError> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
async fn get_live_tv_channels(&self) -> Result<Vec<MediaItem>, RepoError> {
|
||||
unimplemented!()
|
||||
}
|
||||
@@ -1348,6 +1395,10 @@ mod tests {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
async fn clear_watch_history(&self, _item_id: &str) -> Result<(), RepoError> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
async fn get_person(&self, _person_id: &str) -> Result<MediaItem, RepoError> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
pub mod hybrid;
|
||||
pub mod offline;
|
||||
pub mod online;
|
||||
pub mod series_progress;
|
||||
pub mod types;
|
||||
|
||||
pub use hybrid::HybridRepository;
|
||||
@@ -117,6 +118,22 @@ pub trait MediaRepository: Send + Sync {
|
||||
/// @req: JA-007 - Get playback info and stream URL
|
||||
async fn get_audio_stream_url(&self, item_id: &str) -> Result<String, RepoError>;
|
||||
|
||||
/// Get an audio-only stream URL for a *video* item (background-audio handoff).
|
||||
///
|
||||
/// Used when autoplay advances to the next episode while the app is playing a
|
||||
/// video in audio-only mode in the background: the backend needs the next
|
||||
/// episode's audio-only URL without any frontend round-trip. Online-only;
|
||||
/// offline/cache repositories return an error.
|
||||
///
|
||||
/// TRACES: UR-040 | JA-032
|
||||
async fn get_audio_only_stream_url_for_video(
|
||||
&self,
|
||||
item_id: &str,
|
||||
media_source_id: Option<&str>,
|
||||
start_time_seconds: Option<f64>,
|
||||
audio_stream_index: Option<i32>,
|
||||
) -> Result<String, RepoError>;
|
||||
|
||||
/// Get Live TV channels (broadcast / IPTV) for browsing.
|
||||
async fn get_live_tv_channels(&self) -> Result<Vec<MediaItem>, RepoError>;
|
||||
|
||||
@@ -195,6 +212,14 @@ pub trait MediaRepository: Send + Sync {
|
||||
/// Unmark item as favorite
|
||||
async fn unmark_favorite(&self, item_id: &str) -> Result<(), RepoError>;
|
||||
|
||||
/// Erase the viewer's watch history for an item: clear its played flag and
|
||||
/// its resume position. On a container (series, season) this applies to
|
||||
/// everything inside it, so a series is returned to "never watched" and
|
||||
/// reopens on its premiere.
|
||||
///
|
||||
/// TRACES: UR-064 | DR-106
|
||||
async fn clear_watch_history(&self, item_id: &str) -> Result<(), RepoError>;
|
||||
|
||||
/// Get person details
|
||||
async fn get_person(&self, person_id: &str) -> Result<MediaItem, RepoError>;
|
||||
|
||||
|
||||
@@ -587,6 +587,18 @@ impl OfflineRepository {
|
||||
String::new()
|
||||
};
|
||||
|
||||
// When the parent is a LIBRARY, cached items carry no link back to it
|
||||
// (library_id/parent_id are NULL), so the `libraries` EXISTS clause below
|
||||
// matches every downloaded item on the server — both containers
|
||||
// (MusicAlbum/Series/…) AND their leaves (Audio/Episode). Listing the
|
||||
// leaves alongside the containers is the "I see individual songs, not
|
||||
// albums" bug: a library landing page must show only *top-level* items.
|
||||
// So at the library level we exclude any leaf whose own container
|
||||
// (album/season/series/parent) is itself present in `downloaded_items` —
|
||||
// that container represents it in the grid. Items with no downloaded
|
||||
// container (e.g. a downloaded Movie, or a stray track whose album isn't
|
||||
// cached) still surface. This mirrors the online music library, which
|
||||
// routes to a dedicated albums view. See [[offline-libraries-never-cached]].
|
||||
let sql = format!(
|
||||
"{cte}
|
||||
SELECT i.id, i.name, i.item_type, i.server_id, i.parent_id, i.library_id, i.overview, i.genres,
|
||||
@@ -599,9 +611,19 @@ impl OfflineRepository {
|
||||
WHERE i.server_id = ?
|
||||
AND (
|
||||
i.parent_id = ? OR i.album_id = ? OR i.season_id = ? OR i.series_id = ?
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM libraries l
|
||||
WHERE l.id = ? AND l.server_id = i.server_id
|
||||
OR (
|
||||
EXISTS (
|
||||
SELECT 1 FROM libraries l
|
||||
WHERE l.id = ? AND l.server_id = i.server_id
|
||||
)
|
||||
-- Top-level only: hide leaves whose container is downloaded.
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM downloaded_items parent
|
||||
WHERE parent.id = i.album_id
|
||||
OR parent.id = i.season_id
|
||||
OR parent.id = i.series_id
|
||||
OR parent.id = i.parent_id
|
||||
)
|
||||
)
|
||||
){type_filter}
|
||||
ORDER BY i.sort_name ASC, i.name ASC
|
||||
@@ -736,17 +758,32 @@ impl OfflineRepository {
|
||||
// descendants that are NOT downloaded. We compare downloaded-descendant
|
||||
// count against total-cached-descendant count (the offline cache holds
|
||||
// the synced full catalog, so this is meaningful).
|
||||
//
|
||||
// Perf: restrict `c` to containers that actually have a completed
|
||||
// download *first* (the CTE), so the OR-based self-join runs over that
|
||||
// handful of rows instead of the entire synced catalog. Without this the
|
||||
// join is an unindexable O(items²) scan and the Downloaded page hangs on
|
||||
// a large library ("Loading your downloads…" forever).
|
||||
let partial_query = Query::with_params(
|
||||
"SELECT c.id,
|
||||
"WITH downloaded_containers AS (
|
||||
SELECT DISTINCT c.id
|
||||
FROM items c
|
||||
INNER JOIN items children
|
||||
ON (children.parent_id = c.id OR children.album_id = c.id OR children.season_id = c.id OR children.series_id = c.id)
|
||||
INNER JOIN downloads d ON children.id = d.item_id
|
||||
WHERE d.status = 'completed'
|
||||
AND c.server_id = ?
|
||||
AND c.item_type IN ('MusicAlbum', 'Series', 'Season', 'BoxSet', 'Folder', 'CollectionFolder')
|
||||
)
|
||||
SELECT c.id,
|
||||
COUNT(children.id) AS total_children,
|
||||
SUM(CASE WHEN d.status = 'completed' THEN 1 ELSE 0 END) AS downloaded_children
|
||||
FROM items c
|
||||
INNER JOIN downloaded_containers dc ON dc.id = c.id
|
||||
INNER JOIN items children
|
||||
ON (children.parent_id = c.id OR children.album_id = c.id OR children.season_id = c.id OR children.series_id = c.id)
|
||||
LEFT JOIN downloads d ON children.id = d.item_id AND d.status = 'completed'
|
||||
WHERE c.server_id = ?
|
||||
AND c.item_type IN ('MusicAlbum', 'Series', 'Season', 'BoxSet', 'Folder', 'CollectionFolder')
|
||||
AND children.item_type IN ('Audio', 'Movie', 'Episode', 'Season')
|
||||
WHERE children.item_type IN ('Audio', 'Movie', 'Episode', 'Season')
|
||||
GROUP BY c.id",
|
||||
vec![QueryParam::String(self.server_id.clone())],
|
||||
);
|
||||
@@ -1481,6 +1518,17 @@ impl MediaRepository for OfflineRepository {
|
||||
Err(RepoError::Offline)
|
||||
}
|
||||
|
||||
async fn get_audio_only_stream_url_for_video(
|
||||
&self,
|
||||
_item_id: &str,
|
||||
_media_source_id: Option<&str>,
|
||||
_start_time_seconds: Option<f64>,
|
||||
_audio_stream_index: Option<i32>,
|
||||
) -> Result<String, RepoError> {
|
||||
// Audio-only transcode requires the server; offline downloads play locally.
|
||||
Err(RepoError::Offline)
|
||||
}
|
||||
|
||||
async fn get_live_tv_channels(&self) -> Result<Vec<MediaItem>, RepoError> {
|
||||
// Live TV is inherently online-only.
|
||||
Err(RepoError::Offline)
|
||||
@@ -1579,6 +1627,12 @@ impl MediaRepository for OfflineRepository {
|
||||
Err(RepoError::Offline)
|
||||
}
|
||||
|
||||
async fn clear_watch_history(&self, _item_id: &str) -> Result<(), RepoError> {
|
||||
// Erasing history has to reach the server to be meaningful — clearing
|
||||
// it only locally would be silently undone by the next sync.
|
||||
Err(RepoError::Offline)
|
||||
}
|
||||
|
||||
async fn get_person(&self, person_id: &str) -> Result<MediaItem, RepoError> {
|
||||
let query = Query::with_params(
|
||||
"SELECT id, name, overview, primary_image_tag
|
||||
@@ -2340,7 +2394,12 @@ mod tests {
|
||||
/// (synced-but-not-downloaded) catalog is revealed. Fixes the bug where
|
||||
/// offline library pages showed every server item regardless of the toggle.
|
||||
///
|
||||
/// TRACES: UR-052 | DR-078 | UT-067
|
||||
/// This is also the backend half of the end-to-end offline-listing scenario
|
||||
/// IT-016: toggle off ⇒ downloaded media only; toggle on ⇒ the cached server
|
||||
/// catalog is additionally revealed (greyed-out in the UI, distinguished by
|
||||
/// the absence of a `downloads` row — see `MediaCard.isServerOnly`).
|
||||
///
|
||||
/// TRACES: UR-052 | DR-078 | UT-067, IT-016
|
||||
#[tokio::test]
|
||||
async fn test_get_items_toggle_gates_synced_catalog() {
|
||||
use crate::storage::db_service::DatabaseService;
|
||||
@@ -2641,7 +2700,7 @@ mod tests {
|
||||
/// UT: downloaded-only browse returns a downloaded leaf AND its container,
|
||||
/// filtered to the requested album parent. A non-downloaded sibling is omitted.
|
||||
///
|
||||
/// TRACES: UR-055 | DR-082, DR-083 | UT-046
|
||||
/// TRACES: UR-055 | DR-082, DR-083 | UT-072
|
||||
#[tokio::test]
|
||||
async fn test_get_downloaded_items_returns_leaf_and_container() {
|
||||
let db = create_test_db();
|
||||
@@ -2659,10 +2718,112 @@ mod tests {
|
||||
assert_eq!(ids, vec!["track-1"], "only the downloaded track is listed");
|
||||
}
|
||||
|
||||
/// Regression: browsing a downloaded *library* (top level) lists containers,
|
||||
/// not their leaves — a music library shows the album, not the individual
|
||||
/// downloaded songs. The leaf is still reachable by drilling into the album.
|
||||
///
|
||||
/// TRACES: UR-055 | DR-082, DR-083 | UT-076
|
||||
#[tokio::test]
|
||||
async fn test_get_downloaded_items_library_lists_albums_not_tracks() {
|
||||
let db = create_test_db();
|
||||
seed_library(&db, "music-lib", "music").await;
|
||||
insert_item(&db, "album-1", "MusicAlbum", None, None, None).await;
|
||||
// Tracks link to the album via album_id (parent_id NULL in the cache).
|
||||
insert_item(&db, "track-1", "Audio", Some("album-1"), None, None).await;
|
||||
insert_item(&db, "track-2", "Audio", Some("album-1"), None, None).await;
|
||||
seed_completed_download(&db, "track-1", 1000).await;
|
||||
seed_completed_download(&db, "track-2", 1000).await;
|
||||
|
||||
let repo = make_repo(&db);
|
||||
|
||||
// Library level: only the album shows, not the two tracks.
|
||||
let at_library = repo.get_downloaded_items("music-lib", None).await.unwrap();
|
||||
let ids: Vec<&str> = at_library.items.iter().map(|i| i.id.as_str()).collect();
|
||||
assert_eq!(
|
||||
ids,
|
||||
vec!["album-1"],
|
||||
"library browse lists the album container, not its tracks"
|
||||
);
|
||||
|
||||
// Drilling into the album still returns the downloaded tracks.
|
||||
let in_album = repo.get_downloaded_items("album-1", None).await.unwrap();
|
||||
let mut track_ids: Vec<&str> = in_album.items.iter().map(|i| i.id.as_str()).collect();
|
||||
track_ids.sort();
|
||||
assert_eq!(track_ids, vec!["track-1", "track-2"]);
|
||||
}
|
||||
|
||||
/// Regression: a downloaded TV library lists the Series, not its Seasons or
|
||||
/// Episodes — the same "individual songs" bug seen for music, for TV. The
|
||||
/// season and episode are still reachable by drilling into the series.
|
||||
///
|
||||
/// TRACES: UR-055 | DR-082, DR-083 | UT-077
|
||||
#[tokio::test]
|
||||
async fn test_get_downloaded_items_library_lists_series_not_episodes() {
|
||||
let db = create_test_db();
|
||||
seed_library(&db, "tv-lib", "tvshows").await;
|
||||
insert_item(&db, "series-1", "Series", None, None, None).await;
|
||||
// Season links to its series; episode links to both season and series.
|
||||
insert_item(&db, "season-1", "Season", None, Some("series-1"), None).await;
|
||||
insert_item(
|
||||
&db,
|
||||
"ep-1",
|
||||
"Episode",
|
||||
None,
|
||||
Some("series-1"),
|
||||
Some("season-1"),
|
||||
)
|
||||
.await;
|
||||
seed_completed_download(&db, "ep-1", 4000).await;
|
||||
|
||||
let repo = make_repo(&db);
|
||||
|
||||
// Library level: only the series shows.
|
||||
let at_library = repo.get_downloaded_items("tv-lib", None).await.unwrap();
|
||||
let ids: Vec<&str> = at_library.items.iter().map(|i| i.id.as_str()).collect();
|
||||
assert_eq!(
|
||||
ids,
|
||||
vec!["series-1"],
|
||||
"TV library browse lists the series, not seasons/episodes"
|
||||
);
|
||||
|
||||
// Drilling into the series returns its season; into the season, the episode.
|
||||
let in_series = repo.get_downloaded_items("series-1", None).await.unwrap();
|
||||
assert!(
|
||||
in_series.items.iter().any(|i| i.id == "season-1"),
|
||||
"series drill returns the season"
|
||||
);
|
||||
let in_season = repo.get_downloaded_items("season-1", None).await.unwrap();
|
||||
assert!(
|
||||
in_season.items.iter().any(|i| i.id == "ep-1"),
|
||||
"season drill returns the episode"
|
||||
);
|
||||
}
|
||||
|
||||
/// A downloaded leaf with no cached container (e.g. a Movie, or a track whose
|
||||
/// album isn't in the cache) still surfaces at the library level.
|
||||
///
|
||||
/// TRACES: UR-055 | DR-082, DR-083 | UT-078
|
||||
#[tokio::test]
|
||||
async fn test_get_downloaded_items_library_keeps_orphan_leaves() {
|
||||
let db = create_test_db();
|
||||
seed_library(&db, "movie-lib", "movies").await;
|
||||
insert_item(&db, "movie-1", "Movie", None, None, None).await;
|
||||
seed_completed_download(&db, "movie-1", 5000).await;
|
||||
|
||||
let repo = make_repo(&db);
|
||||
let at_library = repo.get_downloaded_items("movie-lib", None).await.unwrap();
|
||||
let ids: Vec<&str> = at_library.items.iter().map(|i| i.id.as_str()).collect();
|
||||
assert_eq!(
|
||||
ids,
|
||||
vec!["movie-1"],
|
||||
"a downloaded movie with no container shows"
|
||||
);
|
||||
}
|
||||
|
||||
/// UT: an empty downloaded-only browse is authoritative — no rows, no error,
|
||||
/// regardless of the catalog-browse flag (which the DR-080 fallthrough uses).
|
||||
///
|
||||
/// TRACES: UR-055 | DR-082 | UT-047
|
||||
/// TRACES: UR-055 | DR-082 | UT-073
|
||||
#[tokio::test]
|
||||
async fn test_get_downloaded_items_empty_is_authoritative() {
|
||||
let db = create_test_db();
|
||||
@@ -2681,7 +2842,7 @@ mod tests {
|
||||
|
||||
/// UT: only libraries with downloaded content are listed; an empty one is omitted.
|
||||
///
|
||||
/// TRACES: UR-055 | DR-082 | UT-048
|
||||
/// TRACES: UR-055 | DR-082 | UT-074
|
||||
#[tokio::test]
|
||||
async fn test_get_downloaded_libraries_omits_empty() {
|
||||
let db = create_test_db();
|
||||
@@ -2703,7 +2864,7 @@ mod tests {
|
||||
/// UT: disk usage reports a leaf's own size, a container's summed descendants,
|
||||
/// and reconciles the device total with the sum of leaves.
|
||||
///
|
||||
/// TRACES: UR-056 | DR-085 | UT-049
|
||||
/// TRACES: UR-056 | DR-085 | UT-075
|
||||
#[tokio::test]
|
||||
async fn test_download_disk_usage_aggregates_containers() {
|
||||
let db = create_test_db();
|
||||
|
||||
@@ -450,7 +450,7 @@ impl OnlineRepository {
|
||||
/// `/universal` endpoint (no `.m3u8` in the path) fails its progressive
|
||||
/// loader with `ERROR_CODE_PARSING_CONTAINER_UNSUPPORTED`. mp3 is universally
|
||||
/// decodable and supports mid-stream `StartTimeTicks`.
|
||||
pub async fn get_audio_only_stream_url_for_video(
|
||||
pub async fn build_audio_only_stream_url_for_video(
|
||||
&self,
|
||||
item_id: &str,
|
||||
media_source_id: Option<&str>,
|
||||
@@ -1355,6 +1355,22 @@ impl MediaRepository for OnlineRepository {
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
async fn get_audio_only_stream_url_for_video(
|
||||
&self,
|
||||
item_id: &str,
|
||||
media_source_id: Option<&str>,
|
||||
start_time_seconds: Option<f64>,
|
||||
audio_stream_index: Option<i32>,
|
||||
) -> Result<String, RepoError> {
|
||||
self.build_audio_only_stream_url_for_video(
|
||||
item_id,
|
||||
media_source_id,
|
||||
start_time_seconds,
|
||||
audio_stream_index,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn get_live_tv_channels(&self) -> Result<Vec<MediaItem>, RepoError> {
|
||||
// Live TV channels (broadcast tuners / IPTV M3U). Returned as items with
|
||||
// type "TvChannel" — playable via open_live_stream.
|
||||
@@ -1675,6 +1691,48 @@ impl MediaRepository for OnlineRepository {
|
||||
result
|
||||
}
|
||||
|
||||
/// `DELETE /Users/{userId}/PlayedItems/{itemId}` — Jellyfin's "mark
|
||||
/// unplayed", which also zeroes the resume position. On a folder (series,
|
||||
/// season) the server applies it recursively to the children.
|
||||
///
|
||||
/// TRACES: UR-064 | DR-106, JA-033
|
||||
async fn clear_watch_history(&self, item_id: &str) -> Result<(), RepoError> {
|
||||
let endpoint = format!("/Users/{}/PlayedItems/{}", self.user_id, item_id);
|
||||
let url = format!("{}{}", self.server_url, endpoint);
|
||||
|
||||
let result = async {
|
||||
let request = self
|
||||
.http_client
|
||||
.client
|
||||
.delete(&url)
|
||||
.header("X-Emby-Authorization", self.auth_header())
|
||||
.build()
|
||||
.map_err(|e| RepoError::Network {
|
||||
message: format!("Failed to build request: {}", e),
|
||||
})?;
|
||||
|
||||
let response = self
|
||||
.http_client
|
||||
.request_with_retry(request)
|
||||
.await
|
||||
.map_err(|e| RepoError::Network {
|
||||
message: e.to_string(),
|
||||
})?;
|
||||
|
||||
if !response.status().is_success() {
|
||||
return Err(RepoError::Server {
|
||||
message: format!("HTTP {}", response.status()),
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
|
||||
self.report_outcome(&result).await;
|
||||
result
|
||||
}
|
||||
|
||||
async fn get_person(&self, person_id: &str) -> Result<MediaItem, RepoError> {
|
||||
let endpoint = format!("/Users/{}/Items/{}", self.user_id, person_id);
|
||||
let item: JellyfinItem = self.get_json(&endpoint).await?;
|
||||
|
||||
@@ -0,0 +1,433 @@
|
||||
//! Where a viewer is in a TV series.
|
||||
//!
|
||||
//! This is domain policy, not presentation: it encodes what Jellyfin's user-data
|
||||
//! means ("in progress", "played") and what Jellyfin's season numbering means
|
||||
//! (season 0 is specials). The frontend asks for *the* current episode and
|
||||
//! renders it; it does not get to decide what "current" means.
|
||||
//!
|
||||
//! Split into a pure half (`pick_current_episode`, `sort_series_order`) and an
|
||||
//! I/O half (`fetch_series_episodes`, `resolve_current_episode`) so the policy
|
||||
//! can be unit-tested without standing up a repository.
|
||||
//!
|
||||
//! TRACES: UR-062 | DR-101
|
||||
|
||||
use super::{GetItemsOptions, MediaItem, MediaRepository, RepoError};
|
||||
|
||||
/// Jellyfin files specials under season 0.
|
||||
const SPECIALS_SEASON: i32 = 0;
|
||||
|
||||
/// Below this fraction watched, a position is a false start rather than
|
||||
/// progress — the same threshold the resume dialog uses.
|
||||
const MIN_PROGRESS_FRACTION: f64 = 0.01;
|
||||
|
||||
/// Above this fraction watched, an episode is effectively finished; resuming it
|
||||
/// would drop the viewer into the closing credits.
|
||||
const MAX_PROGRESS_FRACTION: f64 = 0.95;
|
||||
|
||||
/// Sort key for a season number. Specials sort *after* every numbered season:
|
||||
/// a viewer works through S1, S2, … and only then the extras, so season 0 must
|
||||
/// not lead just because `0 < 1`.
|
||||
fn season_rank(season: Option<i32>) -> i64 {
|
||||
match season {
|
||||
Some(SPECIALS_SEASON) => i64::MAX,
|
||||
Some(n) => n as i64,
|
||||
None => i64::MAX - 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Order episodes as the series is watched: season ascending, then episode,
|
||||
/// specials last.
|
||||
pub fn sort_series_order(episodes: &mut [MediaItem]) {
|
||||
episodes.sort_by(|a, b| {
|
||||
season_rank(a.parent_index_number)
|
||||
.cmp(&season_rank(b.parent_index_number))
|
||||
.then(
|
||||
a.index_number
|
||||
.unwrap_or(0)
|
||||
.cmp(&b.index_number.unwrap_or(0)),
|
||||
)
|
||||
});
|
||||
}
|
||||
|
||||
/// Is this episode genuinely part-watched (not a false start, not finished)?
|
||||
fn is_in_progress(item: &MediaItem) -> bool {
|
||||
let Some(user_data) = item.user_data.as_ref() else {
|
||||
return false;
|
||||
};
|
||||
if user_data.is_played.unwrap_or(false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let position_ms = user_data
|
||||
.playback_position_ms
|
||||
.or_else(|| user_data.playback_position_ticks.map(|t| t / 10_000))
|
||||
.unwrap_or(0);
|
||||
if position_ms <= 0 {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Without a duration we cannot tell "2 minutes in" from "2 minutes left",
|
||||
// so any recorded position counts as progress.
|
||||
let Some(duration_ms) = item.duration_ms.filter(|d| *d > 0) else {
|
||||
return true;
|
||||
};
|
||||
|
||||
let fraction = position_ms as f64 / duration_ms as f64;
|
||||
(MIN_PROGRESS_FRACTION..MAX_PROGRESS_FRACTION).contains(&fraction)
|
||||
}
|
||||
|
||||
fn is_played(item: &MediaItem) -> bool {
|
||||
item.user_data
|
||||
.as_ref()
|
||||
.and_then(|u| u.is_played)
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn belongs_to_series(item: &MediaItem, series_id: &str) -> bool {
|
||||
item.series_id.as_deref() == Some(series_id)
|
||||
}
|
||||
|
||||
/// The episode a viewer should land on when they open `series_id`.
|
||||
///
|
||||
/// Order of preference, and why:
|
||||
///
|
||||
/// 1. **An episode in progress.** That is literally where playback stopped;
|
||||
/// Next Up would skip past it. On a tie the earliest in series order wins, so
|
||||
/// a viewer who dipped into a later episode still returns to the one they are
|
||||
/// working through.
|
||||
/// 2. **The server's Next Up** for this series — it accounts for watch history
|
||||
/// we do not cache locally.
|
||||
/// 3. **The first unwatched episode** in series order. This is the offline path:
|
||||
/// `OfflineRepository::get_next_up_episodes` returns an empty vec, so without
|
||||
/// this rung the whole feature would be online-only.
|
||||
/// 4. **The first episode**, so a never-watched series opens on its premiere
|
||||
/// rather than on nothing.
|
||||
///
|
||||
/// `next_up` / `resume` entries are honoured even when absent from `episodes`
|
||||
/// (the season fan-out can miss an id the server returns), but only when they
|
||||
/// belong to this series.
|
||||
pub fn pick_current_episode(
|
||||
series_id: &str,
|
||||
episodes: &[MediaItem],
|
||||
next_up: &[MediaItem],
|
||||
resume: &[MediaItem],
|
||||
) -> Option<MediaItem> {
|
||||
// 1. In progress — prefer a match inside the ordered episode list so the
|
||||
// "earliest in series order" tie-break is meaningful; fall back to the
|
||||
// resume feed for an episode the fan-out missed.
|
||||
if let Some(found) = episodes.iter().find(|e| is_in_progress(e)) {
|
||||
return Some(found.clone());
|
||||
}
|
||||
if let Some(found) = resume
|
||||
.iter()
|
||||
.find(|e| belongs_to_series(e, series_id) && is_in_progress(e))
|
||||
{
|
||||
return Some(found.clone());
|
||||
}
|
||||
|
||||
// 2. Next Up for this series.
|
||||
if let Some(found) = next_up
|
||||
.iter()
|
||||
.find(|e| e.series_id.is_none() || belongs_to_series(e, series_id))
|
||||
{
|
||||
// Prefer the copy from `episodes` when we have one: it carries the
|
||||
// user-data and images the list already fetched.
|
||||
let matched = episodes.iter().find(|e| e.id == found.id);
|
||||
return Some(matched.unwrap_or(found).clone());
|
||||
}
|
||||
|
||||
// 3. First unwatched in series order.
|
||||
if let Some(found) = episodes.iter().find(|e| !is_played(e)) {
|
||||
return Some(found.clone());
|
||||
}
|
||||
|
||||
// 4. First episode — a fully-watched series reopens at the start.
|
||||
episodes.first().cloned()
|
||||
}
|
||||
|
||||
/// Every episode of a series, in series order.
|
||||
///
|
||||
/// Jellyfin hangs episodes off season folders, except for "flat" series whose
|
||||
/// children are episodes directly. Both shapes are provider vocabulary, so the
|
||||
/// fan-out and the fallback live here rather than in the frontend.
|
||||
pub async fn fetch_series_episodes(
|
||||
repo: &dyn MediaRepository,
|
||||
series_id: &str,
|
||||
) -> Result<Vec<MediaItem>, RepoError> {
|
||||
let children = repo.get_items(series_id, list_options()).await?;
|
||||
|
||||
let mut episodes: Vec<MediaItem> = Vec::new();
|
||||
for season in children.items.iter().filter(|i| is_season(i)) {
|
||||
// One failing season must not blank the whole show.
|
||||
match repo.get_items(&season.id, list_options()).await {
|
||||
Ok(result) => episodes.extend(result.items.into_iter().filter(is_episode)),
|
||||
Err(e) => {
|
||||
log::warn!(
|
||||
"[series] season {} of {} failed to load: {:?}",
|
||||
season.id,
|
||||
series_id,
|
||||
e
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Flat series: the children *are* the episodes.
|
||||
if episodes.is_empty() {
|
||||
episodes.extend(children.items.into_iter().filter(is_episode));
|
||||
}
|
||||
|
||||
sort_series_order(&mut episodes);
|
||||
Ok(episodes)
|
||||
}
|
||||
|
||||
/// Resolve the current episode, fetching everything the policy needs.
|
||||
///
|
||||
/// Next Up and resume are best-effort: offline they fail or come back empty, and
|
||||
/// `pick_current_episode` has fallbacks for exactly that.
|
||||
pub async fn resolve_current_episode(
|
||||
repo: &dyn MediaRepository,
|
||||
series_id: &str,
|
||||
) -> Result<Option<MediaItem>, RepoError> {
|
||||
let episodes = fetch_series_episodes(repo, series_id).await?;
|
||||
|
||||
let next_up = repo
|
||||
.get_next_up_episodes(Some(series_id), Some(1))
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
let resume = repo
|
||||
.get_resume_items(Some(series_id), Some(10))
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
|
||||
Ok(pick_current_episode(
|
||||
series_id, &episodes, &next_up, &resume,
|
||||
))
|
||||
}
|
||||
|
||||
fn list_options() -> Option<GetItemsOptions> {
|
||||
Some(GetItemsOptions {
|
||||
limit: Some(500),
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
fn is_season(item: &MediaItem) -> bool {
|
||||
item.item_type == "Season" || matches!(item.kind, crate::domain::MediaKind::Season)
|
||||
}
|
||||
|
||||
fn is_episode(item: &MediaItem) -> bool {
|
||||
item.item_type == "Episode" || matches!(item.kind, crate::domain::MediaKind::Episode)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::repository::UserData;
|
||||
|
||||
const SERIES: &str = "series-1";
|
||||
|
||||
fn episode(id: &str, season: i32, number: i32) -> MediaItem {
|
||||
MediaItem {
|
||||
id: id.to_string(),
|
||||
name: format!("S{season}E{number}"),
|
||||
item_type: "Episode".to_string(),
|
||||
series_id: Some(SERIES.to_string()),
|
||||
parent_index_number: Some(season),
|
||||
index_number: Some(number),
|
||||
duration_ms: Some(1_000_000),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn watched(mut item: MediaItem) -> MediaItem {
|
||||
item.user_data = Some(UserData {
|
||||
is_played: Some(true),
|
||||
..Default::default()
|
||||
});
|
||||
item
|
||||
}
|
||||
|
||||
fn in_progress(mut item: MediaItem, fraction: f64) -> MediaItem {
|
||||
let duration = item.duration_ms.unwrap_or(1_000_000) as f64;
|
||||
item.user_data = Some(UserData {
|
||||
is_played: Some(false),
|
||||
playback_position_ms: Some((duration * fraction) as i64),
|
||||
..Default::default()
|
||||
});
|
||||
item
|
||||
}
|
||||
|
||||
fn season(n: i32, count: i32) -> Vec<MediaItem> {
|
||||
(1..=count)
|
||||
.map(|i| episode(&format!("s{n}e{i}"), n, i))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sorts_by_season_then_episode() {
|
||||
let mut eps = vec![
|
||||
episode("b", 2, 1),
|
||||
episode("d", 1, 10),
|
||||
episode("a", 1, 2),
|
||||
episode("c", 2, 2),
|
||||
];
|
||||
sort_series_order(&mut eps);
|
||||
let ids: Vec<&str> = eps.iter().map(|e| e.id.as_str()).collect();
|
||||
assert_eq!(ids, ["a", "d", "b", "c"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sorts_specials_after_numbered_seasons() {
|
||||
let mut eps = vec![episode("special", 0, 1), episode("premiere", 1, 1)];
|
||||
sort_series_order(&mut eps);
|
||||
let ids: Vec<&str> = eps.iter().map(|e| e.id.as_str()).collect();
|
||||
assert_eq!(ids, ["premiere", "special"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picks_the_in_progress_episode_over_next_up() {
|
||||
let mut eps = season(1, 5);
|
||||
eps[0] = watched(eps[0].clone());
|
||||
eps[1] = in_progress(eps[1].clone(), 0.4);
|
||||
// The server would send us past it; the half-watched episode wins.
|
||||
let next_up = vec![episode("s1e3", 1, 3)];
|
||||
|
||||
let current = pick_current_episode(SERIES, &eps, &next_up, &[]).unwrap();
|
||||
assert_eq!(current.id, "s1e2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picks_the_earliest_in_progress_episode() {
|
||||
let mut eps = season(1, 5);
|
||||
eps[1] = in_progress(eps[1].clone(), 0.3);
|
||||
eps[3] = in_progress(eps[3].clone(), 0.5);
|
||||
|
||||
let current = pick_current_episode(SERIES, &eps, &[], &[]).unwrap();
|
||||
assert_eq!(current.id, "s1e2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_a_false_start_and_a_finished_episode() {
|
||||
let mut eps = season(1, 5);
|
||||
eps[0] = watched(eps[0].clone());
|
||||
eps[1] = in_progress(eps[1].clone(), 0.001); // barely started
|
||||
eps[2] = in_progress(eps[2].clone(), 0.99); // effectively over
|
||||
|
||||
// Neither counts as progress, so Next Up decides.
|
||||
let next_up = vec![episode("s1e4", 1, 4)];
|
||||
let current = pick_current_episode(SERIES, &eps, &next_up, &[]).unwrap();
|
||||
assert_eq!(current.id, "s1e4");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn falls_back_to_next_up_when_nothing_is_in_progress() {
|
||||
let eps = season(1, 5);
|
||||
let next_up = vec![episode("s1e3", 1, 3)];
|
||||
|
||||
let current = pick_current_episode(SERIES, &eps, &next_up, &[]).unwrap();
|
||||
assert_eq!(current.id, "s1e3");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_up_from_another_series_is_ignored() {
|
||||
let eps = season(1, 3);
|
||||
let mut foreign = episode("other-show-ep", 1, 1);
|
||||
foreign.series_id = Some("series-2".to_string());
|
||||
|
||||
let current = pick_current_episode(SERIES, &eps, &[foreign], &[]).unwrap();
|
||||
assert_eq!(current.id, "s1e1");
|
||||
}
|
||||
|
||||
/// The offline path: `OfflineRepository::get_next_up_episodes` returns an
|
||||
/// empty vec, so the first unwatched episode has to carry the feature.
|
||||
#[test]
|
||||
fn falls_back_to_first_unwatched_when_next_up_is_empty() {
|
||||
let mut eps = [season(1, 3), season(2, 3)].concat();
|
||||
for ep in eps.iter_mut().take(4) {
|
||||
*ep = watched(ep.clone());
|
||||
}
|
||||
|
||||
let current = pick_current_episode(SERIES, &eps, &[], &[]).unwrap();
|
||||
assert_eq!(current.id, "s2e2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crosses_a_season_boundary_when_a_season_is_finished() {
|
||||
let mut eps = [season(1, 3), season(2, 3)].concat();
|
||||
for ep in eps.iter_mut().take(3) {
|
||||
*ep = watched(ep.clone());
|
||||
}
|
||||
|
||||
let current = pick_current_episode(SERIES, &eps, &[], &[]).unwrap();
|
||||
assert_eq!(current.id, "s2e1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_never_watched_series_opens_on_its_premiere() {
|
||||
let eps = [season(2, 3), season(1, 3)].concat();
|
||||
let mut ordered = eps.clone();
|
||||
sort_series_order(&mut ordered);
|
||||
|
||||
let current = pick_current_episode(SERIES, &ordered, &[], &[]).unwrap();
|
||||
assert_eq!(current.id, "s1e1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fully_watched_series_reopens_at_the_start() {
|
||||
let eps: Vec<MediaItem> = season(1, 3).into_iter().map(watched).collect();
|
||||
|
||||
let current = pick_current_episode(SERIES, &eps, &[], &[]).unwrap();
|
||||
assert_eq!(current.id, "s1e1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn honours_a_resume_entry_missing_from_the_episode_list() {
|
||||
// Season fan-out returned nothing usable, but the resume feed knows.
|
||||
let resume = vec![in_progress(episode("s3e7", 3, 7), 0.5)];
|
||||
|
||||
let current = pick_current_episode(SERIES, &[], &[], &resume).unwrap();
|
||||
assert_eq!(current.id, "s3e7");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resume_entries_from_other_series_are_ignored() {
|
||||
let mut foreign = in_progress(episode("other", 1, 1), 0.5);
|
||||
foreign.series_id = Some("series-2".to_string());
|
||||
|
||||
assert!(pick_current_episode(SERIES, &[], &[], &[foreign]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_series_with_no_episodes_has_no_current_episode() {
|
||||
assert!(pick_current_episode(SERIES, &[], &[], &[]).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_episode_without_a_duration_still_counts_as_in_progress() {
|
||||
let mut ep = episode("s1e2", 1, 2);
|
||||
ep.duration_ms = None;
|
||||
ep.user_data = Some(UserData {
|
||||
is_played: Some(false),
|
||||
playback_position_ms: Some(120_000),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
let current = pick_current_episode(SERIES, &[episode("s1e1", 1, 1), ep], &[], &[]).unwrap();
|
||||
assert_eq!(current.id, "s1e2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_tick_positions_still_register_as_progress() {
|
||||
let mut ep = episode("s1e2", 1, 2);
|
||||
ep.user_data = Some(UserData {
|
||||
is_played: Some(false),
|
||||
// 400_000 ms expressed in Jellyfin ticks, no ms field.
|
||||
playback_position_ticks: Some(400_000 * 10_000),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
let current = pick_current_episode(SERIES, &[episode("s1e1", 1, 1), ep], &[], &[]).unwrap();
|
||||
assert_eq!(current.id, "s1e2");
|
||||
}
|
||||
}
|
||||
@@ -39,7 +39,7 @@ pub struct Library {
|
||||
}
|
||||
|
||||
/// User-specific data for an item (playback state, favorites, etc.)
|
||||
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
|
||||
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct UserData {
|
||||
/// Legacy Jellyfin resume position in ticks. Being replaced by
|
||||
@@ -294,6 +294,53 @@ pub struct GetItemsOptions {
|
||||
pub genres: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
/// An opaque search scope the frontend selects; Rust owns what it *means*.
|
||||
///
|
||||
/// The expansion table below is Jellyfin domain vocabulary: it changes when
|
||||
/// Jellyfin adds or renames an item type, never when the UI is redesigned. It
|
||||
/// previously lived in the frontend (`searchScope.ts`), which is the boundary
|
||||
/// leak documented in docs/specs/scoped-search-boundary.md. The frontend now
|
||||
/// sends the enum and never names an item type in connection with search.
|
||||
///
|
||||
/// TRACES: UR-049 | DR-063
|
||||
#[derive(specta::Type, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SearchScope {
|
||||
All,
|
||||
Music,
|
||||
Movies,
|
||||
Tv,
|
||||
}
|
||||
|
||||
impl SearchScope {
|
||||
/// The Jellyfin item types this scope requests, or `None` for `All`.
|
||||
///
|
||||
/// `All` returns `None` rather than the union of every listed type on
|
||||
/// purpose: an explicit `includeItemTypes` list filters out anything not
|
||||
/// named in it, so a union would silently drop People, folders and any type
|
||||
/// nobody enumerated. Callers must omit the filter entirely on `None`.
|
||||
///
|
||||
/// TRACES: UR-049 | DR-063
|
||||
pub fn item_types(self) -> Option<Vec<String>> {
|
||||
match self {
|
||||
SearchScope::All => None,
|
||||
SearchScope::Music => Some(
|
||||
["MusicAlbum", "MusicArtist", "Audio", "Playlist"]
|
||||
.into_iter()
|
||||
.map(String::from)
|
||||
.collect(),
|
||||
),
|
||||
SearchScope::Movies => Some(vec!["Movie".to_string()]),
|
||||
SearchScope::Tv => Some(
|
||||
["Series", "Episode"]
|
||||
.into_iter()
|
||||
.map(String::from)
|
||||
.collect(),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Options for search queries
|
||||
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -304,6 +351,28 @@ pub struct SearchOptions {
|
||||
pub include_item_types: Option<Vec<String>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub search_term: Option<String>,
|
||||
/// Opaque scope selected by the UI. When set it **wins** over
|
||||
/// `include_item_types`, which remains for the non-search `get_items`
|
||||
/// callers that legitimately request a single concrete type.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub scope: Option<SearchScope>,
|
||||
}
|
||||
|
||||
impl SearchOptions {
|
||||
/// Expand `scope` into `include_item_types` in place.
|
||||
///
|
||||
/// Call this once, in the search command, *before* dispatching to the
|
||||
/// cache and server paths — both already honour `include_item_types`, and
|
||||
/// resolving in one place keeps online and offline results identical.
|
||||
///
|
||||
/// TRACES: UR-049 | DR-063
|
||||
pub fn resolve_scope(&mut self) {
|
||||
if let Some(scope) = self.scope {
|
||||
// `All` yields None, which clears the filter — the correct
|
||||
// behaviour, not an omission.
|
||||
self.include_item_types = scope.item_types();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Playback information
|
||||
@@ -455,6 +524,131 @@ impl MeaningfulContent for PlaylistCreatedResult {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod search_scope_tests {
|
||||
use super::*;
|
||||
|
||||
/// Music expands to the four Jellyfin types that make up the category.
|
||||
///
|
||||
/// This table is the domain vocabulary that used to live in the frontend
|
||||
/// (`searchScope.ts`'s `SCOPE_ITEM_TYPES`) — the boundary leak that
|
||||
/// docs/specs/scoped-search-boundary.md was written about.
|
||||
///
|
||||
/// @req-test: UT-089 - SearchScope expands to Jellyfin item types
|
||||
#[test]
|
||||
fn music_scope_expands_to_music_item_types() {
|
||||
assert_eq!(
|
||||
SearchScope::Music.item_types(),
|
||||
Some(vec![
|
||||
"MusicAlbum".to_string(),
|
||||
"MusicArtist".to_string(),
|
||||
"Audio".to_string(),
|
||||
"Playlist".to_string(),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
/// @req-test: UT-089 - SearchScope expands to Jellyfin item types
|
||||
#[test]
|
||||
fn movies_scope_expands_to_movie_only() {
|
||||
assert_eq!(
|
||||
SearchScope::Movies.item_types(),
|
||||
Some(vec!["Movie".to_string()])
|
||||
);
|
||||
}
|
||||
|
||||
/// @req-test: UT-089 - SearchScope expands to Jellyfin item types
|
||||
#[test]
|
||||
fn tv_scope_expands_to_series_and_episode() {
|
||||
assert_eq!(
|
||||
SearchScope::Tv.item_types(),
|
||||
Some(vec!["Series".to_string(), "Episode".to_string()])
|
||||
);
|
||||
}
|
||||
|
||||
/// `All` must send NO filter — not the union of the other scopes.
|
||||
///
|
||||
/// Sending a union would silently drop every type nobody enumerated
|
||||
/// (Person, folders, …), which an explicit `includeItemTypes` list filters
|
||||
/// out. This is why `item_types()` returns Option rather than Vec.
|
||||
///
|
||||
/// @req-test: UT-090 - All scope sends no item-type filter
|
||||
#[test]
|
||||
fn all_scope_sends_no_filter() {
|
||||
assert_eq!(SearchScope::All.item_types(), None);
|
||||
}
|
||||
|
||||
/// Scope wins over an explicitly supplied include_item_types.
|
||||
///
|
||||
/// @req-test: UT-091 - Scope takes precedence over include_item_types
|
||||
#[test]
|
||||
fn resolve_scope_overrides_include_item_types() {
|
||||
let mut options = SearchOptions {
|
||||
include_item_types: Some(vec!["Movie".to_string()]),
|
||||
scope: Some(SearchScope::Music),
|
||||
..Default::default()
|
||||
};
|
||||
options.resolve_scope();
|
||||
|
||||
assert_eq!(
|
||||
options.include_item_types,
|
||||
Some(vec![
|
||||
"MusicAlbum".to_string(),
|
||||
"MusicArtist".to_string(),
|
||||
"Audio".to_string(),
|
||||
"Playlist".to_string(),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
/// `All` clears any include_item_types so no filter reaches the query.
|
||||
///
|
||||
/// @req-test: UT-090 - All scope sends no item-type filter
|
||||
#[test]
|
||||
fn resolve_all_scope_clears_include_item_types() {
|
||||
let mut options = SearchOptions {
|
||||
include_item_types: Some(vec!["Movie".to_string()]),
|
||||
scope: Some(SearchScope::All),
|
||||
..Default::default()
|
||||
};
|
||||
options.resolve_scope();
|
||||
|
||||
assert_eq!(options.include_item_types, None);
|
||||
}
|
||||
|
||||
/// With no scope set, include_item_types passes through untouched — the
|
||||
/// non-search `getItems` callers rely on this.
|
||||
///
|
||||
/// @req-test: UT-091 - Scope takes precedence over include_item_types
|
||||
#[test]
|
||||
fn resolve_without_scope_preserves_include_item_types() {
|
||||
let mut options = SearchOptions {
|
||||
include_item_types: Some(vec!["MusicAlbum".to_string()]),
|
||||
scope: None,
|
||||
..Default::default()
|
||||
};
|
||||
options.resolve_scope();
|
||||
|
||||
assert_eq!(
|
||||
options.include_item_types,
|
||||
Some(vec!["MusicAlbum".to_string()])
|
||||
);
|
||||
}
|
||||
|
||||
/// The frontend sends the enum as camelCase over IPC.
|
||||
///
|
||||
/// @req-test: UT-089 - SearchScope expands to Jellyfin item types
|
||||
#[test]
|
||||
fn scope_deserializes_from_camel_case() {
|
||||
let options: SearchOptions =
|
||||
serde_json::from_str(r#"{"scope": "music", "limit": 10}"#).unwrap();
|
||||
assert!(matches!(options.scope, Some(SearchScope::Music)));
|
||||
|
||||
let all: SearchOptions = serde_json::from_str(r#"{"scope": "all"}"#).unwrap();
|
||||
assert!(matches!(all.scope, Some(SearchScope::All)));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
+250
-1
@@ -1,4 +1,4 @@
|
||||
//! TRACES: UR-023, UR-031, UR-032, UR-033 | DR-034, DR-035, DR-036, DR-048
|
||||
//! TRACES: UR-023, UR-027, UR-031, UR-032, UR-033 | DR-030, DR-034, DR-035, DR-036, DR-048, IR-020
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -26,6 +26,67 @@ impl VolumeLevel {
|
||||
}
|
||||
}
|
||||
|
||||
/// Centre frequencies (Hz) of the fixed 10-band ISO equalizer. The band count
|
||||
/// and layout are a property of the audio engine, not the UI — presets and the
|
||||
/// MPV filter are defined against these bands. See docs/specs/audio-equalizer.md.
|
||||
///
|
||||
/// TRACES: UR-027 | DR-030, IR-020
|
||||
pub const EQ_BANDS: [f32; 10] = [
|
||||
31.0, 62.0, 125.0, 250.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0, 16000.0,
|
||||
];
|
||||
/// Minimum per-band gain in dB.
|
||||
pub const EQ_GAIN_MIN: f32 = -12.0;
|
||||
/// Maximum per-band gain in dB.
|
||||
pub const EQ_GAIN_MAX: f32 = 12.0;
|
||||
|
||||
/// Built-in equalizer presets. A preset *is* a gain curve defined by the band
|
||||
/// layout above (a domain concept), not a mere label — the curve numbers live
|
||||
/// in Rust so the frontend never encodes the taxonomy.
|
||||
///
|
||||
/// TRACES: UR-027 | DR-030
|
||||
#[derive(specta::Type, Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum EqPreset {
|
||||
Flat,
|
||||
Rock,
|
||||
Pop,
|
||||
Jazz,
|
||||
Classical,
|
||||
BassBoost,
|
||||
TrebleBoost,
|
||||
Vocal,
|
||||
}
|
||||
|
||||
impl EqPreset {
|
||||
/// All presets, for enumerating the curve table across the IPC boundary.
|
||||
pub const ALL: [EqPreset; 8] = [
|
||||
EqPreset::Flat,
|
||||
EqPreset::Rock,
|
||||
EqPreset::Pop,
|
||||
EqPreset::Jazz,
|
||||
EqPreset::Classical,
|
||||
EqPreset::BassBoost,
|
||||
EqPreset::TrebleBoost,
|
||||
EqPreset::Vocal,
|
||||
];
|
||||
|
||||
/// The 10-band gain curve (dB) for this preset, one entry per [`EQ_BANDS`].
|
||||
/// Curves are conservative (within ±8 dB) so presets stack safely with the
|
||||
/// player volume. Bands: 31 62 125 250 500 1k 2k 4k 8k 16k.
|
||||
pub fn gains(&self) -> [f32; 10] {
|
||||
match self {
|
||||
EqPreset::Flat => [0.0; 10],
|
||||
EqPreset::Rock => [5.0, 4.0, 3.0, 1.0, -1.0, -1.0, 1.0, 3.0, 4.0, 5.0],
|
||||
EqPreset::Pop => [-1.0, 0.0, 2.0, 4.0, 5.0, 4.0, 2.0, 0.0, -1.0, -1.0],
|
||||
EqPreset::Jazz => [3.0, 2.0, 1.0, 2.0, -1.0, -1.0, 0.0, 1.0, 2.0, 3.0],
|
||||
EqPreset::Classical => [4.0, 3.0, 2.0, 1.0, -1.0, -1.0, 0.0, 2.0, 3.0, 4.0],
|
||||
EqPreset::BassBoost => [7.0, 6.0, 5.0, 3.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0],
|
||||
EqPreset::TrebleBoost => [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 3.0, 5.0, 6.0, 7.0],
|
||||
EqPreset::Vocal => [-2.0, -1.0, 0.0, 2.0, 4.0, 5.0, 4.0, 2.0, 0.0, -1.0],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Audio playback settings
|
||||
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -38,6 +99,18 @@ pub struct AudioSettings {
|
||||
pub normalize_volume: bool,
|
||||
/// Target volume level for normalization
|
||||
pub volume_level: VolumeLevel,
|
||||
/// Enable the graphic equalizer. When false, no EQ filter is applied.
|
||||
#[serde(default)]
|
||||
pub equalizer_enabled: bool,
|
||||
/// Per-band gains in dB, one per [`EQ_BANDS`]. Normalised to 10 entries and
|
||||
/// clamped to [`EQ_GAIN_MIN`, `EQ_GAIN_MAX`] via [`Self::with_equalizer_normalised`].
|
||||
#[serde(default = "default_eq_bands")]
|
||||
pub equalizer_bands: Vec<f32>,
|
||||
}
|
||||
|
||||
/// Flat 10-band curve — the default equalizer state.
|
||||
fn default_eq_bands() -> Vec<f32> {
|
||||
vec![0.0; EQ_BANDS.len()]
|
||||
}
|
||||
|
||||
impl Default for AudioSettings {
|
||||
@@ -47,6 +120,8 @@ impl Default for AudioSettings {
|
||||
gapless_playback: true,
|
||||
normalize_volume: false,
|
||||
volume_level: VolumeLevel::Normal,
|
||||
equalizer_enabled: false,
|
||||
equalizer_bands: default_eq_bands(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -57,6 +132,20 @@ impl AudioSettings {
|
||||
self.crossfade_duration = self.crossfade_duration.clamp(0.0, 12.0);
|
||||
self
|
||||
}
|
||||
|
||||
/// Normalise the equalizer band vector to exactly [`EQ_BANDS`]`.len()`
|
||||
/// entries (pad with 0 dB / truncate) and clamp each gain to the valid
|
||||
/// range. Guards against malformed persisted or IPC input.
|
||||
///
|
||||
/// TRACES: UR-027 | DR-030
|
||||
pub fn with_equalizer_normalised(mut self) -> Self {
|
||||
let n = EQ_BANDS.len();
|
||||
self.equalizer_bands.resize(n, 0.0);
|
||||
for g in &mut self.equalizer_bands {
|
||||
*g = g.clamp(EQ_GAIN_MIN, EQ_GAIN_MAX);
|
||||
}
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Video playback settings
|
||||
@@ -90,10 +179,80 @@ impl VideoSettings {
|
||||
}
|
||||
}
|
||||
|
||||
/// Serialise `AudioSettings` into the JSON payload handed to the Android player
|
||||
/// over JNI.
|
||||
///
|
||||
/// Sanitises first (crossfade clamped, band vector normalised) so a malformed
|
||||
/// vector can never reach the Kotlin parser. JSON is used rather than a wide JNI
|
||||
/// signature so that adding a field does not change the method signature — the
|
||||
/// same approach `load()` already uses for subtitles.
|
||||
///
|
||||
/// The emitted keys are camelCase (serde) and `volumeLevel` is lowercase; the
|
||||
/// Kotlin side matches on those literals. Both are pinned by tests.
|
||||
///
|
||||
/// TRACES: UR-027, UR-032, UR-033 | DR-030, DR-035, DR-036
|
||||
pub fn audio_settings_jni_payload(settings: &AudioSettings) -> Result<String, serde_json::Error> {
|
||||
let sanitised = settings
|
||||
.clone()
|
||||
.with_crossfade_clamped()
|
||||
.with_equalizer_normalised();
|
||||
serde_json::to_string(&sanitised)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The JNI payload must sanitise before serialising: an over-long crossfade
|
||||
/// is clamped and a wrong-length band vector is normalised to EQ_BANDS.len().
|
||||
/// Sending raw values would let a malformed vector reach the Kotlin parser.
|
||||
///
|
||||
/// TRACES: UR-027, UR-032, UR-033 | DR-030, DR-035, DR-036 | UT-AUDIO-JNI-1
|
||||
#[test]
|
||||
fn test_audio_settings_jni_payload_is_sanitised() {
|
||||
let settings = AudioSettings {
|
||||
crossfade_duration: 30.0,
|
||||
equalizer_bands: vec![20.0, -30.0],
|
||||
..AudioSettings::default()
|
||||
};
|
||||
|
||||
let json = audio_settings_jni_payload(&settings).expect("serialises");
|
||||
let v: serde_json::Value = serde_json::from_str(&json).expect("valid JSON");
|
||||
|
||||
assert_eq!(v["crossfadeDuration"], 12.0, "crossfade clamped to 12s");
|
||||
|
||||
let bands = v["equalizerBands"].as_array().expect("bands array");
|
||||
assert_eq!(bands.len(), EQ_BANDS.len(), "band vector normalised to 10");
|
||||
assert_eq!(bands[0], EQ_GAIN_MAX as f64, "gain clamped to +12dB");
|
||||
assert_eq!(bands[1], EQ_GAIN_MIN as f64, "gain clamped to -12dB");
|
||||
}
|
||||
|
||||
/// The Kotlin side parses these exact keys. camelCase is what serde emits
|
||||
/// for AudioSettings; a rename here silently breaks the Android parser,
|
||||
/// which is why the contract is pinned by a test rather than by convention.
|
||||
///
|
||||
/// TRACES: UR-027, UR-032, UR-033 | DR-030, DR-035, DR-036 | UT-AUDIO-JNI-2
|
||||
#[test]
|
||||
fn test_audio_settings_jni_payload_key_contract() {
|
||||
let json = audio_settings_jni_payload(&AudioSettings::default()).expect("serialises");
|
||||
let v: serde_json::Value = serde_json::from_str(&json).expect("valid JSON");
|
||||
|
||||
for key in [
|
||||
"crossfadeDuration",
|
||||
"gaplessPlayback",
|
||||
"normalizeVolume",
|
||||
"volumeLevel",
|
||||
"equalizerEnabled",
|
||||
"equalizerBands",
|
||||
] {
|
||||
assert!(v.get(key).is_some(), "JNI payload must carry `{key}`");
|
||||
}
|
||||
|
||||
// VolumeLevel is #[serde(rename_all = "lowercase")]; Kotlin matches on
|
||||
// these literals.
|
||||
assert_eq!(v["volumeLevel"], "normal");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_default_settings() {
|
||||
let settings = AudioSettings::default();
|
||||
@@ -101,6 +260,95 @@ mod tests {
|
||||
assert!(settings.gapless_playback);
|
||||
assert!(!settings.normalize_volume);
|
||||
assert_eq!(settings.volume_level, VolumeLevel::Normal);
|
||||
// Equalizer defaults: disabled and flat.
|
||||
assert!(!settings.equalizer_enabled);
|
||||
assert_eq!(settings.equalizer_bands, vec![0.0; EQ_BANDS.len()]);
|
||||
}
|
||||
|
||||
/// EQ presets each return one gain per band; Flat is all zeros.
|
||||
///
|
||||
/// TRACES: UR-027 | DR-030 | UT-079
|
||||
#[test]
|
||||
fn test_eq_preset_curves() {
|
||||
for preset in EqPreset::ALL {
|
||||
assert_eq!(
|
||||
preset.gains().len(),
|
||||
EQ_BANDS.len(),
|
||||
"preset {:?} must have one gain per band",
|
||||
preset
|
||||
);
|
||||
// Every preset stays within the advertised gain range.
|
||||
for g in preset.gains() {
|
||||
assert!(
|
||||
(EQ_GAIN_MIN..=EQ_GAIN_MAX).contains(&g),
|
||||
"preset {:?} gain {} out of range",
|
||||
preset,
|
||||
g
|
||||
);
|
||||
}
|
||||
}
|
||||
assert_eq!(EqPreset::Flat.gains(), [0.0; 10]);
|
||||
// Bass boost lifts the low bands and leaves the top flat.
|
||||
let bass = EqPreset::BassBoost.gains();
|
||||
assert!(bass[0] > 0.0 && bass[9] == 0.0);
|
||||
}
|
||||
|
||||
/// `with_equalizer_normalised` clamps out-of-range gains and forces the
|
||||
/// band vector to exactly EQ_BANDS.len() (pad short, truncate long).
|
||||
///
|
||||
/// TRACES: UR-027 | DR-030 | UT-080
|
||||
#[test]
|
||||
fn test_eq_normalisation() {
|
||||
// Out-of-range gains are clamped.
|
||||
let s = AudioSettings {
|
||||
equalizer_bands: vec![100.0, -100.0, 3.0],
|
||||
..Default::default()
|
||||
}
|
||||
.with_equalizer_normalised();
|
||||
assert_eq!(s.equalizer_bands.len(), EQ_BANDS.len());
|
||||
assert_eq!(s.equalizer_bands[0], EQ_GAIN_MAX);
|
||||
assert_eq!(s.equalizer_bands[1], EQ_GAIN_MIN);
|
||||
assert_eq!(s.equalizer_bands[2], 3.0);
|
||||
// Short vector padded with 0 dB.
|
||||
assert_eq!(s.equalizer_bands[9], 0.0);
|
||||
|
||||
// Over-long vector truncated.
|
||||
let long = AudioSettings {
|
||||
equalizer_bands: vec![1.0; 20],
|
||||
..Default::default()
|
||||
}
|
||||
.with_equalizer_normalised();
|
||||
assert_eq!(long.equalizer_bands.len(), EQ_BANDS.len());
|
||||
}
|
||||
|
||||
/// Old persisted JSON without the EQ fields loads as disabled + flat.
|
||||
///
|
||||
/// TRACES: UR-027 | DR-030 | UT-081
|
||||
#[test]
|
||||
fn test_audio_settings_eq_backward_compat() {
|
||||
let json = r#"{"crossfadeDuration":0.0,"gaplessPlayback":true,"normalizeVolume":false,"volumeLevel":"normal"}"#;
|
||||
let parsed: AudioSettings = serde_json::from_str(json).unwrap();
|
||||
assert!(!parsed.equalizer_enabled);
|
||||
assert_eq!(parsed.equalizer_bands, vec![0.0; EQ_BANDS.len()]);
|
||||
}
|
||||
|
||||
/// EQ fields serialize as camelCase and round-trip.
|
||||
///
|
||||
/// TRACES: UR-027 | DR-030 | UT-082
|
||||
#[test]
|
||||
fn test_audio_settings_eq_serialization() {
|
||||
let settings = AudioSettings {
|
||||
equalizer_enabled: true,
|
||||
equalizer_bands: EqPreset::Rock.gains().to_vec(),
|
||||
..Default::default()
|
||||
};
|
||||
let json = serde_json::to_string(&settings).unwrap();
|
||||
assert!(json.contains("\"equalizerEnabled\":true"));
|
||||
assert!(json.contains("\"equalizerBands\":"));
|
||||
|
||||
let parsed: AudioSettings = serde_json::from_str(&json).unwrap();
|
||||
assert!(parsed.equalizer_enabled);
|
||||
assert_eq!(parsed.equalizer_bands, EqPreset::Rock.gains().to_vec());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -134,6 +382,7 @@ mod tests {
|
||||
gapless_playback: true,
|
||||
normalize_volume: true,
|
||||
volume_level: VolumeLevel::Loud,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let json = serde_json::to_string(&settings).unwrap();
|
||||
|
||||
@@ -24,6 +24,7 @@ pub const MIGRATIONS: &[(&str, &str)] = &[
|
||||
("017_downloads_resume_url", MIGRATION_017),
|
||||
("018_items_is_folder", MIGRATION_018),
|
||||
("019_genres_cache", MIGRATION_019),
|
||||
("020_items_season_index", MIGRATION_020),
|
||||
];
|
||||
|
||||
/// Initial schema migration
|
||||
@@ -281,6 +282,7 @@ CREATE INDEX IF NOT EXISTS idx_items_parent ON items(parent_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_items_type ON items(item_type);
|
||||
CREATE INDEX IF NOT EXISTS idx_items_album ON items(album_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_items_series ON items(series_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_items_season ON items(season_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_user_data_user ON user_data(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_user_data_item ON user_data(item_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_downloads_status ON downloads(status);
|
||||
@@ -714,3 +716,15 @@ CREATE TABLE IF NOT EXISTS genres (
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_genres_scope ON genres(server_id, library_id);
|
||||
"#;
|
||||
|
||||
/// Migration to index `items.season_id`.
|
||||
///
|
||||
/// Episodes link to their season via `season_id` (parent_id is NULL in the
|
||||
/// cache). The container-rollup queries used by the Downloaded browse and the
|
||||
/// disk-usage aggregation join `children.season_id = c.id`, which without this
|
||||
/// index degrades to an unindexable scan — a large synced catalog then makes
|
||||
/// the Downloaded page hang ("Loading your downloads…"). `parent_id`,
|
||||
/// `album_id`, and `series_id` were already indexed; this closes the gap.
|
||||
const MIGRATION_020: &str = r#"
|
||||
CREATE INDEX IF NOT EXISTS idx_items_season ON items(season_id);
|
||||
"#;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "jellytau",
|
||||
"version": "0.0.16",
|
||||
"version": "0.3.0",
|
||||
"identifier": "com.dtourolle.jellytau",
|
||||
"build": {
|
||||
"beforeDevCommand": "bun run dev",
|
||||
@@ -23,7 +23,7 @@
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"targets": ["deb", "rpm"],
|
||||
"targets": ["deb", "rpm", "nsis"],
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
|
||||
+120
-5
@@ -173,6 +173,16 @@ async playerSetAudioSettings(settings: AudioSettings) : Promise<AudioSettings> {
|
||||
async playerGetAudioSettings() : Promise<AudioSettings> {
|
||||
return await TAURI_INVOKE("player_get_audio_settings");
|
||||
},
|
||||
/**
|
||||
* The built-in equalizer presets and their per-band gain curves (dB), for the
|
||||
* settings UI. The curve numbers are domain data defined by the band layout,
|
||||
* so the frontend reads them here rather than encoding them.
|
||||
*
|
||||
* TRACES: UR-027 | DR-030
|
||||
*/
|
||||
async playerGetEqPresets() : Promise<([EqPreset, number[]])[]> {
|
||||
return await TAURI_INVOKE("player_get_eq_presets");
|
||||
},
|
||||
async playerSetVideoSettings(settings: VideoSettings) : Promise<VideoSettings> {
|
||||
return await TAURI_INVOKE("player_set_video_settings", { settings });
|
||||
},
|
||||
@@ -227,6 +237,8 @@ async playerPlayNextEpisode(item: PlayItemRequest) : Promise<PlayerStatus> {
|
||||
* - Frontend when HTML5 video ends (Linux/desktop) - passes itemId + repositoryHandle for the video
|
||||
* - Frontend when audio track ends via backend event - no itemId/repositoryHandle needed
|
||||
* - Android JNI callback also triggers this logic directly
|
||||
*
|
||||
* TRACES: UR-023, UR-026, UR-040 | DR-047, DR-052
|
||||
*/
|
||||
async playerOnPlaybackEnded(itemId: string | null, repositoryHandle: string | null) : Promise<null> {
|
||||
return await TAURI_INVOKE("player_on_playback_ended", { itemId, repositoryHandle });
|
||||
@@ -1255,6 +1267,46 @@ async repositoryGetResumeItems(handle: string, parentId: string | null, limit: n
|
||||
async repositoryGetNextUpEpisodes(handle: string, seriesId: string | null, limit: number | null) : Promise<MediaItem[]> {
|
||||
return await TAURI_INVOKE("repository_get_next_up_episodes", { handle, seriesId, limit });
|
||||
},
|
||||
/**
|
||||
* Every episode of a series, across all seasons, in series order.
|
||||
*
|
||||
* Jellyfin hangs episodes off season folders — except for "flat" series whose
|
||||
* children are episodes directly. Both shapes are provider vocabulary, so the
|
||||
* fan-out and its fallback live in Rust rather than being reimplemented in the
|
||||
* frontend (which is what it used to do).
|
||||
*
|
||||
* TRACES: UR-062 | DR-101
|
||||
*/
|
||||
async repositoryGetSeriesEpisodes(handle: string, seriesId: string) : Promise<MediaItem[]> {
|
||||
return await TAURI_INVOKE("repository_get_series_episodes", { handle, seriesId });
|
||||
},
|
||||
/**
|
||||
* The episode a viewer should land on when they open a series.
|
||||
*
|
||||
* "Current" is domain policy, not layout: an episode in progress, else the
|
||||
* server's Next Up for the series, else the first unwatched episode, else the
|
||||
* first. The third rung is what makes this work offline, where Next Up is
|
||||
* always empty. Returns `None` only when the series has no episodes at all.
|
||||
*
|
||||
* TRACES: UR-062 | DR-101
|
||||
*/
|
||||
async repositoryGetSeriesCurrentEpisode(handle: string, seriesId: string) : Promise<MediaItem | null> {
|
||||
return await TAURI_INVOKE("repository_get_series_current_episode", { handle, seriesId });
|
||||
},
|
||||
/**
|
||||
* Erase the viewer's watch history for an item.
|
||||
*
|
||||
* Clears the played flag and the resume position; on a series or season the
|
||||
* server applies it to everything inside. A series cleared this way is "never
|
||||
* watched" again, so `repository_get_series_current_episode` returns its
|
||||
* premiere. Requires the server — offline this fails rather than diverging
|
||||
* local state the next sync would overwrite.
|
||||
*
|
||||
* TRACES: UR-064 | DR-106
|
||||
*/
|
||||
async repositoryClearWatchHistory(handle: string, itemId: string) : Promise<null> {
|
||||
return await TAURI_INVOKE("repository_clear_watch_history", { handle, itemId });
|
||||
},
|
||||
/**
|
||||
* Get recently played audio
|
||||
*/
|
||||
@@ -1280,7 +1332,12 @@ async repositoryGetGenres(handle: string, parentId: string | null) : Promise<Gen
|
||||
return await TAURI_INVOKE("repository_get_genres", { handle, parentId });
|
||||
},
|
||||
/**
|
||||
* Search for items
|
||||
* Search for items.
|
||||
*
|
||||
* Resolves `SearchOptions::scope` into concrete Jellyfin item types before
|
||||
* dispatching, so scope taxonomy stays in Rust.
|
||||
*
|
||||
* TRACES: UR-049, UR-050 | DR-063
|
||||
*/
|
||||
async repositorySearch(handle: string, query: string, options: SearchOptions | null, requestId: number) : Promise<SearchResult> {
|
||||
return await TAURI_INVOKE("repository_search", { handle, query, options, requestId });
|
||||
@@ -1570,7 +1627,16 @@ normalizeVolume: boolean;
|
||||
/**
|
||||
* Target volume level for normalization
|
||||
*/
|
||||
volumeLevel: VolumeLevel }
|
||||
volumeLevel: VolumeLevel;
|
||||
/**
|
||||
* Enable the graphic equalizer. When false, no EQ filter is applied.
|
||||
*/
|
||||
equalizerEnabled?: boolean;
|
||||
/**
|
||||
* Per-band gains in dB, one per [`EQ_BANDS`]. Normalised to 10 entries and
|
||||
* clamped to [`EQ_GAIN_MIN`, `EQ_GAIN_MAX`] via [`Self::with_equalizer_normalised`].
|
||||
*/
|
||||
equalizerBands?: number[] }
|
||||
/**
|
||||
* Response for audio track switching operations
|
||||
*/
|
||||
@@ -1746,6 +1812,14 @@ export type DownloadVideoRequest = { itemId: string; userId: string; filePath: s
|
||||
* Enhanced response with pre-computed stats
|
||||
*/
|
||||
export type DownloadsResponse = { downloads: DownloadInfo[]; stats: DownloadStats }
|
||||
/**
|
||||
* Built-in equalizer presets. A preset *is* a gain curve defined by the band
|
||||
* layout above (a domain concept), not a mere label — the curve numbers live
|
||||
* in Rust so the frontend never encodes the taxonomy.
|
||||
*
|
||||
* TRACES: UR-027 | DR-030
|
||||
*/
|
||||
export type EqPreset = "flat" | "rock" | "pop" | "jazz" | "classical" | "bassBoost" | "trebleBoost" | "vocal"
|
||||
/**
|
||||
* Genre
|
||||
*/
|
||||
@@ -2028,7 +2102,18 @@ artist?: string | null; primaryImageTag?: string | null; serverId?: string | nul
|
||||
* handoff so the lockscreen MediaSession advertises a real duration — a
|
||||
* zero-duration session renders no scrubber, even with ACTION_SEEK_TO set.
|
||||
*/
|
||||
durationSeconds?: number | null }
|
||||
durationSeconds?: number | null;
|
||||
/**
|
||||
* Item type (e.g. "Episode", "Movie", "Audio"). Carried through the
|
||||
* background-audio handoff so an episode played as audio-only is still
|
||||
* recognised as an episode by autoplay (UR-040) and advances to the next one.
|
||||
*/
|
||||
itemType?: string | null;
|
||||
/**
|
||||
* Series ID for TV episodes. Needed alongside `item_type` so the backend can
|
||||
* look up the next episode when a background-audio track ends.
|
||||
*/
|
||||
seriesId?: string | null }
|
||||
/**
|
||||
* Queue context for remote transfer - what type of queue is this?
|
||||
*/
|
||||
@@ -2356,7 +2441,19 @@ export type PlayerStatusEvent =
|
||||
* or remote so they can pause/play/seek/stop the webview element.
|
||||
* `playerEvents.ts` routes this to the active PlayerAdapter via the facade.
|
||||
*/
|
||||
{ type: "control_command"; action: string; position: number | null }
|
||||
{ type: "control_command"; action: string; position: number | null } |
|
||||
/**
|
||||
* Ask the frontend webview `<audio>` element to load and play a stream.
|
||||
*
|
||||
* Emitted by `WebviewAudioBackend` on platforms with no native audio
|
||||
* backend (e.g. Windows): audio-only playback is rendered by an `<audio>`
|
||||
* element in the webview, mirroring how all video already renders through
|
||||
* the webview `<video>`. The element then reports its state/position back
|
||||
* through the `player_report_*` commands, so the Rust controller stays the
|
||||
* single source of truth. Subsequent play/pause/seek/stop reach the element
|
||||
* via `ControlCommand`.
|
||||
*/
|
||||
{ type: "webview_audio_load"; url: string; media_id: string | null; position: number; autoplay: boolean }
|
||||
/**
|
||||
* Result of creating a playlist
|
||||
*
|
||||
@@ -2467,11 +2564,29 @@ failed: number }
|
||||
/**
|
||||
* Options for search queries
|
||||
*/
|
||||
export type SearchOptions = { limit?: number | null; includeItemTypes?: string[] | null; searchTerm?: string | null }
|
||||
export type SearchOptions = { limit?: number | null; includeItemTypes?: string[] | null; searchTerm?: string | null;
|
||||
/**
|
||||
* Opaque scope selected by the UI. When set it **wins** over
|
||||
* `include_item_types`, which remains for the non-search `get_items`
|
||||
* callers that legitimately request a single concrete type.
|
||||
*/
|
||||
scope?: SearchScope | null }
|
||||
/**
|
||||
* Search result with pagination
|
||||
*/
|
||||
export type SearchResult = { items: MediaItem[]; totalRecordCount: number }
|
||||
/**
|
||||
* An opaque search scope the frontend selects; Rust owns what it *means*.
|
||||
*
|
||||
* The expansion table below is Jellyfin domain vocabulary: it changes when
|
||||
* Jellyfin adds or renames an item type, never when the UI is redesigned. It
|
||||
* previously lived in the frontend (`searchScope.ts`), which is the boundary
|
||||
* leak documented in docs/specs/scoped-search-boundary.md. The frontend now
|
||||
* sends the enum and never names an item type in connection with search.
|
||||
*
|
||||
* TRACES: UR-049 | DR-063
|
||||
*/
|
||||
export type SearchScope = "all" | "music" | "movies" | "tv"
|
||||
/**
|
||||
* Security status info
|
||||
*/
|
||||
|
||||
@@ -137,6 +137,37 @@ export class RepositoryClient {
|
||||
return commands.repositoryGetNextUpEpisodes(this.ensureHandle(), seriesId ?? null, limit ?? null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Every episode of a series, across all seasons, already in series order.
|
||||
* The backend owns the season fan-out and the flat-series fallback.
|
||||
*
|
||||
* TRACES: UR-062 | DR-101
|
||||
*/
|
||||
async getSeriesEpisodes(seriesId: string): Promise<MediaItem[]> {
|
||||
return commands.repositoryGetSeriesEpisodes(this.ensureHandle(), seriesId);
|
||||
}
|
||||
|
||||
/**
|
||||
* The episode the viewer should land on when opening this series. `null` only
|
||||
* when the series has no episodes.
|
||||
*
|
||||
* TRACES: UR-062 | DR-101
|
||||
*/
|
||||
async getSeriesCurrentEpisode(seriesId: string): Promise<MediaItem | null> {
|
||||
return commands.repositoryGetSeriesCurrentEpisode(this.ensureHandle(), seriesId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Erase watch history for an item. On a series or season the server applies
|
||||
* it to everything inside, so the container returns to "never watched".
|
||||
* Requires the server — this fails offline rather than diverging local state.
|
||||
*
|
||||
* TRACES: UR-064 | DR-106
|
||||
*/
|
||||
async clearWatchHistory(itemId: string): Promise<void> {
|
||||
await commands.repositoryClearWatchHistory(this.ensureHandle(), itemId);
|
||||
}
|
||||
|
||||
async getRecentlyPlayedAudio(limit?: number): Promise<MediaItem[]> {
|
||||
return commands.repositoryGetRecentlyPlayedAudio(this.ensureHandle(), limit ?? null);
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
import { goto } from "$app/navigation";
|
||||
import type { Library, MediaItem } from "$lib/api/types";
|
||||
import LibraryGrid from "$lib/components/library/LibraryGrid.svelte";
|
||||
import { seasonRedirectTarget, episodeFocusHref } from "$lib/components/library/seriesNavigation";
|
||||
import { formatBytes } from "$lib/utils/formatBytes";
|
||||
import {
|
||||
downloadedCatalog,
|
||||
@@ -62,6 +63,16 @@
|
||||
void openLibrary(item as Library);
|
||||
return;
|
||||
}
|
||||
// Seasons and episodes resolve inside their series (DR-103): a season has
|
||||
// no page of its own and an episode is never browsed bare.
|
||||
if (item.kind === "season") {
|
||||
goto(seasonRedirectTarget(item) ?? `/library/${item.id}`);
|
||||
return;
|
||||
}
|
||||
if (item.kind === "episode") {
|
||||
goto(episodeFocusHref(item));
|
||||
return;
|
||||
}
|
||||
goto(`/library/${item.id}`);
|
||||
}
|
||||
|
||||
|
||||
@@ -7,10 +7,11 @@
|
||||
title: string;
|
||||
items: MediaItem[];
|
||||
onItemClick?: (item: MediaItem) => void;
|
||||
onItemLongPress?: (item: MediaItem) => void;
|
||||
showAll?: () => void;
|
||||
}
|
||||
|
||||
let { title, items, onItemClick, showAll }: Props = $props();
|
||||
let { title, items, onItemClick, onItemLongPress, showAll }: Props = $props();
|
||||
|
||||
let scrollContainer: HTMLDivElement | null = $state(null);
|
||||
let showLeftArrow = $state(false);
|
||||
@@ -60,6 +61,7 @@
|
||||
size="medium"
|
||||
showProgress={true}
|
||||
onclick={() => onItemClick?.(item)}
|
||||
onLongPress={onItemLongPress ? () => onItemLongPress(item) : undefined}
|
||||
/>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
<!--
|
||||
Erase watch history for a series or a season.
|
||||
|
||||
The backend does the work (`repository_clear_watch_history` → Jellyfin's
|
||||
mark-unplayed, which is recursive over a container and also zeroes resume
|
||||
positions); this only confirms the intent and reports the outcome. Clearing a
|
||||
series returns it to "never watched", so it reopens on S1E1.
|
||||
|
||||
TRACES: UR-064 | DR-106
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { auth } from "$lib/stores/auth";
|
||||
import { isServerReachable } from "$lib/stores/connectivity";
|
||||
|
||||
interface Props {
|
||||
/** Series or season id to clear. */
|
||||
itemId: string;
|
||||
/** Name shown in the confirm prompt. */
|
||||
itemName: string;
|
||||
/** What is being cleared, for the prompt wording. */
|
||||
scope: "series" | "season";
|
||||
size?: "sm" | "lg";
|
||||
/** Called after a successful clear so the caller can reload. */
|
||||
onCleared?: () => void;
|
||||
}
|
||||
|
||||
let { itemId, itemName, scope, size = "lg", onCleared }: Props = $props();
|
||||
|
||||
let busy = $state(false);
|
||||
|
||||
const label = $derived(scope === "series" ? "Clear history" : "Clear season history");
|
||||
|
||||
async function handleClick() {
|
||||
if (busy) return;
|
||||
|
||||
const subject = scope === "series" ? `all of “${itemName}”` : `“${itemName}”`;
|
||||
// Destructive and not undoable — always ask, even though the server keeps
|
||||
// no undo of its own.
|
||||
if (
|
||||
!confirm(
|
||||
`Erase watch history for ${subject}?\n\n` +
|
||||
"Every episode is marked unwatched and resume positions are cleared. " +
|
||||
"This cannot be undone."
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
busy = true;
|
||||
try {
|
||||
await auth.getRepository().clearWatchHistory(itemId);
|
||||
onCleared?.();
|
||||
} catch (e) {
|
||||
console.error("Failed to clear watch history:", e);
|
||||
alert(
|
||||
`Could not clear watch history: ${e instanceof Error ? e.message : String(e)}`
|
||||
);
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<button
|
||||
onclick={handleClick}
|
||||
disabled={busy || !$isServerReachable}
|
||||
title={$isServerReachable
|
||||
? "Mark everything unwatched and clear resume positions"
|
||||
: "Needs a connection to the server"}
|
||||
class="rounded-lg font-medium flex items-center gap-2 transition-colors
|
||||
bg-[var(--color-surface)] hover:bg-[var(--color-surface-hover)]
|
||||
disabled:opacity-40 disabled:cursor-not-allowed
|
||||
{size === 'lg' ? 'px-6 py-2' : 'px-3 py-1.5 text-sm'}"
|
||||
>
|
||||
{#if busy}
|
||||
<div
|
||||
class="border-2 border-current border-t-transparent rounded-full animate-spin
|
||||
{size === 'lg' ? 'w-5 h-5' : 'w-4 h-4'}"
|
||||
></div>
|
||||
{:else}
|
||||
<svg
|
||||
class={size === "lg" ? "w-5 h-5" : "w-4 h-4"}
|
||||
fill="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
d="M13 3a9 9 0 0 0-9 9H1l3.89 3.89.07.14L9 12H6a7 7 0 1 1 7 7c-1.93
|
||||
0-3.68-.79-4.94-2.06l-1.42 1.42A8.95 8.95 0 0 0 13 21a9 9 0 0 0
|
||||
0-18zm-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8H12z"
|
||||
/>
|
||||
</svg>
|
||||
{/if}
|
||||
{busy ? "Clearing…" : label}
|
||||
</button>
|
||||
@@ -4,6 +4,11 @@
|
||||
import { truncateMiddle } from "$lib/utils/truncateMiddle";
|
||||
import type { MediaItem } from "$lib/api/types";
|
||||
import CachedImage from "$lib/components/common/CachedImage.svelte";
|
||||
import {
|
||||
isCurrentEpisode as isSameEpisode,
|
||||
adjacentEpisodes as computeAdjacent,
|
||||
stripCardLabel,
|
||||
} from "./episodeStrip";
|
||||
|
||||
interface Props {
|
||||
episode: MediaItem;
|
||||
@@ -14,63 +19,12 @@
|
||||
|
||||
let { episode, series, allEpisodes, onBack }: Props = $props();
|
||||
|
||||
// Check if an episode matches the focused episode (by ID or season/episode number)
|
||||
// Pure logic lives in ./episodeStrip.ts (unit-tested). Wrap for local use.
|
||||
function isCurrentEpisode(ep: MediaItem): boolean {
|
||||
if (ep.id === episode.id) return true;
|
||||
// Also match by season/episode number in case IDs differ
|
||||
return ep.parentIndexNumber === episode.parentIndexNumber &&
|
||||
ep.indexNumber === episode.indexNumber;
|
||||
return isSameEpisode(ep, episode);
|
||||
}
|
||||
|
||||
// Find adjacent episodes - use season/episode numbers if ID not found
|
||||
const adjacentEpisodes = $derived(() => {
|
||||
// First, try to find the episode by ID
|
||||
let idx = allEpisodes.findIndex((e) => e.id === episode.id);
|
||||
|
||||
// If not found by ID, try to find by season/episode number
|
||||
if (idx === -1 && episode.parentIndexNumber !== undefined && episode.indexNumber !== undefined) {
|
||||
idx = allEpisodes.findIndex(
|
||||
(e) => e.parentIndexNumber === episode.parentIndexNumber && e.indexNumber === episode.indexNumber
|
||||
);
|
||||
}
|
||||
|
||||
// If still not found, filter to same season and show those centered around the episode number
|
||||
if (idx === -1) {
|
||||
const sameSeasonEpisodes = allEpisodes
|
||||
.filter((e) => e.parentIndexNumber === episode.parentIndexNumber)
|
||||
.sort((a, b) => (a.indexNumber || 0) - (b.indexNumber || 0));
|
||||
|
||||
if (sameSeasonEpisodes.length > 0) {
|
||||
// Find position based on episode number
|
||||
const epNum = episode.indexNumber || 1;
|
||||
const centerIdx = sameSeasonEpisodes.findIndex((e) => (e.indexNumber || 0) >= epNum);
|
||||
const actualIdx = centerIdx === -1 ? sameSeasonEpisodes.length - 1 : centerIdx;
|
||||
const start = Math.max(0, actualIdx - 3);
|
||||
const end = Math.min(sameSeasonEpisodes.length, actualIdx + 7);
|
||||
const result = sameSeasonEpisodes.slice(start, end);
|
||||
|
||||
// Insert the focused episode if not already present (by season/episode number match)
|
||||
const hasCurrentEpisode = result.some(isCurrentEpisode);
|
||||
if (!hasCurrentEpisode) {
|
||||
// Insert at correct position based on episode number
|
||||
const insertIdx = result.findIndex((e) => (e.indexNumber || 0) > epNum);
|
||||
if (insertIdx === -1) {
|
||||
result.push(episode);
|
||||
} else {
|
||||
result.splice(insertIdx, 0, episode);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
// Last resort: return focused episode with first 9 episodes
|
||||
return [episode, ...allEpisodes.slice(0, 9)];
|
||||
}
|
||||
|
||||
// Get 3 before and 6 after (or adjust based on position)
|
||||
const start = Math.max(0, idx - 3);
|
||||
const end = Math.min(allEpisodes.length, idx + 7);
|
||||
return allEpisodes.slice(start, end);
|
||||
});
|
||||
const adjacentEpisodes = $derived(() => computeAdjacent(episode, allEpisodes));
|
||||
|
||||
// Compute best backdrop source (no fetch, pure derivation)
|
||||
const backdropSource = $derived.by(() => {
|
||||
@@ -295,8 +249,8 @@
|
||||
<!-- Episode info -->
|
||||
<div class="mt-2 space-y-1">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="text-[var(--color-jellyfin)] text-sm font-semibold">
|
||||
{ep.indexNumber || 0}.
|
||||
<span class="text-[var(--color-jellyfin)] text-sm font-semibold whitespace-nowrap">
|
||||
{stripCardLabel(ep, episode)}
|
||||
</span>
|
||||
<p class="text-white font-medium truncate {isCurrent ? 'text-yellow-400' : 'group-hover/card:text-[var(--color-jellyfin)]'} transition-colors">
|
||||
{ep.name}
|
||||
|
||||
@@ -10,15 +10,21 @@
|
||||
interface Props {
|
||||
episode: MediaItem;
|
||||
focused?: boolean;
|
||||
/**
|
||||
* This is the episode the viewer is up to. Marked and scrolled to when the
|
||||
* series page opens, so a viewer four seasons deep lands on their place
|
||||
* instead of the top of season 1. TRACES: UR-062 | DR-102
|
||||
*/
|
||||
current?: boolean;
|
||||
onclick?: () => void;
|
||||
}
|
||||
|
||||
let { episode, focused = false, onclick }: Props = $props();
|
||||
let { episode, focused = false, current = false, onclick }: Props = $props();
|
||||
|
||||
let buttonRef: HTMLButtonElement | null = null;
|
||||
|
||||
onMount(() => {
|
||||
if (focused && buttonRef) {
|
||||
if ((focused || current) && buttonRef) {
|
||||
// Scroll into view with some offset from top
|
||||
setTimeout(() => {
|
||||
buttonRef?.scrollIntoView({ behavior: "smooth", block: "center" });
|
||||
@@ -51,7 +57,11 @@
|
||||
<button
|
||||
bind:this={buttonRef}
|
||||
type="button"
|
||||
class="group/row flex gap-4 w-full text-left p-3 rounded-lg hover:bg-[var(--color-surface-hover)] transition-colors {focused ? 'ring-2 ring-[var(--color-jellyfin)] bg-[var(--color-surface)]' : ''}"
|
||||
class="group/row flex gap-4 w-full text-left p-3 rounded-lg hover:bg-[var(--color-surface-hover)] transition-colors {focused
|
||||
? 'ring-2 ring-[var(--color-jellyfin)] bg-[var(--color-surface)]'
|
||||
: current
|
||||
? 'ring-2 ring-yellow-400 bg-[var(--color-surface)]'
|
||||
: ''}"
|
||||
{onclick}
|
||||
>
|
||||
<!-- Thumbnail -->
|
||||
@@ -137,6 +147,13 @@
|
||||
<h3 class="text-white font-medium truncate group-hover/row:text-[var(--color-jellyfin)] transition-colors">
|
||||
{truncateMiddle(episode.name, 56)}
|
||||
</h3>
|
||||
{#if current}
|
||||
<span
|
||||
class="flex-shrink-0 px-2 py-0.5 rounded bg-yellow-400 text-black text-xs font-semibold"
|
||||
>
|
||||
Up next
|
||||
</span>
|
||||
{/if}
|
||||
<!-- Played indicator -->
|
||||
{#if episode.userData?.isPlayed}
|
||||
<svg class="w-4 h-4 flex-shrink-0 text-[var(--color-jellyfin)]" fill="currentColor" viewBox="0 0 24 24">
|
||||
|
||||
@@ -34,9 +34,16 @@
|
||||
|
||||
interface Props {
|
||||
config: GenreConfig;
|
||||
/**
|
||||
* Suppress the back button + title when this renders as a *tab* of a
|
||||
* library page that already has a header. Drilling into a single genre
|
||||
* still shows the header — there the back button is the way out.
|
||||
* TRACES: UR-063 | DR-105
|
||||
*/
|
||||
showHeader?: boolean;
|
||||
}
|
||||
|
||||
let { config }: Props = $props();
|
||||
let { config, showHeader = true }: Props = $props();
|
||||
|
||||
let genres = $state<Genre[]>([]);
|
||||
let filteredGenres = $state<Genre[]>([]);
|
||||
@@ -153,17 +160,20 @@
|
||||
</script>
|
||||
|
||||
<div class="space-y-6">
|
||||
<!-- Header -->
|
||||
<div class="flex items-center gap-4">
|
||||
<BackButton onClick={goBack} label="Back" />
|
||||
<h1 class="text-3xl font-bold text-white">
|
||||
{#if selectedGenre}
|
||||
{selectedGenre.name}
|
||||
{:else}
|
||||
{config.title}
|
||||
{/if}
|
||||
</h1>
|
||||
</div>
|
||||
<!-- Header. Inside a genre the back button is the only way out, so it shows
|
||||
even when the host page suppresses the top-level header. -->
|
||||
{#if showHeader || selectedGenre}
|
||||
<div class="flex items-center gap-4">
|
||||
<BackButton onClick={goBack} label="Back" />
|
||||
<h1 class="text-3xl font-bold text-white">
|
||||
{#if selectedGenre}
|
||||
{selectedGenre.name}
|
||||
{:else}
|
||||
{config.title}
|
||||
{/if}
|
||||
</h1>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if !selectedGenre}
|
||||
<!-- Genre Browser -->
|
||||
|
||||
@@ -41,9 +41,15 @@
|
||||
|
||||
interface Props {
|
||||
config: MediaListConfig;
|
||||
/**
|
||||
* Suppress the back button + title. Set when this renders as a *tab* of a
|
||||
* library page, which already has its own header — two stacked headers and
|
||||
* two back buttons read as two pages. TRACES: UR-063 | DR-105
|
||||
*/
|
||||
showHeader?: boolean;
|
||||
}
|
||||
|
||||
let { config }: Props = $props();
|
||||
let { config, showHeader = true }: Props = $props();
|
||||
|
||||
let items = $state<MediaItem[]>([]);
|
||||
let loading = $state(true);
|
||||
@@ -246,10 +252,12 @@
|
||||
|
||||
<div class="space-y-6">
|
||||
<!-- Header -->
|
||||
<div class="flex items-center gap-4">
|
||||
<BackButton onClick={goBack} label="Back" />
|
||||
<h1 class="text-3xl font-bold text-white">{config.title}</h1>
|
||||
</div>
|
||||
{#if showHeader}
|
||||
<div class="flex items-center gap-4">
|
||||
<BackButton onClick={goBack} label="Back" />
|
||||
<h1 class="text-3xl font-bold text-white">{config.title}</h1>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Search and Sort Bar -->
|
||||
<div class="flex flex-col sm:flex-row gap-4">
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { goto } from "$app/navigation";
|
||||
|
||||
import type { MediaKind } from "$lib/api/types";
|
||||
import { libraryViewUrl } from "$lib/utils/libraryView";
|
||||
|
||||
interface Props {
|
||||
genres: string[];
|
||||
@@ -17,7 +18,9 @@
|
||||
itemKind
|
||||
}: Props = $props();
|
||||
|
||||
// Map the item kind to its genre-browse route
|
||||
// Map the item kind to its genre-browse surface. Video genres are a tab of
|
||||
// the library page now, not a route of their own (DR-105); linking straight
|
||||
// to the tab avoids a redirect hop through the legacy paths.
|
||||
function genreBasePath(kind: MediaKind | undefined): string {
|
||||
switch (kind) {
|
||||
case "album":
|
||||
@@ -28,11 +31,11 @@
|
||||
case "series":
|
||||
case "season":
|
||||
case "episode":
|
||||
return "/library/shows/genres";
|
||||
return libraryViewUrl("/library/tv", "genres");
|
||||
case "movie":
|
||||
return "/library/movies/genres";
|
||||
return libraryViewUrl("/library/movies", "genres");
|
||||
default:
|
||||
return "/library/movies/genres";
|
||||
return libraryViewUrl("/library/movies", "genres");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
<!--
|
||||
Browse / All / Genres for a video library.
|
||||
|
||||
These were three routes per library with names that did not agree across the
|
||||
two libraries; they are now tabs on one route, driven by `?view=` so a tab is
|
||||
linkable and survives a back navigation.
|
||||
|
||||
TRACES: UR-063 | DR-105
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { goto } from "$app/navigation";
|
||||
import { LIBRARY_VIEWS, libraryViewUrl, type LibraryView } from "$lib/utils/libraryView";
|
||||
|
||||
interface Props {
|
||||
/** Route the tabs live on, e.g. `/library/tv`. */
|
||||
basePath: string;
|
||||
active: LibraryView;
|
||||
/** Per-view labels — "All Shows" vs "All Movies". */
|
||||
labels: Record<LibraryView, string>;
|
||||
}
|
||||
|
||||
let { basePath, active, labels }: Props = $props();
|
||||
|
||||
function select(view: LibraryView) {
|
||||
if (view === active) return;
|
||||
// replaceState: switching tabs is not a navigation step worth a back press.
|
||||
goto(libraryViewUrl(basePath, view), { replaceState: true, noScroll: true });
|
||||
}
|
||||
</script>
|
||||
|
||||
<nav class="flex items-center gap-1 px-4" aria-label="Library sections">
|
||||
{#each LIBRARY_VIEWS as view (view)}
|
||||
<button
|
||||
onclick={() => select(view)}
|
||||
aria-current={view === active ? "page" : undefined}
|
||||
class="px-4 py-2 rounded-lg text-sm font-medium transition-colors
|
||||
{view === active
|
||||
? 'bg-[var(--color-jellyfin)] text-white'
|
||||
: 'text-gray-400 hover:text-white hover:bg-white/10'}"
|
||||
>
|
||||
{labels[view]}
|
||||
</button>
|
||||
{/each}
|
||||
</nav>
|
||||
@@ -30,9 +30,69 @@
|
||||
*/
|
||||
onRemove?: () => void;
|
||||
onclick?: () => void;
|
||||
/**
|
||||
* When set, a long press (touch hold / mouse hold) fires this instead of the
|
||||
* regular tap. The tap that would otherwise follow the release is suppressed.
|
||||
* Used on the home page: tap opens the detail page, long-press plays now.
|
||||
* TRACES: UR-058 | DR-087
|
||||
*/
|
||||
onLongPress?: () => void;
|
||||
}
|
||||
|
||||
let { item, size = "medium", showProgress = false, showDownloadStatus = true, sizeLabel, downloadedBadge, onRemove, onclick }: Props = $props();
|
||||
let { item, size = "medium", showProgress = false, showDownloadStatus = true, sizeLabel, downloadedBadge, onRemove, onclick, onLongPress }: Props = $props();
|
||||
|
||||
// Long-press detection. We arm a timer on pointerdown; if it fires before the
|
||||
// pointer is released (or moves too far), we treat it as a long press and set a
|
||||
// flag so the ensuing click is swallowed. Pointer events cover touch + mouse.
|
||||
const LONG_PRESS_MS = 500;
|
||||
const MOVE_CANCEL_PX = 10;
|
||||
let pressTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let longPressFired = false;
|
||||
let pressStartX = 0;
|
||||
let pressStartY = 0;
|
||||
|
||||
function clearPressTimer() {
|
||||
if (pressTimer !== null) {
|
||||
clearTimeout(pressTimer);
|
||||
pressTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function handlePointerDown(e: PointerEvent) {
|
||||
if (!onLongPress || isServerOnly) return;
|
||||
longPressFired = false;
|
||||
pressStartX = e.clientX;
|
||||
pressStartY = e.clientY;
|
||||
clearPressTimer();
|
||||
pressTimer = setTimeout(() => {
|
||||
longPressFired = true;
|
||||
pressTimer = null;
|
||||
onLongPress?.();
|
||||
}, LONG_PRESS_MS);
|
||||
}
|
||||
|
||||
function handlePointerMove(e: PointerEvent) {
|
||||
if (pressTimer === null) return;
|
||||
if (
|
||||
Math.abs(e.clientX - pressStartX) > MOVE_CANCEL_PX ||
|
||||
Math.abs(e.clientY - pressStartY) > MOVE_CANCEL_PX
|
||||
) {
|
||||
clearPressTimer();
|
||||
}
|
||||
}
|
||||
|
||||
function handlePointerUp() {
|
||||
clearPressTimer();
|
||||
}
|
||||
|
||||
function handleClick() {
|
||||
// A long press already handled this interaction; swallow the trailing click.
|
||||
if (longPressFired) {
|
||||
longPressFired = false;
|
||||
return;
|
||||
}
|
||||
onclick?.();
|
||||
}
|
||||
|
||||
// Check if this item is downloaded
|
||||
const downloadInfo = $derived(
|
||||
@@ -150,7 +210,13 @@
|
||||
type={isServerOnly ? undefined : "button"}
|
||||
role={isServerOnly ? "group" : undefined}
|
||||
class="group/card flex flex-col text-left {sizeClasses[size]} flex-shrink-0 transition-transform duration-200 {isServerOnly ? '' : 'hover:scale-105'}"
|
||||
onclick={isServerOnly ? undefined : onclick}
|
||||
style={onLongPress ? "touch-action: manipulation; -webkit-touch-callout: none;" : undefined}
|
||||
onclick={isServerOnly ? undefined : handleClick}
|
||||
onpointerdown={isServerOnly ? undefined : handlePointerDown}
|
||||
onpointermove={isServerOnly ? undefined : handlePointerMove}
|
||||
onpointerup={isServerOnly ? undefined : handlePointerUp}
|
||||
onpointercancel={isServerOnly ? undefined : handlePointerUp}
|
||||
oncontextmenu={onLongPress ? (e: Event) => e.preventDefault() : undefined}
|
||||
>
|
||||
<div class="relative {aspectRatio()} w-full rounded-lg overflow-hidden bg-[var(--color-surface)] shadow-md group-hover/card:shadow-2xl transition-shadow duration-200">
|
||||
<CachedImage
|
||||
|
||||
@@ -1,26 +1,56 @@
|
||||
<!-- TRACES: UR-062, UR-064 | DR-102, DR-103, DR-106, DR-107 -->
|
||||
<script lang="ts">
|
||||
import type { MediaItem } from "$lib/api/types";
|
||||
import EpisodeRow from "./EpisodeRow.svelte";
|
||||
import SeasonDownloadButton from "./SeasonDownloadButton.svelte";
|
||||
import ClearHistoryButton from "./ClearHistoryButton.svelte";
|
||||
import CachedImage from "$lib/components/common/CachedImage.svelte";
|
||||
import { seasonAnchorId } from "./seriesNavigation";
|
||||
|
||||
interface Props {
|
||||
season: MediaItem;
|
||||
episodes: MediaItem[];
|
||||
focusedEpisodeId?: string;
|
||||
/** The episode the viewer is up to — highlighted and scrolled into view. */
|
||||
currentEpisodeId?: string;
|
||||
/**
|
||||
* Whether this season's episode list is open. Only the current season
|
||||
* starts expanded, so a ten-season show does not render every episode at
|
||||
* once. TRACES: UR-062 | DR-107
|
||||
*/
|
||||
expanded?: boolean;
|
||||
onToggle?: () => void;
|
||||
onEpisodeClick?: (episode: MediaItem) => void;
|
||||
onHistoryCleared?: () => void;
|
||||
}
|
||||
|
||||
let { season, episodes, focusedEpisodeId, onEpisodeClick }: Props = $props();
|
||||
let {
|
||||
season,
|
||||
episodes,
|
||||
focusedEpisodeId,
|
||||
currentEpisodeId,
|
||||
expanded = false,
|
||||
onToggle,
|
||||
onEpisodeClick,
|
||||
onHistoryCleared,
|
||||
}: Props = $props();
|
||||
|
||||
const holdsCurrentEpisode = $derived(
|
||||
currentEpisodeId != null && episodes.some((e) => e.id === currentEpisodeId)
|
||||
);
|
||||
const watchedCount = $derived(episodes.filter((e) => e.userData?.isPlayed).length);
|
||||
|
||||
const episodeCount = $derived(episodes.length);
|
||||
const seasonNumber = $derived(season.indexNumber || season.parentIndexNumber);
|
||||
const seasonNumber = $derived(season.indexNumber ?? season.parentIndexNumber);
|
||||
const seasonName = $derived(
|
||||
season.name || (seasonNumber ? `Season ${seasonNumber}` : "Unknown Season")
|
||||
season.name || (seasonNumber != null ? `Season ${seasonNumber}` : "Unknown Season")
|
||||
);
|
||||
// Seasons have no page of their own; a season link scrolls to this anchor
|
||||
// inside the series' single continuous episode list.
|
||||
const anchor = $derived(seasonAnchorId(seasonNumber));
|
||||
</script>
|
||||
|
||||
<section class="space-y-4">
|
||||
<section class="space-y-4 scroll-mt-4" id={anchor}>
|
||||
<!-- Season header -->
|
||||
<div class="flex gap-4 p-4 bg-[var(--color-surface)] rounded-xl">
|
||||
<!-- Season poster -->
|
||||
@@ -38,28 +68,60 @@
|
||||
<!-- Season info -->
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="flex items-start justify-between gap-4">
|
||||
<div class="flex-1 min-w-0">
|
||||
<h2 class="text-xl font-bold text-white">
|
||||
{seasonName}
|
||||
<!-- The whole title block toggles the season open/closed. -->
|
||||
<button
|
||||
type="button"
|
||||
onclick={onToggle}
|
||||
aria-expanded={expanded}
|
||||
aria-controls="{anchor}-episodes"
|
||||
class="flex-1 min-w-0 text-left group/season"
|
||||
>
|
||||
<h2 class="text-xl font-bold text-white flex items-center gap-2">
|
||||
<svg
|
||||
class="w-5 h-5 flex-shrink-0 text-gray-400 transition-transform duration-200
|
||||
group-hover/season:text-white {expanded ? 'rotate-90' : ''}"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
viewBox="0 0 24 24"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7" />
|
||||
</svg>
|
||||
<span class="truncate">{seasonName}</span>
|
||||
{#if holdsCurrentEpisode}
|
||||
<span
|
||||
class="flex-shrink-0 px-2 py-0.5 rounded bg-yellow-400 text-black text-xs font-semibold"
|
||||
>
|
||||
Up next
|
||||
</span>
|
||||
{/if}
|
||||
</h2>
|
||||
|
||||
<div class="flex items-center gap-3 mt-1 text-sm text-gray-400">
|
||||
<div class="flex items-center gap-3 mt-1 text-sm text-gray-400 pl-7">
|
||||
<span>{episodeCount} {episodeCount === 1 ? "Episode" : "Episodes"}</span>
|
||||
<!-- Collapsed, this is the only progress signal the season shows. -->
|
||||
{#if watchedCount > 0}
|
||||
<span>•</span>
|
||||
<span>
|
||||
{watchedCount === episodeCount ? "Watched" : `${watchedCount} watched`}
|
||||
</span>
|
||||
{/if}
|
||||
{#if season.productionYear}
|
||||
<span>•</span>
|
||||
<span>{season.productionYear}</span>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if season.overview}
|
||||
<p class="text-gray-400 text-sm mt-3 line-clamp-3">
|
||||
{#if season.overview && expanded}
|
||||
<p class="text-gray-400 text-sm mt-3 line-clamp-3 pl-7">
|
||||
{season.overview}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<!-- Download Season Button -->
|
||||
<div class="flex-shrink-0">
|
||||
<!-- Per-season actions -->
|
||||
<div class="flex-shrink-0 flex items-center gap-2">
|
||||
<SeasonDownloadButton
|
||||
seasonId={season.id}
|
||||
seriesName={season.seriesName || ""}
|
||||
@@ -68,19 +130,29 @@
|
||||
{episodeCount}
|
||||
size="sm"
|
||||
/>
|
||||
<ClearHistoryButton
|
||||
itemId={season.id}
|
||||
itemName={seasonName}
|
||||
scope="season"
|
||||
size="sm"
|
||||
onCleared={onHistoryCleared}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Episode list -->
|
||||
<div class="space-y-1 pl-2">
|
||||
{#each episodes as episode (episode.id)}
|
||||
<EpisodeRow
|
||||
{episode}
|
||||
focused={episode.id === focusedEpisodeId}
|
||||
onclick={() => onEpisodeClick?.(episode)}
|
||||
/>
|
||||
{/each}
|
||||
</div>
|
||||
{#if expanded}
|
||||
<div class="space-y-1 pl-2" id="{anchor}-episodes">
|
||||
{#each episodes as episode (episode.id)}
|
||||
<EpisodeRow
|
||||
{episode}
|
||||
focused={episode.id === focusedEpisodeId}
|
||||
current={episode.id === currentEpisodeId}
|
||||
onclick={() => onEpisodeClick?.(episode)}
|
||||
/>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</section>
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import type { MediaItem } from "$lib/api/types";
|
||||
import { isCurrentEpisode, adjacentEpisodes, compareSeriesOrder, stripCardLabel } from "./episodeStrip";
|
||||
|
||||
// Minimal episode factory — only the fields the strip logic reads.
|
||||
function ep(
|
||||
id: string,
|
||||
season: number | null,
|
||||
number: number | null,
|
||||
): MediaItem {
|
||||
return {
|
||||
id,
|
||||
name: `S${season}E${number}`,
|
||||
kind: "episode",
|
||||
parentIndexNumber: season,
|
||||
indexNumber: number,
|
||||
} as unknown as MediaItem;
|
||||
}
|
||||
|
||||
function season(n: number, count: number): MediaItem[] {
|
||||
return Array.from({ length: count }, (_, i) => ep(`s${n}e${i + 1}`, n, i + 1));
|
||||
}
|
||||
|
||||
describe("isCurrentEpisode", () => {
|
||||
const current = ep("abc", 1, 3);
|
||||
|
||||
it("matches by id", () => {
|
||||
expect(isCurrentEpisode(ep("abc", 9, 9), current)).toBe(true);
|
||||
});
|
||||
|
||||
it("matches by season+episode number when id differs", () => {
|
||||
expect(isCurrentEpisode(ep("other", 1, 3), current)).toBe(true);
|
||||
});
|
||||
|
||||
it("does not match a different episode number", () => {
|
||||
expect(isCurrentEpisode(ep("other", 1, 4), current)).toBe(false);
|
||||
});
|
||||
|
||||
it("does NOT treat two number-less episodes as the same (the reported bug)", () => {
|
||||
const a = ep("a", null, null);
|
||||
const b = ep("b", null, null);
|
||||
expect(isCurrentEpisode(a, b)).toBe(false);
|
||||
});
|
||||
|
||||
it("does not match when only one side has numbers", () => {
|
||||
expect(isCurrentEpisode(ep("a", null, null), current)).toBe(false);
|
||||
expect(isCurrentEpisode(ep("a", 1, 3), ep("b", null, null))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("adjacentEpisodes", () => {
|
||||
it("returns just the current episode when there are no others", () => {
|
||||
const current = ep("only", 1, 1);
|
||||
expect(adjacentEpisodes(current, [])).toEqual([current]);
|
||||
});
|
||||
|
||||
it("returns siblings, not just the current episode", () => {
|
||||
const eps = season(1, 8);
|
||||
const current = eps[2]; // S1E3
|
||||
const strip = adjacentEpisodes(current, eps);
|
||||
expect(strip.length).toBeGreaterThan(1);
|
||||
expect(strip).toContain(current);
|
||||
});
|
||||
|
||||
it("windows to 3 before and 6 after the current episode", () => {
|
||||
const eps = season(1, 20);
|
||||
const current = eps[9]; // S1E10, index 9
|
||||
const strip = adjacentEpisodes(current, eps);
|
||||
// start = max(0, 9-3)=6 (E7), end = min(20, 9+7)=16 → E7..E16 (10 items)
|
||||
expect(strip.map((e) => e.indexNumber)).toEqual([7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
|
||||
expect(strip).toContain(current);
|
||||
});
|
||||
|
||||
// ux-flows §5B.2, "Cross-season continuity": the window spans the whole
|
||||
// series in episode order, so it runs past a season boundary rather than
|
||||
// dead-ending at the end of a season.
|
||||
it("runs past the end of a season into the next one", () => {
|
||||
const eps = [...season(1, 5), ...season(2, 5)];
|
||||
const current = eps[4]; // S1E5 — the season finale
|
||||
const strip = adjacentEpisodes(current, eps);
|
||||
expect(strip.map((e) => e.id)).toEqual([
|
||||
"s1e2", "s1e3", "s1e4", "s1e5",
|
||||
"s2e1", "s2e2", "s2e3", "s2e4", "s2e5",
|
||||
]);
|
||||
});
|
||||
|
||||
it("reaches back into the previous season from a season opener", () => {
|
||||
const eps = [...season(1, 5), ...season(2, 5)];
|
||||
const current = eps[5]; // S2E1
|
||||
const strip = adjacentEpisodes(current, eps);
|
||||
expect(strip.slice(0, 3).map((e) => e.id)).toEqual(["s1e3", "s1e4", "s1e5"]);
|
||||
expect(strip[3].id).toBe("s2e1");
|
||||
});
|
||||
|
||||
it("orders by season then episode, never interleaving seasons", () => {
|
||||
const eps = [...season(2, 3), ...season(1, 3)]; // deliberately out of order
|
||||
const current = eps[3]; // S1E1
|
||||
const strip = adjacentEpisodes(current, eps);
|
||||
expect(strip.map((e) => e.id)).toEqual([
|
||||
"s1e1", "s1e2", "s1e3", "s2e1", "s2e2", "s2e3",
|
||||
]);
|
||||
});
|
||||
|
||||
it("sorts specials (season 0) after the numbered seasons", () => {
|
||||
const eps = [...season(0, 2), ...season(1, 2)];
|
||||
const current = eps[2]; // S1E1
|
||||
const strip = adjacentEpisodes(current, eps);
|
||||
expect(strip.map((e) => e.id)).toEqual(["s1e1", "s1e2", "s0e1", "s0e2"]);
|
||||
});
|
||||
|
||||
it("splices in a directly-fetched episode absent from the list (ID mismatch)", () => {
|
||||
const eps = season(1, 5);
|
||||
// Focused episode has a different id than any in the list but same numbers.
|
||||
const current = ep("fetched-directly", 1, 3);
|
||||
const strip = adjacentEpisodes(current, eps);
|
||||
// It should appear once, anchored at its numeric position, alongside siblings.
|
||||
expect(strip.filter((e) => e.indexNumber === 3).length).toBe(1);
|
||||
expect(strip.length).toBeGreaterThan(1);
|
||||
});
|
||||
|
||||
it("falls back to the full list when the current season is unknown", () => {
|
||||
const eps = season(1, 5);
|
||||
const current = ep("mystery", null, 3); // no season number
|
||||
const strip = adjacentEpisodes(current, eps);
|
||||
expect(strip.length).toBeGreaterThan(1);
|
||||
// Anchored at its episode number, not dumped at one end of the list.
|
||||
expect(strip.indexOf(current)).toBeGreaterThan(0);
|
||||
expect(strip.indexOf(current)).toBeLessThan(strip.length - 1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("compareSeriesOrder", () => {
|
||||
it("orders by season, then episode", () => {
|
||||
expect(compareSeriesOrder(ep("a", 1, 9), ep("b", 2, 1))).toBeLessThan(0);
|
||||
expect(compareSeriesOrder(ep("a", 2, 1), ep("b", 2, 2))).toBeLessThan(0);
|
||||
expect(compareSeriesOrder(ep("a", 2, 2), ep("b", 2, 2))).toBe(0);
|
||||
});
|
||||
|
||||
it("puts specials last", () => {
|
||||
expect(compareSeriesOrder(ep("a", 0, 1), ep("b", 1, 1))).toBeGreaterThan(0);
|
||||
expect(compareSeriesOrder(ep("a", 0, 1), ep("b", 9, 1))).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("falls back to episode number when a season is unknown", () => {
|
||||
expect(compareSeriesOrder(ep("a", null, 2), ep("b", 1, 5))).toBeLessThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("stripCardLabel", () => {
|
||||
const current = ep("cur", 2, 4);
|
||||
|
||||
it("shows a bare episode number within the current season", () => {
|
||||
expect(stripCardLabel(ep("a", 2, 6), current)).toBe("6.");
|
||||
});
|
||||
|
||||
it("shows SxEy once the card crosses a season boundary", () => {
|
||||
expect(stripCardLabel(ep("a", 3, 1), current)).toBe("S3E1");
|
||||
expect(stripCardLabel(ep("a", 1, 8), current)).toBe("S1E8");
|
||||
});
|
||||
|
||||
it("degrades to the episode number when the season is unknown", () => {
|
||||
expect(stripCardLabel(ep("a", null, 7), current)).toBe("7.");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,110 @@
|
||||
// Pure logic for the "More Episodes" strip in EpisodeFocusView.
|
||||
//
|
||||
// Extracted from the component so it can be unit-tested: the strip must never
|
||||
// collapse to just the current episode while real siblings exist, must not
|
||||
// mistake number-less episodes for the current one, and must run past a season
|
||||
// boundary rather than dead-ending at the end of a season (ux-flows §5B.2).
|
||||
//
|
||||
// TRACES: UR-048, UR-062 | DR-062, DR-104
|
||||
import type { MediaItem } from "$lib/api/types";
|
||||
|
||||
/** Episodes shown before / after the current one in the strip window. */
|
||||
const BEFORE = 3;
|
||||
const AFTER = 6;
|
||||
|
||||
/** Jellyfin puts specials in season 0; they air outside the numbered run. */
|
||||
const SPECIALS_SEASON = 0;
|
||||
|
||||
/**
|
||||
* Does `ep` refer to the same episode as `current`?
|
||||
*
|
||||
* Matches by id first. Falls back to season+episode number, but ONLY when both
|
||||
* numbers are known on both sides — otherwise `undefined === undefined` would
|
||||
* mark every number-less episode as the current one (the bug that made the
|
||||
* whole strip look like the current episode).
|
||||
*/
|
||||
export function isCurrentEpisode(ep: MediaItem, current: MediaItem): boolean {
|
||||
if (ep.id === current.id) return true;
|
||||
if (
|
||||
ep.indexNumber == null || current.indexNumber == null ||
|
||||
ep.parentIndexNumber == null || current.parentIndexNumber == null
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
ep.parentIndexNumber === current.parentIndexNumber &&
|
||||
ep.indexNumber === current.indexNumber
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort key for a season: specials (season 0) come *after* every numbered
|
||||
* season, matching how a viewer works through a show — S1, S2, …, then the
|
||||
* extras — rather than opening on a special because 0 < 1.
|
||||
*/
|
||||
function seasonRank(seasonNumber: number | null | undefined): number {
|
||||
return seasonNumber === SPECIALS_SEASON ? Number.MAX_SAFE_INTEGER : seasonNumber!;
|
||||
}
|
||||
|
||||
/**
|
||||
* Broadcast order across a whole series: season ascending, then episode.
|
||||
*
|
||||
* When *either* side's season is unknown there is no season axis to compare on,
|
||||
* so it falls through to episode number. That makes the comparator technically
|
||||
* non-transitive across such a mix, which is safe here because only the
|
||||
* directly-fetched `current` episode can lack a season and it is never part of
|
||||
* the array being sorted — it is only positioned against it (see
|
||||
* `adjacentEpisodes`).
|
||||
*/
|
||||
export function compareSeriesOrder(a: MediaItem, b: MediaItem): number {
|
||||
if (a.parentIndexNumber != null && b.parentIndexNumber != null) {
|
||||
const bySeason = seasonRank(a.parentIndexNumber) - seasonRank(b.parentIndexNumber);
|
||||
if (bySeason !== 0) return bySeason;
|
||||
}
|
||||
return (a.indexNumber ?? 0) - (b.indexNumber ?? 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* The window of episodes shown under the hero: up to 3 before and 6 after the
|
||||
* current episode, in series order across *all* seasons.
|
||||
*
|
||||
* Crossing a season boundary is the point (ux-flows §5B.2): finishing a season
|
||||
* finale should offer the next season's premiere, not an empty strip. Degrades
|
||||
* gracefully:
|
||||
* - splices the current episode into the pool at its ordered position when it
|
||||
* isn't present (an API id mismatch on a directly-fetched episode), so it
|
||||
* still anchors the window;
|
||||
* - returns just `[current]` only when there genuinely are no other episodes.
|
||||
*/
|
||||
export function adjacentEpisodes(current: MediaItem, allEpisodes: MediaItem[]): MediaItem[] {
|
||||
const pool = allEpisodes.slice().sort(compareSeriesOrder);
|
||||
|
||||
let idx = pool.findIndex((e) => isCurrentEpisode(e, current));
|
||||
|
||||
if (idx === -1) {
|
||||
const insertAt = pool.findIndex((e) => compareSeriesOrder(e, current) > 0);
|
||||
idx = insertAt === -1 ? pool.length : insertAt;
|
||||
pool.splice(idx, 0, current);
|
||||
}
|
||||
|
||||
const start = Math.max(0, idx - BEFORE);
|
||||
const end = Math.min(pool.length, idx + AFTER + 1);
|
||||
return pool.slice(start, end);
|
||||
}
|
||||
|
||||
/**
|
||||
* Label for a strip card, relative to the episode in focus.
|
||||
*
|
||||
* Within the current season a bare number reads cleanly ("6."). Once the window
|
||||
* crosses into another season that number is ambiguous, so the card names the
|
||||
* season too ("S3E1") — otherwise the premiere after a finale just reads "1."
|
||||
*/
|
||||
export function stripCardLabel(ep: MediaItem, current: MediaItem): string {
|
||||
const crossesSeason =
|
||||
ep.parentIndexNumber != null &&
|
||||
current.parentIndexNumber != null &&
|
||||
ep.parentIndexNumber !== current.parentIndexNumber;
|
||||
|
||||
if (crossesSeason) return `S${ep.parentIndexNumber}E${ep.indexNumber ?? 0}`;
|
||||
return `${ep.indexNumber ?? 0}.`;
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import type { MediaItem } from "$lib/api/types";
|
||||
import {
|
||||
seasonAnchorId,
|
||||
seasonRedirectTarget,
|
||||
episodeFocusHref,
|
||||
seriesPlayHref,
|
||||
seriesPlayLabel,
|
||||
groupEpisodesBySeason,
|
||||
initialExpandedSeasons,
|
||||
} from "./seriesNavigation";
|
||||
|
||||
const SERIES = "series-1";
|
||||
|
||||
function ep(id: string, season: number | null, number: number | null): MediaItem {
|
||||
return {
|
||||
id,
|
||||
name: `S${season}E${number}`,
|
||||
kind: "episode",
|
||||
seriesId: SERIES,
|
||||
parentIndexNumber: season,
|
||||
indexNumber: number,
|
||||
durationMs: 1_000_000,
|
||||
} as unknown as MediaItem;
|
||||
}
|
||||
|
||||
function seasonHeader(number: number, id = `season-${number}`): MediaItem {
|
||||
return {
|
||||
id,
|
||||
name: `Season ${number}`,
|
||||
kind: "season",
|
||||
seriesId: SERIES,
|
||||
indexNumber: number,
|
||||
} as unknown as MediaItem;
|
||||
}
|
||||
|
||||
function withProgress(episode: MediaItem, fraction: number): MediaItem {
|
||||
return {
|
||||
...episode,
|
||||
userData: { playbackPositionMs: (episode.durationMs ?? 0) * fraction },
|
||||
} as MediaItem;
|
||||
}
|
||||
|
||||
describe("seriesPlayHref", () => {
|
||||
// The reported bug: Play resolved the first *season* child and navigated to
|
||||
// /player/<seasonId>, which bounced back to the season-1 page.
|
||||
it("opens the current episode's focus view, never a season or the player", () => {
|
||||
const href = seriesPlayHref(SERIES, ep("s2e4", 2, 4));
|
||||
expect(href).toBe("/library/series-1?episode=s2e4");
|
||||
expect(href).not.toContain("/player/");
|
||||
});
|
||||
|
||||
it("returns null for a series with no episodes so the button can hide", () => {
|
||||
expect(seriesPlayHref(SERIES, null)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("seriesPlayLabel", () => {
|
||||
it("names the episode it will open", () => {
|
||||
expect(seriesPlayLabel(ep("s2e4", 2, 4))).toBe("Play S2E4");
|
||||
});
|
||||
|
||||
it("says Resume for a part-watched episode", () => {
|
||||
expect(seriesPlayLabel(withProgress(ep("s2e4", 2, 4), 0.4))).toBe("Resume S2E4");
|
||||
});
|
||||
|
||||
it("says Play for a barely-started or nearly-finished episode", () => {
|
||||
expect(seriesPlayLabel(withProgress(ep("s1e1", 1, 1), 0.001))).toBe("Play S1E1");
|
||||
expect(seriesPlayLabel(withProgress(ep("s1e1", 1, 1), 0.99))).toBe("Play S1E1");
|
||||
});
|
||||
|
||||
it("degrades to a bare verb when the numbering is unknown", () => {
|
||||
expect(seriesPlayLabel(ep("x", null, null))).toBe("Play");
|
||||
expect(seriesPlayLabel(null)).toBe("Play");
|
||||
});
|
||||
});
|
||||
|
||||
describe("seasonRedirectTarget", () => {
|
||||
it("sends a season to its series, anchored at that season", () => {
|
||||
expect(seasonRedirectTarget(seasonHeader(3))).toBe("/library/series-1#season-3");
|
||||
});
|
||||
|
||||
it("returns null when the series is unknown, so the caller can fall back", () => {
|
||||
const orphan = { ...seasonHeader(3), seriesId: undefined } as MediaItem;
|
||||
expect(seasonRedirectTarget(orphan)).toBeNull();
|
||||
});
|
||||
|
||||
it("matches the anchor the season section renders", () => {
|
||||
expect(seasonRedirectTarget(seasonHeader(2))).toBe(
|
||||
`/library/${SERIES}#${seasonAnchorId(2)}`
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("episodeFocusHref", () => {
|
||||
it("opens an episode inside its series (never a bare episode page)", () => {
|
||||
expect(episodeFocusHref(ep("s1e2", 1, 2))).toBe("/library/series-1?episode=s1e2");
|
||||
});
|
||||
|
||||
it("falls back to the bare item page when the series is unknown", () => {
|
||||
const orphan = { ...ep("lone", 1, 2), seriesId: undefined } as MediaItem;
|
||||
expect(episodeFocusHref(orphan)).toBe("/library/lone");
|
||||
});
|
||||
});
|
||||
|
||||
describe("groupEpisodesBySeason", () => {
|
||||
it("groups episodes under their season headers, in season order", () => {
|
||||
const seasons = [seasonHeader(2), seasonHeader(1)];
|
||||
const episodes = [ep("s1e1", 1, 1), ep("s1e2", 1, 2), ep("s2e1", 2, 1)];
|
||||
|
||||
const grouped = groupEpisodesBySeason(seasons, episodes);
|
||||
expect(grouped.map((g) => g.season.indexNumber)).toEqual([1, 2]);
|
||||
expect(grouped[0].episodes.map((e) => e.id)).toEqual(["s1e1", "s1e2"]);
|
||||
expect(grouped[1].episodes.map((e) => e.id)).toEqual(["s2e1"]);
|
||||
});
|
||||
|
||||
it("puts specials after the numbered seasons", () => {
|
||||
const grouped = groupEpisodesBySeason(
|
||||
[seasonHeader(0), seasonHeader(1)],
|
||||
[ep("s0e1", 0, 1), ep("s1e1", 1, 1)]
|
||||
);
|
||||
expect(grouped.map((g) => g.season.indexNumber)).toEqual([1, 0]);
|
||||
});
|
||||
|
||||
// A flat series: episodes hang off the series, no season folders exist.
|
||||
it("synthesizes headers when the server returned no seasons", () => {
|
||||
const grouped = groupEpisodesBySeason([], [ep("s1e1", 1, 1), ep("s2e1", 2, 1)]);
|
||||
expect(grouped.map((g) => g.season.name)).toEqual(["Season 1", "Season 2"]);
|
||||
expect(grouped.every((g) => g.season.kind === "season")).toBe(true);
|
||||
});
|
||||
|
||||
it("names a synthesized season 0 'Specials'", () => {
|
||||
const grouped = groupEpisodesBySeason([], [ep("s0e1", 0, 1)]);
|
||||
expect(grouped[0].season.name).toBe("Specials");
|
||||
});
|
||||
|
||||
it("gives synthesized headers distinct ids so keyed #each blocks are stable", () => {
|
||||
const grouped = groupEpisodesBySeason([], [ep("s1e1", 1, 1), ep("s2e1", 2, 1)]);
|
||||
const ids = grouped.map((g) => g.season.id);
|
||||
expect(new Set(ids).size).toBe(ids.length);
|
||||
});
|
||||
|
||||
it("drops seasons that have no episodes", () => {
|
||||
const grouped = groupEpisodesBySeason(
|
||||
[seasonHeader(1), seasonHeader(2), seasonHeader(3)],
|
||||
[ep("s2e1", 2, 1)]
|
||||
);
|
||||
expect(grouped.map((g) => g.season.indexNumber)).toEqual([2]);
|
||||
});
|
||||
|
||||
it("buckets season-less episodes into season 1 rather than losing them", () => {
|
||||
const grouped = groupEpisodesBySeason([], [ep("lone", null, 1)]);
|
||||
expect(grouped).toHaveLength(1);
|
||||
expect(grouped[0].episodes.map((e) => e.id)).toEqual(["lone"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("initialExpandedSeasons", () => {
|
||||
const seasons = groupEpisodesBySeason(
|
||||
[seasonHeader(1), seasonHeader(2), seasonHeader(3)],
|
||||
[
|
||||
ep("s1e1", 1, 1),
|
||||
ep("s2e1", 2, 1),
|
||||
ep("s2e2", 2, 2),
|
||||
ep("s3e1", 3, 1),
|
||||
]
|
||||
);
|
||||
|
||||
it("expands only the season holding the current episode", () => {
|
||||
const expanded = initialExpandedSeasons(seasons, "s2e2");
|
||||
expect([...expanded]).toEqual(["season-2"]);
|
||||
});
|
||||
|
||||
it("also expands the season of a ?episode= deep link", () => {
|
||||
const expanded = initialExpandedSeasons(seasons, "s1e1", "s3e1");
|
||||
expect(expanded.has("season-1")).toBe(true);
|
||||
expect(expanded.has("season-3")).toBe(true);
|
||||
expect(expanded.has("season-2")).toBe(false);
|
||||
});
|
||||
|
||||
it("collapses nothing extra when current and focused share a season", () => {
|
||||
const expanded = initialExpandedSeasons(seasons, "s2e1", "s2e2");
|
||||
expect([...expanded]).toEqual(["season-2"]);
|
||||
});
|
||||
|
||||
it("falls back to the first season when there is no current episode", () => {
|
||||
expect([...initialExpandedSeasons(seasons, null)]).toEqual(["season-1"]);
|
||||
});
|
||||
|
||||
it("falls back to the first season when the current episode is unknown here", () => {
|
||||
expect([...initialExpandedSeasons(seasons, "not-in-this-show")]).toEqual(["season-1"]);
|
||||
});
|
||||
|
||||
it("returns nothing for a series with no seasons", () => {
|
||||
expect(initialExpandedSeasons([], "s1e1").size).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,167 @@
|
||||
// Pure navigation/grouping logic for the series detail page.
|
||||
//
|
||||
// Extracted from `/library/[id]/+page.svelte` so it can be unit-tested: the
|
||||
// series Play button used to resolve `$libraryItems[0]` — the first *season* by
|
||||
// SortName — and navigate to `/player/<seasonId>`, which the player route
|
||||
// bounced back to `/library/<seasonId>`. Play on a series therefore played
|
||||
// nothing and landed on the season-1 page.
|
||||
//
|
||||
// Note what is NOT here: *which* episode is current. That is domain policy and
|
||||
// lives in Rust (`repository_get_series_current_episode`); this module only
|
||||
// renders and routes around the answer.
|
||||
//
|
||||
// TRACES: UR-062 | DR-102, DR-103
|
||||
import type { MediaItem } from "$lib/api/types";
|
||||
|
||||
export interface SeasonData {
|
||||
season: MediaItem;
|
||||
episodes: MediaItem[];
|
||||
}
|
||||
|
||||
/** Jellyfin files specials under season 0. */
|
||||
const SPECIALS_SEASON = 0;
|
||||
|
||||
/** Sort key for a season number: specials come after every numbered season. */
|
||||
function seasonRank(seasonNumber: number | null | undefined): number {
|
||||
if (seasonNumber == null) return Number.MAX_SAFE_INTEGER - 1;
|
||||
return seasonNumber === SPECIALS_SEASON ? Number.MAX_SAFE_INTEGER : seasonNumber;
|
||||
}
|
||||
|
||||
/**
|
||||
* The in-page anchor for a season, so a season link scrolls the series' single
|
||||
* continuous episode list instead of opening a page of its own.
|
||||
*/
|
||||
export function seasonAnchorId(seasonNumber: number | null | undefined): string {
|
||||
return `season-${seasonNumber ?? 0}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a link naming a season should actually go: the series, anchored at that
|
||||
* season. Returns `null` when the season carries no `seriesId` (a deep link into
|
||||
* a stale cache), in which case the caller must keep rendering something rather
|
||||
* than strand the user.
|
||||
*/
|
||||
export function seasonRedirectTarget(season: MediaItem): string | null {
|
||||
if (!season.seriesId) return null;
|
||||
const seasonNumber = season.indexNumber ?? season.parentIndexNumber;
|
||||
return `/library/${season.seriesId}#${seasonAnchorId(seasonNumber)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where an episode link should go: the episode in the context of its series
|
||||
* (ux-flows §5B.1 — an episode is never browsed as a bare Episode page).
|
||||
* Falls back to the bare item page only when the series is unknown.
|
||||
*/
|
||||
export function episodeFocusHref(episode: MediaItem): string {
|
||||
if (!episode.seriesId) return `/library/${episode.id}`;
|
||||
return `/library/${episode.seriesId}?episode=${episode.id}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the series hero button goes.
|
||||
*
|
||||
* The Episode Focus View, not the player: ux-flows §5B.5 makes Play on a
|
||||
* *container* navigation and Play on a *leaf* the commitment. Returns `null`
|
||||
* when there is no current episode (an empty series), so the caller can hide
|
||||
* the button rather than link nowhere.
|
||||
*/
|
||||
export function seriesPlayHref(seriesId: string, current: MediaItem | null): string | null {
|
||||
if (!current) return null;
|
||||
return `/library/${seriesId}?episode=${current.id}`;
|
||||
}
|
||||
|
||||
/** Fraction of an episode already watched, 0 when unknown. */
|
||||
function progressFraction(episode: MediaItem): number {
|
||||
const position = episode.userData?.playbackPositionMs ?? 0;
|
||||
if (!episode.durationMs || position <= 0) return 0;
|
||||
return position / episode.durationMs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Label for the series hero button — it names the episode it will open, so the
|
||||
* viewer knows where the button leads before pressing it.
|
||||
*/
|
||||
export function seriesPlayLabel(current: MediaItem | null): string {
|
||||
if (!current) return "Play";
|
||||
|
||||
const fraction = progressFraction(current);
|
||||
const verb = fraction > 0.01 && fraction < 0.95 ? "Resume" : "Play";
|
||||
|
||||
if (current.parentIndexNumber == null || current.indexNumber == null) return verb;
|
||||
return `${verb} S${current.parentIndexNumber}E${current.indexNumber}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Group a series' episodes under its season headers.
|
||||
*
|
||||
* The episodes arrive from Rust already in series order; this only decides which
|
||||
* header each one renders beneath, and synthesizes a header for any season the
|
||||
* server did not return one for (a flat series, or a season fetch that failed).
|
||||
* Seasons with no episodes are dropped — an empty accordion row is noise.
|
||||
*/
|
||||
export function groupEpisodesBySeason(
|
||||
seasons: MediaItem[],
|
||||
episodes: MediaItem[]
|
||||
): SeasonData[] {
|
||||
const headerFor = new Map<number, MediaItem>();
|
||||
for (const season of seasons) {
|
||||
const number = season.indexNumber ?? season.parentIndexNumber;
|
||||
if (number != null && !headerFor.has(number)) headerFor.set(number, season);
|
||||
}
|
||||
|
||||
const grouped = new Map<number, MediaItem[]>();
|
||||
for (const episode of episodes) {
|
||||
const number = episode.parentIndexNumber ?? 1;
|
||||
const bucket = grouped.get(number);
|
||||
if (bucket) bucket.push(episode);
|
||||
else grouped.set(number, [episode]);
|
||||
}
|
||||
|
||||
return [...grouped.entries()]
|
||||
.sort(([a], [b]) => seasonRank(a) - seasonRank(b))
|
||||
.map(([number, seasonEpisodes]) => ({
|
||||
season:
|
||||
headerFor.get(number) ??
|
||||
({
|
||||
...seasonEpisodes[0],
|
||||
id: `synthetic-season-${number}`,
|
||||
kind: "season",
|
||||
indexNumber: number,
|
||||
name: number === SPECIALS_SEASON ? "Specials" : `Season ${number}`,
|
||||
overview: null,
|
||||
} as MediaItem),
|
||||
episodes: seasonEpisodes,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Which seasons start expanded.
|
||||
*
|
||||
* Only the one the viewer is in. A ten-season show otherwise renders every
|
||||
* episode of every season at once, burying the one episode they came for. A
|
||||
* `?episode=` deep link expands that episode's season as well, and a show with
|
||||
* no resolved current episode falls back to its first season so the page is
|
||||
* never entirely collapsed.
|
||||
*
|
||||
* Returns season ids (not numbers) so the caller can key state per section,
|
||||
* including the synthesized headers.
|
||||
*/
|
||||
export function initialExpandedSeasons(
|
||||
seasons: SeasonData[],
|
||||
currentEpisodeId: string | null | undefined,
|
||||
focusedEpisodeId?: string | null
|
||||
): Set<string> {
|
||||
if (seasons.length === 0) return new Set();
|
||||
|
||||
const expanded = new Set<string>();
|
||||
for (const id of [currentEpisodeId, focusedEpisodeId]) {
|
||||
if (!id) continue;
|
||||
const owner = seasons.find((s) => s.episodes.some((e) => e.id === id));
|
||||
if (owner) expanded.add(owner.season.id);
|
||||
}
|
||||
|
||||
// Nothing matched — open the first season rather than nothing at all.
|
||||
if (expanded.size === 0) expanded.add(seasons[0].season.id);
|
||||
|
||||
return expanded;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
<!-- TRACES: UR-003, UR-005, UR-020, UR-021, UR-026, UR-040 | DR-010, DR-023, DR-024, DR-051, DR-052 -->
|
||||
<!-- TRACES: UR-003, UR-005, UR-020, UR-021, UR-026, UR-040, UR-061 | DR-010, DR-023, DR-024, DR-051, DR-052, DR-092, DR-098, DR-099 -->
|
||||
<script lang="ts">
|
||||
import { onMount, onDestroy, untrack } from "svelte";
|
||||
import { goto } from "$app/navigation";
|
||||
@@ -12,6 +12,7 @@
|
||||
import SleepTimerModal from "./SleepTimerModal.svelte";
|
||||
import SleepTimerIndicator from "./SleepTimerIndicator.svelte";
|
||||
import CachedImage from "../common/CachedImage.svelte";
|
||||
import { videoFitClass } from "./videoFit";
|
||||
import { sleepTimerActive, sleepTimerExpiredSignal } from "$lib/stores/sleepTimer";
|
||||
import { playbackPosition } from "$lib/stores/player";
|
||||
import * as html5Adapter from "$lib/player/html5Adapter";
|
||||
@@ -20,11 +21,22 @@
|
||||
import { createRustReportHost } from "$lib/player/adapters/rustReportHost";
|
||||
import { isPipSupported, enterPip, setAutoEnterEnabled } from "$lib/utils/pictureInPicture";
|
||||
import {
|
||||
isBackgroundAudioSupported,
|
||||
createTapGestureState,
|
||||
registerTap,
|
||||
resolveSeekTarget,
|
||||
clampSeekTarget,
|
||||
isSynthesizedTouchClick,
|
||||
isControlSurfaceTouch,
|
||||
SEEK_FORWARD_SECONDS,
|
||||
SEEK_BACKWARD_SECONDS,
|
||||
type TapFeedback,
|
||||
} from "./tapGestures";
|
||||
import {
|
||||
setBackgroundAudioEnabled,
|
||||
subscribeAppBackgrounded,
|
||||
subscribeAppForegrounded,
|
||||
} from "$lib/utils/backgroundAudio";
|
||||
import { platform } from "@tauri-apps/plugin-os";
|
||||
import {
|
||||
computeHandoffPosition,
|
||||
initialHandoffState,
|
||||
@@ -101,12 +113,25 @@
|
||||
let touchStartX = $state(0);
|
||||
let touchStartY = $state(0);
|
||||
let touchStartTime = $state(0);
|
||||
let lastTapTime = $state(0);
|
||||
let tapTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||
let tapGestures = createTapGestureState();
|
||||
// When a touch tap last ran the gesture handler, so the compatibility click
|
||||
// the browser synthesizes afterwards can be ignored (see handleVideoClick).
|
||||
let lastTouchTapAt = 0;
|
||||
let brightness = $state(1); // 0-2, default 1
|
||||
let showDoubleTapFeedback = $state<"left" | "right" | null>(null);
|
||||
let showDoubleTapFeedback = $state<TapFeedback | null>(null);
|
||||
let doubleTapFeedbackTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||
// Target of a skip already requested but not yet reported back by the player,
|
||||
// so back-to-back double taps chain instead of stacking on a stale position.
|
||||
let pendingSeekTarget: number | null = null;
|
||||
let swipeGestureActive = $state(false);
|
||||
// Whether the in-flight touch belongs to the player surface (and so may be
|
||||
// read as a tap/swipe gesture) rather than to a control. Set on touchstart,
|
||||
// cleared on touchend — see handleTouchMove for why a per-gesture flag and not
|
||||
// just a per-event target check.
|
||||
let playerGestureActive = false;
|
||||
// Raised when the user changes the seek bar's value, cleared by whichever
|
||||
// release signal commits the seek. See handleSeekBarRelease.
|
||||
let seekCommitArmed = false;
|
||||
|
||||
// Backend info from Rust (Rust decides which backend to use based on platform)
|
||||
let useHtml5Element = $state(true); // Default to HTML5, Rust will override if using native backend
|
||||
@@ -673,15 +698,19 @@
|
||||
bufferedRanges.push(`[${buffered.start(i).toFixed(1)} - ${buffered.end(i).toFixed(1)}]`);
|
||||
}
|
||||
|
||||
console.log("[VideoPlayer Debug]", {
|
||||
currentTime: videoElement.currentTime.toFixed(2),
|
||||
displayTime: currentTime.toFixed(2),
|
||||
buffered: bufferedRanges.join(", "),
|
||||
readyState: videoElement.readyState,
|
||||
paused: videoElement.paused,
|
||||
seeking: videoElement.seeking,
|
||||
playbackRate: videoElement.playbackRate,
|
||||
});
|
||||
// Flattened to a single string on purpose: the Android WebView console
|
||||
// bridge stringifies objects as "[object Object]" in logcat, which made
|
||||
// this whole payload useless when diagnosing over adb.
|
||||
console.log(
|
||||
`[VideoPlayer Debug] t=${videoElement.currentTime.toFixed(2)}` +
|
||||
` display=${currentTime.toFixed(2)}` +
|
||||
` readyState=${videoElement.readyState}` +
|
||||
` networkState=${videoElement.networkState}` +
|
||||
` paused=${videoElement.paused}` +
|
||||
` seeking=${videoElement.seeking}` +
|
||||
` rate=${videoElement.playbackRate}` +
|
||||
` buffered=${bufferedRanges.join(", ")}`
|
||||
);
|
||||
}
|
||||
}, 1000);
|
||||
});
|
||||
@@ -702,6 +731,11 @@
|
||||
if (debugLogInterval) {
|
||||
clearInterval(debugLogInterval);
|
||||
}
|
||||
tapGestures.cancel();
|
||||
if (doubleTapFeedbackTimeout) {
|
||||
clearTimeout(doubleTapFeedbackTimeout);
|
||||
doubleTapFeedbackTimeout = null;
|
||||
}
|
||||
|
||||
// Remove native backend event listeners (incl. background-audio lifecycle subs)
|
||||
for (const unlisten of nativeUnlisteners) {
|
||||
@@ -1078,6 +1112,21 @@
|
||||
}
|
||||
|
||||
function handlePause() {
|
||||
// The element pausing is normally user intent, but a stall, a source change,
|
||||
// or a competing controller can also do it — and the pause itself carries no
|
||||
// reason. Log the element state so an unexplained pause/resume loop can be
|
||||
// attributed from an adb capture instead of guessed at.
|
||||
const el = videoElement;
|
||||
console.log(
|
||||
`[VideoPlayer] pause event — t=${el ? el.currentTime.toFixed(2) : "?"}` +
|
||||
` readyState=${el?.readyState}` +
|
||||
` networkState=${el?.networkState}` +
|
||||
` seeking=${el?.seeking}` +
|
||||
` ended=${el?.ended}` +
|
||||
` isSeeking=${isSeeking}` +
|
||||
` isBuffering=${isBuffering}` +
|
||||
` handoff=${handoffState.active}`
|
||||
);
|
||||
isPlaying = false;
|
||||
stopTimeUpdates(); // Stop RAF loop when paused
|
||||
html5Adapter.reportState("paused", reportMediaId ?? null);
|
||||
@@ -1121,11 +1170,33 @@
|
||||
const targetTime = parseFloat(input.value);
|
||||
// Update the displayed time immediately for smooth visual feedback
|
||||
currentTime = targetTime;
|
||||
// The user has moved the value; the next release must commit it.
|
||||
seekCommitArmed = true;
|
||||
}
|
||||
|
||||
async function handleSeekBarChange(e: Event) {
|
||||
const input = e.target as HTMLInputElement;
|
||||
const targetTime = parseFloat(input.value);
|
||||
/**
|
||||
* Seek-bar released — commit the value the user landed on, at most once.
|
||||
*
|
||||
* Wired to `touchend`/`mouseup` AND `change`, because `change` alone is not
|
||||
* dependable: Android's WebView does not reliably fire it for a touch
|
||||
* interaction on a range input, so the thumb moved to the tapped position but
|
||||
* the seek never ran ("the bar moves, playback doesn't"). Engines that DO fire
|
||||
* `change` deliver both signals, hence the arm/disarm — whichever arrives
|
||||
* first commits and the other is a no-op.
|
||||
*/
|
||||
function handleSeekBarRelease(e: Event) {
|
||||
isDraggingSeekBar = false;
|
||||
if (!seekCommitArmed) return;
|
||||
seekCommitArmed = false;
|
||||
const input = (e.currentTarget ?? e.target) as HTMLInputElement;
|
||||
void commitSeek(parseFloat(input.value));
|
||||
}
|
||||
|
||||
async function commitSeek(rawTarget: number) {
|
||||
// Clamp strictly inside the media: the range input's max IS the duration, so
|
||||
// dragging fully right would otherwise request a segment past the media end,
|
||||
// which the server never produces (see END_SEEK_MARGIN_SECONDS).
|
||||
const targetTime = clampSeekTarget(rawTarget, duration);
|
||||
|
||||
// Set isSeeking immediately to prevent timeupdate from interfering
|
||||
isSeeking = true;
|
||||
@@ -1178,16 +1249,26 @@
|
||||
// playback off to the native ExoPlayer audio service; the WebView <video> is
|
||||
// torn down so no video is decoded. Mutually exclusive with auto-PiP.
|
||||
//
|
||||
// Resolved synchronously (no await) for the same native-mode reason as PiP.
|
||||
const backgroundAudioSupported = isBackgroundAudioSupported();
|
||||
// Gate on the platform, NOT on the AndroidBackgroundAudio JS-bridge probe.
|
||||
// The native isSupported() is unconditionally true on Android, but the bridge
|
||||
// is injected into the WebView asynchronously and races component mount — a
|
||||
// one-shot bridge probe here comes out false on some loads and, being a const,
|
||||
// never recovers, so the button vanished on "some videos". platform() is
|
||||
// available synchronously and is stable. toggleBackgroundAudio() no-ops safely
|
||||
// if the bridge is momentarily absent.
|
||||
const backgroundAudioSupported = platform() === "android";
|
||||
let backgroundAudioOn = $state(false); // v1: default OFF each session
|
||||
let handoffState: BackgroundAudioState = { ...initialHandoffState };
|
||||
|
||||
function toggleBackgroundAudio() {
|
||||
backgroundAudioOn = !backgroundAudioOn;
|
||||
console.log("[VideoPlayer] Background-audio toggle ->", backgroundAudioOn);
|
||||
// Arm/disarm native background-audio mode AND flip auto-PiP the other way,
|
||||
// so exactly one background behavior is active.
|
||||
setBackgroundAudioEnabled(backgroundAudioOn);
|
||||
const armed = setBackgroundAudioEnabled(backgroundAudioOn);
|
||||
if (!armed) {
|
||||
console.warn("[VideoPlayer] Background audio NOT armed natively (no bridge)");
|
||||
}
|
||||
setAutoEnterEnabled(!backgroundAudioOn);
|
||||
}
|
||||
|
||||
@@ -1227,6 +1308,10 @@
|
||||
serverId: media.serverId ?? null,
|
||||
// Real duration so the lockscreen scrubber has a range to draw.
|
||||
durationSeconds: duration > 0 ? duration : null,
|
||||
// Episode identity so the backend can auto-advance to the next episode
|
||||
// when this audio-only stream ends while backgrounded (UR-040).
|
||||
itemType: media.type ?? null,
|
||||
seriesId: media.seriesId ?? null,
|
||||
},
|
||||
pos,
|
||||
);
|
||||
@@ -1331,7 +1416,16 @@
|
||||
async function seekRelative(seconds: number) {
|
||||
isSeeking = true;
|
||||
|
||||
const newTime = Math.max(0, Math.min(duration, currentTime + seconds));
|
||||
// The facade seeks by absolute position, so resolve the delta here —
|
||||
// chaining off a still-in-flight target so rapid double taps accumulate
|
||||
// instead of all resolving against the same not-yet-updated position.
|
||||
const newTime = resolveSeekTarget({
|
||||
delta: seconds,
|
||||
reportedPosition: currentTime,
|
||||
duration,
|
||||
pendingTarget: pendingSeekTarget,
|
||||
});
|
||||
pendingSeekTarget = newTime;
|
||||
|
||||
console.log("[VideoPlayer] Relative seek:", {
|
||||
offset: `${seconds > 0 ? "+" : ""}${seconds}s`,
|
||||
@@ -1339,15 +1433,13 @@
|
||||
to: newTime.toFixed(2),
|
||||
});
|
||||
|
||||
// Call the unified handleSeekBarChange logic with the new time
|
||||
// Create a synthetic event to reuse the existing logic
|
||||
const syntheticEvent = {
|
||||
target: {
|
||||
value: newTime.toString()
|
||||
}
|
||||
} as unknown as Event;
|
||||
|
||||
await handleSeekBarChange(syntheticEvent);
|
||||
// Same commit path as the seek bar — one place decides how a seek is issued.
|
||||
try {
|
||||
await commitSeek(newTime);
|
||||
} finally {
|
||||
// The player is authoritative again from here on.
|
||||
if (pendingSeekTarget === newTime) pendingSeekTarget = null;
|
||||
}
|
||||
}
|
||||
|
||||
function handleKeydown(e: KeyboardEvent) {
|
||||
@@ -1364,42 +1456,88 @@
|
||||
}
|
||||
} else if (e.key === "ArrowLeft") {
|
||||
e.preventDefault();
|
||||
seekRelative(-10);
|
||||
seekRelative(SEEK_BACKWARD_SECONDS);
|
||||
} else if (e.key === "ArrowRight") {
|
||||
e.preventDefault();
|
||||
seekRelative(10);
|
||||
seekRelative(SEEK_FORWARD_SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk up from the touch target collecting the tag/attribute pairs
|
||||
* `isControlSurfaceTouch` needs, so the rule itself stays DOM-free and testable.
|
||||
*/
|
||||
function ancestorChain(target: EventTarget | null) {
|
||||
const chain: Array<{
|
||||
tag: string;
|
||||
isPlayerControls?: boolean;
|
||||
isPlayerSurface?: boolean;
|
||||
}> = [];
|
||||
let node = target as HTMLElement | null;
|
||||
// Bounded walk: controls live a few levels below the player root, and
|
||||
// stopping at <body> keeps this cheap and avoids depending on a bound ref.
|
||||
while (node && node.tagName !== "BODY") {
|
||||
chain.push({
|
||||
tag: node.tagName ?? "",
|
||||
isPlayerControls: node.dataset?.playerControls !== undefined,
|
||||
isPlayerSurface: node.dataset?.playerSurface !== undefined,
|
||||
});
|
||||
node = node.parentElement;
|
||||
}
|
||||
return chain;
|
||||
}
|
||||
|
||||
// Touch gesture handlers
|
||||
function handleTouchStart(e: TouchEvent) {
|
||||
// Taps on the controls belong to those controls. This listener is on the
|
||||
// container and touch events bubble, so without this a tap on the bottom
|
||||
// play button would toggle here AND again via the button's own click — the
|
||||
// two cancelling out and leaving the control apparently dead (DR-098).
|
||||
if (isControlSurfaceTouch(ancestorChain(e.target))) {
|
||||
// The move handler must stay out of it too. It reads touchStartX/Y, which
|
||||
// this early return leaves at the PREVIOUS gesture's values, so a seek-bar
|
||||
// drag came out as a huge vertical delta: it was mis-read as a brightness
|
||||
// swipe, which dimmed the screen and fired a spurious play/pause
|
||||
// "correction" mid-drag (DR-098).
|
||||
playerGestureActive = false;
|
||||
return;
|
||||
}
|
||||
playerGestureActive = true;
|
||||
|
||||
const touch = e.touches[0];
|
||||
touchStartX = touch.clientX;
|
||||
touchStartY = touch.clientY;
|
||||
touchStartTime = Date.now();
|
||||
|
||||
const now = Date.now();
|
||||
const timeSinceLastTap = now - lastTapTime;
|
||||
const outcome = registerTap(tapGestures, {
|
||||
x: touch.clientX,
|
||||
screenWidth: window.innerWidth,
|
||||
now: Date.now(),
|
||||
});
|
||||
|
||||
// Double tap detection (within 300ms)
|
||||
if (timeSinceLastTap < 300 && timeSinceLastTap > 0) {
|
||||
// Suppress the compatibility click this touch will synthesize.
|
||||
lastTouchTapAt = Date.now();
|
||||
|
||||
if (outcome.action === "seek") {
|
||||
e.preventDefault();
|
||||
handleDoubleTap(touch.clientX);
|
||||
lastTapTime = 0; // Reset to prevent triple-tap
|
||||
if (tapTimeout) {
|
||||
clearTimeout(tapTimeout);
|
||||
tapTimeout = null;
|
||||
}
|
||||
} else {
|
||||
lastTapTime = now;
|
||||
// Set timeout to clear if no second tap
|
||||
tapTimeout = setTimeout(() => {
|
||||
lastTapTime = 0;
|
||||
}, 300);
|
||||
handleDoubleTap(outcome.seekSeconds, outcome.feedback);
|
||||
// Re-toggle so the first tap's toggle is undone: a double tap seeks and
|
||||
// leaves the play state as it was (playing keeps playing, paused stays
|
||||
// paused).
|
||||
if (outcome.togglePlayPause) togglePlayPause();
|
||||
return;
|
||||
}
|
||||
|
||||
// First tap: act now. Nothing is deferred, so there is no timer to race the
|
||||
// compatibility click Android synthesizes after a touch tap (see DR-098).
|
||||
togglePlayPause();
|
||||
}
|
||||
|
||||
function handleTouchMove(e: TouchEvent) {
|
||||
// Only a gesture that began on the bare video surface is ours. Re-checking
|
||||
// the target here would not be enough: the touch that started on a control
|
||||
// never recorded a start point, so any delta computed here is meaningless.
|
||||
if (!playerGestureActive) return;
|
||||
if (!e.touches[0]) return;
|
||||
|
||||
const touch = e.touches[0];
|
||||
@@ -1409,6 +1547,15 @@
|
||||
|
||||
// Minimum movement to register as swipe (50px)
|
||||
if (Math.abs(deltaY) > 50 && timeDelta > 50) {
|
||||
// Only on the frame the gesture is first recognised as a swipe — this runs
|
||||
// on every touchmove, and the correction below must happen exactly once.
|
||||
if (!swipeGestureActive) {
|
||||
// The touchstart already toggled play/pause (taps act immediately now),
|
||||
// so undo it: a swipe must not change the play state. Forget the tap too,
|
||||
// so it cannot pair with a later tap into a spurious seek.
|
||||
togglePlayPause();
|
||||
tapGestures.cancel();
|
||||
}
|
||||
swipeGestureActive = true;
|
||||
|
||||
// Brightness control on vertical swipe
|
||||
@@ -1423,23 +1570,28 @@
|
||||
}
|
||||
|
||||
function handleTouchEnd(e: TouchEvent) {
|
||||
playerGestureActive = false;
|
||||
swipeGestureActive = false;
|
||||
swipeType = null;
|
||||
}
|
||||
|
||||
function handleDoubleTap(x: number) {
|
||||
const screenWidth = window.innerWidth;
|
||||
const isLeftSide = x < screenWidth / 2;
|
||||
/**
|
||||
* Mouse clicks toggle play/pause immediately. Touch taps are handled fully by
|
||||
* `handleTouchStart`, so the compatibility click the browser synthesizes after
|
||||
* a tap must be ignored or every tap toggles twice.
|
||||
*
|
||||
* Used by EVERY click target layered over the video, not just the <video>:
|
||||
* pausing renders the full-screen play overlay, so the synthesized click lands
|
||||
* on that button instead and would re-toggle straight back to playing.
|
||||
*/
|
||||
function handleSurfaceClick(e: MouseEvent) {
|
||||
if (isSynthesizedTouchClick(e.detail, Date.now(), lastTouchTapAt)) return;
|
||||
togglePlayPause();
|
||||
}
|
||||
|
||||
if (isLeftSide) {
|
||||
// Double tap left: rewind 10 seconds
|
||||
seekRelative(-10);
|
||||
showDoubleTapFeedback = "left";
|
||||
} else {
|
||||
// Double tap right: forward 10 seconds
|
||||
seekRelative(10);
|
||||
showDoubleTapFeedback = "right";
|
||||
}
|
||||
function handleDoubleTap(seekSeconds: number, feedback: TapFeedback) {
|
||||
seekRelative(seekSeconds);
|
||||
showDoubleTapFeedback = feedback;
|
||||
|
||||
// Hide feedback after animation
|
||||
if (doubleTapFeedbackTimeout) {
|
||||
@@ -1585,7 +1737,7 @@
|
||||
<video
|
||||
bind:this={videoElement}
|
||||
src={currentStreamUrl.includes('.m3u8') && Hls.isSupported() ? '' : currentStreamUrl}
|
||||
class="max-w-full max-h-full"
|
||||
class={videoFitClass()}
|
||||
class:invisible={!isMediaReady}
|
||||
style="filter: brightness({brightness})"
|
||||
playsinline
|
||||
@@ -1601,7 +1753,7 @@
|
||||
onwaiting={handleWaiting}
|
||||
onplaying={handlePlaying}
|
||||
onloadstart={handleLoadStart}
|
||||
onclick={togglePlayPause}
|
||||
onclick={handleSurfaceClick}
|
||||
>
|
||||
<!-- Temporarily disabled to debug playback issues
|
||||
{#each subtitleTracks() as track}
|
||||
@@ -1654,7 +1806,7 @@
|
||||
<div class="bg-white/20 rounded-full p-6 backdrop-blur-sm">
|
||||
<svg class="w-12 h-12 text-white" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm1-13H11v6l5.25 3.15.75-1.23-4-2.42z" />
|
||||
<text x="12" y="14" text-anchor="middle" font-size="6" fill="white" font-weight="bold">-10</text>
|
||||
<text x="12" y="14" text-anchor="middle" font-size="6" fill="white" font-weight="bold">{SEEK_BACKWARD_SECONDS}</text>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1665,7 +1817,7 @@
|
||||
<div class="bg-white/20 rounded-full p-6 backdrop-blur-sm">
|
||||
<svg class="w-12 h-12 text-white" fill="currentColor" viewBox="0 0 24 24">
|
||||
<path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm1-13H11v6l5.25 3.15.75-1.23-4-2.42z" />
|
||||
<text x="12" y="14" text-anchor="middle" font-size="6" fill="white" font-weight="bold">+10</text>
|
||||
<text x="12" y="14" text-anchor="middle" font-size="6" fill="white" font-weight="bold">+{SEEK_FORWARD_SECONDS}</text>
|
||||
</svg>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1694,10 +1846,17 @@
|
||||
<div class="w-12 h-12 border-4 border-white border-t-transparent rounded-full animate-spin"></div>
|
||||
</div>
|
||||
{:else if !isPlaying}
|
||||
<!-- Play/Pause overlay -->
|
||||
<!-- Play overlay. Visually this IS the video surface, so it is marked
|
||||
`data-player-surface`: it must keep participating in tap gestures even
|
||||
though it is a <button>, or the second tap of a double tap (which lands
|
||||
here, because the first tap paused and raised this overlay) is
|
||||
discarded as "a tap on a control" and seeking dies. It still shares the
|
||||
synthesized-click guard, since it appears exactly when a tap pauses.
|
||||
See DR-098. -->
|
||||
<button
|
||||
data-player-surface
|
||||
class="absolute inset-0 flex items-center justify-center bg-black/30"
|
||||
onclick={togglePlayPause}
|
||||
onclick={handleSurfaceClick}
|
||||
aria-label="Play"
|
||||
>
|
||||
<svg class="w-20 h-20 text-white" fill="currentColor" viewBox="0 0 24 24">
|
||||
@@ -1745,8 +1904,10 @@
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Controls -->
|
||||
<!-- Controls. `data-player-controls` marks this subtree as interactive so
|
||||
container-level tap gestures ignore touches here (see DR-098). -->
|
||||
<div
|
||||
data-player-controls
|
||||
class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent p-4 transition-opacity duration-300"
|
||||
class:opacity-0={!showControls}
|
||||
class:pointer-events-none={!showControls}
|
||||
@@ -1773,11 +1934,11 @@
|
||||
max={duration || 100}
|
||||
value={currentTime}
|
||||
oninput={handleSeekBarInput}
|
||||
onchange={handleSeekBarChange}
|
||||
onchange={handleSeekBarRelease}
|
||||
onmousedown={() => isDraggingSeekBar = true}
|
||||
onmouseup={() => isDraggingSeekBar = false}
|
||||
onmouseup={handleSeekBarRelease}
|
||||
ontouchstart={() => isDraggingSeekBar = true}
|
||||
ontouchend={() => isDraggingSeekBar = false}
|
||||
ontouchend={handleSeekBarRelease}
|
||||
class="flex-1 h-1 bg-white/30 rounded-full appearance-none cursor-pointer
|
||||
[&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3
|
||||
[&::-webkit-slider-thumb]:bg-white [&::-webkit-slider-thumb]:rounded-full"
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
/**
|
||||
* Behavioural regression tests for the video tap surface — rendered against the
|
||||
* REAL component, not a hand-modelled DOM.
|
||||
*
|
||||
* TRACES: UR-005, UR-061 | DR-098 | UT-092
|
||||
*
|
||||
* Why this file exists:
|
||||
*
|
||||
* `tapGestures.test.ts` tests `registerTap` / `isControlSurfaceTouch` /
|
||||
* `isSynthesizedTouchClick` as isolated pure functions. Every one of those tests
|
||||
* passed while, on the device, in sequence: the player pause-looped, then
|
||||
* pausing became impossible, then the bottom controls went dead, then
|
||||
* double-tap-to-seek stopped working. The helpers were each behaving exactly as
|
||||
* specified — the bugs were all in the *composition*: which element actually
|
||||
* receives a tap once Svelte has re-rendered.
|
||||
*
|
||||
* Testing my own helpers could not catch that, and modelling the DOM by hand in
|
||||
* a test just re-encodes the same wrong assumption. So these tests render
|
||||
* VideoPlayer and dispatch real touch/click events at whatever element is
|
||||
* genuinely on top, asserting user-visible outcomes ("a double tap seeks")
|
||||
* rather than internals.
|
||||
*
|
||||
* The specific traps encoded here, each a bug that shipped:
|
||||
* - pausing renders a full-screen <button> play overlay OVER the video, so the
|
||||
* second tap of a double tap lands on a button, not the video;
|
||||
* - the browser synthesizes a `click` after a touch tap, which must not toggle
|
||||
* a second time, on ANY layered target;
|
||||
* - the bottom controls bar must drive its own buttons and NOT the container's
|
||||
* tap gestures.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { render } from "@testing-library/svelte";
|
||||
import { tick } from "svelte";
|
||||
import VideoPlayer from "./VideoPlayer.svelte";
|
||||
import { SEEK_FORWARD_SECONDS } from "./tapGestures";
|
||||
|
||||
// --- Mocks: everything VideoPlayer reaches for that is not the tap surface. ---
|
||||
|
||||
const toggleSpy = vi.fn();
|
||||
const seekVideoSpy = vi.fn();
|
||||
const seekSpy = vi.fn();
|
||||
|
||||
vi.mock("$app/navigation", () => ({ goto: vi.fn() }));
|
||||
|
||||
vi.mock("$lib/player", () => ({
|
||||
playerController: {
|
||||
toggle: (...a: unknown[]) => {
|
||||
toggleSpy(...a);
|
||||
return Promise.resolve();
|
||||
},
|
||||
seekVideo: (...a: unknown[]) => {
|
||||
seekVideoSpy(...a);
|
||||
return Promise.resolve();
|
||||
},
|
||||
seek: (...a: unknown[]) => {
|
||||
seekSpy(...a);
|
||||
return Promise.resolve();
|
||||
},
|
||||
setActiveAdapter: vi.fn(),
|
||||
clearActiveAdapter: vi.fn(),
|
||||
getActiveAdapter: vi.fn(() => null),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("$lib/player/adapters/rustReportHost", () => ({
|
||||
createRustReportHost: () => ({
|
||||
onState: vi.fn(),
|
||||
onPosition: vi.fn(),
|
||||
onMediaLoaded: vi.fn(),
|
||||
onEnded: vi.fn(),
|
||||
onError: vi.fn(),
|
||||
onStreamUrlChanged: vi.fn(),
|
||||
onBuffering: vi.fn(),
|
||||
onReady: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("$lib/player/html5Adapter", () => ({
|
||||
reportState: vi.fn(),
|
||||
reportPosition: vi.fn(),
|
||||
reportMediaLoaded: vi.fn(),
|
||||
resetReporting: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("$lib/utils/pictureInPicture", () => ({
|
||||
isPipSupported: () => false,
|
||||
enterPip: vi.fn(),
|
||||
setAutoEnterEnabled: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("$lib/stores/auth", () => ({
|
||||
auth: {
|
||||
getRepository: () => ({ getHandle: () => "h", jrayActorsAt: async () => [] }),
|
||||
subscribe: (fn: (v: unknown) => void) => {
|
||||
fn({ isAuthenticated: true });
|
||||
return () => {};
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
const MEDIA = {
|
||||
id: "item-1",
|
||||
name: "Test Episode",
|
||||
type: "Episode",
|
||||
runTimeTicks: 6_000_000_000, // 600s
|
||||
} as any;
|
||||
|
||||
/** Dispatch a touch at (x, y) on whatever element is topmost there. */
|
||||
function touchAt(el: Element, x: number) {
|
||||
const touch = { clientX: x, clientY: 300 } as Touch;
|
||||
el.dispatchEvent(
|
||||
new TouchEvent("touchstart", {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
touches: [touch] as unknown as Touch[],
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function renderPlayer() {
|
||||
return render(VideoPlayer, {
|
||||
props: { media: MEDIA, streamUrl: "http://x/master.m3u8", onClose: vi.fn() },
|
||||
});
|
||||
}
|
||||
|
||||
describe("VideoPlayer tap surface (real component)", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("a single tap on the video toggles play/pause exactly once", async () => {
|
||||
const { container } = renderPlayer();
|
||||
const video = container.querySelector("video");
|
||||
expect(video).toBeTruthy();
|
||||
|
||||
touchAt(video!, 900);
|
||||
|
||||
expect(toggleSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("the synthesized click after a tap does not toggle a second time", async () => {
|
||||
const { container } = renderPlayer();
|
||||
const video = container.querySelector("video")!;
|
||||
|
||||
touchAt(video, 900);
|
||||
// The compatibility click the browser fires after a touch tap. detail=0 is
|
||||
// how engines mark it; a late real-detail click is covered by the recency
|
||||
// guard, which this exercises too since it lands immediately.
|
||||
video.dispatchEvent(new MouseEvent("click", { bubbles: true, detail: 0 }));
|
||||
|
||||
expect(toggleSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("a double tap seeks even though the first tap raised the play overlay", async () => {
|
||||
// THE regression this file exists for. On device the first tap pauses, which
|
||||
// makes Svelte render a full-screen <button> play overlay over the video —
|
||||
// so the SECOND tap lands on a button, not the video. A control-surface
|
||||
// guard that does not know about that overlay discards it and seeking dies.
|
||||
//
|
||||
// Reproducing it requires the overlay to actually render, which means
|
||||
// driving `isPlaying` the way the real element does: via its `pause` event.
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const { container } = renderPlayer();
|
||||
const video = container.querySelector("video")!;
|
||||
|
||||
// Tap 1 on the video.
|
||||
touchAt(video, 900);
|
||||
|
||||
// The element reports it paused → isPlaying=false → overlay renders.
|
||||
video.dispatchEvent(new Event("pause"));
|
||||
await Promise.resolve();
|
||||
await tick();
|
||||
|
||||
const overlay = container.querySelector("[data-player-surface]");
|
||||
expect(overlay, "the play overlay should be covering the video").toBeTruthy();
|
||||
|
||||
vi.advanceTimersByTime(120); // inside DOUBLE_TAP_WINDOW_MS
|
||||
// Tap 2 lands on the OVERLAY, exactly as on device.
|
||||
touchAt(overlay!, 900);
|
||||
|
||||
// Either seek route is acceptable — which one runs depends on whether a
|
||||
// video adapter is registered. What must hold is that a seek happened, to
|
||||
// roughly the forward-skip target.
|
||||
const calls = [...seekVideoSpy.mock.calls, ...seekSpy.mock.calls];
|
||||
expect(calls.length).toBe(1);
|
||||
const [position] = calls[0];
|
||||
expect(position).toBeGreaterThan(0);
|
||||
expect(position).toBeLessThanOrEqual(SEEK_FORWARD_SECONDS);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("tapping the bottom play/pause button toggles once, not twice", async () => {
|
||||
const { container } = renderPlayer();
|
||||
const controls = container.querySelector("[data-player-controls]");
|
||||
expect(controls).toBeTruthy();
|
||||
|
||||
const playBtn = controls!.querySelector("button");
|
||||
expect(playBtn).toBeTruthy();
|
||||
|
||||
// A real press: touchstart bubbles to the container's gesture handler, then
|
||||
// the button's own click fires. Only ONE toggle may result.
|
||||
touchAt(playBtn!, 40);
|
||||
playBtn!.dispatchEvent(new MouseEvent("click", { bubbles: true, detail: 1 }));
|
||||
|
||||
expect(toggleSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,218 @@
|
||||
/**
|
||||
* VideoPlayer seek-bar TOUCH scrub regression tests (Android).
|
||||
*
|
||||
* Reported bug: on Android, dragging the progress bar does not change the
|
||||
* playback location.
|
||||
*
|
||||
* The gesture listener lives on the outer container and touch events bubble.
|
||||
* `handleTouchStart` ignores touches that land on a control (the seek bar is an
|
||||
* <input>, inside `data-player-controls`) — but `handleTouchMove` does not, so a
|
||||
* seek-bar drag is still interpreted as a container swipe. That mis-read swipe
|
||||
* fires `togglePlayPause()` (undoing a first-tap toggle that never happened) and
|
||||
* hijacks the drag into brightness control.
|
||||
*
|
||||
* The existing scrub regression tests only drive the slider with MOUSE events,
|
||||
* which never reach the touch handlers — which is why this survived.
|
||||
*
|
||||
* The seek was also committed only from `change`, which Android's WebView does
|
||||
* not reliably fire for a touch interaction on a range input — so a tap moved
|
||||
* the thumb and no seek ever ran. Release now commits from touchend/mouseup too.
|
||||
*
|
||||
* TRACES: UR-005, UR-061 | DR-098, DR-099 | UT-089, UT-090
|
||||
*/
|
||||
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
// ---- Mocks (must precede component import) --------------------------------
|
||||
|
||||
const channelHandlers: Record<string, (event: any) => void> = {};
|
||||
vi.mock("@tauri-apps/api/event", () => ({
|
||||
listen: vi.fn(async (channel: string, handler: any) => {
|
||||
channelHandlers[channel] = handler;
|
||||
return () => {
|
||||
delete channelHandlers[channel];
|
||||
};
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("@tauri-apps/api/core", () => ({
|
||||
invoke: vi.fn(),
|
||||
}));
|
||||
|
||||
const playerPlayItem = vi.fn(async () => ({
|
||||
useHtml5Element: false,
|
||||
backend: "exoplayer",
|
||||
state: { kind: "playing" },
|
||||
}));
|
||||
const playerSeekVideo = vi.fn(async (_h: string, position: number) => ({
|
||||
strategy: "native",
|
||||
position,
|
||||
}));
|
||||
const playerStop = vi.fn(async () => ({}));
|
||||
const playerToggle = vi.fn(async () => ({ state: "playing" }));
|
||||
|
||||
vi.mock("$lib/api/bindings", () => ({
|
||||
commands: {
|
||||
playerPlayItem: (...a: any[]) => playerPlayItem(...(a as [])),
|
||||
playerSeekVideo: (...a: any[]) => playerSeekVideo(...(a as [string, number])),
|
||||
playerStop: (...a: any[]) => playerStop(...(a as [])),
|
||||
playerToggle: (...a: any[]) => playerToggle(...(a as [])),
|
||||
playerPlay: vi.fn(async () => ({})),
|
||||
playerPause: vi.fn(async () => ({})),
|
||||
playerSetSleepTimer: vi.fn(async () => ({})),
|
||||
playerCancelSleepTimer: vi.fn(async () => ({})),
|
||||
playerSetSubtitleTrack: vi.fn(async () => ({})),
|
||||
playerSwitchAudioTrack: vi.fn(async () => ({})),
|
||||
storageGetSeriesAudioPreference: vi.fn(async () => null),
|
||||
storageSaveSeriesAudioPreference: vi.fn(async () => ({})),
|
||||
},
|
||||
events: {
|
||||
playerStatusEvent: { listen: vi.fn(async () => () => {}) },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("$lib/stores/auth", () => ({
|
||||
auth: {
|
||||
getUserId: () => "user-1",
|
||||
getRepository: () => ({
|
||||
getHandle: () => "repo-1",
|
||||
getSubtitleUrl: async () => "",
|
||||
jrayActorsAt: async () => [],
|
||||
}),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("$app/navigation", () => ({
|
||||
goto: vi.fn(),
|
||||
}));
|
||||
|
||||
import { render, fireEvent, waitFor } from "@testing-library/svelte";
|
||||
import { tick } from "svelte";
|
||||
import VideoPlayer from "./VideoPlayer.svelte";
|
||||
import type { MediaItem } from "$lib/api/types";
|
||||
|
||||
function makeEpisode(): MediaItem {
|
||||
return {
|
||||
id: "ep1",
|
||||
name: "Episode 1",
|
||||
kind: "episode",
|
||||
durationMs: 24 * 60 * 1000, // 24 min
|
||||
} as MediaItem;
|
||||
}
|
||||
|
||||
async function mountAndroidPlayer() {
|
||||
const utils = render(VideoPlayer, {
|
||||
props: {
|
||||
media: makeEpisode(),
|
||||
streamUrl: "http://server/videos/ep1/master.m3u8",
|
||||
mediaSourceId: "src-1",
|
||||
needsTranscoding: false,
|
||||
onClose: vi.fn(),
|
||||
},
|
||||
});
|
||||
|
||||
await waitFor(() => expect(playerPlayItem).toHaveBeenCalled());
|
||||
await waitFor(() => expect(playerStop).toHaveBeenCalled());
|
||||
|
||||
const slider = utils.container.querySelector(
|
||||
'input[type="range"]'
|
||||
) as HTMLInputElement;
|
||||
const video = utils.container.querySelector("video") as HTMLVideoElement;
|
||||
expect(slider).not.toBeNull();
|
||||
return { ...utils, slider, video };
|
||||
}
|
||||
|
||||
function touch(x: number, y: number) {
|
||||
return { clientX: x, clientY: y } as Touch;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drag the seek bar with TOUCH events, the way a finger does on Android.
|
||||
*
|
||||
* A real drag along the bar moves the finger far enough that the container's
|
||||
* swipe detector (50px) would trigger if it were still listening.
|
||||
*/
|
||||
async function touchScrubTo(
|
||||
slider: HTMLInputElement,
|
||||
video: HTMLVideoElement,
|
||||
target: number
|
||||
) {
|
||||
await fireEvent.touchStart(slider, { touches: [touch(100, 700)] });
|
||||
// Finger travels across the bar. Small vertical wander is normal for a thumb
|
||||
// drag; the horizontal travel is what matters.
|
||||
await fireEvent.touchMove(slider, { touches: [touch(400, 690)] });
|
||||
slider.value = String(target);
|
||||
await fireEvent.input(slider);
|
||||
await fireEvent.touchMove(slider, { touches: [touch(700, 705)] });
|
||||
await fireEvent.change(slider);
|
||||
await fireEvent.touchEnd(slider, { touches: [] });
|
||||
if (video) await fireEvent(video, new Event("seeked"));
|
||||
await tick();
|
||||
}
|
||||
|
||||
describe("VideoPlayer seek bar — touch drag (Android)", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
for (const key of Object.keys(channelHandlers)) delete channelHandlers[key];
|
||||
});
|
||||
|
||||
it("a touch drag on the seek bar seeks to the dragged position", async () => {
|
||||
const { slider, video } = await mountAndroidPlayer();
|
||||
|
||||
await touchScrubTo(slider, video, 600);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(playerSeekVideo).toHaveBeenCalledWith("repo-1", 600, "src-1", null, true)
|
||||
);
|
||||
expect(parseFloat(slider.value)).toBeCloseTo(600);
|
||||
});
|
||||
|
||||
it("a touch drag on the seek bar never toggles play/pause", async () => {
|
||||
const { slider, video } = await mountAndroidPlayer();
|
||||
|
||||
await touchScrubTo(slider, video, 600);
|
||||
|
||||
// The container gesture layer must stay out of a control drag entirely:
|
||||
// no swipe mis-read, so no play/pause correction.
|
||||
expect(playerToggle).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("commits the seek on touchend even when the engine never fires `change`", async () => {
|
||||
const { slider, video } = await mountAndroidPlayer();
|
||||
|
||||
// Android's WebView does not reliably fire `change` for a touch interaction
|
||||
// on a range input. A tap on the track still moves the thumb and fires
|
||||
// `input` — the seek must be committed on release regardless.
|
||||
await fireEvent.touchStart(slider, { touches: [touch(400, 700)] });
|
||||
slider.value = "600";
|
||||
await fireEvent.input(slider);
|
||||
await fireEvent.touchEnd(slider, { touches: [] });
|
||||
if (video) await fireEvent(video, new Event("seeked"));
|
||||
await tick();
|
||||
|
||||
await waitFor(() =>
|
||||
expect(playerSeekVideo).toHaveBeenCalledWith("repo-1", 600, "src-1", null, true)
|
||||
);
|
||||
});
|
||||
|
||||
it("commits the seek exactly once when both touchend and change fire", async () => {
|
||||
const { slider, video } = await mountAndroidPlayer();
|
||||
|
||||
await touchScrubTo(slider, video, 600);
|
||||
|
||||
expect(playerSeekVideo).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("a touch drag on the seek bar does not hijack into brightness control", async () => {
|
||||
const { slider, video, container } = await mountAndroidPlayer();
|
||||
|
||||
await touchScrubTo(slider, video, 600);
|
||||
|
||||
// Brightness is applied as a CSS filter on the <video>; a control drag must
|
||||
// leave it untouched.
|
||||
const el = container.querySelector("video") as HTMLVideoElement | null;
|
||||
if (el) {
|
||||
expect(el.style.filter).toBe("brightness(1)");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* Regression tests for the `/player/[id]` surface decision.
|
||||
*
|
||||
* The bug these pin down: a video that was left and re-entered rendered in the
|
||||
* AUDIO player. Exiting a webview-rendered video does not stop the Rust
|
||||
* controller (`onReportStop` deliberately emits no `stopped` state, so the
|
||||
* autoplay handoff survives), so the backend still reports that episode/movie as
|
||||
* the loaded media. Re-entering the route therefore took the "already playing,
|
||||
* just show the UI" shortcut, which returns *before* a stream URL is fetched —
|
||||
* and the render then fell through to `<AudioPlayer>` because it treated
|
||||
* "video without a stream URL" as audio.
|
||||
*
|
||||
* TRACES: UR-005 | DR-100 | UT-092, UT-093
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { shouldReuseActivePlayback, resolvePlayerSurface } from "./playerSurface";
|
||||
|
||||
describe("shouldReuseActivePlayback", () => {
|
||||
it("reuses playback when the same audio track is already loaded", () => {
|
||||
expect(
|
||||
shouldReuseActivePlayback({
|
||||
requestedId: "track-1",
|
||||
activeMediaId: "track-1",
|
||||
isVideo: false,
|
||||
forceRestart: false,
|
||||
})
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("does NOT reuse playback for video, even when the backend reports it loaded", () => {
|
||||
// Video needs a full load: the shortcut skips fetching the stream URL, and
|
||||
// <VideoPlayer> cannot render without one.
|
||||
expect(
|
||||
shouldReuseActivePlayback({
|
||||
requestedId: "episode-1",
|
||||
activeMediaId: "episode-1",
|
||||
isVideo: true,
|
||||
forceRestart: false,
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("does not reuse playback for a different item", () => {
|
||||
expect(
|
||||
shouldReuseActivePlayback({
|
||||
requestedId: "track-2",
|
||||
activeMediaId: "track-1",
|
||||
isVideo: false,
|
||||
forceRestart: false,
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("does not reuse playback when nothing is loaded", () => {
|
||||
expect(
|
||||
shouldReuseActivePlayback({
|
||||
requestedId: "track-1",
|
||||
activeMediaId: null,
|
||||
isVideo: false,
|
||||
forceRestart: false,
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("does not reuse playback when an explicit start position is requested", () => {
|
||||
expect(
|
||||
shouldReuseActivePlayback({
|
||||
requestedId: "track-1",
|
||||
activeMediaId: "track-1",
|
||||
isVideo: false,
|
||||
startPosition: 42,
|
||||
forceRestart: false,
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("does not reuse playback when restarting (next-episode advance)", () => {
|
||||
expect(
|
||||
shouldReuseActivePlayback({
|
||||
requestedId: "episode-2",
|
||||
activeMediaId: "episode-2",
|
||||
isVideo: true,
|
||||
forceRestart: true,
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolvePlayerSurface", () => {
|
||||
it("renders the video surface for video with a stream URL", () => {
|
||||
expect(resolvePlayerSurface({ isVideo: true, streamUrl: "http://s/master.m3u8" })).toBe(
|
||||
"video"
|
||||
);
|
||||
});
|
||||
|
||||
it("renders the audio surface for audio content", () => {
|
||||
expect(resolvePlayerSurface({ isVideo: false, streamUrl: null })).toBe("audio");
|
||||
});
|
||||
|
||||
it("never renders video content in the audio surface when the stream URL is missing", () => {
|
||||
// A video whose stream URL has not resolved yet is pending, not audio —
|
||||
// otherwise the movie/episode shows up in the audio player.
|
||||
expect(resolvePlayerSurface({ isVideo: true, streamUrl: null })).toBe("pending");
|
||||
expect(resolvePlayerSurface({ isVideo: true, streamUrl: "" })).toBe("pending");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* Pure decisions for the `/player/[id]` route: which player surface to render,
|
||||
* and whether a load can be skipped because the backend is already playing the
|
||||
* requested item.
|
||||
*
|
||||
* Kept free of Svelte so both can be unit-tested without mounting the route.
|
||||
*
|
||||
* TRACES: UR-005 | DR-100 | UT-092, UT-093
|
||||
*/
|
||||
|
||||
/** Which player component the route should render. */
|
||||
export type PlayerSurface = "video" | "audio" | "pending";
|
||||
|
||||
export interface ReuseActivePlaybackInput {
|
||||
/** Item id the route was asked to play. */
|
||||
requestedId: string;
|
||||
/** Id of the media the backend currently reports as loaded, if any. */
|
||||
activeMediaId: string | null | undefined;
|
||||
/** Whether the requested item is video content. */
|
||||
isVideo: boolean;
|
||||
/** Explicit start position, if the caller asked for one. */
|
||||
startPosition?: number;
|
||||
/** Advancing to a next episode always restarts from the beginning. */
|
||||
forceRestart: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the route can show its UI over the backend's existing playback
|
||||
* instead of reloading the item (e.g. expanding the audio mini player).
|
||||
*
|
||||
* Never for video. The shortcut returns before a stream URL is fetched, which
|
||||
* is fine for audio (the backend owns the stream and the UI only mirrors it)
|
||||
* but leaves `<VideoPlayer>` with nothing to render. Leaving a webview-rendered
|
||||
* video does not clear the Rust controller's media — closing the route emits no
|
||||
* `stopped` state by design — so re-entering the same movie/episode hit this
|
||||
* shortcut and rendered the audio player instead.
|
||||
*/
|
||||
export function shouldReuseActivePlayback(input: ReuseActivePlaybackInput): boolean {
|
||||
return (
|
||||
!input.isVideo &&
|
||||
input.activeMediaId === input.requestedId &&
|
||||
!input.startPosition &&
|
||||
!input.forceRestart
|
||||
);
|
||||
}
|
||||
|
||||
export interface PlayerSurfaceInput {
|
||||
isVideo: boolean;
|
||||
streamUrl: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Which surface to render for the loaded item.
|
||||
*
|
||||
* Video without a stream URL is `pending`, never `audio` — falling through to
|
||||
* the audio player is how a movie/episode ended up in it.
|
||||
*/
|
||||
export function resolvePlayerSurface(input: PlayerSurfaceInput): PlayerSurface {
|
||||
if (input.isVideo) {
|
||||
return input.streamUrl ? "video" : "pending";
|
||||
}
|
||||
return "audio";
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
DOUBLE_TAP_WINDOW_MS,
|
||||
SEEK_FORWARD_SECONDS,
|
||||
SEEK_BACKWARD_SECONDS,
|
||||
createTapGestureState,
|
||||
registerTap,
|
||||
resolveSeekTarget,
|
||||
clampSeekTarget,
|
||||
END_SEEK_MARGIN_SECONDS,
|
||||
isSynthesizedTouchClick,
|
||||
isControlSurfaceTouch,
|
||||
TOUCH_CLICK_SUPPRESS_MS,
|
||||
} from "./tapGestures";
|
||||
|
||||
const SCREEN_WIDTH = 1000;
|
||||
const LEFT = 100;
|
||||
const RIGHT = 900;
|
||||
|
||||
function tap(state: ReturnType<typeof createTapGestureState>, x: number, at: number) {
|
||||
return registerTap(state, { x, screenWidth: SCREEN_WIDTH, now: at });
|
||||
}
|
||||
|
||||
/** Narrow a tap outcome to the seek variant, failing the test if it is not one. */
|
||||
function asSeek(outcome: ReturnType<typeof tap>) {
|
||||
if (outcome.action !== "seek") {
|
||||
throw new Error(`expected a seek outcome, got "${outcome.action}"`);
|
||||
}
|
||||
return outcome;
|
||||
}
|
||||
|
||||
describe("tap gesture resolution", () => {
|
||||
// Every tap acts IMMEDIATELY — there is no deferral and no timer.
|
||||
//
|
||||
// 1st tap: toggle play/pause
|
||||
// 2nd tap: seek, then toggle play/pause AGAIN
|
||||
//
|
||||
// The second toggle undoes the first, so a double tap seeks while leaving the
|
||||
// play state exactly as it was: playing -> jump and keep playing; paused ->
|
||||
// jump and stay paused. The old design deferred the first tap behind a 300ms
|
||||
// timer, which raced the synthesized click and produced a pause/unpause loop.
|
||||
|
||||
it("toggles play/pause immediately on the first tap", () => {
|
||||
const state = createTapGestureState();
|
||||
expect(tap(state, RIGHT, 1000)).toEqual({ action: "togglePlayPause" });
|
||||
});
|
||||
|
||||
it("seeks forward 30s AND toggles again on a second right-side tap", () => {
|
||||
const state = createTapGestureState();
|
||||
tap(state, RIGHT, 1000);
|
||||
const second = asSeek(tap(state, RIGHT, 1150));
|
||||
|
||||
expect(second.seekSeconds).toBe(SEEK_FORWARD_SECONDS);
|
||||
expect(second.seekSeconds).toBe(30);
|
||||
expect(second.feedback).toBe("right");
|
||||
// The re-toggle is what preserves the play state across a double tap.
|
||||
expect(second.togglePlayPause).toBe(true);
|
||||
});
|
||||
|
||||
it("seeks back 10s AND toggles again on a second left-side tap", () => {
|
||||
const state = createTapGestureState();
|
||||
tap(state, LEFT, 1000);
|
||||
const second = asSeek(tap(state, LEFT, 1100));
|
||||
|
||||
expect(second.seekSeconds).toBe(SEEK_BACKWARD_SECONDS);
|
||||
expect(second.seekSeconds).toBe(-10);
|
||||
expect(second.feedback).toBe("left");
|
||||
expect(second.togglePlayPause).toBe(true);
|
||||
});
|
||||
|
||||
it("net play state is unchanged by a double tap (two toggles cancel out)", () => {
|
||||
const state = createTapGestureState();
|
||||
let playing = true;
|
||||
const apply = (outcome: ReturnType<typeof tap>) => {
|
||||
if (outcome.action === "togglePlayPause") playing = !playing;
|
||||
else if (outcome.action === "seek" && outcome.togglePlayPause) playing = !playing;
|
||||
};
|
||||
|
||||
apply(tap(state, RIGHT, 1000)); // toggle -> paused
|
||||
apply(tap(state, RIGHT, 1100)); // seek + toggle -> playing again
|
||||
expect(playing).toBe(true);
|
||||
|
||||
// And from paused, a double tap leaves it paused.
|
||||
playing = false;
|
||||
apply(tap(state, RIGHT, 2000));
|
||||
apply(tap(state, RIGHT, 2100));
|
||||
expect(playing).toBe(false);
|
||||
});
|
||||
|
||||
it("treats a tap after the window as a fresh first tap", () => {
|
||||
const state = createTapGestureState();
|
||||
tap(state, RIGHT, 1000);
|
||||
const late = tap(state, RIGHT, 1000 + DOUBLE_TAP_WINDOW_MS + 1);
|
||||
|
||||
expect(late.action).toBe("togglePlayPause");
|
||||
});
|
||||
|
||||
it("only ever has first and second taps — the tap after a pair is a fresh toggle", () => {
|
||||
const state = createTapGestureState();
|
||||
tap(state, RIGHT, 1000);
|
||||
expect(tap(state, RIGHT, 1100).action).toBe("seek");
|
||||
|
||||
// The pair is consumed. The next tap is a FIRST tap again, so it toggles
|
||||
// play/pause — there is no "third tap" concept.
|
||||
expect(tap(state, RIGHT, 1200).action).toBe("togglePlayPause");
|
||||
});
|
||||
|
||||
it("accumulates repeated double taps on the same side", () => {
|
||||
const state = createTapGestureState();
|
||||
tap(state, RIGHT, 1000);
|
||||
const a = asSeek(tap(state, RIGHT, 1100));
|
||||
tap(state, RIGHT, 1200);
|
||||
const b = asSeek(tap(state, RIGHT, 1300));
|
||||
|
||||
expect(a.seekSeconds).toBe(30);
|
||||
expect(b.seekSeconds).toBe(30);
|
||||
});
|
||||
|
||||
it("uses the tap side, so a double tap split across halves follows the second tap", () => {
|
||||
const state = createTapGestureState();
|
||||
tap(state, LEFT, 1000);
|
||||
const second = asSeek(tap(state, RIGHT, 1100));
|
||||
|
||||
expect(second.seekSeconds).toBe(SEEK_FORWARD_SECONDS);
|
||||
expect(second.feedback).toBe("right");
|
||||
});
|
||||
|
||||
it("cancel() makes the next tap a fresh first tap (swipe interrupted the pair)", () => {
|
||||
const state = createTapGestureState();
|
||||
tap(state, RIGHT, 1000);
|
||||
state.cancel();
|
||||
|
||||
// Without cancel() this would have been the seeking second tap.
|
||||
expect(tap(state, RIGHT, 1100).action).toBe("togglePlayPause");
|
||||
});
|
||||
});
|
||||
|
||||
describe("seek target resolution", () => {
|
||||
const DURATION = 600;
|
||||
|
||||
it("adds the delta to the reported position", () => {
|
||||
expect(resolveSeekTarget({ delta: 30, reportedPosition: 100, duration: DURATION })).toBe(130);
|
||||
});
|
||||
|
||||
it("clamps to zero when rewinding past the start", () => {
|
||||
expect(resolveSeekTarget({ delta: -10, reportedPosition: 4, duration: DURATION })).toBe(0);
|
||||
});
|
||||
|
||||
it("clamps short of the duration when skipping past the end", () => {
|
||||
// Never land exactly on `duration`: hls.js would then request the segment
|
||||
// that starts at/after the media end, which the server never produces —
|
||||
// the fetch times out and the gap-controller stalls in a pause loop.
|
||||
expect(resolveSeekTarget({ delta: 30, reportedPosition: 590, duration: DURATION })).toBe(
|
||||
DURATION - END_SEEK_MARGIN_SECONDS
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps the end clamp strictly inside the media for a long transcoded item", () => {
|
||||
// Regression: seeking near the end of a ~105min transcoded item clamped to
|
||||
// the exact runtime (6330.324s), making hls.js fetch segment 1055 which
|
||||
// starts at 6336.33s — past the end. That segment 404s/times out forever.
|
||||
const runtime = 6330.324;
|
||||
const target = resolveSeekTarget({ delta: 30, reportedPosition: 6320, duration: runtime });
|
||||
|
||||
expect(target).toBeLessThan(runtime);
|
||||
expect(target).toBeCloseTo(runtime - END_SEEK_MARGIN_SECONDS, 5);
|
||||
});
|
||||
|
||||
it("does not clamp below zero for media shorter than the end margin", () => {
|
||||
expect(resolveSeekTarget({ delta: 30, reportedPosition: 1, duration: 1 })).toBe(0);
|
||||
});
|
||||
|
||||
it("chains off a pending target so rapid taps do not compound off a stale position", () => {
|
||||
// The player has not yet reported the first seek's result, so the
|
||||
// reported position is still the pre-seek value.
|
||||
const first = resolveSeekTarget({ delta: 30, reportedPosition: 100, duration: DURATION });
|
||||
const second = resolveSeekTarget({
|
||||
delta: 30,
|
||||
reportedPosition: 100,
|
||||
duration: DURATION,
|
||||
pendingTarget: first,
|
||||
});
|
||||
|
||||
expect(second).toBe(160);
|
||||
});
|
||||
|
||||
it("ignores a pending target once the player has caught up past it", () => {
|
||||
const target = resolveSeekTarget({
|
||||
delta: 30,
|
||||
reportedPosition: 200,
|
||||
duration: DURATION,
|
||||
pendingTarget: 130,
|
||||
});
|
||||
|
||||
expect(target).toBe(230);
|
||||
});
|
||||
|
||||
it("falls back to the delta alone when duration is unknown", () => {
|
||||
expect(resolveSeekTarget({ delta: 30, reportedPosition: 100, duration: 0 })).toBe(130);
|
||||
});
|
||||
});
|
||||
|
||||
describe("control-surface touches are not gestures", () => {
|
||||
// Regression: the gesture listener is on the outer container and touch events
|
||||
// bubble, so tapping the bottom play/pause button ran the gesture handler
|
||||
// (toggle #1) AND the button's own click handler (toggle #2). The two
|
||||
// cancelled out and the control appeared dead.
|
||||
it("treats a tap on a button as a control, not a gesture", () => {
|
||||
expect(isControlSurfaceTouch([{ tag: "svg" }, { tag: "button" }, { tag: "div" }])).toBe(true);
|
||||
});
|
||||
|
||||
it("treats the seek bar input as a control", () => {
|
||||
expect(isControlSurfaceTouch([{ tag: "input" }, { tag: "div" }])).toBe(true);
|
||||
});
|
||||
|
||||
it("treats anything inside the controls bar as a control", () => {
|
||||
expect(
|
||||
isControlSurfaceTouch([{ tag: "span" }, { tag: "div", isPlayerControls: true }])
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("lets a tap on the bare video surface through as a gesture", () => {
|
||||
expect(isControlSurfaceTouch([{ tag: "video" }, { tag: "div" }, { tag: "div" }])).toBe(false);
|
||||
});
|
||||
|
||||
it("is case-insensitive about tag names", () => {
|
||||
expect(isControlSurfaceTouch([{ tag: "BUTTON" }])).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("synthesized touch-click suppression", () => {
|
||||
// Regression: pausing renders a full-screen play-overlay button over the
|
||||
// video, so the compatibility click Android synthesizes from the tap lands on
|
||||
// the OVERLAY, not the <video>. With no guard there it re-toggled and undid
|
||||
// the pause — pausing looked impossible while unpausing worked fine (the
|
||||
// overlay is removed when playing, so nothing intercepted that direction).
|
||||
it("suppresses a click with detail 0 (clearly synthesized)", () => {
|
||||
expect(isSynthesizedTouchClick(0, 10_000, 0)).toBe(true);
|
||||
});
|
||||
|
||||
it("suppresses a real-detail click that closely follows a touch tap", () => {
|
||||
const tapAt = 10_000;
|
||||
expect(isSynthesizedTouchClick(1, tapAt + 120, tapAt)).toBe(true);
|
||||
expect(isSynthesizedTouchClick(1, tapAt + TOUCH_CLICK_SUPPRESS_MS - 1, tapAt)).toBe(true);
|
||||
});
|
||||
|
||||
it("allows a genuine mouse click well after any touch", () => {
|
||||
const tapAt = 10_000;
|
||||
expect(isSynthesizedTouchClick(1, tapAt + TOUCH_CLICK_SUPPRESS_MS + 1, tapAt)).toBe(false);
|
||||
});
|
||||
|
||||
it("allows a genuine mouse click when no touch has ever happened", () => {
|
||||
expect(isSynthesizedTouchClick(1, 10_000, 0)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("seek target clamping (shared by skip and seek-bar drag)", () => {
|
||||
it("keeps a mid-stream target untouched", () => {
|
||||
expect(clampSeekTarget(100, 600)).toBe(100);
|
||||
});
|
||||
|
||||
it("pulls a drag to the very end back inside the media", () => {
|
||||
// The seek bar's max IS the duration, so dragging fully right yields
|
||||
// exactly `duration` — the value that triggers the dead-segment stall.
|
||||
expect(clampSeekTarget(6330.324, 6330.324)).toBeCloseTo(6330.324 - END_SEEK_MARGIN_SECONDS, 5);
|
||||
});
|
||||
|
||||
it("clamps negative and non-finite targets to zero", () => {
|
||||
expect(clampSeekTarget(-5, 600)).toBe(0);
|
||||
expect(clampSeekTarget(NaN, 600)).toBe(0);
|
||||
});
|
||||
|
||||
it("leaves the target alone when the duration is unknown", () => {
|
||||
expect(clampSeekTarget(500, 0)).toBe(500);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,234 @@
|
||||
/**
|
||||
* Tap-gesture interpretation for the video player surface.
|
||||
*
|
||||
* Every tap acts IMMEDIATELY — there are only first and second taps, and no
|
||||
* deferral:
|
||||
*
|
||||
* 1st tap: toggle play/pause
|
||||
* 2nd tap (within the window): seek, then toggle play/pause AGAIN
|
||||
*
|
||||
* The second toggle undoes the first, so a double tap seeks while leaving the
|
||||
* play state exactly as it started — playing stays playing, paused stays paused.
|
||||
*
|
||||
* This replaced a design that deferred the first tap behind a 300ms timer so it
|
||||
* could be cancelled if a second tap arrived. That deferral raced the
|
||||
* compatibility `click` Android's WebView synthesizes after a touch tap: the
|
||||
* timer cleared its own handle *before* running the toggle, reopening the guard
|
||||
* that was meant to suppress the late click, which then toggled a second time.
|
||||
* The result was a play/pause loop about a second apart. Acting immediately
|
||||
* removes the timer, the window race, and the loop.
|
||||
*
|
||||
* TRACES: UR-005, UR-061 | DR-092, DR-095, DR-098 | UT-085, UT-086, UT-087, UT-088
|
||||
*/
|
||||
|
||||
/** A second tap within this window pairs with the previous one (seek + re-toggle). */
|
||||
export const DOUBLE_TAP_WINDOW_MS = 300;
|
||||
|
||||
/**
|
||||
* How long after a touch tap a mouse `click` is assumed to be the compatibility
|
||||
* event the browser synthesizes from that touch. Android's WebView can deliver it
|
||||
* noticeably late, so this is generous.
|
||||
*/
|
||||
export const TOUCH_CLICK_SUPPRESS_MS = 700;
|
||||
|
||||
/**
|
||||
* Whether a touch landed on an interactive control rather than the bare video
|
||||
* surface, and so must NOT be interpreted as a play/pause or seek gesture.
|
||||
*
|
||||
* The gesture listener sits on the outer container, and touch events bubble, so
|
||||
* without this a tap on the bottom control bar runs the gesture handler (toggle
|
||||
* #1) *and* the button's own click handler (toggle #2) — the two cancel out and
|
||||
* the button appears dead. Buttons, links, inputs (the seek bar), and anything
|
||||
* inside an element marked `data-player-controls` are treated as controls.
|
||||
*
|
||||
* Takes the ancestor chain as plain tag/attribute pairs so the rule is unit
|
||||
* testable without a DOM.
|
||||
*/
|
||||
export function isControlSurfaceTouch(
|
||||
ancestors: Array<{ tag: string; isPlayerControls?: boolean; isPlayerSurface?: boolean }>
|
||||
): boolean {
|
||||
const INTERACTIVE = new Set(["button", "a", "input", "select", "textarea", "label"]);
|
||||
for (const node of ancestors) {
|
||||
// `data-player-surface` wins over the tag check: the full-screen play overlay
|
||||
// is a <button> but is visually the video itself, and must keep taking tap
|
||||
// gestures — otherwise the second tap of a double tap (which lands on it,
|
||||
// because the first tap paused and raised it) is discarded and seeking dies.
|
||||
if (node.isPlayerSurface === true) return false;
|
||||
if (node.isPlayerControls === true) return true;
|
||||
if (INTERACTIVE.has(node.tag.toLowerCase())) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a `click` should be ignored because a touch tap already handled it.
|
||||
*
|
||||
* EVERY click target layered over the video must consult this — not just the
|
||||
* `<video>` element. Pausing swaps in a full-screen play-overlay button, so the
|
||||
* synthesized click lands on *that* button rather than the video, and an
|
||||
* unguarded handler there re-toggles and undoes the pause (pause appeared
|
||||
* impossible while unpause worked, because unpausing removes the overlay).
|
||||
*
|
||||
* `detail === 0` catches the synthesized click on engines that report it; the
|
||||
* recency check covers engines that report a real `detail`.
|
||||
*/
|
||||
export function isSynthesizedTouchClick(
|
||||
detail: number,
|
||||
now: number,
|
||||
lastTouchTapAt: number
|
||||
): boolean {
|
||||
if (detail === 0) return true;
|
||||
return now - lastTouchTapAt < TOUCH_CLICK_SUPPRESS_MS;
|
||||
}
|
||||
|
||||
/** Double tap on the right half: skip forward. */
|
||||
export const SEEK_FORWARD_SECONDS = 30;
|
||||
|
||||
/** Double tap on the left half: skip back. */
|
||||
export const SEEK_BACKWARD_SECONDS = -10;
|
||||
|
||||
export type TapFeedback = "left" | "right";
|
||||
|
||||
export type TapOutcome =
|
||||
/** First tap: toggle play/pause right now. */
|
||||
| { action: "togglePlayPause" }
|
||||
/**
|
||||
* Second tap: seek, and toggle play/pause again so the first tap's toggle is
|
||||
* undone and the play state survives the double tap unchanged.
|
||||
*/
|
||||
| {
|
||||
action: "seek";
|
||||
seekSeconds: number;
|
||||
feedback: TapFeedback;
|
||||
togglePlayPause: true;
|
||||
};
|
||||
|
||||
export interface TapInput {
|
||||
/** Tap x position, viewport pixels. */
|
||||
x: number;
|
||||
screenWidth: number;
|
||||
now: number;
|
||||
}
|
||||
|
||||
export interface TapGestureState {
|
||||
/**
|
||||
* Forget the previous tap, so the next one is treated as a first tap. Used
|
||||
* when the gesture turns out to be a swipe.
|
||||
*/
|
||||
cancel(): void;
|
||||
}
|
||||
|
||||
interface InternalState extends TapGestureState {
|
||||
lastTapTime: number;
|
||||
}
|
||||
|
||||
export function createTapGestureState(): TapGestureState {
|
||||
const state: InternalState = {
|
||||
lastTapTime: 0,
|
||||
cancel() {
|
||||
state.lastTapTime = 0;
|
||||
},
|
||||
};
|
||||
return state;
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify a tap and return the action to perform *now*.
|
||||
*
|
||||
* A tap that closely follows another is the second of a pair: it seeks and
|
||||
* re-toggles play/pause (undoing the first tap's toggle). Any other tap is a
|
||||
* first tap and simply toggles. Nothing is deferred, so there is no window to
|
||||
* race and no third-tap case — a consumed pair resets the state.
|
||||
*/
|
||||
export function registerTap(state: TapGestureState, input: TapInput): TapOutcome {
|
||||
const s = state as InternalState;
|
||||
const sinceLastTap = input.now - s.lastTapTime;
|
||||
|
||||
if (s.lastTapTime > 0 && sinceLastTap > 0 && sinceLastTap < DOUBLE_TAP_WINDOW_MS) {
|
||||
s.lastTapTime = 0; // pair consumed; the next tap is a first tap again
|
||||
const isLeftSide = input.x < input.screenWidth / 2;
|
||||
return isLeftSide
|
||||
? {
|
||||
action: "seek",
|
||||
seekSeconds: SEEK_BACKWARD_SECONDS,
|
||||
feedback: "left",
|
||||
togglePlayPause: true,
|
||||
}
|
||||
: {
|
||||
action: "seek",
|
||||
seekSeconds: SEEK_FORWARD_SECONDS,
|
||||
feedback: "right",
|
||||
togglePlayPause: true,
|
||||
};
|
||||
}
|
||||
|
||||
s.lastTapTime = input.now;
|
||||
return { action: "togglePlayPause" };
|
||||
}
|
||||
|
||||
/**
|
||||
* Safety margin (seconds) kept between a clamped seek target and the media end.
|
||||
*
|
||||
* Landing *exactly* on `duration` makes hls.js request the segment whose start
|
||||
* time is at/after the end of the media. The server never produces that segment,
|
||||
* so the fetch times out and hls.js' gap-controller stalls forever at the last
|
||||
* buffered position — surfacing as "unpausing bounces straight back to paused".
|
||||
* One segment length (~6s for Jellyfin's ts segments) is comfortably clear of
|
||||
* the final segment boundary.
|
||||
*/
|
||||
export const END_SEEK_MARGIN_SECONDS = 6;
|
||||
|
||||
/**
|
||||
* Clamp an absolute seek target into the safely-playable range.
|
||||
*
|
||||
* Shared by the relative-skip path ({@link resolveSeekTarget}) and the seek-bar
|
||||
* drag path, which can otherwise land exactly on `duration` because the range
|
||||
* input's `max` is the duration itself.
|
||||
*/
|
||||
export function clampSeekTarget(target: number, duration: number): number {
|
||||
if (!Number.isFinite(target) || target < 0) return 0;
|
||||
if (duration > 0 && target > duration - END_SEEK_MARGIN_SECONDS) {
|
||||
return Math.max(0, duration - END_SEEK_MARGIN_SECONDS);
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
export interface SeekTargetInput {
|
||||
/** Relative offset in seconds (negative rewinds). */
|
||||
delta: number;
|
||||
/** Latest position reported by the player — the authoritative source. */
|
||||
reportedPosition: number;
|
||||
/** Media duration; 0/unknown disables the upper clamp. */
|
||||
duration: number;
|
||||
/**
|
||||
* Target of a seek already requested but not yet reflected in
|
||||
* `reportedPosition`. Consecutive double taps chain off this so they add up
|
||||
* instead of all resolving against the same stale position.
|
||||
*/
|
||||
pendingTarget?: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a relative skip to the absolute position the facade expects.
|
||||
*
|
||||
* The player facade seeks by absolute position only (the backend picks the seek
|
||||
* strategy), so the delta is applied here — against the pending target when one
|
||||
* is still in flight and still ahead of what the player has reported.
|
||||
*/
|
||||
export function resolveSeekTarget(input: SeekTargetInput): number {
|
||||
const { delta, reportedPosition, duration, pendingTarget } = input;
|
||||
|
||||
const base =
|
||||
pendingTarget != null && Math.abs(pendingTarget - reportedPosition) > 0.5 && pendingTarget > reportedPosition
|
||||
? pendingTarget
|
||||
: reportedPosition;
|
||||
|
||||
const target = base + delta;
|
||||
if (target < 0) return 0;
|
||||
// Clamp strictly inside the media — see END_SEEK_MARGIN_SECONDS. Guard against
|
||||
// going negative on media shorter than the margin itself.
|
||||
if (duration > 0 && target > duration) {
|
||||
return Math.max(0, duration - END_SEEK_MARGIN_SECONDS);
|
||||
}
|
||||
return target;
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { videoFitClass, fittedVideoSize } from "./videoFit";
|
||||
|
||||
describe("videoFitClass", () => {
|
||||
it("fills the container instead of capping at the source's intrinsic size", () => {
|
||||
const cls = videoFitClass();
|
||||
// max-w/max-h only shrink oversized media; a 480p source would stay a small
|
||||
// box in the middle of a large window.
|
||||
expect(cls).not.toContain("max-w-full");
|
||||
expect(cls).not.toContain("max-h-full");
|
||||
expect(cls).toContain("w-full");
|
||||
expect(cls).toContain("h-full");
|
||||
});
|
||||
|
||||
it("preserves aspect ratio while fitting (letterbox, never crop)", () => {
|
||||
const cls = videoFitClass();
|
||||
expect(cls).toContain("object-contain");
|
||||
expect(cls).not.toContain("object-cover");
|
||||
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 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
// Sizing rules for the HTML5 <video> element in the full-screen player.
|
||||
// Extracted from VideoPlayer.svelte so the fit behaviour is unit-testable.
|
||||
|
||||
/**
|
||||
* Classes applied to the <video> element so it fits the player viewport.
|
||||
*
|
||||
* TRACES: UR-005
|
||||
*
|
||||
* `max-w-full max-h-full` only ever *shrinks* oversized media, so a source
|
||||
* smaller than the window (e.g. 480p on a 1080p display) rendered at its
|
||||
* intrinsic size - a small box in the middle of a black screen. Filling the
|
||||
* container and letting `object-contain` do the scaling fits the picture to
|
||||
* whichever axis constrains it, in both directions, preserving aspect ratio.
|
||||
*/
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -53,7 +53,7 @@
|
||||
<MediaCard
|
||||
{item}
|
||||
size="medium"
|
||||
showProgress={group.id !== "artists"}
|
||||
showProgress={group.id !== "artists" && group.id !== "people"}
|
||||
onclick={() => onItemClick?.(item)}
|
||||
/>
|
||||
{/each}
|
||||
|
||||
@@ -95,6 +95,63 @@ describe("Html5PlayerAdapter", () => {
|
||||
expect(video.play).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// A stalling HLS stream makes hls.js' gap-controller nudge the element, which
|
||||
// aborts an in-flight play(). That AbortError is transient — the element is
|
||||
// still trying to play — so it must not be surfaced as a player error, or the
|
||||
// UI reports failure ~once a second for the whole stall.
|
||||
it("play() does not report an interrupted-by-pause AbortError as an error", async () => {
|
||||
const abort = new DOMException(
|
||||
"The play() request was interrupted by a call to pause().",
|
||||
"AbortError"
|
||||
);
|
||||
video.play = vi.fn(async () => {
|
||||
throw abort;
|
||||
});
|
||||
|
||||
await adapter.play();
|
||||
|
||||
expect(host.onError).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("play() still reports a genuine failure", async () => {
|
||||
video.play = vi.fn(async () => {
|
||||
throw new DOMException("no supported source", "NotSupportedError");
|
||||
});
|
||||
|
||||
await adapter.play();
|
||||
|
||||
expect(host.onError).toHaveBeenCalledTimes(1);
|
||||
expect(String((host.onError as any).mock.calls[0][0])).toContain("play() failed");
|
||||
});
|
||||
|
||||
it("play() coalesces concurrent attempts into one element.play() call", async () => {
|
||||
// During a stall the UI and recovery paths can both ask to play. Stacking
|
||||
// element.play() calls is what generates the AbortError storm.
|
||||
let resolvePlay: () => void = () => {};
|
||||
video.play = vi.fn(
|
||||
() =>
|
||||
new Promise<void>((r) => {
|
||||
resolvePlay = () => {
|
||||
video.paused = false;
|
||||
r();
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
const first = adapter.play();
|
||||
const second = adapter.play();
|
||||
resolvePlay();
|
||||
await Promise.all([first, second]);
|
||||
|
||||
expect(video.play).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("play() works again after a previous attempt settled", async () => {
|
||||
await adapter.play();
|
||||
await adapter.play();
|
||||
expect(video.play).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("pause() calls element.pause()", async () => {
|
||||
video.paused = false;
|
||||
await adapter.pause();
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user