Compare commits

...
Author SHA1 Message Date
amarildoandGitHub 33557f0eda chore(deps): update golang docker tag to 1.27.1 (#2289) 2026-09-08 16:21:35 +02:00
edde746 a4f3c5393b fix(release): scope symbol uploads to shipped platform artifacts
Mixed-platform build trees sent stale artifacts in unbounded DIF assembles. Select shipped identities explicitly, bound uploads, and require native, Dart-map, source, and release phases to complete.

Verified the actual mixed-build Android release against a local Bugs server, 10 uploader tests, 39 release tests, and scoped Dart analysis. The repository-wide analyzer reports unrelated warnings in nested worktrees; the pre-commit hook is skipped for that known check failure.
2026-09-08 12:58:11 +02:00
edde746 533028fa0e build(android): pin mpv-build with the audio-output stall watchdog
Moves the native pin to edde746/mpv-build@6fcf0f2 so Android MPV ends
playback with an audio-output error instead of freezing when the audio
device stops taking audio. Also picks up 5521906 (hardware subtitles
aligned with the video rectangle), which sits between the previous pin and
this one.
2026-09-08 02:38:04 +02:00
edde746 d7f1d4a8fc fix(player): exit with an audio-output error when the Android audio device stalls
On a Fire TV whose audio HAL stopped taking audio (#2255 investigation),
mpv playback froze silently: the AudioTrack writer blocked forever and
nothing surfaced. The native side now gives up after one bounded recovery
and ends the file with MPV_ERROR_AO_INIT_FAILED; this carries that verdict
to the UI.

The JNI bridge forwards mpv_event_end_file.error (previously discarded),
MpvEvent.EndFile exposes it as a typed MpvError, and
MpvEndFileDiagnostics tags an AO failure with the audio-output-failed
cause. The Dart failure policy treats that cause as terminal before any
HTTP diagnosis or the live-TV ladder, since re-opening the stream would
only run the same dead output again, and the player shows localized
guidance instead of raw log text. Progress is preserved; nothing is
marked completed.

Requires the mpv-build revision carrying the audiotrack stall watchdog;
until the lock is bumped, the new cause can only come from audio-only
media whose output fails to open.
2026-09-08 02:27:10 +02:00
github-actions[bot] c6c0ce8bea chore: update cask to 2.19.1 2026-09-07 20:20:58 +00:00
edde746 5a7e0966a3 chore: bump version to 2.19.1 2026-09-07 20:50:59 +02:00
edde746 c84b12eacd fix(livetv): allow cold MediaBrowser tuners time to open
Emby and Jellyfin Live TV could fail before playback when opening a cold tuner took longer than ten seconds. Use the existing thirty-second tune timeout only for live PlaybackInfo requests that open a source, preserving other request budgets and transport aborts.

Cover delayed initial tuning and recovery, bounded cancellation without replay, and unchanged VOD and metadata timeouts.

close #2274
2026-09-07 20:32:16 +02:00
edde746 f9b9fbf611 fix(player): restore Android MPV surfaces after screensaver
Paused playback could remain stuck after the screensaver destroyed its video and OSD surfaces, leaving later resume and initialization blocked.

Attach video and OSD surfaces together, drain placeholder frames, and bound surface retirement with explicit failure handling. Preserve native surface ownership through teardown and cover recreation, pause preservation, and disposal.

close #2249
2026-09-07 20:32:16 +02:00
edde746 e727f5bef4 fix(emby): negotiate MPEG-TS HLS for live TV
Emby Live TV can fail to parse fMP4 HLS fragments, and retrying the same negotiated URL cannot change the segment container.

Restrict Emby Live TV negotiation to the existing MPEG-TS profile on initial tune and direct-play recovery. Preserve direct play, stream copy, Jellyfin negotiation, and Emby VOD. Cover transport scoping and recovery with protocol regressions.

close #2273
2026-09-07 20:32:16 +02:00
edde746 3cf412b9c8 fix(player): use native AV1 decoding when Android hardware support is absent
Software MediaCodec AV1 decoding on Pixel fails during ambient lighting and lock/unlock surface transitions, leaving corrupt or black video.

Check hardware AV1 capability before decoder initialization and reuse the per-file software decoding policy to select dav1d with GPU output. Preserve hardware decoding for supported files.

close #2272
2026-09-07 20:32:15 +02:00
edde746 048bf688b2 fix(player): await terminal playback reporting before desktop exit
Closing the app during video playback left the backend session alive until it timed out. Await shared shutdown completion and the terminal video report before closing server clients, while keeping exit bounded when teardown stalls.

close #2275
2026-09-07 20:09:12 +02:00
edde746 8238705d3e fix(android): pin MPV with stable frame scheduling
Android MPV could turn timing jitter into uneven frame presentation without reporting dropped frames.

Pin mpv-build d38d607fd299e106a83f3557e310ac4b8202b39c to consume cadence prediction and refresh-selection hysteresis. Update the unified pin and Apple lock mirrors; only Android binary artifacts change.

Refs #2262
2026-09-07 07:01:09 +02:00
edde746 722c4ddd00 fix(homebrew): migrate cask to postflight steps
Homebrew warns when loading the deprecated postflight hook. Use structured steps with install-time appdir expansion while preserving recursive extended-attribute removal.

close #2259
2026-09-07 07:01:09 +02:00
56b990c04c feat(jellyfin): report the platform in the MediaBrowser client name (#2261)
Jellyfin and Emby sessions expose Client and DeviceName but no platform,
so dashboards and session trackers (Tracearr's normalizeClient, for one)
keyword-match the Client string the way they do for "Jellyfin Android TV"
and "Swiftfin tvOS". Plezy sent Client="Plezy" on every platform, so every
install showed up as platform "Plezy", and an unresolvable device name
became Device="Plezy" as well.

Add jellyfinClientName, which appends the platform ("Plezy Android TV",
"Plezy tvOS", "Plezy iOS", ...), and jellyfinDeviceName, which falls back
through the hardware model and the platform before the app name, and use
both at the two Jellyfin/Emby header call sites. Every emitted client
string was checked against Tracearr's matcher. The Plex headers and the
DisplayPreferences client key are unchanged.


Claude-Session: https://claude.ai/code/session_0134eXvhukgvG6Szg5NTwAim

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-07 01:39:07 +02:00
edde746 b904c11750 fix(network): use default ports for websocket connections
Watch Together could not reach relays when their URLs omitted a port because Dart passes port 0 to custom WebSocket connection factories.

Resolve port 0 to the HTTP/HTTPS default in the Happy Eyeballs factory while preserving explicit destination and proxy ports. Cover portless ws/wss connections with isolated regression tests.

close #2263
2026-09-07 01:30:08 +02:00
edde746 8870852a9e fix(player): reset TrueHD passthrough state after seeks
TrueHD passthrough retains stale muxer timing and partial MAT frames across seeks, including Android's startup decoder refresh. Pin mpv-build d3a1e12c9da054026aa0d546fee29e2ceeae0226, which publishes the upstream SPDIF reset backport for every native platform, and synchronize all Apple and non-Apple locks.

Refs #2262. The timing-warning regression is reproduced and fixed; sustained Fire TV judder still needs reporter confirmation.
2026-09-07 01:18:57 +02:00
github-actions[bot] 6039fde33b chore: update cask to 2.19.0 2026-09-06 21:34:04 +00:00
edde746 82ae3609f6 chore: bump version to 2.19.0 2026-09-06 22:11:54 +02:00
edde746 32f72c6dd2 chore(deps): normalize lockfile git revision quoting 2026-09-06 22:08:01 +02:00
edde746 8c5d0b4213 fix(seerr): refresh authority without crossing session ownership
Permission changes could be confused with expired authentication, and delayed session persistence could cross a profile boundary.

Refresh raw authority after route denials and foreground resumes without login or request replay. Fence refreshes to the current binding, serialize persisted session ownership, and reconcile open request surfaces after grants and revocations.
2026-09-06 20:21:11 +02:00
edde746 3dd5b5d48e fix(details): invalidate deleted items and pending actions
Deleting a detail item or its ancestor could leave stale controls visible and allow pending actions to complete.

Make exact and complete bulk deletion terminal for the detail subtree, invalidate asynchronous continuations, and retain a localized unavailable state when the first route cannot pop. Normalize translation sources and regenerate the affected output.
2026-09-06 20:21:11 +02:00
edde746 b6aa83af74 fix(watch-together): separate room authority from player bindings
Source reloads and role changes could reset room state or let obsolete player continuations change the current session.

Separate room authority from output bindings, fence selection and playback work with ownership leases, preserve room state across failed opens, and serialize native seek completion before newer intent.
2026-09-06 20:21:11 +02:00
edde746 4712414b3d fix(focus): reclaim detached grid nodes without stealing live focus
Historical focus contexts kept detached grid nodes alive, while stale menu captures could queue focus after their row was gone.

Track actual attachment lifetime, preserve pending and remembered destinations, and restore captured focus only to a live eligible leaf without overriding a covering route.
2026-09-06 20:21:11 +02:00
edde746 89b326e3f3 fix(catalog): retain native titles within the bounded matching budget
Native-title library copies could be missed when only display and romaji titles reached the bounded search budget.

Prefer typed Japanese titles, preserve row and detail aliases, and keep matching within the existing four-query budget and external-ID verification rules.
2026-09-06 20:21:11 +02:00
edde746 cf0dd0607e fix(profiles): keep playback preferences bound to their authenticated account
Picker ordering could select another account for playback preferences, and delayed operations could publish data after the active account changed.

Resolve playback authority independently of the account picker and fence repository, controller, and inline settings operations to their original authenticated account.
2026-09-06 20:21:11 +02:00
edde746 9a44f062a6 fix(network): own connection races and rearm exhausted push channels
One stalled DNS family or a cancelled WebSocket upgrade could keep a connection attempt alive. Push channels also stayed exhausted after the app returned to the foreground.

Race address families independently, own connection tasks through upgrade handoff, and rearm exhausted push channels on a genuine foreground resume.
2026-09-06 20:21:11 +02:00
edde746 178634e943 fix(watch-together): authenticate retained room recovery
A transport reconnect could recover the wrong room or retain obsolete host authority.

Authenticate retained membership and recover the relay-authoritative role without falling back to create or join. Release retained membership through authenticated teardown and document the coordinated relay rollout.
2026-09-06 20:21:11 +02:00
edde746 99f4fda55a fix(android): retire mpv sessions without blocking hook callbacks 2026-09-06 19:11:25 +02:00
edde746 908ccbb233 fix(android): retain mpv callbacks and end dismissed TV input sessions
Minified MPV initialization aborted because callback keep rules retained obsolete JNI signatures. Android TV IME dismissal also left editing active, requiring an extra Back press to leave the screen.

Keep only the named JNI callbacks without duplicating argument signatures and exercise them through the permanent minified reachability gate. Centralize native editing-session termination, observe owning-view keyboard dismissal, and reject stale completion or reopening work.

Verified the minified gate on Galaxy Z Fold3, debug MPV lifecycle and log-level suites on SHIELD and Pixel 7, native Done/Previous and two-Back behavior on SHIELD and Fire TV, 76 focused Flutter tests, analyzer parity, and shrinker checks. Both new regressions reject the original implementations.
2026-09-06 17:53:30 +02:00
edde746 2b176861b7 fix(mobile): keep landscape foreground controls clear of the trailing system inset
On a landscape phone, the app's mobile shell lets the navigation rail absorb the leading inset and leaves the trailing one for each screen to own — but several screens never did. The Plex-only alphabet scroll handle sat under the notch or rounded corner, the library grid's last column and the folder tree ran under it, the player's landscape header and timeline dropped horizontal insets entirely, and the catalog detail and Discover hero content used fixed margins. Automotive was already protected at the root.

Each region owner now applies a horizontal-only SafeArea to its foreground content: the browse tab's alpha overlay and content scroll view, the mobile video controls in landscape, the catalog detail's content column, and the Discover hero text and buttons. Backdrops, hero artwork, and the video surface stay full-bleed, and the root inset policy is unchanged.
2026-09-06 15:33:36 +02:00
edde746 647971a5d6 fix(seerr): follow permission grants and revocations on open request surfaces
A Seerr permission change reached the app only as a sign-in-time snapshot: a catalog detail decided once, when opened, whether it could show Request, and the request sheet only re-read the mask when something else rebuilt it. A grant left the action hidden until the screen was reopened, a revocation left it visible, and submitting then surfaced Seerr's raw English 403 body while the sheet stayed open with gates it no longer had. A disconnect while a detail was open left it holding a source wrapping a disposed client.

Permission changes now propagate through the existing provider graph without replacing clients: the client adopts the fresh `/auth/me` body it already fetches while telling a permission miss from a dead session, and a live-session denial is a typed `SeerrPermissionException`. The detail screen derives its Request eligibility from the account's current mask and source on every build; the sheet reconciles grants (loads destinations, shows 4K) and revocations (trims them, or closes with a localized reason the host surfaces) and re-checks authority locally before submitting.
2026-09-06 15:25:49 +02:00
edde746 a18c54f5ce fix(logs): keep record boundaries in copied log selections
Copying a drag or keyboard selection from the logs screen produced one run-on line: every log entry and the device header is its own paragraph, and Flutter's selection area concatenates adjacent paragraphs with no separator.

Each record is now its own selection container whose selected text ends with a newline, and the screen-level container drops the one dangling after the last selected record, so a partial drag copies exactly what was highlighted. Rows stay lazily built with their geometry unchanged, and the toolbar's copy-all export keeps its own format.
2026-09-06 15:16:37 +02:00
edde746 c5ed666aa9 fix(navigation): leave a deleted detail through its own route, not whatever is on top
Deleting the last episode or season from a detail page popped the wrong route whenever something covered the detail: the download progress dialog (the deletion event fires before the delete returns), a player, a sheet fallback modal, or another detail. The cover disappeared and the empty detail stayed on screen.

The detail now leaves through the route it was pushed as: popped when it is current, removed from under the cover otherwise, with the same null result; a detail that is the navigator's only route stays, and a route already leaving is not touched twice. A delayed player launch checks that the route it was started from is still active before pushing, so a launch whose detail was deleted during its awaits does not land on an unrelated screen.
2026-09-06 15:06:08 +02:00
edde746 6580c4cf97 fix(library): credit a content push only when the reload it triggered lands
A library that a server push had marked stale stayed stale for good if the reload triggered on the next activation failed: the tab wrote the push's epoch down as consumed before starting the reload, so every later activation, tab switch, and visibility replay saw nothing to do until another push arrived. The same shared load-start snapshot was also read by whichever load committed last rather than the one that had taken it, and in folder grouping the epoch was credited from a paged fetch nobody renders while the displayed folder tree was never reloaded.

Each load now owns its epoch snapshot and commits it only when its data actually landed and it is still the current load; a failed or dropped load releases the snapshot without credit. An in-flight snapshot still dedupes an activation that lands mid-fetch. Folder grouping refreshes the displayed tree and credits the push only when that refresh succeeded, and switching libraries resets the previous library's credit.
2026-09-06 15:04:51 +02:00
edde746 3ca565baa9 fix(watch-together): adopt the room on promotion independently of the player, and fence old-role continuations
A guest promoted to host while its player was detached — mid-reload, in the lobby, between episodes — took the room over with no epoch: the coordinator could not answer state requests, and when the player rebound it opened a fresh epoch that resumed a paused room, reset the room rate to the new host's saved speed, and published the reload position as the room's timeline. Separately, commands issued under the previous role kept landing after the role changed: a guest's end-of-file hard seek still played the player after promotion, leaving the new host broadcasting a moving position while gating on peers, and a demoted host's rate continuation still reported a room rate change.

The host coordinator now adopts the room — epoch identity, rate, intent, phase, and the inherited anchor — the moment the role changes, whether or not a player is bound; a player bound later for the same media rebinds into that epoch and keeps its pause, rate, and timeline. Authority over the player is a per-engine generation, revoked before every role change, epoch change, detach, and disposal, and every asynchronous follow-up captures and re-checks it; the attachment's acknowledgement ledger still survives role swaps, and the coordinator now watches consumed acks so a play its predecessor set in motion cannot run under a stopped room. The reconciler ends its epoch when the host leaves the player, so a promotion after that adopts nothing.
2026-09-06 15:04:39 +02:00
edde746 bc1a715411 fix(linux): read the restart position off the GTK main thread
Every seek on Linux stalled the UI thread: the playback-restart handler read `time-pos` with a synchronous mpv_get_property from the GLib main context, which parks that thread on mpv's playloop for as long as the core takes — and the core's render path can itself be waiting on the main thread to post the next render job.

The position is now requested through the existing asynchronous property registry when the restart is dequeued, with the source identity captured at that moment, and the unchanged playback-restart envelope is sent when the reply lands. A source boundary — start-file or end-file — delivers any restart still waiting as a position-less envelope for its captured source and retires the reply, so no restart is ever reported after its source's boundary or attributed to the next source. No new event type or thread.
2026-09-06 15:00:49 +02:00
edde746 c20a6cf162 fix(catalog): keep a library copy's label through a retry that lost its stamp
A catalog detail's library labels disappeared for the rest of the session after a re-lookup: the matcher replaced each answering server's copies with the raw items of the new wave, so a Jellyfin retry whose best-effort ancestors stamp failed overwrote a labeled copy with an unlabeled one, and the unlabeled copy was then memoized as the authoritative hit.

Membership stays the answering server's to define, but every copy it returns again is folded onto its predecessor through the shared merge policy, which now treats library id and title as a pair: a copy naming a different library takes the new id with its own (possibly null) title instead of inheriting the old library's name, one naming the same library fills a missing title, and one naming no library keeps the known pair.
2026-09-06 15:00:27 +02:00
edde746 ab1c9b9afd fix(tv): claim the whole Back press when the text-input host closes an IME session
On Android TV, pressing Back to dismiss the keyboard while editing a field with no back handler of its own — an mpv config row, for instance — also popped the screen. The shared native text-input host consumed only the Back key-down that closed the IME session; the matching key-up then reached an ancestor that pops on key-up, and the same press's platform back callback was never deduped.

The host now marks the back coordinator and arms the key-up suppressor when it closes the session, and consults the suppressor before the field's own onBack so a field without one still swallows its in-flight key-up. IME completion and a second, intentional Back behave as before.
2026-09-06 15:00:27 +02:00
edde746 9ef3de985f fix(livetv): keep backed channel logos legible when adapting them to light surfaces
A light logo that carries its own dark ink — dark text on a white plate, white letters inside a dark outline — lost its contrast on light theme surfaces: the tone analysis granted the light-neutral remap to any mostly-light frame, and the remap then folded the plate and its ink into one dark tone.

A light majority no longer grants the remap. The analysis first decides whether the transformation is safe: on the sampled grid, four linear scans find neutral pixels enclosed on every side by the opposite neutral tone, and when most of either tone is enclosed the artwork is classified as backed and left untouched, like a dark disc already was. Dark ink that only touches the mark along an edge — an underline, a badge — stays open and keeps adapting, so accented and mixed-color marks remap as before. `LogoTone.dark` is renamed `backed` to name what the gate protects.
2026-09-06 15:00:09 +02:00
edde746 54438c8d7a test(android): drive fallback opens through an explicit native-command seam
Three ExoPlayerPluginTest fallback cases failed after commandForSource started rejecting a load with no native player: the test core seamed property writes but not commands, so every fallback loadfile reported OPEN_FAILED. The core now takes an optional command runner beside the property writer; with none, a command without a native player still fails. The tests assert what mpv was handed — the loadfile URI as open ownership and its pause option as playback intent — instead of reflecting private flags, and one sets up its held state through setPauseIntentForLoad. ExoPlayer production behavior is unchanged.
2026-09-06 14:53:05 +02:00
edde746 1d5b175cc8 fix(android): bind every libmpv JNI call and callback to its native session
Tearing down the mpv player while a hook handler or property write was still in flight could reach the replacement player: the native side kept one process-global handle, the Kotlin wrapper was published before the native session existed, callbacks were routed to whichever wrapper was current, and hook continuations were validated only against a `closed` flag read before the native call. A retiring player's on_preloaded handler could therefore reconfigure the successor's tracks, its late `mpv_hook_continue` could land on the successor's core, and the successor could ingest the predecessor's end-file and property tail.

Every native session now has an immutable monotonic id minted by nativeCreate. Create/init/destroy hold a write lock; every other JNI entry takes a read lock and is refused when it names a retired session, so a call admitted under a live session keeps that handle alive until it returns and retirement waits for it. The event thread is bound to its session before it starts and stamps every callback with it; Kotlin dispatches a callback only to the wrapper published for that session and passes its session on every native call. create() publishes the wrapper only after the native session exists, and a superseded create fails instead of publishing a dead session.
2026-09-06 14:50:51 +02:00
edde746 b80aa1916e chore(watch-together): regenerate the recent-rooms serializer with the pinned toolchain 2026-09-06 14:43:03 +02:00
edde746 5c40ba0505 build(android): pin mpv-build with the pending-vid property
Move the native pin to edde746/mpv-build@3fd89c2, whose android binaries carry
fork patch 0010 (read-only pending-vid: mpv's own default video selection,
readable inside on_preloaded). The Android decode-policy hook reads it to route
DV-P5 and Hi10 for the track mpv will actually select. Only the android group
moved (key 23f2764e9e97 -> d109720a9b8e); linux, windows and Apple bytes are
unchanged.
2026-09-06 13:49:41 +02:00
edde746 cbc47790c3 test(watch-together): lift the widget-test HTTP mock for loopback relay tests
The relay-authority tests drive a real loopback relay; with the upgrade now
running on a per-attempt HttpClient, the widget binding's mock client
answered every upgrade with 400.
2026-09-06 13:33:39 +02:00
edde746 baa31742cb fix(player): bind live TV clock generations to the source the load reports
Live-TV clock generations were matched to mpv sources first-in-first-out: every
start-file popped the oldest registered open, on the assumption of exactly one
start-file per open in dispatch order. Opens without a generation on the same
player, an Android loadfile rejected silently by nativeCommand, and the
independent delivery of the command ack and the start-file event all broke
that, so a seek that reopened the stream could calibrate against the wrong
source.

The loadfile reply now carries mpv's playlist_entry_id on Android, Apple, Linux
and Windows, PlayerNative.open resolves with it, and the live session binds
each generation to that id explicitly. Source events that land before the
reply are buffered per id and replayed on binding; a rejected or unreachable
load fails its generation instead of leaving a phantom; opens with no
generation are invisible to clock binding. Android now reports a rejected mpv
command as COMMAND_FAILED like the other cores.
2026-09-06 13:29:37 +02:00
edde746 01750ad92b fix(network): own a WebSocket connection attempt through cancellation and TLS
Cancelling a WebSocket connect (deadline, stop, dispose, a newer attempt)
only dropped or timed out a future: the shared never-closed HttpClient kept
the address race and TLS handshake alive, and once SecureSocket.secure had
detached the raw socket even a real task cancel was a no-op, so after
ClientHello the peer stayed open and the connect future never settled.

The happy-eyeballs task now owns the transport through the TLS handoff:
cancel is idempotent, settles the task at once, destroys an undelivered raw
winner, and destroys whatever a handshake in flight eventually yields. Each
WebSocket upgrade runs on its own HttpClient inside a connection attempt
with completion plus cancellation; the library-event, companion-remote and
Watch Together relay sockets cancel it on stop, disposal, deadline and
supersession. dart:io offers no handle to abort an in-flight handshake, so
a black-holed ClientHello closes when the handshake settles, not at cancel.
2026-09-06 13:28:51 +02:00
edde746 5de2d28166 fix(seerr): only a rejection Seerr itself emits may invalidate a session
A JSON-bodied 401 or 403 from a gateway or auth proxy in front of Seerr was
read as a Seerr session rejection, so a valid Quick Connect session was
unlinked by a Cloudflare or forward-auth wall, and the /auth/me confirmation
probe was never checked for the same.

One endpoint-aware classifier now recognizes only the two rejection shapes
Seerr's middleware and error handler actually produce (403 with their exact
bodies; the forwarded Jellyfin 401 on /auth/jellyfin) and is applied to the
primary request, the identity probe, the post-reauth retry, login and the
post-login identity read. Anything else keeps the stored credentials and
surfaces as an intermediary failure; genuine expiry and credential rejection
keep their re-auth and unlink behavior.
2026-09-06 13:24:52 +02:00
edde746 88e6d33221 fix(seerr): drop stale destination detail loads in the request sheet
Switching the destination server or the 4K variant while a previous server's
details were still loading let the late response install the old profiles,
root folders and tags, clear the loading state, and overwrite tags the user
had edited; adopting no server left the spinner stuck.

Every destination/variant adoption, including null, now advances a
selection generation; a detail load applies neither its success nor its
failure unless it still belongs to the accepted generation, defaults hydrate
once per generation, and an explicitly emptied tag list stays empty.
2026-09-06 13:24:52 +02:00
edde746 ac7fb87ade fix(android): route decode policy by the video track mpv will select
The Dolby Vision and Hi10 decode policies run in mpv's on_preloaded hook,
before track selection, and read the first demuxed video track. A file whose
first video track is not the one mpv picks (attached pictures, a
default-flagged second track, --vlang, an explicit vid) got the wrong
routing.

The hook now resolves one pending track for both policies: an explicit
vid=no or vid=N is authoritative on its own, and auto asks the fork's
pending-vid property, which runs mpv's own default selection ahead of time.
On a libmpv without that property the first-track guess stays, logged once.
The predecoder gate is unchanged (#2065). The fork patch lands separately
through the native pin flow.
2026-09-06 13:22:20 +02:00
edde746 ce3a3b177c fix(watch-together): keep the room position across a host promotion
A guest promoted to host published its own player position as the room's
anchor the moment its readiness gates passed, but readiness is not
alignment: that player could be mid-correction, drifted, or at a stale
pre-seek spot, and every guest was then pulled to the wrong position.

The controller now reads the room position on the old host's clock before
discarding it and hands it to the new coordinator as a transition anchor.
The promoted host broadcasts that anchor, gates the group start, and aligns
its own player to it through the normal seek path; only once the seek has
rendered (or cannot: live, or a render timeout) does its local position
become the room's. A player replaced mid-handover inherits the anchor, and
a paused room hands over its paused position unchanged.
2026-09-06 13:22:01 +02:00
edde746 b795ef1604 fix(library): replay a push dropped under a route once the tab is visible again
A library tab sitting under an opaque route (detail page, player) has
TickerMode disabled, so a server push arriving then was dropped while the
provider still marked the library stale; nothing observed the route pop, and
the tab stayed stale until the user switched tabs.

The tab now listens to the same effective-visibility notifier its suppression
predicate reads and, when an active stale tab becomes visible, wakes the
existing paced in-place refresh — no clearing reload, so scroll and focus
stay put. Main-tab activation still consumes the epoch first, so no second
pass is scheduled.
2026-09-06 13:17:40 +02:00
edde746 deeec6810d fix(library): never let merged library events narrow their refresh coverage
Coalescing library-change frames could lose libraries: a frame that could
not name its libraries (whole server) merged with a frame naming {A} flushed
as {A}, and an event naming physical Jellyfin folders where only some
resolved to a loaded library bumped the resolved one and silently skipped the
grouped view the rest belonged to.

Whole-server scope is now absorbing in the socket's pending window, and the
provider widens to every library on the server whenever any named id fails
to resolve; a fully resolved id set stays precise.
2026-09-06 13:16:51 +02:00
edde746 d27cb61a2b fix(watch-together): re-authenticate a release the relay rejects for a changed role
A host transfer that lands while a peer is leaving made the exit lie: the
relay answers a role-mismatched leave or endSession with the same
peer_id_unavailable it uses for a lost identity, so a guest promoted
mid-teardown read the refusal as 'already released' and walked away as the
live host of a running room, while a demoted host's refused endSession
surfaced as a failed exit with its guest reservation leaked.

Release now tells re-admission failures (terminal: the token names no
identity here) apart from release failures. A refused release reauthenticates
through the existing token; the joined admission names the current host, and
the next pass sends the operation that role requires, inside the existing
bounded retry loop. Success still means an acknowledgment, room absence, or
established loss of identity.
2026-09-06 13:16:34 +02:00
edde746 e660a06499 fix(watch-together): seed a fresh host's room rate from its saved speed
A host that created a room started the room at 1.0x while its own player later
moved to the saved playback speed: the coordinator seeded the room rate from
the player at attach, but attach runs before the track-selection pass that
applies the saved speed, and rate intent is (deliberately) no longer inferred
from the player's rate stream. Guests then kept correcting against a rate the
host was not running.

The screen now resolves the saved speed up front and declares it through
attachment; the coordinator seeds a fresh epoch with it before the loading
broadcast and applies it to the host player, keeps the room's agreed rate on a
same-item reload, and a promoted host without a broadcast rate falls back to
the declared one. While a room owns playback, track-selection passes no longer
reapply the local saved speed underneath it.
2026-09-06 13:11:28 +02:00
edde746 2fb04a14ad fix(player): read the restart position without holding the Apple lifecycle lock
iOS/tvOS playback could deadlock on PLAYBACK_RESTART: the event queue held
lifecycleLock across a synchronous mpv_get_property(time-pos) round-trip while
the core waited on the avfoundation VO, which itself waits on the main thread;
the main thread meanwhile blocked on lifecycleLock in isLifecycleActive.

Snapshot the handle under the lock and query without it. The read stays on the
serial event queue, which also serializes destruction, so the handle cannot be
torn down mid-read.
2026-09-06 13:07:41 +02:00
edde746 c228a12d1e fix(media): preserve profile, source, and focus identity across refreshes
Library refreshes could move focus, catalog lookups could cross profile or query boundaries, and detail labels could describe a different source from playback.

Keep hub and grid focus with committed item identities. Pace pushed deletions without delaying local eviction. Bind push channels to committed authentication sessions and catalog completeness to the active profile and effective query. Resolve preview source and container defaults with playback selection rules.

The shared client contracts and all consumers migrate together. Include regression fixtures and document safe host-transfer compatibility.

Verified: 6826 Flutter tests passed, 5 skipped; aggregate quality checks and final analyzer/formatting checks passed. All 86 owned paths match the isolated validated snapshot.
2026-09-06 04:34:58 +02:00
edde746 d47bcdec12 fix(music): respect horizontal system insets in the mini-player
The floating mini-player could overlap horizontal system padding on mobile layouts.

Compose directional safe insets with navigation width without counting the rail twice. Preserve suspended-navigation, RTL, and desktop placement.

Verified by the complete Flutter suite: 6826 passed, 5 skipped. Aggregate quality checks passed in the isolated validation checkout.
2026-09-06 04:33:30 +02:00
edde746 bd9fb38413 fix(watch-together): preserve player ownership and enforce atomic host transfers 2026-09-06 04:03:14 +02:00
edde746 dca8029a99 fix(settings): normalize legacy skip modes across persistence boundaries 2026-09-06 03:54:43 +02:00
edde746 7aa1679036 fix(network): retain socket ownership through connection cancellation 2026-09-06 03:53:14 +02:00
edde746 9ae34473af build(apple): refresh pod locks for media-controls SwiftPM migration 2026-09-06 03:51:44 +02:00
edde746 3fb8794619 fix(player): dispatch newer live seeks after a failed reopen 2026-09-06 03:50:26 +02:00
edde746 98c6a09b41 chore(player): remove temporary native playback diagnostics
Production playback still carried recurring Windows HDR probes, Android subtitle profiling, and verbose mpv logs with debug logging disabled.

Remove the Windows probe, pin the published mpv-build profiler cleanup, and honor Android debug logging preferences for video and music while preserving warnings and errors.
2026-09-06 02:30:08 +02:00
edde746 621b50141c test(windows): decouple source lifecycle assertions from diagnostic logs
The native source-lifecycle test fails when HDR diagnostics emit a log during file load. Exclude diagnostic messages from lifecycle assertions and remove the incidental total-event count while retaining signed source IDs, queued-event ownership, and finite-position checks.
2026-09-06 01:37:54 +02:00
edde746 02dc57bd55 fix(windows): restore snapped windows in their monitor workspace
Snapped windows on secondary displays can restore with the primary monitor's taskbar offset. Normalize the saved screen rect using its own monitor inset and reverse that conversion when checking restored placement. Keep missing-monitor fallback coordinates in the creation monitor's workspace.

The Win32 API model changes four-cycle drift from plus or minus 192 pixels to zero. Single-monitor native fullscreen and quit-fullscreen/relaunch roundtrips passed; physical multi-monitor and mixed-DPI verification remains unavailable in the disconnected session.
2026-09-06 01:37:54 +02:00
edde746 38f00f51c4 fix(windows): throttle HDR probing by elapsed time
Playback event bursts make HDR diagnostics query mpv and the display far more often than intended. Schedule samples and display reads from steady-clock completion deadlines, and read both source metadata streams from one node.

The x64 60 fps smoke reduced property sample runs from 21.7/s to 3.25/s. A generated per-frame HDR metadata stream still produced diagnostic changes; these are sampled changes, not per-frame LUT invalidation counts.
2026-09-06 01:37:54 +02:00
edde746 77422f2e6e style(android): format GL capability and surface helpers
Native formatting rejects the release baseline's GL capability and surface helpers. Apply the repository ktlint formatting without changing behavior.
2026-09-06 01:37:54 +02:00
AlbertandGitHub d2d73f35f8 fix(jellyfin): send the token as ApiKey so Jellyfin 12 accepts trickplay, subtitle and socket URLs (#2252)
Jellyfin 12 ships with EnableLegacyAuthorization=false, which drops the
legacy `api_key=` query spelling (jellyfin/jellyfin#15559). Every
authenticated URL Plezy self-authenticates via the query string then
fails with 401: trickplay sprite sheets (visible as missing scrub
thumbnails), transcoding/subtitle/Live TV URLs built through
_withApiKey, and the library-event websocket (403 on upgrade).

`ApiKey=` is read unconditionally by Jellyfin 10.8 through 12, while
Emby only accepts `api_key=`, so the parameter name now comes from
MediaBrowserDialect.tokenQueryParam. Emby output is byte-identical.
Image URLs keep `api_key`: Jellyfin serves item images without
authentication, and the artwork cache keys strip that exact name.

Fixes #2247
2026-09-06 01:21:51 +02:00
edde746 d6f0aa8936 fix(catalog): keep library copies held by a server that was never asked
A title's copy disappeared from a catalog item's library matches when the
server holding it went offline, and the screen then claimed the title was not
in the library at all.

The reverse-lookup fan-out only reaches online clients, so a registered
server that is offline lands in neither the succeeded, failed nor cancelled
set. The fold read that absence as "left the account" and dropped the
server's verified copies. Worse, the surviving wave looked complete, so it
was memoized for the rest of the profile session and never asked again. With
no server online at all, every server's copies were erased and the detail
screen asserted "Not in your library" over servers nobody had queried.

LibraryLookupResult now names the registered servers a wave could not even
reach, which needs a registered-server set on MultiServerManager because an
auth-rejected Plex server holds no client at all. The fold's rule is stated
positively -- only a server that answered may replace its own entry -- a wave
that skipped a server is never memoized past the TTL, and the detail screen
counts those servers as unchecked alongside the ones that failed.
2026-09-06 00:53:55 +02:00
edde746 e35f6b3a64 fix(navigation): keep the D-pad highlight on its title when content shifts
A live library refresh or a sort change moved the highlight to a different
title, and Select then opened that one instead of the one the viewer chose.

Grid focus nodes are keyed by index while the cards are keyed by item, so a
merge that inserts an item before the focused slot leaves the highlight
pinned to the slot rather than the title: Flutter parks the node across the
rebuild and the replacement card re-attaches it. The library refresh already
compensated the scroll offset for that same index shift; focus is equally
index-pinned and was not compensated at all.

GridFocusNodeMixin.remapGridFocus carries the highlight with the item, and
the three grids that mutate content in place now use it: library browse, the
paginated card grid behind collections and playlists, and hub detail -- where
a user changing the sort was enough, no server push needed. Hub cards also
gain a key; they had none, so the element was silently updated with a
different item. The key is the global one, because aggregated hubs such as
Continue Watching can hold colliding per-server ids.
2026-09-06 00:53:55 +02:00
edde746 80bc37eb34 fix(watch-together): gate a promoted host on its roster and its player rate
A promoted host started playing while other participants were still loading,
and could run at a different speed than the one it told the room.

The coordinator resolves the first epoch's readiness synchronously inside
attach, so seeding the known-peer roster afterwards had already missed it:
the fresh epoch saw an empty room, solo-started, and marked the first start
complete, after which the still-loading peers no longer gated anything. The
roster now seeds in _createCoordinator, so no coordinator exists without the
room it has to wait for.

Adopting the room's rate on promotion only set the value the coordinator
broadcasts. A guest that was paused when the rate changed never applied it to
its player -- position is aligned while stopped, rate is not -- so the new
host advertised one speed and ran another, and every guest kept correcting
against the difference. The host player is the room clock, so an adopted rate
is now applied to it.
2026-09-06 00:53:40 +02:00
edde746 0490de5b5b fix(relay): publish admission authority under the room lock
A guest joining while the host handed the room to someone else could end up
following the host everyone else had just left behind.

join installs the client into the room and snapshots HostPeerID under
room.mu, then released the lock before enqueueing joined. The client is a
hostChanged recipient and a legal transfer target from the moment it is
installed, so a transfer committing in that gap enqueued the newer authority
first and the stale joined frame overwrote it on the client. transferHost
already enqueues while holding the lock for exactly this reason; joined
carries the same authority field and did not.

The admission frame is now built and enqueued while the room is still locked,
and enqueueFrame never blocks, so nothing waits on network I/O under the
lock. A beforeJoinRoomAck barrier alongside the two existing test hooks pins
the ordering: a transfer cannot commit while an admission is unpublished.
2026-09-06 00:53:40 +02:00
edde746 f738e74994 fix(watch-together): derive the host role from the relay's authority
A host that handed the room to someone else and then lost its connection
could not get back in, and a guest promoted while it was offline came back
as a guest.

The relay names the host in every admission and every hostChanged, but the
client also kept its own _isHost flag beside that identity. Reconnect adopted
the relay's host id without recomputing the flag, so the two disagreed: a
demoted host still required the response to name itself and rejected its own
legitimate re-admission as an invalid response, retry after retry; a promoted
guest updated the session but left the transport a guest, so ending the
session sent leave instead of endSession and room re-creation stayed off.

The role is now derived from the host identity rather than stored next to it.
Before the relay has admitted us there is no authority yet, so the role is
the one we announced, which is what releasing a possibly-committed setup has
to go by. The identity assertion moves from mutable role state to message
semantics: a created response must name us, a joined response is adopted.
2026-09-06 00:53:28 +02:00
edde746 65af57dd93 fix(playback): preview tracks from the same media source the player will use
The detail page's audio/subtitle preview could contradict playback on Jellyfin and Emby: a server default of -1 (subtitles off) previewed as a subtitle track, and a missing default with a container-default subtitle previewed as on where playback plays none (#1779 again).

The preview rebuilt a MediaSourceInfo from the item's version by hand, a third mapping beside the two the backends use for playback, and had already diverged twice. It now runs the ladder over the MediaSourceInfo the backend maps for playback, fetched from the metadata cache in the existing probe, and the hand-built mapping is deleted.
2026-09-05 23:14:12 +02:00
edde746 bc483a8206 fix(catalog): keep a server's verified library copies when it sits out a later lookup wave
A catalog item that had a copy on server A lost it from the detail page when a later refresh could not reach A: partial results expire after the negative TTL and the fresh wave replaced the cache as a unit, so A failing while B answered empty left nothing, with no evidence A had removed anything.

The cache now holds per-server answers with one invariant: a server's answer is replaced only by that server. Servers that failed or were cancelled keep their last-known copies, servers named in no set have left the account, and the failed set still passes through so the outage stays visible and the wave is retried.
2026-09-05 23:14:11 +02:00
edde746 c0d090079b fix(library-events): close a websocket whose upgrade lands after the connect deadline
A library notification connection that timed out could still complete later and stay open after the owner was disposed. IOWebSocketChannel.connect applies connectTimeout with Future.timeout and drops the pending connect, so nothing could ever close a socket that finished late.

The channel factory now resolves only to established channels: it owns WebSocket.connect, applies its own deadline, closes a late upgrade, and returns a channel built from the resolved socket. The socket class no longer holds half-open channels, which also removes the connected-flag workaround around the library's close semantics.
2026-09-05 23:14:11 +02:00
edde746 6147736bba build(android): compile the MPV lifecycle device test only for the debug instrumentation variant
The minified instrumentation variant, which the R8 reachability gate builds, no longer compiled: MpvLifecycleDeviceTest references MpvLifecycleTestActivity, which exists only in the debug source set. The test moves to androidTestDebug so it is compiled only when instrumentation targets debug.
2026-09-05 23:14:11 +02:00
edde746 7885bea016 fix(watch-together): let a reconnecting guest adopt a host transfer it was offline for
A guest whose connection dropped during a host transfer could not get back in. The relay broadcasts hostChanged only to connected peers, and the guest's reconnect rejected the re-admission because the host differed from the one it had pinned, then left the room.

The pin predates transfers. The relay is the authority on host identity and verifies the reconnect token, so a valid re-admission naming a different host can only be a transfer: the client now adopts it and surfaces it through the same onHostChanged path.

On the relay, hostChanged is enqueued while the room lock is still held. Two transfers in quick succession run on different connections, and enqueueing after unlock could deliver the older authority change after the newer one; enqueueFrame never blocks, so holding the lock across it is safe.
2026-09-05 23:14:11 +02:00
edde746 05598f1708 fix(watch-together): gate host transfer on a join capability instead of the sync version
Transferring the room to a 2.18.0 client left it with no host: that build speaks the same sync protocol version but does not handle the relay's hostChanged broadcast, so eligibility passed, the relay moved authority, the current host stepped down and the target never stepped up. A 2.18.0 bystander kept following the demoted host.

Join messages now advertise capabilities beside the version (cap: [hostTransfer]). A transfer requires the target and every same-version bystander to advertise it; peers on another version are already outside the room's sync and do not count. A version bump would have excluded every older peer from mixed rooms for a feature they may never use.

An older relay rejects transferHost as invalid_message; while a transfer is pending that is now a failed transfer, not a session error.
2026-09-05 23:14:11 +02:00
edde746 dc06b2e181 fix(watch-together): bound self-stall recovery by remaining media and a wait deadline
A host that stalled near the end of a file kept the whole room paused for good. Recovery demanded three times the stall in buffered headroom, and with ten seconds of media left a four-second stall asked for twelve that could never arrive; the known-cache branch re-checked every half second forever.

The two limits are now explicit: how much headroom to want (scaled by the stall, capped by what is left to buffer) and how long to wait for it (a deadline from the stall's end, shared with the no-cache branch). selfRecoveryMaxHoldMs was a headroom cap and is renamed to say so.
2026-09-05 23:14:11 +02:00
edde746 dbf8bf54c5 fix(tv): keep the Discover rail focus claim through an explicit sidebar handoff
Selecting Home from the sidebar on TV left focus on the collapsed sidebar item: the content appeared, but the remote went nowhere. MainScreen hands a tab over while focus still sits on the sidebar item that selected it, and the guard added to lapse stale rail-focus claims read that as the user having navigated away.

Where focus sits cannot tell a live handoff from a stale claim. What distinguishes a stale claim is that focus moved after it was armed, so the claim now records the primary focus at arm time and lapses only once focus has changed and rests off-screen. A handoff made while hubs are still loading is honored when they land; a claim armed on a bare scope still lapses when the user moves to the sidebar.
2026-09-05 23:14:11 +02:00
edde746 36e898067a fix(subtitles): honor Render Resolution on the Android mpv OSD plane
The subtitle "Render Resolution" setting was shown to every Android user
but only reached the ExoPlayer overlay; the mpv vo=mediacodec OSD plane
always rasterized at the full surface size. On a Fire TV Stick 4K Max
Gen 2 the edde746/plezy#2242 phone sign then cost up to 2 s of libass
render plus composite per frame at 1080p, showing late and lingering past
the cut.

Pass the fraction to the mpv core on initialize and give the OSD
SurfaceView a fixed buffer size below its view size; mpv rasterizes at
that size and the compositor scales the plane. At 1/2 the same sign
tracks its zoom at 12-24 updates/s and clears on the cut.
2026-09-05 23:12:28 +02:00
edde746 a475e92d7e fix(logs): let D-pad leave the app-bar back button on the logs screen
On TV, pressing Up on the Logs screen put focus on the back button and no
direction key could move it again, so the upload/copy actions were out of
reach (edde746/plezy#2242). The SelectionArea added in 8fe7e4bcf installs
always-enabled caret-movement actions that Android's default text-editing
shortcuts map plain arrow keys to; the keys were consumed as no-op
selection moves and never reached DirectionalFocusIntent.

Override those two intents above the region with an action that is
disabled for the collapsing (unshifted) variants and defers to the
region's own handler otherwise, so Shift+Arrow selection keeps working.
2026-09-05 23:12:28 +02:00
edde746 55985b8f9c build(player): bump mpv-build to 847fa34e8f9e 2026-09-05 21:47:39 +02:00
edde746 c5968029e0 fix(plex): send metadata type on Discover guid match so library items resolve for the watchlist
"Add to Watchlist" disappeared from library card menus after the first open, and
the detail-screen bookmark never appeared, for every Plex movie and show (#1873).
Plex Discover's `/library/metadata/matches` answers a `guid` lookup only when
paired with the numeric metadata `type`; a bare guid returns an empty container.
The empty result was cached as "no source can hold this item", hiding the entry
on the next open.

`PlexDiscoverClient.match` now takes the item kind and sends `type=1` (movie) or
`type=2` (show) alongside the guid; other kinds return null without a request.

Fixes #1873
2026-09-05 15:15:19 +02:00
edde746 cd22475cb6 fix(plex): send the media type to Discover's matches endpoint so external ids resolve
Adding a Trakt, MAL or library title to the Plex watchlist failed with "no
rating key": /library/metadata/matches answers an empty container unless
`type` is sent, so every external-id resolution against Discover came back
empty. The client now passes the movie/show type with the guid.
2026-09-05 14:44:02 +02:00
edde746 bc13ff007a perf(explore): resolve library copies with one guid filter and a native-title search per server
The Explore library lookup spent up to eight search-index queries per
server per tap, plus one children fetch per candidate for sequels, and the
Trakt path added two alias/translation requests per detail open to reach
romaji and localized library titles.

Both backends index originalTitle on every copy of a foreign title whatever
language it is filed under, so the lookup now leads with the native title
and drops alternate titles as candidates: one query reaches the English,
romaji, localized and native copies alike. Plex's /library/all?guid= filter
is a literal prefix match with comma as OR, so every legacy-agent guid form
the external ids imply rides one indexed request alongside the Discover
guid, and the sequel gate asks for the season of every candidate in one
/library/all?type=3&show.id=…&season.index=N request. Worst case is five
concurrent requests per server, typically two or three, with no cloud call.

The Trakt alias/translation fetch is removed: the copies it reached are the
ones the native title reaches, and Trakt already sends original_title.

close #2098
2026-09-05 14:44:02 +02:00
edde746 29a6286fe6 fix(linux): suppress Steam Input duplicate actions
With Steam Input enabled on Linux, every controller press acted twice:
Steam's desktop layout injects arrow/Enter/Escape keys through a uinput
keyboard while the physical controller stays readable over evdev, so
GamepadService synthesized the same key a second time. The duplicate
guard that fixed this on Windows was gated to Platform.isWindows and its
native key handler was never registered on Linux. Enable both on Linux.

close #1694
2026-09-05 14:44:02 +02:00
edde746 6815850b61 feat(explore): match Trakt items to romaji and localized library titles via Trakt aliases
A Trakt item only carried its English title, so a Plex or Jellyfin library
filed under the romaji title (`Sousou no Frieren`), the user's language
(`Frieren: Tras finalizar el viaje`) or the native title stayed invisible to
the Explore library lookup.

The Trakt detail load now fetches /aliases and /translations/{app locale}
alongside people and related, picks one ASCII alias from the item's own
country plus the locale translation as alternate titles, and the matcher
reads original_title for every source. The lookup budget grows to four
title families, the matcher keys its cache on the candidate titles, and the
detail screen re-resolves when a detail load adds titles, not only ids.

close #2098
2026-09-05 14:44:02 +02:00
edde746 a2c9bea041 fix(explore): find library copies through the Plex search index and report servers that could not answer
Explore showed "Not in your library" for titles the user owns. Two causes:
Plex's /library/all?title= filter is an ordered word-prefix substring match,
so `Oshi no Ko` never found a library titled `[Oshi no Ko]` and a romaji or
localized title was unreachable once the first candidate hit; and a server
that answered slower than the 10s header budget was treated as a dead
endpoint, dropped from the wave, cached as a negative for ten minutes and
cascaded through its stale LAN candidates.

Plex title candidates now go through /hubs/search with includeGuids, the
full-text index behind Plex's own search, which also covers originalTitle.
Both backends search every candidate concurrently and union the id-verified
copies instead of stopping at the first title that hit; the candidate cap
becomes two title families so a sequel can reach its alternate title. Lookup
requests run under a dedicated deadline with endpoint failover off. The
aggregation layer reports per-server failures, the matcher only memoizes
complete positive waves, and the detail screen shows "Couldn't check N
servers" instead of claiming absence.

close #2098
2026-09-05 14:44:01 +02:00
edde746 a629a3407a fix(player): route Hi10 to software up front and drop to bilinear on GPUs without norm16
H.264 High 10 on Android TV boxes without a 10-bit hardware decoder
(Amlogic S905X4 class: onn 4K Pro, Homatics Box R) started black for over
ten seconds and then played choppy: mpv tried MediaCodec first, hit
"Could not initialize video chain", and only then fell back to software
decode on the GL vo, where the Mali-G31 driver has no
GL_EXT_texture_norm16 and pays an integer-texture conversion pass plus
lanczos scaling it cannot afford at 1080p.

Decide the decoder before mpv creates it. An on_preloaded hook now carries
both per-file policies (Dolby Vision P5 reshaping and this one): when the
track's codec-profile is High 10 (published at demux by the fork, see the
mpv-build pin) and MediaCodecList advertises no hardware AVCProfileHigh10,
hwdec is held at `no` and the session goes to the GL vo directly. The hold
parks any hwdec write from Dart and restores it for the next file, as the
DV P5 hold already did.

On a GL vo whose driver lacks norm16 (probed once through a pbuffer EGL
context), scale/cscale/dscale drop to bilinear and dither to off for the
session, restored when the vo goes back to the plane. Only options still at
their mpv defaults are touched, so a user's mpv.conf wins. Paired with the
fork's rg8-backed 16-bit plane emulation, the box goes from 13 drops/s and
a 13.7 s first frame to 0.7 drops/s and 2.5 s. Devices with norm16 (Shield,
Pixel 7) take neither the tier nor the emulation.

The native pin moves to edde746/mpv-build@0601b034da, which also picks up
the earlier android/linux/windows patch-series squash.

close #2065
2026-09-05 14:08:05 +02:00
edde746 7e930580cf fix(media-detail): tighten hero chips and give landscape phones a full hero
The phone hero's chip rows were spaced 8px apart with 12/6 padding and a
16px gap to the action row, which read loose against the centred layout.
The scores pill and the tappable Rate chip also came out taller than the
plain text chips because their 16px icons pushed past the 13px label
line, so the row had a visible step in it.

Chip geometry now lives in one _HeroChips table: 4px spacing between
chips and rows, 10/5 padding, a 10px (6px on short heroes) gap to the
actions, and every chip sizes its content to a shared 20px box so icons
and text can never make one chip taller than its neighbours.

Landscape phones got a hero at 60% of a short viewport, which shrank the
logo to a sliver and let the overview run under the camera cutout. The
hero now has a floor of one full hero — status bar and back strip,
full-size logo, both chip rows and the action row — and the body sliver
sits in a SliverSafeArea so section text keeps the same horizontal inset
as the hero content above it. The hero's top padding also reserves the
back-button strip explicitly instead of relying on the logo budget.
2026-09-05 08:54:06 +02:00
edde746 b79af75a1f feat(media-detail): centre the phone hero's logo, chips and actions
On phones the movie/show hero hugged the left edge under a full-bleed
backdrop while the new collection page stacks its poster, title and
actions on the centre line, so the two pages read differently.

At widths under the mobile breakpoint the hero now centres the clear
logo (or title fallback), both chip rows and the action row; the hero
height, chip shedding, focus order and back button are unchanged. Wide
heroes keep the bottom-left column — a 400px logo centred in a
tablet-wide hero floats, and the wide collection header is left-aligned
too. TV is untouched.

_buildDetailLogoOrTitle gains an alignment and _buildDetailTitle a
textAlign, both defaulting to the previous values.
2026-09-05 08:54:06 +02:00
edde746 a873009fff feat(collections): show poster, summary and item count in a header above the collection grid
Collections opened as a bare poster grid under a plain app bar: no
collection artwork, no summary, no count, so they looked unrelated to
the movie/show and album pages around them (#1493).

The collection screen now leads with the same header the album and
artist pages use: the collection poster (square for music collections)
beside its title, item count, year span, content rating and collapsible
summary, with the Play / Shuffle / Download / Delete row underneath.
The collection's backdrop art washes the header region behind a scrim
that fades to the scaffold background before the grid starts; a
collection with only a poster gets a blurred copy of it instead so the
wash still reads as colour. A transparent title bar fades in once the
header scrolls away, and the circular back button matches the detail
pages. The year span is only shown once every page has loaded so a
partially fetched collection never reports a narrower range.

buildDetailScaffold gains optional `behind`/`above` layers so a detail
screen can paint art under, and chrome over, its scroll view without
re-implementing the overlay-sheet host and back handling.

Verified on Pixel 9a, 10" tablet and Android TV emulators: touch scroll
and pinned title, D-pad up from the grid lands on the action row and
scrolls the header back into view, D-pad back pops, Plex collection with
art and Jellyfin collection without art.
2026-09-05 08:54:06 +02:00
edde746 41c92b6324 fix(windows): persist the on-screen rect of a snapped window
Snapping the window with Aero Snap (edge drag, Win+Arrow, Snap Layouts)
and quitting restored it where it sat before the snap. Windows keeps a
snapped window in the "arranged" state: GetWindowPlacement still reports
SW_SHOWNORMAL with the pre-snap rect in rcNormalPosition, so the saved
placement never reflected what was on screen.

Resolve IsWindowArranged from user32 at runtime (exported since Windows
10 1903, no header declaration) and, when the window is arranged, save
GetWindowRect converted to workspace coordinates instead. The same
correction covers the pre-fullscreen placement captured by the native
fullscreen toggle. Relaunch lands a normal window on the snapped rect;
there is no API to re-enter the snapped state.

close #1895
2026-09-05 07:14:59 +02:00
edde746 e59b79266a docs(readme): collapse package manager installation instructions
Keep package manager instructions out of the main download section until expanded. Add the community RPM repository as a setup link and place Moss last, below Nix.
2026-09-05 06:26:21 +02:00
edde746 d2fe21b169 feat(player): per-marker skip modes with an Off option for intros and credits
Turning auto-skip off still surfaced a skip button on every intro and
credits marker, so a viewer who wants to watch episodes in full had no
way to silence it. The two auto-skip switches become per-marker
selectors — Off, Show button, Automatic — stored as skip_intro_mode and
skip_credits_mode. Off filters the marker before it becomes current, so
the player behaves as if the server had sent none: no prompt, no
countdown, no TV autofocus, and Back reaches the screen. Flipping a kind
to Off while its prompt is up drops the prompt immediately.

The legacy auto_skip_intro/auto_skip_credits booleans migrate on first
read: true becomes Automatic, false becomes Show button, matching what
each meant before.

close #2138
2026-09-05 04:18:36 +02:00
edde746 f45eaf1367 feat(library): add a toggle to hide watched indicators on cards
Watched posters always carried the corner checkmark, and viewers who
find it noisy had no way to turn it off. A new Appearance switch,
Show Watched Indicators (default on), gates the checkmark on every
surface that stamps watch state onto artwork: grid cards, hub rows,
folder tree rows, episode and playlist thumbnails. Progress bars and the
unwatched-count pill keep their own behavior.

close #1998
2026-09-05 04:18:35 +02:00
edde746 4f9e527ef2 feat(tvos): default audio passthrough on for Apple TV
Apple TV shipped with passthrough opt-in while the E-AC-3/Atmos
sample-buffer renderer was unverified, so Atmos titles played as PCM
until the viewer found the switch. The renderer is now hardware-verified
on real receivers, so the pref defaults on for Apple TV the same way it
does for Android TV. An explicit stored value still wins.

close #1300
2026-09-05 04:18:35 +02:00
edde746 5efc4f384c fix(plex): honor the quality preset on Live TV instead of leaving the server to pick the tier
Playing a Plex live channel from outside the LAN always came back as a full
re-encode at the server's highest transcode tier (20 Mbps 1080p on the
reporter's server), no matter which quality the app was set to. The Plex live
path never sent a ceiling: a live source has no bitrate the server can check
against its remote-stream limit, so a remote session without a client cap
falls onto the server's own top tier. On the LAN the server remuxes anyway,
which hid the gap.

The live stream path now reads the same saved preset the library path and
the Jellyfin live path (#2198) already honor. Original is unchanged: a remux
(directStream=1) with no ceiling. A capped preset pins directStream=0 and
sends the bitrate limitation clause plus the videoResolution/videoQuality caps
so the encode lands at the chosen tier rather than the server's. The preset is
session state, so a recovery re-tune keeps the cap.

directPlay stays 0: a tuned Plex session is only reachable through the
transcoder's HLS output, so "no re-encode" on live means a remux, not direct
play. Capped sessions use the h264-only TS target because every codec in the
target becomes an encode output once directStream is off, and HEVC into TS is
the #1859 corruption; the broadcast-codec live target remains the Original
remux menu.

close #2072
2026-09-05 04:15:17 +02:00
edde746 12a380807d fix(live-tv): anchor the live clock on the playback transcode's server origin
A skip back of 10-20 s on a freshly tuned Plex Live TV channel landed on
or after the frame being shown, while the same skip worked once the viewer
had already time-shifted. Offset-less opens (initial tune, retry, channel
zap, subtitle switch at the edge) pinned stream position zero to wall clock
at open time, but the transcode starts behind real time by tuner ingest and
encoder start-up latency; offset opens were exact because the server
defines their origin.

Every /:/timeline response already carries the playback transcode as the
top-level TranscodeSession next to the CaptureBuffer wrapper; its timeStamp
is the epoch of stream position zero, which Plex's own client uses as the
playhead origin. The parser used to return only the capture window. It now
returns both, and each heartbeat re-anchors the clock on the playback
origin unless the response predates the current open or an open is still
calibrating. Offset-less opens seed a provisional anchor from the capture
edge instead of wall clock, and the live-edge threshold is widened to 15 s
so a live stream trailing the edge by normal latency still reads as live.
2026-09-05 01:51:03 +02:00
edde746 af9fb3f17c fix(live-tv): calibrate replacement stream clocks 2026-09-04 16:49:55 +02:00
edde746 781fb66421 fix(player): keep blocking MPV lifecycle work off main thread
A disposal race could call blocking native destruction after initialization resumed on Android's main thread. Finish that teardown on IO, enforce the lifecycle threading invariant, and bound exit responsiveness and teardown latency in the device regression test.
2026-09-04 14:43:54 +02:00
edde746 1b45588d3b fix(player): keep MediaCodec surface alive through MPV teardown
Setting vo=null during disposal could reinitialize MediaCodec and deadlock vendor decoders while the surface was already being released. Terminate libmpv synchronously with its surface references intact, then release the Android surfaces, and cover repeated hardware-decoded teardown on devices.
2026-09-04 14:43:54 +02:00
1a3dc3d3c9 fix(android): gate the DTS-HD IEC carrier on advertised DTS-HD support (#2231)
The ExoPlayer carrier gate only asked whether the route could open a
192kHz/7.1 IEC 61937 track. TrueHD rides that same tuple, so a sink that
decodes Dolby but no DTS-HD passed the probe and was handed a DTS-HD
burst it discards: the AudioTrack initialises and drains, Android reports
no error, and neither the audio-recovery ladder nor the mpv fallback
fires, so the file plays with no audio at all.

Evaluate the gate per format. TrueHD keeps the transport-only probe, so
the #1804 routes are unchanged; DTS-HD additionally requires the route to
advertise ENCODING_DTS_HD, the pairing mpvSpdifCodecs already applies and
the reason mpv plays these files while ExoPlayer does not.

Declining the carrier is not a forced decode: the format falls through to
media3's raw path, which downgrades DTS-HD to the DTS core for receivers
that take the core but not the lossless stream.

Co-authored-by: claude-opus-5 (high effort, 1M context) <noreply@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 12:48:34 +02:00
edde746 5d6ee0861e fix(player): snap Android MediaCodec frames to display vsync 2026-09-04 12:02:39 +02:00
edde746 986e769ac0 fix(player): stop subtitle updates from dropping video frames on the mpv Android backend
With the mpv backend on Android, every subtitle change cost two dropped
video frames on a Fire TV Cube (36 per minute with PGS SDH subtitles, 15
with srt, #2240) and accounts for the residual drops on the Shield in #2202,
whose sessions also had subtitles on. The diagnostic build showed the drops
in pairs: a frame handed over on time, then the video thread waking 90-100
ms late. vo_mediacodec rasterized subtitles and blitted them into the OSD
Surface on that thread, and locking the Surface waits CPU-side for the
compositor - dequeue plus the release fence, one or two vsyncs, 42-83 ms at
23.976 Hz. Kodi, VLC 4 and ExoPlayer all keep subtitle output off the
presentation thread.

Move the native pin to edde746/mpv-build@88c1b135e7: the whole OSD stage
runs on its own thread, fed with the video pts at every flip, so the video
thread never waits on the compositor or on libass. Subtitles latch on the
same vsync as the video in the common case and one later when the lock has
to wait. Shield on vo=mediacodec with ASS subtitles: no video-thread stage
over 10 ms and 0 drops across five 150 s runs, subtitles verified on
screen; DTS-HD MA 4K unchanged at 0 drops. The pin keeps the #2202
diagnostics and adds VO stage timing to them. Apple, Linux and Windows
assets are unchanged.
2026-09-04 06:14:18 +02:00
edde746 b61fc9e661 fix(audio): stop the passthrough clock from overshooting after a stall on the mpv Android backend
The smoothed passthrough clock from aeb06c2c9 (edde746/mpv-build 0105)
still let the Shield in #2202 drop a frame every 70 s or so on TrueHD and
DTS-HD MA. The average handles head jitter completely - on a Shield with
the raw head artificially held for 150 ms it went from 410 dropped frames
in 200 s to 0 - but it regresses on stalls: when the head freezes (device
underrun, rebuffer, a HAL that stops updating) while the wall clock runs,
the estimate runs past what was written, (written - head) wraps, and
getLatency reports 0 - the core sees the whole device buffer vanish in one
step and drops video. With the AO starved for 400 ms every 15 s that was 77
drops in 170 s against 8 with the raw clock, and a Box R 4K Plus hit the
wrap 361 times in four minutes of ordinary DTS-HD playback.

Move the native pin to edde746/mpv-build@a58f0c1336: the estimate is
clamped to the written position and its window restarted on overshoot, and
between reports it may deviate from "last report + elapsed" by at most 10%
of the elapsed time unless it is a second or more off - the two guards
media3's AudioTrackPositionTracker keeps over the same average. Starvation
run: 9 drops, no wrap; real HAL with pauses and seeks: 0 drops. The pin also
carries verbose-level diagnostics for this issue (per-drop timing in vo.c,
passthrough clock anomalies and a 10 s summary in ao_audiotrack) so the
next log from the reporter pins whatever remains. Apple, Linux and Windows
assets are unchanged (their content keys did not move).
2026-09-04 01:58:34 +02:00
edde746 fa8da33ec8 fix(tv): drop a stale Discover rail-focus claim, log swallowed tvOS Menu presses, and unblock shelf test resets
Three findings from the #2239 investigation.

Discover armed "focus the browse rail when it has hubs" on its first
load and kept it armed indefinitely while the rail had nothing to show.
Hubs landing minutes later — reconnect, push refresh — then yanked the
remote off a sidebar item the user had since moved to. The claim now
lapses once focus sits on a control outside the screen; a bare content
scope (the startup state) still lets the rail take its initial focus.

On Apple TV a Menu press that reaches MainScreen at the home root is
consumed silently by design (the engine normally hands root Menu to
UIKit). That branch is what turned a focus slip into a "dead remote"
report, so it now logs passthrough state, picker state, and the primary
focus label.

SystemShelfService.debugReset awaited the mutation tail queued by the
previous widget test, whose FakeAsync zone ends without flushing the
microtasks that settle the chain, so any second test in a file using it
hung in setUp. It now drops the queue synchronously; the #2239 session
regression test moves back beside the profile-switch test it belongs
with.
2026-09-03 23:54:09 +02:00
edde746 44599549e1 fix(focus): keep root-navigator routes from losing the remote to the covered profile session
On tvOS the profile picker shown after a background/standby resume lost
its focus highlight and the Siri Remote went dead until a force-quit.
Android TV hit the same shape with the player (#2034).

The picker and PIN dialog are pushed on the root navigator, above the
nested profile-session navigator. Nested routes still report
`isCurrent == true` under that cover, and Flutter leaves a covered
route's scope focusable, so any focus self-heal under MainScreen —
the sidebar reveal on an offline/online flip, a Libraries grid reload,
the TV browse rail — won the remote behind the picker. With menu
passthrough pinned off while the picker is up, Menu was swallowed too.

Restore the invariant once at the navigator boundary instead of at
every reclaim site: CoveredRouteFocusBoundary wraps the session in an
ExcludeFocus keyed on the root route's currency, so requests below a
cover are no-ops, and re-requests its own scope on uncover so focus
walks back to the leaf that had it (the covering route's pop culls the
excluded scope from the route scope's history before the exclusion
lifts, which is why Flutter's own restoration cannot). This makes
isRouteChainCurrent redundant; the player's guards return to plain
nested currency.

close #2239
2026-09-03 23:47:27 +02:00
edde746 e46b3dab7c fix(seerr): diagnose an auth proxy in front of Seerr instead of misreporting it
A Seerr instance behind forward-auth (Authelia, Authentik, Cloudflare
Access) or HTTP Basic failed setup with "No Seerr instance at … (HTTP
200)": the probe followed the proxy's redirect to its login page and
decoded the HTML as "not JSON". A live session that later hit the same
wall took the proxy's 401 as Seerr's, re-authed through the wall, failed,
and unlinked a perfectly good stored session.

Seerr's API never redirects and always answers with JSON, so a 3xx or a
non-JSON 401/403 is the proxy talking. Seerr requests no longer follow
redirects, that shape maps to a SeerrProxyException with a message that
says what to do, the probe reports it in place of "no instance", and the
client neither re-auths nor unlinks on it.

close #1877
2026-09-03 21:42:47 +02:00
edde746 e67bf996c5 fix(player): keep subtitles on the picture when ambient lighting is on
With ambient lighting enabled, ASS subtitles anchored to a corner (and PGS
bitmaps) rendered against the whole screen instead of the video: the effect
stretches mpv's frame to the window with video-aspect-override and lets the
shader composite the real picture inside it, and mpv places subtitles against
that stretched frame.

The pinned libmpv now carries --sub-video-rect-aspect (edde746/mpv-build
ec08018), which makes mpv derive its subtitle margins from the picture's real
aspect inside the displayed rect. AmbientLightingService hands it the video
aspect before overriding the frame, so a libmpv without the option refuses
cleanly with the frame untouched, and resets it on disable.

Verified on a Pixel 7 (2400x1080) with a 16:9 file whose OP credits are
\pos-anchored: subtitle extents are pixel-identical with ambient lighting on
and off, and mpv reports OSD borders l=240 r=240 for the overridden frame.

close #2120
2026-09-03 21:28:10 +02:00
edde746 66cc6fc192 fix(player): hide the header clock on a portrait phone
On a phone in portrait the video controls header is too narrow: the clock crowds the back button, title, and track/chapter controls. Hide it there; landscape, tablets, desktop, and TV keep it.
2026-09-03 20:32:05 +02:00
edde746 691d10b3c6 feat(navigation): landscape rail for the mobile shell and phone rotation
Phones were locked to portrait outside the video player, and the mobile
shell had no answer for a wide, short viewport: car head units (which use
the mobile layout) and tablets in landscape spent their scarce height on
a bottom navigation bar and a 500dp hero.

In landscape the mobile shell now puts the bottom bar's destinations on a
leading Material NavigationRail (MobileNavigationRail) and keeps every
other mobile layout decision as it is. The rail keeps the bottom bar's
extras: the offline reconnect affordance as its leading action and the
long-press library quick picker on the Libraries destination. Labels
follow the existing nav-bar-labels setting but give way automatically
when the destinations cannot fit (a landscape phone is ~410dp tall), and
the rail scrolls as a last resort. The content beside it drops the leading
system inset the rail already absorbs.

Phones now allow every orientation; OrientationHelper.restoreDefaultOrientations
is context-free and the player exit path uses it instead of its own copy
of the phone lock. The Discover hero fills the viewport in mobile landscape
and compacts its logo and bottom offset when short, so its content stays
below the top bar.

The music mini-player learns a start inset (MiniPlayerInsetController.setNavInsets)
so it floats beside the rail in landscape and above the bar in portrait;
route suspension zeroes both.

Known follow-up: the media detail header is not yet laid out for a
landscape phone (logo runs under the status bar and back button).
2026-09-03 20:29:08 +02:00
edde746 42b9bf7fb8 fix(automotive): keep every screen beside a side car system bar
On Android Automotive head units with a left- or right-positioned system
bar, the whole edge of the app rendered underneath it: Discover's title,
hero text and first card were clipped, and the player controls sat under
the bar. Play's car app quality AR-1 requires interactive UI to stay clear
of system bars.

The platform reports the bar as a systemBars inset and Flutter forwards it
as MediaQuery.padding.left/right, but the mobile screens only honour the
top and bottom insets. On the emulator this only showed after the first
video session (the player's edge-to-edge restore stops the DecorView from
fitting a navigation-bar-typed left bar); on Android 14+ CarSystemUI the
left bar is a status-bar-typed inset, so it is under the bar from launch.

Car bars are opaque and may be impossible to hide, so nothing is worth
drawing under them: FormFactorScale now wraps the automotive surface in a
horizontal SafeArea inside the scaled MediaQuery, consuming the insets
once for every route.

Reproduced and verified on the API 33 automotive image with the
com.android.systemui.rro.left overlay enabled for the foreground user.
2026-09-03 20:28:53 +02:00
edde746 2efd300a5f fix(downloads): show resume progress bar on downloaded episodes
Downloaded episodes never showed the partially-watched progress bar, so a
user resuming offline could not tell which episode they had started.

Offline playback already records progress: the tracker queues a progress
action and emits a WatchStateNotifier event, and DownloadProvider hydrates
those rows back into WatchStateStore on load. EpisodeCard consumed that
state via withFreshWatchState but then passed progressAvailable: false to
WatchedIndicator for offline cards, a guard left over from before offline
progress tracking existed. Downloaded movie cards (MediaCard) never had the
guard and already showed the bar.

Drop the guard and the now-unused WatchedIndicator.progressAvailable flag.

close #2236
2026-09-03 19:14:45 +02:00
edde746 8b1ac156f3 fix(player): drop chapter-derived intro markers longer than three minutes
A movie whose first chapter is titled "Opening Credits" or "Introduction"
got a Skip Intro button that skipped the whole chapter — several minutes
of picture. Detected intros are short; only Plezy's own chapter-title
fallback produced these. Cap chapter-derived intros at three minutes.
Server-supplied markers and credits chapters are unaffected.

close #2235
2026-09-03 18:34:44 +02:00
edde746 be8fa15733 chore: restore pubspec.lock quoting rewritten by pub get 2026-09-03 18:24:41 +02:00
edde746 fa054153ae fix(plex): surface a stale-endpoint failure instead of cascading after a mid-probe promotion 2026-09-03 18:22:13 +02:00
edde746 a230d51598 fix(plex): keep a LAN session on its local endpoint after device sleep
Apple TV (and any suspended process) wakes with dead keep-alive sockets in
the HTTP pool. The first request after resume — the health probe — failed
with a connection error, and the failover cascade treated that as a dead
endpoint: it validated the remote candidate, switched to it, and persisted
it as preferred. Nothing walked the session back to the local endpoint,
because the only re-optimization trigger is a connectivity event and a
same-interface sleep/wake never produces one. Only killing the app fixed it.

FailoverHttpClient now runs the existing candidate trust gate against the
current endpoint on a connection error and retries in place when it answers;
timeouts and 5xx still cascade directly. MultiServerManager gains
reoptimizeDemotedServers, called from the resume probe, which re-races any
online Plex server sitting on a remote or relay endpoint while a local one
is published.

close #2056
2026-09-03 18:13:28 +02:00
edde746 e4f3888694 fix(seerr): seed advanced requests from the Sonarr anime defaults and expose tags
Requesting an anime series with REQUEST_ADVANCED routed it to the standard
Sonarr profile and root folder. The sheet seeded its pickers from
activeProfileId/activeDirectory only, then posted them as explicit overrides,
which beat the anime defaults Seerr would otherwise apply at approval. A user
without the permission sent no overrides and was routed correctly.

The service DTOs now carry activeAnimeProfileId, activeAnimeDirectory,
activeAnimeLanguageProfileId, activeTags, activeAnimeTags and the instance's
tag list. The sheet detects the TMDB anime keyword on the TV details it
already fetches and seeds each picker the way Seerr's web requester does:
the anime value when the series is an anime and the instance configures one,
else the standard value. Options carry the "(Default)" marker and an anime
series shows the same note as the web UI.

Tags are editable: an inline checklist under the advanced pickers, seeded from
the instance's (anime) default tags and posted as `tags`. It is inline rather
than a nested sheet page because the host builds only the top page, so a push
would dispose the sheet and drop the season and picker selections on the way
back.

close #2215
2026-09-03 16:46:27 +02:00
Jan HaiderandGitHub 2087dff32d fix(tvos): eliminate runtime and project build warnings (#2228) 2026-09-03 14:41:16 +02:00
edde746 d112ade601 style(android): space out the annotated and commented libmpv lock declarations
ktlint's spacing-between-declarations-with-annotations and
-with-comments rules failed on android/libmpv/build.gradle.kts, so
scripts/format_native.sh --check - and with it scripts/ci_checks.sh -
reported a failure on an untouched file.

Add the blank line before the @Suppress'd mpvAssets declaration and
before the comment above stagedArchiveName.
2026-09-03 13:12:48 +02:00
edde746 6301d5124e chore(plex): send the JSON Accept header unconditionally
PlexConfig.acceptJson defaulted to true in both constructors and
travelled through copyWith, but no production or test caller ever passed
false, and every Plex path decodes JSON, so the header was conditional on
a flag that could not be off.

Emit `Accept: application/json` directly and drop the field. Headers on
the wire are unchanged.
2026-09-03 13:08:46 +02:00
edde746 13acd41b09 refactor(player): classify player keys with the shared D-pad extension
The video controls' key handling redefined the directional, horizontal
and select key sets privately, duplicating DpadKeyExtension with
identical members; the private select helper then handed the event to
handleOneShotSelect, which classified it again with the canonical
isSelectKey.

Use isDpadDirection, isLeftKey/isRightKey and isSelectKey and delete the
copies.
2026-09-03 13:08:46 +02:00
edde746 0003d95c0a refactor(watch_together): handle created and joined in one branch
The two setup acknowledgements ran the same sequence twice: accept and
validate the response, handle the same two exceptions, install the peer
roster, publish connected state, and complete the setup completer. Only
the log line differed, plus a roster loop that skipped the
already-present check.

One case handles both, using the guarded add so the roster publishes
idempotently for either acknowledgement.
2026-09-03 13:08:46 +02:00
edde746 4d2aa8f9a2 chore(plex): trim LiveTvDvr to the fields Live TV renders
LiveTvDvr parsed 21 DVR fields plus nested Setting and raw Device lists
on every Live TV availability refresh, while the app reads only the key,
the three lineup labels, and the enabled channel mappings. The rest
describe tuner hardware and DVR setup, which Plezy does not implement.

Keep key, lineup, lineupTitle, lineupURL and channelMappings, and
channelKey/enabled on ChannelMapping. The tests keep the root
channel-mapping fallback, malformed-sibling tolerance and flexible
`enabled` parsing.
2026-09-03 13:08:46 +02:00
edde746 deadf712a8 perf(profiles): resolve accounts from the registry watcher payloads
AccountPreferencesController subscribed to watchConnections() and
watchForProfile() and threw both payloads away, then re-read the same two
tables through list() and listForProfile() on every resolve - four
one-shot queries during attach alone, each re-decoding rows and revealing
credentials the watcher had already decoded. The generation counter
discarded stale results but never the queries.

Retain the rows the subscriptions deliver and resolve from them, clearing
the profile rows whenever the watched profile changes so one profile's
rows can never pair with another's. Until both watchers have delivered,
the resolve task parks on that first delivery, so ensureActiveLoaded
still has something to wait for.
2026-09-03 13:08:46 +02:00
edde746 ef91156827 perf(music): observe only the properties the audio-only core needs
The audio-only core reused the video core's property registrations
wholesale, so every music session observed track-list,
demuxer-cache-state, audio-device-list, audio-device, secondary-sid,
seekable, paused-for-cache, volume, speed, aid and sid. libmpv sends an
initial notification plus an event per edge for each one, and three of
them decode structured nodes into track and device models nothing on the
music path reads.

Register time-pos, duration, pause, eof-reached and playlist-pos there;
the video path keeps the full set. Also drop the post-initialization
`gapless-audio` write: every native audio core already sets it before
mpv_initialize, which is where libmpv wants initial configuration.
2026-09-03 13:08:46 +02:00
edde746 42b6710f04 fix(player): stop letting item metadata language override the audio track
The audio ladder still carried a per-item language tier between the
server's selected stream and the account preference. For Jellyfin and
Emby the value mapped to it was `PreferredMetadataLanguage`, which is the
library's metadata-scraping language - it inherits from the parent, the
library options, or the server config and says nothing about playback -
so on any source whose selected/default stream did not map to a native
track it silently picked audio in the scraping language instead of the
user's preferred one. Plex's item-level `audioLanguage` reached the same
tier, after 2dfebf32b and 7ae293631 had already settled that the server
folds every preference level into the stream `selected` flags.

Drop the tier and the plumbing that only fed it:
TrackSelectionPriority.perMedia, MediaItem.audioLanguage and
subtitleLanguage, PlexMetadataDto.audioLanguage/subtitleLanguage/
subtitleMode, and the Jellyfin PreferredMetadataLanguage mapping. The
order is now carried selection, server-selected or default source
stream, account preference, native default. Persisted cache entries
holding the old keys decode unchanged.
2026-09-03 13:08:46 +02:00
edde746 7e583ef05a style(tv): sit the detail track status on the action row's bottom edge 2026-09-03 13:03:25 +02:00
edde746 2132c23fab fix(tv): put the detail track status at the screen edge, not inside the hero column 2026-09-03 13:03:25 +02:00
edde746 c4be378219 fix(detail): make the track status read-only and right-align it
The action row's track status was a button that opened a pre-play
chooser, but on TV the hero describes whichever episode the rail has
focused, and focusing the row hands the hero back to the show, so there
was never a per-episode target for the control to act on. It also sat
inline with the buttons in muted grey, reading as a sixth, low-contrast
action.

The status is now plain text at the row's far end, right-aligned to the
hero's text column, in the hero's own ink, off the focus path. The
chooser sheet, the per-screen choice, and the Play pass-through go with
it, along with the overlay-host and track-tile changes that only served
the chooser.
2026-09-03 13:03:24 +02:00
edde746 f967b9b2f2 feat(detail): preview and choose the audio and subtitle tracks before Play
The detail screen gave no hint of what pressing Play would do with the
file: which audio track and which subtitles the player would start with,
or the picture format. Changing tracks meant starting playback first.

The action row now ends with a status line — picture labels, then the
audio and subtitle rows the player will select — computed by the player's
own selection ladder (TrackSelectionService) over the server's stream
rows, so it agrees with what the player then does. Select opens a
pre-play chooser with the track sheet's two columns; Play and rail
activation pass the pick to the player as its navigation-tier preference,
and a pick carries across episodes by semantics, forced-ness included.
Plex listings carry no stream rows, so a focused episode is probed once,
debounced, and cached for the screen.

Along the way: MediaStream keeps the server's `selected` apart from the
container `default` flag (they were OR'd, so the account's pick was
indistinguishable from the default track); the overlay sheet host no
longer overrides a row that claimed focus itself.
2026-09-03 13:03:13 +02:00
edde746 eafacff3be fix(tv): let the detail hero and rail describe the focused episode once
The TV show detail page spent its hero rows on information that never
changes while browsing episodes (the show's genres, the file's stream
quality) while the rail cards repeated the show name on every card and
pushed the episode title into a truncated subtitle. The Play button also
kept naming the on-deck episode while the hero described the focused one.

Rail cards inside the show now headline the episode title with
`S1 E3 · 23min` as subtitle; genres and quality labels move from the hero
to the details sheet (which now also names the episode and takes the show's
genres explicitly); Play follows the hero's episode and falls back to
on-deck when nothing is focused. The freed rows go back to the logo and the
third description line.

close #2217
2026-09-03 12:57:39 +02:00
edde746 33d845dcdd feat(tv): show the focused episode's title in the detail hero
On the TV detail screen the hero follows the focused episode: its metadata
line and description update, but the episode's own title is nowhere in the
hero. The only copy is the rail card's subtitle, which truncates for most
titles, so the viewer cannot read what they are about to play.

Add a title line between the show logo and the episode metadata line,
reserved in the hero's height budget like the other rows, announced in the
hero's accessibility label, and inside the focusable info block that opens
the details sheet. The hide-spoilers path no longer substitutes the episode
title for a missing summary, since the title line already names it.

close #2217
2026-09-03 12:57:05 +02:00
edde746 0134d9dbc0 fix(tv): tighten the spacing between mpv.conf editor rows
The remove button's default 48px tap target set each row's height, adding
about 12px of dead space around every 36px field on top of the row gap.
Constrain the button to 36px so the field decides the row height, and trim
the field padding and row gap.
2026-09-03 12:01:37 +02:00
edde746 4fd9034e8e feat(tv): edit mpv.conf line by line with the system keyboard on TV
On Android TV the mpv.conf editor used Plezy's own on-screen keyboard
instead of Gboard, and the only way to get a long conf onto a TV was to
retype it key by key (#2232). The system keyboards cannot host the
multiline editor: FireTVIME has no newline key, and both FireTVIME and
Gboard could wipe a pre-filled multiline field on the first keystroke
after the first-show restartInput.

On TV, render one single-line native field per line, with a line-number
gutter, a remove button per row and an Add line button. Rows open their
keyboard on Select only, so D-pad traversal does not raise it. A value
arriving with newlines (a paste from a phone remote) is split into rows
and typing continues on the last one; the rows are keyed so the split
does not rebind another row's input host. The keyboard's action key does
not insert a row: the app never learns which action the IME sent, and
FireTVIME reports Back as `previous`, so an insert-on-action editor kept
opening rows on every Back. Completion hands focus down instead — the
next row, or Add line after the last one.

TvTextInputController gains focusAndOpenTextInput() so a row the app
creates (Add line, paste split) can be typed into without a second
Select; it activates after the focus request lands, since the host's
focus sync deactivates an unfocused field.

Verified on a Google TV box (Gboard, Android 14) and a Fire TV Stick
(FireTVIME): rows keep their text on open, Back closes the keyboard
without side effects, edits persist across leaving the screen. Phone,
desktop and pointer platforms keep the text-area editor.

close #2232
2026-09-03 11:56:03 +02:00
edde746 51beb5ac4b fix(player): leave Plex subtitle auto-selection to the server
Plex Web reads only the `selected` flag PMS stamps on each stream; the
account's autoSelectSubtitle is applied server-side when that flag is
computed. Plezy's Priority 2 already trusts the same flag, but once
playback read AccountPreferences the Plex mode became non-null and could
reach the client-side profile pass whenever there was no media info or no
embedded subtitle streams - forcing subtitles off for Plex's 0 ("manually
selected") or on for 2, over a decision the server had already made.

TrackSelectionService now skips the profile subtitle mode for Plex items;
MediaBrowser keeps it because those servers do not pre-select.
2026-09-03 11:37:12 +02:00
edde746 b43cd81102 chore(profiles): let AccountPreferencesController own the active user's playback preferences
UserProfileProvider kept a second cache of the active user's audio/subtitle
defaults beside AccountPreferencesRepository, re-implemented the active
profile/connection listener wiring and Plex Home token resolution, and for
Plex Home profiles bypassed the shared cache entirely (fetching /user with
its own client), so a write in the Account preferences screen never reached
Home-profile playback.

The controller now resolves the active account (the head of its sorted
account list), loads it through the one repository on attach, on profile
switch, and when the account's token changes, and exposes it as
activePreferences; ensureActiveLoaded replaces initialize() for the startup
gate. Playback, offline waiting, and logout storage clearing read the
controller directly; UserProfileProvider, the per-backend user-profile DTOs,
PlexAuthService.getUserProfile, and JellyfinClient.fetchUserProfile are
deleted.

The ranked defaultAudioLanguages/defaultSubtitleLanguages lists go with
them: Plex Web never reads them, PMS applies them when it stamps `selected`
on streams, and Plezy already trusts that flag ahead of the profile. They
only refined a best-effort audio fallback for Plex items with no media
info, which the primary language covers; on that path a second preferred
language is no longer tried before the file's default track.

Plex Home profiles now read /user/profile with the switched token through
the same cache as local profiles.
2026-09-03 11:36:56 +02:00
edde746 5112d71820 chore(player,cards): share budgeted card realization and scope player subscriptions in bags
The memo-lookup, scroll-budget, skeleton-scheduling sequence was copied
in the paginated grid, the browse tab, and hub rows; SkeletonUpgradeScheduler
now owns it as realizeBudgeted with per-site skeleton and card builders,
keeping the hub's focus salt and padded skeleton.

The video player screen held fourteen nullable subscription fields and
listed them twice when cancelling; they are two lists (player re-wire,
media controls) snapshotted and cleared before cancellation, with the
screen-lifetime Apple TV and sleep-timer subscriptions left as named
fields. Live seek and subtitle switches open through one helper, and the
initial live open applies the shared stream options instead of an
inline property write.
2026-09-03 11:36:29 +02:00
edde746 ab477c971d chore(relay): generate reconnect token size and version predicate from the protocol spec
The 32-byte reconnect token and its 43-character base64url shape were
pinned by hand in both server/main.go and the Dart peer service, and the
supported-version check was spelled out three times in Go. The spec now
carries reconnectTokenBytes and the generator emits the token size,
encoded length, and validator for Dart plus the size and
supportedRelayProtocolVersion for Go, failing before writing either
target when the key is missing. The last handwritten error code in lib/
('not_in_room') uses the generated constant, and releaseSession's
in-flight join is a FutureCoalescer.
2026-09-03 11:36:29 +02:00
edde746 59f44d9ae1 chore(trackers,downloads): share rating request matching and download queue feedback
MDBList and Trakt repeated the rating type, entry matching, and request
body construction; tracker_rating_match.dart now owns them with the
service label passed in. The collection detail screen re-implemented
fetchAndQueueListDownload minus its cellular-blocked branch and now uses
it, and the three showDownloadOptionsAndQueue call sites share
queueDownloadWithFeedback, so the detail action buttons surface a queue
failure as an error snackbar instead of an unhandled async error.
2026-09-03 11:36:29 +02:00
edde746 de39e15e36 chore(sheets): build flat sheets on BottomSheetPageScaffold
Seven sheets hand-rolled the Column(min) + BottomSheetHeader + Flexible
tree that BottomSheetPageScaffold already produces; each now passes its
header arguments to the scaffold. No onBack is supplied, so the widget
tree, height, and focus behaviour are unchanged.
2026-09-03 11:36:29 +02:00
edde746 7b1b0d766b chore: reuse drainPages, SerialFutureQueue, and FutureCoalescer for hand-rolled equivalents
Three MediaBrowser pagination loops re-implemented drainPages; it gains an
onPage hook (fires after intermediate pages only) so the two
progressive-render loops fit as well as the episode queue. Five
handwritten FIFO future tails (companion lifecycle, Seerr persistence,
tracker write lock, companion host-auth commit, Watch Together message
routing) become SerialFutureQueue, and the companion peer service's
disconnect/dispose in-flight joins become FutureCoalescer.
2026-09-03 11:36:29 +02:00
edde746 960adf42f2 perf(downloads): resolve cache scopes once per server and build one deletion plan
Loading the downloads list re-resolved the backend and profile scope for
every row, and the provider's bulk lookup only tried the public key, so
every MediaBrowser leaf fell back to a per-item lookup that resolved the
scope again (twice more for episodes and tracks). Startup was therefore
O(downloads x profile bindings) in database selects.

getAllPinnedMetadata now resolves each distinct server once, covers
queued and in-progress rows too, and returns the scope snapshot beside
the items; hydration tries the exact compound key, then the public key,
then the existing per-item fallback, and reuses the snapshot for parent
rows. findProfileScopeId prefetches bound connections in one select while
keeping binding precedence. A provider test pins the select count as
constant across download count.

Deleting a container also read the row, resolved metadata, and queried
its children twice; deleteDownload now loads them once and threads the
snapshot through the file deletion, keeping the cancel/progress/file/row
order intact.
2026-09-03 11:36:29 +02:00
edde746 d181bd34ae chore(mpv): share desktop startup options and stop forwarding unused Android events
Linux and Windows each wrote the same eleven pre-initialize mpv options
(keep-open, idle, input disabling, OSC, ytdl, audio fallback, and the
audio-only set); ApplyCommonStartupOptions in mpv_player_common.h owns
them once, with the ytdl security rationale kept in one place. Rendering,
windowing, HDR, and log-level options stay per platform.

The Android JNI event thread forwarded every mpv event to Kotlin, where
MpvEvent modelled ten variants but MpvPlayerCore consumes four. The
native switch now forwards only START_FILE, FILE_LOADED, and
PLAYBACK_RESTART (END_FILE keeps its own path), and the unused variants
are gone.
2026-09-03 11:36:29 +02:00
edde746 b27cab4510 build: read Windows libmpv pins from the lock and share the Linux fetch and version parsing
windows/CMakeLists.txt repeated the mpv-build key, asset base, and both
SHA-256 values that mpv-build.lock.json already owns, and the pin mover
never touched it, so a lock bump left Windows silently stale. CMake now
reads artifacts.windows with string(JSON) (floor raised to 3.19) and the
Windows native cache key hashes the lock; a workflow guard rejects
hand-pinned checksums.

The byte-identical Linux libmpv fetch heredoc in build.yml and ci.yml
moves to scripts/fetch_linux_libmpv.py, which verifies the checksum
before extracting and is what the packaging script now points local
builds at. The package-windows and release jobs and
linux/packaging/build-packages.py read the version through
scripts/pubspec_version.py instead of three looser regexes.
2026-09-03 11:36:29 +02:00
edde746 17c877c973 chore(website): share page metadata, model screenshot devices as records, honor reduced motion
Home, privacy, and scan each repeated the same 13 title/canonical/Open
Graph/Twitter tags; PageMetadata now emits them once with route-specific
title, description, url, and an optional noindex. Screenshots keeps one
record per device instead of four parallel arrays plus a lookup table.

FAQ hash jumps and screenshot arrows forced behavior: 'smooth' from JS,
which bypasses the prefers-reduced-motion override in layout.css; both
now defer to CSS scroll-behavior. Removes the unused adapter-auto
dependency.
2026-09-03 11:36:29 +02:00
edde746 1373c299df chore(plex): hydrate Plex Home users at bootstrap through PlexHomeService
ConnectionBootstrap kept a private cache read/fetch/write path for Plex
Home users beside PlexHomeService, which already owns refresh
coalescing, generation checks, durable writes, and publication. The
bootstrap now keeps only the one-time legacy cache migration, then
reloads the service from storage or asks it to refresh, and reads the
hydrated users from the service snapshot. A failed hydration clears the
service's empty cache slot before the migrated account is removed.
2026-09-03 11:36:29 +02:00
edde746 7e84df6385 perf(livetv): rebuild the live timeline once per second instead of per position tick
The timeline bar rendered whole seconds but rebuilt on every ~250ms
position emission, so three of four rebuilds produced identical output.
It now derives a distinct position-seconds stream, the same pattern
ContentStrip uses for its chapter index, and rebinds only when the player
changes; streamStartEpoch changes still apply on the next build.
2026-09-03 11:36:29 +02:00
edde746 e8e67df379 chore(plex): map metadata type codes and fetch detail metadata in one place
The movie/show/season/episode/artist/album/track to 1/2/3/4/8/9/10 table
was repeated in the query translator (forward and inverse), collection
creation, and the metadata-edit adapter; PlexMetadataType now owns
forKind/kindFor and each caller keeps its own unsupported sentinel.

getMetadataWithImagesAndOnDeck and _getMetadataWithImages shared the
endpoint, cache key, query flags, first-row parsing, and library-section
stamping and differed only by includeOnDeck; they are one private typed
fetcher returning (metadata, onDeckEpisode), so fetchItemWithOnDeck no
longer reads a string-keyed dynamic map.
2026-09-03 11:36:29 +02:00
edde746 c70f88cee0 fix(android): transcode mpv strings as standard UTF-8 across JNI
Emoji and other supplementary-plane characters in titles, file names, and
subtitle paths were corrupted on the Android MPV path, and malformed bytes
from mpv logs could abort under CheckJNI. NewStringUTF/GetStringUTFChars
speak JNI's modified UTF-8, not the standard UTF-8 mpv produces and
consumes; the native lead-byte filter and the Kotlin surrogate scrubber
ran on the wrong side of that conversion and could not recover it.

Both directions now go through UTF-16 (NewString/GetStringChars) with a
small JNI-free transcoder that replaces malformed input with U+FFFD, the
same policy as shared/cpp/sanitize_utf8.h on desktop. The header is
covered by the Android host native test harness.
2026-09-03 11:36:29 +02:00
edde746 54efd4fe73 fix(emby): stop leading the transcode codec list with AV1
Capping quality against an Emby server on macOS (or any device with an
AV1 decoder) failed with HTTP 500: Emby takes the first entry of the
TranscodingProfile codec list verbatim and has no AV1 encoder. Jellyfin
rotates admin-disabled codecs to the back, which is what the AV1-first
list relied on. Gate AV1 on that dialect behavior.

close #2230
2026-09-03 08:02:09 +02:00
edde746 deaa06826c fix(player): stop corrupting high-bitrate HEVC at large keyframes on MediaTek Fire TV
High-bitrate HEVC episodes showed smeared frames and green flashes for the
first 10-15 seconds of playback on the Fire TV Stick 4K Max 2nd gen with the
mpv backend, while ExoPlayer played the same file cleanly (#2227). The
reporter's clip failed at exactly two timestamps on every run: the two IDR
frames larger than 1 MiB.

The FFmpeg mediacodec decoder never set "max-input-size" on the codec
format, so OMX.MTK.VIDEO.DECODER.HEVC allocated 1,052,672-byte input buffers
and FFmpeg split any larger packet across several queueInputBuffer calls.
The MediaTek VPU treats each buffer as a complete access unit, rejects the
remainder ("invalid u4BufferAccumulated"), fails the slice and conceals with
lost-picture references until the next IDR. ExoPlayer is unaffected because
media3 sizes HEVC input buffers at max(2 MiB, w*h*3/4) and never splits a
sample.

Move the native pin to edde746/mpv-build@83879375c9, which sizes the
buffers the same way ExoPlayer does for H.264, HEVC, MPEG-4, VP8, VP9 and
AV1 and logs a warning if a packet still does not fit. Verified on the
AFTKRT with the reporter's clip: zero VPU errors and no lost pictures across
repeated runs, and an H.264 file with ~1 MB keyframes still plays on the
MediaTek AVC decoder; both files also play on a Pixel 7 (Exynos C2). Apple,
Linux and Windows assets are unchanged (their content keys did not move).

close #2227
2026-09-03 07:47:58 +02:00
edde746 d371bfed3a fix(networking): connect in resolver address order with a Happy Eyeballs race
On a dual-stack network Plezy pinned API traffic and the notification
websocket to IPv4 while the native Plex apps and the media stream used
IPv6. dart:io looks up A before AAAA and connects in arrival order, so
the AAAA address was never tried when the IPv4 path answered within
250 ms.

Install an HttpClient.connectionFactory that does one lookup (keeping
the resolver's RFC 6724 order), interleaves families per RFC 8305 and
races candidates 250 ms apart. The task is returned before the lookup
starts so connectionTimeout and cancel cover resolution. TLS is done in
the factory since the SDK skips it once one is installed; proxied
requests stay plain. The library-event and companion-remote websockets
get the same client because WebSocket.connect otherwise builds its own.

Supersedes #2233.
2026-09-03 07:35:34 +02:00
edde746 aeb06c2c9e fix(audio): smooth the passthrough audio clock on the mpv Android backend
Playing lossless passthrough audio (TrueHD, DTS-HD MA) on an Nvidia Shield
running Android 9 dropped a video frame every ten to twenty seconds with the
mpv backend, while lossy passthrough and PCM were unaffected and A/V sync
never moved (#2202).

IEC 61937 and raw passthrough tracks in ao_audiotrack never use
AudioTimestamp; their clock is AudioTrack.getPlaybackHeadPosition() taken at
face value, which on a direct track is the HAL's render position and
advances in HAL-period steps - 8192 frames at 192 kHz (42.7 ms) for the HBR
output on the Shield, longer than a 24p frame. The AO thread samples it once
per chunk and feeds it straight into the end time mpv schedules video
against, so a forward snap larger than a frame's remaining lead makes mpv
drop that frame; lossy passthrough runs at 48 kHz where the period stays
below a frame.

Move the native pin to edde746/mpv-build@af74e1906e, which estimates the
passthrough position the way media3 does: a ten-sample average of
(head - clock) offsets taken at least 30 ms apart, so a period-sized step is
spread over the window instead of landing on one frame. PCM tracks keep
their AudioTimestamp path. Apple, Linux and Windows assets are unchanged
(their content keys did not move).
2026-09-03 05:35:03 +02:00
edde746 9a9b89082b fix(home): apply the grid spacing setting to hub rows
Grid Spacing (Settings > Appearance) only changed the library grid. The
home, explore, detail and library-recommended rows were byte-identical
across Tight/Normal/Spacious because #2083 deliberately opted hub-row
cell packing out of the setting and hard-coded a 2px pad per card, and
the TV home rail never read the setting at all.

Treat a hub row as one row of the grid. MediaGridDelegate.cellWidth
packs row cells with the same gutter MediaGridGeometry uses, so a row
and the "see all" grid behind it render the same card at every setting.
HubSection renders max(4, gap) between cards - Tight keeps its historical
4px so nothing moves on update, Normal/Spacious render the grid's 6/12px
gutter - and feeds the same gap into its D-pad item extent and card memo
epoch. TvBrowseRail threads GridSpacing through metricsForHub,
maxActiveRailHeight and estimateHeight; non-full-card rails use the
setting scaled with the rest of the rail metrics, full-card rails keep
their own scale-derived gutter like full-bleed grids. The spotlight and
detail rail height reservations pass the setting too so reserved
heights track the narrower cards. Both surfaces watch the pref, so rows
re-lay out live.

close #2226
2026-09-02 22:38:11 +02:00
edde746 c79ff68a7b perf(tv): shape spotlight text once per swap instead of twice
Every D-pad step on the TV home ends with a spotlight swap, and on a
low-end box that frame ran over budget: 12 % of UI-thread CPU during
navigation was paragraph layout, most of it shaping strings a second time
to measure them before the render tree shaped them for real.

- FittingTitleText no longer lays the title out to learn whether it fits:
  Text wraps and ellipsizes at maxLines, so the box can only overflow
  vertically, and one cached one-glyph line height settles that. Only a
  box shorter than maxLines lines still searches, now bracketed by the
  proportional shrink of the base layout and stopped at a 0.25 px
  tolerance instead of a fixed 12 bisections.
- FittedMetadataLine and inlineRatingBadgeWidth measure through a small
  bounded cache keyed by text, style, scaler and direction, so separators,
  type labels, certifications, runtimes and years measure once per
  session.
- MediaHub.isContinueWatchingHub/usesContinueWatchingAction memoize their
  regex tokenisation per key; every card build and step re-asked them.

Cold navigation on the Android 14 box (30 steps over three hubs): build
312-316 ms -> 284-285 ms, layout 530-540 ms -> 515 ms, UI frame p90
7.5-7.9 ms -> 6.8-7.2 ms.
2026-09-02 22:38:11 +02:00
edde746 7e1f18f93f perf(android): skip the semantics tree when no enabled accessibility service can read it
Android enables Flutter semantics for any bound accessibility service, so a
TV running the Projectivy Launcher (whose service only wants foreground-app
events) paid for a full semantics tree on every frame that touched a node:
on an Android 14 box, 2 ms per frame, ~20 ms on each spotlight swap, and a
third of the navigation-time GC churn.

The Android side now reports whether any enabled service can consume the
tree (touch exploration, an accessibility tool, or spoken/braille/audible/
visual feedback; an empty list means UiAutomation, which reads it too), and
AssistiveTechnologyService closes a SemanticsTreeGate on the app binding
when none can. The gate sits under SemanticsBinding.semanticsEnabled, so the
pipeline owner drops the semantics owner exactly as if the platform had
turned accessibility off; explicit ensureSemantics clients (the debug handle
for Maestro) always win. Re-evaluated on platform toggles, service-list
changes (API 33+) and resume.

Cold navigation on the box with Projectivy's service bound, 30 D-pad steps
over three hubs: SEMANTICS phase 700-770 ms -> 0, UI frame max 31-37 ms ->
25 ms, GC 3.0 s -> 2.2-2.6 s.
2026-09-02 22:38:11 +02:00
edde746 5bd742c8b8 fix(tv): glide D-pad row and hub scrolls in 150ms on Android TV instead of 500ms
D-pad navigation on Android TV felt sluggish next to Projectivy and the
Fire TV launcher: every step of the home rail and hub rows trailed the
focus border in a 500ms ease-out, and hub moves deferred the vertical
glide by a frame. The 500ms was measured from the tvOS focus engine
(f357be407) and applied to every platform; Leanback prices a one-card
step at roughly 100-150ms, so the same glide reads as input lag on a
D-pad.

FocusTheme.navigationScrollDuration now vends the per-platform value:
Apple TV keeps the measured 500ms, everything else glides in 150ms.
TvBrowseRail and HubSection use it for row and hub-list scrolls, and a
hub move starts the vertical animation in the same frame when the
build-time section offsets are already known.

Measured with screen recordings on a Shield TV (2019) and a Fire TV
Stick 4K Max: row motion per press 470-510ms before, 135-150ms after;
hub move 480ms before, 120-150ms after.
2026-09-02 22:38:11 +02:00
Jan HaiderandGitHub 5c37c72a08 fix(tvos): adopt UIScene lifecycle for Xcode 27 (#2225) 2026-09-02 22:16:11 +02:00
edde746 22c1ad56d3 fix(player): play Dolby Vision profile 7 and DV+HDR10+ files on MediaTek Fire TV devices
Dolby Vision profile 7 titles (UHD Blu-ray remuxes, typically TrueHD or
DTS-HD MA) never showed a frame on the Fire TV Stick 4K Max 2nd gen with the
mpv backend: the spinner stayed forever while audio came up. Profile 8.1
titles carrying HDR10+ on the same device went fully black, controls
included, with audio playing.

Both are the FFmpeg mediacodec DV packet filter. It emitted every rewritten
access unit with a five-byte "00 00 00 00 01" start code - the leading zero
was copied once as head bytes and again as part of the first NAL region -
and MediaTek's VPU rejects such units ("H265_decode invalid NALU"), so the
profile 7 conversion and strip paths both produced nothing. And the filter
never dropped in-band HDR10+ SEI, which these chipsets cannot take next to
the RPU on the native DV decoder (#1296 on the ExoPlayer path).

Move the native pin to edde746/mpv-build@0ad6388c, which counts that zero
once and strips the ST 2094-40 SEI whenever a video/dolby-vision decoder is
selected. Verified on an AFTKRT with the published armeabi-v7a asset: a
P7.6 remux sample decodes on both the HEVC (strip) and DVHE.STH (convert)
paths with no VPU errors, and a P8.1 + HDR10+ remux plays on the DV decoder
with a single output-format change. Apple, Linux and Windows assets are
unchanged (their content keys did not move).

close #2176
2026-09-02 20:59:02 +02:00
edde746 3b3a816de0 fix(player): deinterlace software-decoded video on Android and Linux
Enabling Deinterlacing had no effect on Android and Android TV for
interlaced MPEG-2 (and any other software-decoded stream): mpv asks
libavfilter for bwdif, and the pinned Android and Linux FFmpeg builds were
configured with --disable-filters, so the request failed with
"filter 'bwdif' not found" and the frame passed through combed. Windows
and Apple ship FFmpeg with the filter, which is why the same file
deinterlaced on Windows.

Move the native pin to edde746/mpv-build@9bfbcd69, which builds bwdif into
the Android and Linux FFmpeg. Apple and Windows assets are unchanged
(content-addressed keys did not move). Verified on a Shield TV Pro with the
published arm64 asset: 480i MPEG-2 now deinterlaces cleanly.

close #2224
2026-09-02 20:05:38 +02:00
edde746 3fc229cd6c fix(android): tell external players to start unwatched items from the beginning
With an external player on Plex, starting a never-watched episode could
open a "resume playback?" prompt at the position the previous, unrelated
file was exited. The intent carried no start hint when the item had no
resume point, so players with their own bookmark store (Zidoo native
player, VLC) consulted it - and every Plex part URL ends in the same
`file.<ext>`, so those bookmarks collide across items.

Send `from_start=true` on fresh launches and `from_start=false` beside
`position` when resuming, matching the Zidoo integrations in
jellyfin-androidtv-zidoo and PlexToZidoo. MX, Just Player and mpv ignore
the extra.

close #2223
2026-09-02 15:43:04 +02:00
edde746 b5186624b8 fix(android): output 5.1 PCM at 44.1 kHz on the mpv backend instead of downmixing to stereo
AAC/AC3/EAC3 5.1 tracks at 44.1 kHz played as stereo through mpv on Android:
ao_audiotrack sized its buffer as 75 ms aligned to the sample size, which at
44.1 kHz is not a whole number of 6-channel frames, so AudioTrack refused it
("Invalid audio buffer size") and mpv fell back to the stereo-only OpenSL ES
output. 48 kHz sources (DTS, or audio-samplerate=48000) happened to align.

Pin mpv-build 1779135, which frame-aligns the audiotrack PCM buffer
(edde746/mpv-build@d89cfbb). Only the Android libmpv key moves.

close #1445
2026-09-02 14:16:20 +02:00
edde746 0c809491c7 fix(watch-together): declare rate changes to the room and stop the host clock during its own stalls
Rooms drifted in speed and kept pausing on poor links. A 2x long-press or a
speed pick on any peer propagated with no attribution, so it read as the app
changing speed on its own; a host whose cache starved let mpv resume its player
on its own timetable while the room waited, so every recovery re-anchored ahead
of the guests and they hard-seeked in a loop; and a wall-clock step on a guest
made every host anchor read stale and seeked the file by the size of the step.

Rate intent is now declared by the screen (speed sheet, keyboard, long-press,
media controls) through WatchTogetherProvider.onLocalRate instead of being
inferred from the player's rate stream, matching how seeks already work. The
expectation ledger no longer tracks rate at all, so a nudge, a default-speed
apply or a late ack can never become a room rate change, and a promoted host
adopts the room rate rather than its player's momentary one. Remote rate
changes surface as "<name> set the speed to <rate>".

The host pauses its own player when it stalls, anchors the room there, raises
mpv's cache-pause-wait to 4s, and holds the resume until it has buffered three
times the stall it just had. Heartbeats during a sub-grace blip keep
extrapolating the previous anchor instead of re-anchoring on a frozen position.

The sync layer's clock is monotonic. ClockSync discards its window when a
sample's offset moves further than the round trips involved can explain, and a
guest that receives an anchor reading implausibly old holds corrections and
re-converges instead of seeking.
2026-09-02 12:31:27 +02:00
edde746 5860079b43 fix(plex): include personal media libraries in search results
Searching for items in a Plex "Other Videos"/home-video library returned
nothing, while the same query worked in Plex Web. `/library/search` with
`searchTypes=movies,tv,music` skips libraries on the Personal Media agent;
they only answer to the `otherVideos` category.

Add `otherVideos` to the search request and treat personal-media rows
(`*.agents.none://` guids) as their own category when a saturated response
is supplemented, so a large movie library cannot starve home videos and
vice versa.

close #2216
2026-09-02 11:31:47 +02:00
edde746andClaude Fable 5.1 ce03857588 fix(seerr): take permissions from /auth/me, not the partial login body
A local Seerr account with request rights could sign in to Plezy but never
saw the Request action. POST /auth/local loads only the columns it needs to
check the password, so the entity it returns carries the class default
permissions of 0 (and the email as display name); the session stored that
snapshot and the detail screen gated Request on it.

Sign-in now ignores the login body and reads the user back through
GET /auth/me with the fresh cookie, for every method. SeerrUser.permissions
is required, so a user without a mask fails sign-in instead of persisting 0.

Two related gaps kept an affected session broken until a manual reconnect:

- Seerr answers an expired session with 403, never 401, so the silent
  re-auth never ran. A 403 now re-auths once GET /auth/me confirms the
  cookie is dead; a 403 from a live session stays a permission denial so a
  Quick Connect session is not unlinked over one.
- Nothing refreshed a stored session's permissions. The account provider
  now re-reads the user on bind, so sessions persisted with 0 by earlier
  builds, and admin-side permission changes, reach the Request action on
  the next launch.

close #2213

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-02 11:31:47 +02:00
edde746 200d896bea build: switch every platform's libmpv supply chain to the unified mpv-build repo
Plezy consumed mpv through four unrelated supply chains: an MPVKit fork
via SwiftPM for the Apple platforms, a libmpv-android fork's AAR for
Android, an in-CI from-source build for Linux, and an unpinned
sourceforge mpv-dev 7z for Windows. All four now consume the same
per-commit, content-addressed binaries from
https://github.com/edde746/mpv-build, pinned to one commit and built
from one set of pinned sources (mpv v0.41.0 on Apple/Android/Windows,
ffmpeg n8.0.1, our libass fork).

- Apple: the SwiftPM package moves from edde746/MPVKit to
  edde746/mpv-build across the ios/macos/tvos projects;
  scripts/set_mpvkit_revision.sh becomes set_native_revision.sh, writes
  every pin site plus the new repo-root mpv-build.lock.json, and
  tvos/scripts/wire_mpv.rb derives the package repo from the locks.
- Android: the mpv Kotlin API and JNI glue move in-app under
  android/libmpv (repackaged com.edde746.plezy.libmpv, exports renamed,
  shrinker rules covered), and the module downloads per-ABI native
  tarballs (lib/*.so incl. libc++_shared.so + include/) driven entirely
  by mpv-build.lock.json, with a PLEZY_LOCAL_MPV_DIR escape hatch for
  locally built artifacts. The fork AAR and its Maven coordinates are
  gone.
- Linux: CI downloads the prebuilt self-relocating libmpv prefix
  (lock-driven, sha256-verified) instead of compiling mpv/ffmpeg/dav1d/
  libplacebo/shaderc from source; linux/packaging/build-libmpv.sh and
  its test are deleted and native-inputs.json shrinks to the simdutf
  entry the CMake builds still fetch.
- Windows: both arches FetchContent the mpv-build dev zips with
  URL_HASH enforcement, replacing the checksum-less sourceforge
  download and its ARM64 7-Zip special case; guard scripts updated.

The lock plus the Apple pin sites all point at mpv-build commit
d7c3d559, whose manifest was verified asset-by-asset against the
published release digests (17/17 match). Verified locally: wire and
pin-script suites green, runtime-input checks green, all four Android
ABI tarballs downloaded/verified/extracted through the real Gradle
tasks, the Windows FetchContent block exercised end to end through
cmake, the Linux asset hash and layout checked against the workflow
contract, and xcodebuild resolved the flipped SwiftPM graph with
SwiftPM validating every binary checksum.
2026-09-02 11:31:47 +02:00
edde746 8fe7e4bcfd fix(logs): render log entries lazily to stop OOM kills on the logs screen
Opening View Logs with a full 5 MiB buffer laid out the entire log as one
paragraph, freezing the frame for tens of seconds and using ~1 GB of glyph
data — the OS killed the app on low-memory phones and TVs (watchdog/OOM).

Render one Text.rich per entry in a SliverList.builder so only the visible
slice is laid out, keeping selection through a SelectionArea. Also cap the
copy-to-clipboard payload at 256 KiB (newest lines kept) to stay under
Android's ~1 MiB binder transaction limit.
2026-09-02 11:31:47 +02:00
edde746 d2b5039bb3 fix(explore): stop d-pad on detail prose instead of skipping to the next button
On TV, pressing down on the Explore detail screen jumped straight from the
action bar to the next focusable button, scrolling the description and
background prose past unread. The overview and background sections are now
collapsible focus stops wired into the d-pad chain in both directions, so a
viewer can stop, read, and expand them before moving on.

close #2199
2026-09-02 11:31:46 +02:00
edde746 12b8c7e7ef fix(windows): log tone-map input churn on Adreno for #2191 diagnosis
4K HDR->SDR playback on Windows-on-ARM stutters and flickers because libplacebo regenerates its tone-map and gamut-map LUTs on every drawn frame. The two earlier workarounds targeted peak detection and HDR10+ metadata, but both regenerating LUTs log at info level, which libplacebo only does for non-dynamic LUTs, so something else is moving the LUT keys. The same libmpv build on a Snapdragon X Elite CRD (Adreno X1-85, driver 31.0.160.0) shows no churn at all, so the trigger is specific to the reporter's machine.

Add an HdrProbe to the Windows runner that polls the two LUT inputs every 250 ms - mpv's video-target-params (destination colour space, derived per frame from DXGI_OUTPUT_DESC1 and the DisplayConfig SDR white level) and video-out-params (source HDR metadata) - plus the raw DXGI output description, SDR white level and factory IsCurrent() state once a second, and reports every change and a 10 s summary into the app log as hdr-probe lines. Change streams are rate limited so an uploaded log stays within the relay's 1 MiB.
2026-09-02 03:59:26 +02:00
edde746 e9988165df style: run the repo formatters over the Dart and Kotlin stragglers
CI's formatting jobs were red on main: dart format wanted
media_card_grid_spacing_test.dart collapsed, and ktlint wanted three
Kotlin expression bodies on their signature line plus one import moved
into lexicographic order.

Pure formatter output from `dart format` and `scripts/format_native.sh
--fix`; no behavior change.
2026-09-01 16:21:07 +02:00
edde746 582d419618 fix(libraries): keep a sidebar library selection that mounts the Libraries tab
Choosing a hidden library from the sidebar on a fresh launch opened the
topmost visible library instead, and reordering the sidebar changed which
wrong library appeared. A second attempt worked.

The first visit to the Libraries tab mounts LibrariesScreen, and two
post-frame callbacks then run in registration order: MainScreen's, which
applies the requested library, and the one initState registers during that
frame's build, which picks the saved or topmost-visible default. The second
one overwrote the first — and a hidden library can be neither default, so
the selection was always lost.

Initialization now treats an existing selection as authoritative, both on
entry and after each of its awaits, so a selection arriving while it is
suspended (the refresh() stale-resume path) also survives.

close #2207
2026-09-01 16:11:09 +02:00
edde746 72d15b96a2 fix(linux): spell the maybe_unused attribute on the plugin keepalive globals
The Linux build stopped compiling everywhere: d9e31fd1a wrote the
attribute as [[maybe unused]], with a space instead of an underscore.
An attribute-list is comma-separated, so two bare identifiers are a
parse error rather than an ignorable unknown attribute, and
linux/runner/mpv/mpv_plugin.cc reaches every Linux build.

Use [[maybe_unused]], which is what clang 23's -Wunused-but-set-global
actually checks for, so the diagnostic the original change was chasing
stays suppressed.
2026-09-01 16:01:55 +02:00
K1ngfish3randGitHub d9e31fd1a4 fix for llvm23 (#2212) 2026-09-01 15:38:21 +02:00
edde746 23f9afa5b1 fix(windows): strip HDR10+ metadata from the Adreno tone-map path
Disabling peak detection (efb0e885) did not stop the per-frame shader LUT regeneration on Snapdragon devices: libplacebo keys the tone-map LUT on the frame's raw HDR metadata, and mpv forwards HDR10+ per-scene values (scene_max, scene_avg, ootf) on every decoded frame, so the LUT - at tens of milliseconds per rebuild on Qualcomm's D3D11 driver - still regenerated continuously and playback kept stuttering and flickering (#2191).

Zero the dynamic metadata before the renderer with vf=format:hdr10plus=no on Qualcomm GPUs; tone mapping uses the static HDR10 mastering metadata and the LUT is generated once. Dolby Vision L1 metadata is deliberately not stripped: dovi=no would break profile-5 rendering. The applied HDR pipeline options are now reported into the app log on first file load so uploaded logs are self-diagnosing.
2026-09-01 09:02:59 +02:00
edde746 efb0e885ae fix(windows): disable dynamic HDR peak detection on Qualcomm GPUs
Playing HDR content tone-mapped to an SDR display on Windows-on-ARM stutters heavily and flickers in brightness: dynamic peak detection moves the tone-mapping parameters every frame, libplacebo regenerates its tone-map and gamut-map shader LUTs each time, and Qualcomm's Adreno D3D11 driver takes tens of milliseconds per regeneration - roughly 100 ms of work against a 42 ms frame budget at 24 fps.

Scan the DXGI adapter list for a Qualcomm vendor id and set hdr-compute-peak=no when one is present, keeping auto elsewhere; static metadata-driven tone mapping generates its LUTs once.

close #2191
2026-09-01 07:37:10 +02:00
edde746 5fb4c78385 fix(jellyfin): restore Live TV on ts-only tuners and honor the quality preset
Since 2.18.0 no Jellyfin Live TV channel plays: opening one fails with
"Could not start the live channel", and switching channel inside the player
does nothing at all. Negotiating video transcodes as fMP4 (#2131) left the
device profile with no MPEG-TS entry, and Jellyfin discards every non-ts
transcoding profile for a live source whose tuner sets
UseMostCompatibleTranscodingProfile - hardcoded for every HDHomeRun host, the
default for M3U ones - so the negotiation came back with no HLS URL at all.

The device profile now sends a ts profile alongside the fMP4 one, listed
second, the way jellyfin-web does. Both of its codec lists are strict subsets
of the fMP4 entry's and the server ranks profiles with a stable sort, so ts
can only win where fMP4 has been filtered out; VOD keeps negotiating fMP4.
flac and truehd are absent because TS cannot carry them, av1 because that is
the gap fMP4 exists to fill.

Live TV also stops being unconditionally transcode-only. It now reads the same
saved quality preset the library path does: Original asks for direct play and
sends no bitrate ceiling, so a channel the server can hand over untouched no
longer costs a GPU encode session per viewer, and a capped preset transcodes at
that ceiling. A direct-play session whose stream dies re-negotiates a forced
transcode instead of re-opening a URL the server will not serve.

Two smaller holes on the same path: a negotiation that bailed out left the live
stream AutoOpenLiveStream had already opened running, because no playback
session existed to ever stop-report it - a few failed tunes could saturate a
provider's connection budget - and a channel switch that failed to start showed
no message at all.

close #2198
2026-08-31 19:23:22 +02:00
edde746 5a666fd10f feat(discover): refresh home and library content from server library push events
New media added server-side was invisible while the app was open - the
client had no channel for library-change notifications, so the home
screen and library tabs sat stale until an app restart.

Each online server now runs a reconnecting websocket push channel
(Plex `/:/websockets/notifications`; Jellyfin/Emby `/socket` with the
dialect deltas, including Emby's capabilities registration), owned per
server by a LibraryEventService supervisor that follows server
online/offline/replaced-client transitions and app lifecycle. Channels
emit one coalesced LibraryChangeEvent per burst on a leading-edge
throttle modeled on Plex Web's repopulate pacing: the first settled
change surfaces immediately and a library scan's flood merges behind
it. Connection failure degrades silently to the stale-refresh paths -
bounded reconnect backoff, re-armed on every status sync.

Consumers pace their reaction through one shared RefreshPacer: burst
debounce, blocked retry while video playback or an active scroll owns
the surface, a cooldown bounding pass frequency during bulk imports,
and credit for committed pull passes so a push landing right after a
fresh load defers to the cooldown's trailing edge.

- Discover runs a debounced full pass and swaps the result in place;
  the hero carousel resets only when a pass lands first content, so a
  push never yanks a screen the user is reading. Pushed removals drop
  from every visible list immediately via the deletion bus, scoped to
  the emitting server.
- The visible library tab swaps its data in place: transaction tabs
  reload without clearing, and the browse and paginated card grids
  refetch their loaded span (Plex Web's repopulateRange) with the
  scroll offset anchored on the first visible item and the span
  clamped after alpha jumps. Hidden tabs - and tabs behind another
  main tab - mark per-library staleness epochs instead and reload when
  next shown; epochs are snapshotted at load start so a push racing an
  in-flight fetch stays stale.
- The stale-resume and tab-shown paths refetch home hubs (previously
  Continue Watching only), covering setups where the socket cannot
  connect.

close #1646
2026-08-31 18:52:03 +02:00
edde746 56312a9eb2 fix(ui): keep clear logos with significant color untouched on heroes
Remapping a mark whose color is part of its identity - a red-outline
wordmark with white fill, a colored badge - fixes legibility but changes
the logo's character, which reads worse on hero surfaces than the
partial invisibility it cures.

The light tone class now splits on measured colored-pixel fraction:
light-dominant marks with incidental color (<=15% saturated pixels,
lightAccented) always remap, while lightMixed marks remap only when the
new ToneMappedLogoImage.remapMixed policy allows it. Heroes pass false
on the network, offline, and TV spotlight logo paths; the Live TV
guide's channel cells keep remapping mixed marks. The policy joins the
image-cache key. The threshold comes from a real clear-logo set:
remap-friendly marks measured at <=0.11 colored, identity-colored marks
at >=0.28.
2026-08-31 18:51:46 +02:00
edde746 976bdbd021 fix(ui): keep hero titles and clear logos legible in light theme
On the light theme, the detail hero's fallback title was hard-coded
white over a scrim that washes artwork toward the near-white background,
and white-on-transparent clear logos vanished into the same wash on the
detail, home, and TV spotlight heroes.

The title fallback now defaults to the theme foreground with a
background-side halo, matching what the TV hero already did. Clear logos
run through the channel-logo tone remap: light-toned marks recolor
toward the theme foreground on light backdrops (network and downloaded
artwork alike), colored marks keep their pixels, and dark themes render
the original artwork. The backdrop-luminance gate is shared with the
Live TV guide as logoToneTargetFor.
2026-08-31 18:51:46 +02:00
edde746 274b31ebac fix(livetv): recolor light channel logos for legibility in light theme
White-on-transparent broadcast logos (CBS, FOX, the NBC wordmark) vanish
on the light theme's white guide cards, making channels hard to identify.

Channel logo decodes now classify the frame's tone once per image-cache
entry and bake light-neutral pixels toward the theme foreground:
monochrome white marks recolor fully, mixed marks (colored peacock plus
white wordmark) keep their colored pixels, and self-backed or dark
artwork decodes unchanged. Applied in the guide channel column, guide
search, and favorite reordering whenever the backdrop is light,
including the dark theme's inverted focus card; dark backdrops keep the
original artwork.

close #2197
2026-08-31 18:51:46 +02:00
edde746 e1ef52aba1 fix(android): fall back to software decoding for non-Main-profile AV1
4:4:4 (High profile) AV1 played as green or black video on Android TV
devices with AV1 hardware decoders: MediaCodec defines no profile
constants beyond Main, but decoders like the Fire Stick 4K Max (MTK)
and Amlogic C2 accept the stream at configure time and emit garbage or
nothing, so no error ever reached the player and no fallback ran.

libmpv v1.2.2 carries an FFmpeg patch that reads seq_profile from the
bitstream at av1_mediacodec init and refuses High/Professional streams,
letting mpv's hwdec probing fall through to dav1d software decoding.
Main-profile AV1 keeps hardware decoding.

close #2194
2026-08-31 13:29:13 +02:00
edde746 9db6f54b7a feat(plex): make the covered-source direct play optional
A quality preset the source already fits under direct plays the file
since #2152, but a transcode above the source bitrate is sometimes the
point: a device that cannot decode the source (10-bit H.264, AV1, 4:4:4)
wants the server's highest-quality encode, and the shortcut silently
handed it the very file it cannot play smoothly.

A new Quality switch, "Play Smaller Videos at Original Quality" (on by
default), gates the shortcut in PlexClient._presetNeedsTranscode; off
restores the pre-#2152 behavior where any non-original preset always
transcodes. Plex-only by design: MediaBrowser servers make the
equivalent direct-play-vs-transcode call server-side.

close #2193
2026-08-31 11:32:07 +02:00
edde746 39ee089212 fix(audio): reload the mpv audio output when the HDMI route changes
TrueHD/Atmos passthrough with Frame Rate Matching enabled never engaged
the receiver on the mpv backend (Ugoos SK1 -> Denon AVR): the display
mode switch settles 2 s before the audio output opens, but some HDMI
chains are still renegotiating audio then, so the IEC 61937 track binds
a half-negotiated route and the sink never locks onto the MAT
bitstream - for the whole session. The same file with Frame Rate
Matching off, or on ExoPlayer, engages Atmos immediately: media3
rebuilds its sink when the audio device set changes, while mpv's
ao_audiotrack never revisited a track once created.

libmpv v1.2.1 polls AudioTrack.getRoutedDevice from the AO thread and
reloads the AO when the route changes - or vanishes and rebinds - under
a live IEC or raw passthrough track, reopening it against the settled
route. PCM tracks are exempt, and audiotrack-route-reload=no is the
escape hatch.

close #2190
2026-08-31 10:05:08 +02:00
edde746 89d54d8f1d feat(watch-together): let the host hand the room to another participant
close #2183

Reusing a room means whoever enters first becomes the host, and moving the
session to someone else's library meant everyone leaving and re-entering in
the right order. The host can now promote any connected guest from the
participant list (Watch Together screen and the in-player session sheet),
with playback, control mode, and reconnect identities carried across.

The relay owns the swap: a new `transferHost` message validates the sender
is the live host and the target a connected modern-protocol guest, then
swaps `HostPeerID` and the reconnect verifiers (each peer keeps its own
token), persists the room, and broadcasts `hostChanged` to every peer.

Clients flip roles in place: the controller swaps its role engine while
keeping the session, message queue, and player attachment. A promoted guest
seeds the coordinator with the room's last known intent (a paused room
stays paused) and the known-peer roster so the fresh epoch re-gates
instead of solo-starting; a demoted host falls back to a reconciler with a
fresh clock sync and asks the new authority for state. Guests re-pin the
host identity, reset their sequence, and re-converge their clocks.

A rejected transfer (`not_host` / `peer_not_found`) surfaces as a toast
instead of tearing the session down. Pre-transfer app builds in the room
ignore `hostChanged` and stop following the room at the next transfer;
targets on an old sync protocol are not offered the action.
2026-08-31 08:55:45 +02:00
edde746 44773fd742 feat(player): remember the swipe brightness level between playbacks
The brightness set with the left-edge swipe was lost the moment playback
ended, so every session started back at the system level. A new
"Remember Brightness Level" toggle under Settings > Playback > Gestures
persists the level a swipe settles on and reapplies it when the next
playback starts (and when the app resumes mid-session). Leaving the
player still restores the pre-playback brightness, so the rest of the
app is unaffected. Default off, preserving current behavior.

close #2178
2026-08-31 06:43:47 +02:00
edde746 4f4a7338e0 fix(search): tighten spacing around the kind filter chip strip
The chip strip sat 24px below the search field and 24px above the first
result. Drop the strip's own top padding (the field's bottom padding
already provides 16px) and halve the results sliver's top padding when
the strip is shown, so both gaps read as an even 16px.
2026-08-31 06:01:48 +02:00
edde746 10f9139ac6 fix(audio): bitstream Dolby/DTS as raw tracks on the mpv path
Audio Passthrough on 2.18.0 played EAC3 silently on a Shield in front of
a Dolby-Digital-only receiver: mpv's IEC 61937 AudioTrack bypasses the
platform's Dolby transcoder, so the pre-packed DD+ bitstream reached a
sink that cannot decode it, drained at full rate, and no failure was
observable app-side. Disabling passthrough lost surround instead, because
multichannel PCM collapses to stereo in the platform mixer before the
HDMI re-encode.

libmpv v1.2.0 unwraps the IEC bursts and feeds AC3, E-AC3 and the DTS
core to a raw ENCODING_AC3/E_AC3/DTS track - the transport ExoPlayer and
Kodi use - keeping the platform decoder/transcoder in the path, with the
IEC track as fallback and audiotrack-raw-passthrough=no as an escape
hatch. TrueHD and DTS-HD MA stay on the 8-channel IEC carrier.

The audio-spdif route probe now accepts a codec when the route takes its
raw track (the same direct-playback tiering media3 uses; encoding-only
below API 29) or one of the IEC shapes, matching the AO's transport
ladder. A dev-only PLEZY_LOCAL_MPV_AAR override allows testing locally
built fork AARs before a release is pinned.

close #2177
close #2179
2026-08-30 19:22:14 +02:00
edde746 3c1ab3cc6c fix(windows): bundle the Vulkan loader so libmpv's vulkan-1.dll import resolves
Since the libmpv bump to 20260809 (2.15.0), libmpv-2.dll dynamically links
the Khronos Vulkan loader instead of statically linking it. plezy.exe links
libmpv at load time, so on machines whose GPU driver does not install
vulkan-1.dll - Windows-on-ARM Adreno drivers, driverless x64 VMs - the
process failed before startup with "vulkan-1.dll was not found".

Download the LunarG-built loader (pinned, hash-verified) at configure time
and install it next to the executable with its license. Without a Vulkan
ICD the gpu-api=auto probe fails cleanly and falls back to D3D11, matching
the old static-loader behavior.

close #2110
2026-08-30 12:16:26 +02:00
github-actions[bot] c597390e1c chore: update cask to 2.18.0 2026-08-30 08:39:52 +00:00
edde746 2806115015 chore: bump version to 2.18.0 2026-08-30 09:28:50 +02:00
edde746 d9493c6157 feat(player): move every Android install to the mpv backend
Making mpv the Android default only moved installs that had never opened
the Player Backend setting. Anyone who had ever picked ExoPlayer kept it,
including the low-end TVs and Hi10P devices the new backend was built for.

The backend choice now lives under a new `android_use_exoplayer` key and
the old `use_exoplayer` one is dropped at startup, so every install starts
on mpv. ExoPlayer stays selectable in Settings > Playback > Player Backend,
and a pick made there writes the new key and sticks.
2026-08-30 09:22:31 +02:00
edde746 7cfb890046 fix(i18n): translate the Live TV guide search and TV options labels
The guide-search sheet and the TV rail's options button fell back to
English in every non-English locale: their six keys existed only as
empty strings in the sibling translation files.

Fill all 126 empty targets across the 21 locales and regenerate the
slang bindings. searchNoResults keeps its ${query} placeholder and each
locale's quote convention, and channelsSection uses the broadcast sense
of "channel" rather than the audio-channel word already used by
fileInfo.channels.
2026-08-30 08:48:32 +02:00
edde746 c6458295a1 fix(player): let the HDR exit settle before restoring the display mode
Stopping HDR playback with frame rate matching enabled left some TVs
black for up to 30 seconds. The teardown reset preferredDisplayModeId
while the display was still signaling HDR, folding the HDR exit and the
refresh-rate restore into one HDMI renegotiation that slow sink chains
take many seconds to complete (8.5 s on a Shield Pro with an HDR10
display; ~30 s on the reporter's DV AVR+TV chain). Sequenced, the HDR
infoframe clear is free and the SDR mode switch takes about a second.

FrameRateManager.clearVideoFrameRate now takes an hdrActive hint from
the core (mpv: the content-color-transfer decision; ExoPlayer: the
selected track's colorInfo transfer) and defers the restore by 400 ms so
the surface teardown commits the HDR exit first. The deferred restore
lives on its own main-looper handler because core dispose clears the
shared player handler wholesale, and a new setVideoFrameRate cancels it
so a fresh session's switch is never clobbered. SDR teardown behavior is
unchanged.

Verified on a Shield Pro (mpv backend, 1917 DV P8/TrueHD, Jellyfin):
link recovery after stop went from ~8.5 s to ~0.8 s, with the SMPTE 2086
clear now committing before the mode set.

close #2172
2026-08-30 08:25:18 +02:00
edde746 6e2dda092d feat(music): make the background fill the mini player's only progress display
The mini player drew a thin scrubbable progress bar along its top edge on
top of the ambient background fill. Drop the scrub lane: the fill is the
card's only progress display, and precise seeking stays on the
now-playing screen's seek bar. Horizontal drags across the card's top
edge swipe-dismiss the card again.
2026-08-29 19:12:03 +02:00
edde746 45e8da1610 feat(music): restore the last music session paused on launch
Quitting the app lost the music session: on the next launch the queue,
current song, and playhead were gone. The session now persists per
profile (new MusicSessions Drift table, schema v22) through throttled
write-through during playback, and the next launch rehydrates it as a
parked-paused queue — no audio core and no source resolution until the
first play, which opens the track at the saved offset. Ending the
session (stop, swipe-dismiss, video claim) clears the snapshot, and a
new "Remember music session" playback setting (default on) gates the
restore.

close #2148
2026-08-29 19:11:58 +02:00
edde746 ad026cecc1 fix(player): keep hardware decoding after a transient VideoToolbox failure
Some HEVC files carry a frame Apple's hardware decoder refuses to decode
(kVTVideoDecoderBadDataErr on an otherwise conformant P-frame). mpv fell
back to software decoding for the rest of the file after the first error,
and 4K HEVC software decode drops frames every few minutes on Apple TV.

MPVKit b8b922ec carries an mpv vd_lavc patch that keeps the configured
fast fallback while probing but lets a hardware decoder that has already
delivered frames ride out a mid-stream error burst: the burst one
undecodable frame causes ends at the next keyframe by construction, so
fallback now requires errors to survive two keyframe intervals. Verified
against the reporter's sample: playback logs "Hardware decoding
recovered after 90 errored frames" and stays on VideoToolbox instead of
switching to software.

close #2167
2026-08-29 17:39:35 +02:00
edde746 ffc95d6b2c feat(tv): mark whole seasons watched from the show detail rail
On TV the show detail screen exposed season actions nowhere: marking a
season watched meant toggling every episode one by one, and the action
row's menu only covered the whole show.

Each season row on the TV detail rail now carries a full-size Options
card that opens the same season context menu the mobile season tabs
offer (mark watched/unwatched, download, delete, add to). The card
rests off-screen left of the first episode — the row is a
center-anchored scroll view and the card lives in the negative-offset
region before the anchor — so the resting layout and default focus are
unchanged and normal playback gains no extra steps; pressing LEFT from
the first episode slides it in. The trailing View All / retry / loading
slots become matching full-size cards instead of compact pills.

close #2156
2026-08-29 13:56:24 +02:00
edde746 a3cbf323b3 feat(livetv): search the guide for channels and programs
Live TV had no search: finding a channel or a program meant scrolling
the guide row by row, which is close to unusable on TV with a few
hundred IPTV channels, and the global search tab covers neither
channels nor EPG data.

A search action on the Live TV tab bar (shown on every tab, since the
D-pad route through the chips selects each tab it crosses) opens a
sheet that filters channels by name, call sign, and number, and the
next 24 hours of programs by title and series name, from one
fetchSchedule fan-out per open. Selecting a result jumps the guide to
it: the favorites filter is dropped when it would hide the target row,
the time window is re-anchored when the airing is outside the visible
six hours, and D-pad focus lands on the channel cell or program block.
While the sheet is open, companion-remote search queries land in it
instead of the global Search tab (same save/restore idiom as the video
player overrides). Jumps requested while a guide load is in flight are
stashed and replayed when the load commits.

Based on #1526 by @l3gitpanda, rebased over the guide virtualization
and source-group work, with the schedule fan-out moved onto
forEachLiveTvServer and the jump focus routed through the guide's
focus-snapshot publisher so the landed cell actually renders focused.

close #2168
2026-08-29 01:54:21 +02:00
edde746 2f2016fdbe feat(player): show the next episode's thumbnail in the play-next prompt
The end-of-episode autoplay prompt only named the next episode; Plex shows
a visual preview, which is what non-readers navigate by. The prompt card now
paints the episode's 16:9 still edge-to-edge behind the text under a bottom
gradient scrim, falling back to the text-only card when no thumbnail can be
served (no thumb, or no client and no downloaded artwork). Unwatched stills
respect the hide-spoilers blur, and the lookup only runs while the prompt is
visible to keep the playback-path build cheap.

close #2166
2026-08-28 18:43:26 +02:00
edde746 ff1064d35f fix(player): render HDR letterbox bars off the SDR window plane
HDR/Dolby Vision playback on Fire TV (and some Sony/Philips models)
shows gray letterbox bars instead of black on OLED panels: the bars
were the player container's window-plane background, and those device
compositors raise SDR graphics-plane black while the display is in
HDR/DV output mode. Black inside the video plane is unaffected (same
mechanism as ExoPlayer #8803 and Kodi #25300).

Add a fullscreen, buffer-less SurfaceView beneath the video surface in
the shared player container. Like any below-window SurfaceView it
registers its rect as a window transparent region, so the letterbox
area scans out as the SurfaceFlinger backdrop instead of window-plane
pixels. No buffer is ever posted: SurfaceFlinger skips buffer-less
layers, and drawing into one would put the bars back on an SDR layer.
Covers both the ExoPlayer and mpv backends.

close #2163
2026-08-28 11:24:37 +02:00
edde746 861111a191 feat(player): offer a 140% zoom preset
close #2158
2026-08-28 08:12:38 +02:00
edde746 463ad6b933 fix(i18n): translate settings and account preferences into all locales
94 strings added since the settings rework were empty placeholders in every
non-English locale, so those screens fell back to blanks. Fill all 1974
missing values across 21 locales, reuse each file's existing terminology,
and translate the few verbatim-English leftovers (es rankPopular, fr tags,
it dynamicRange, pl stop, nb tag). Regenerated Slang output.
2026-08-28 06:51:10 +02:00
edde746 1ee648f442 fix(plex): direct play a source the quality preset already covers
Any quality preset other than Original started a transcode even when the
file was already well under it: a 6.2 Mbps 1080p h264 source under the
"1080p 10 Mbps" preset came back from PMS as a 10.4 Mbps encode, so capping
quality on mobile data spent more data than leaving it uncapped, plus server
CPU nobody asked for (#2152).

A preset is a ceiling, so a version that fits under both its bitrate and its
resolution is now served by the file itself, on the same direct-play path
Original takes, and no transcode decision is sent at all. Height counts as
well as bitrate because the preset's label promises a resolution too, and a
device that asked for 1080p may not decode the 4K source a bitrate-only
comparison would hand it. An unreported bitrate or height leaves the
transcode standing.

The comparison has to happen in the client: PMS answers directPlay=1 with
"Direct play OK" whatever bitrate cap the request carries, measured on 1.43
with a 65 Mbps 4K source under a 10 Mbps cap, so its MDE cannot be asked to
enforce one. Plex Web reaches its own directPlay/directStream flags the same
way, folding the preset's bitrate into its client-side direct-play profile
first. Jellyfin already gets this right server-side.

close #2152
2026-08-27 20:37:56 +02:00
edde746 ed71b200b9 feat(music): make the mini player progress bar scrubbable
While music plays, the persistent mini player showed progress only as a
subtle background tint with no way to seek; the full seek bar sat one
navigation hop away on the now-playing screen (#2141).

The card's top edge now hosts a thin visible progress bar inside a taller
touch lane: tap seeks proportionally, dragging scrubs and commits one seek
on release, and hovering or dragging grows the bar and shows a thumb. Card
taps outside the lane still open the now-playing screen. Pointer-only by
design: the overlay never renders on TV and the keyboard focus chain leads
to the now-playing screen's focusable seek bar.

close #2141
2026-08-27 16:59:08 +02:00
edde746 a1d8ab5210 fix(plex): surface instant mix failures instead of silently doing nothing
Tapping Instant Mix on Plex often did nothing: the /playQueues POST used no
endpoint failover, createPlayQueue swallowed every error into null,
fetchInstantMix mapped that to an empty list, playInstantMix returned
silently on empty tracks, and the errors stream's only listener is the
now-playing screen, which is not mounted at tap time (#2141).

The play-queue POST now rides the shared endpoint failover (replaying it is
safe: an orphaned duplicate queue on the server is inert), createPlayQueue
and fetchInstantMix propagate typed errors, playInstantMix reports
started/empty/superseded and throws fetch failures, and the tap site shows
a translated snackbar for a failed or empty mix. A failed collection or
playlist queue launch now also reaches the real failure snackbar instead of
the misleading "no items" path.
2026-08-27 16:59:08 +02:00
edde746 a13febf67b fix(downloads): store music tracks as Music/{Artist}/{Album}/{NN - Title}
Downloaded tracks landed in the generic downloads/{serverId}/{ratingKey}/
layout as video.mp3 because the path builder only special-cases movies and
episodes, so a user-visible download folder showed opaque folders and
meaningless names (#2141).

Tracks now get Music/{Artist}/{Album}/{NN - Title}.{ext} in both file and
SAF modes, grouped by sanitized album-artist with Unknown Artist/Album
fallbacks and a disc prefix on multi-disc albums. Existing downloads keep
working: playback and deletion resolve the stored path per record, and the
empty-parent cleanup keeps shared album folders while a sibling track
remains.
2026-08-27 16:58:52 +02:00
edde746 a97be5823f feat(player): add play-next countdown, gesture toggles, and deinterlacing
Users could not adjust the five-second Play Next timer, switch off the
edge-swipe/pinch gestures they trigger by accident, deinterlace DVD-era
content, or keep always-on-top across episodes.

Play Next Countdown (0-30 s) joins Auto-Play & Skip; zero skips the
prompt and starts the next episode immediately, while the transient-
retry prompt keeps its fixed five-second spacing. Brightness swipe,
volume swipe, and pinch-to-zoom each get a switch in a mobile-only
Gestures group; a disabled edge also stops stealing the content-strip
drag. A Deinterlacing toggle (mpv-only — ExoPlayer has no filter chain)
sets mpv's deinterlace=auto at player init. The player's always-on-top
toggle now persists via a pref that is re-applied when the next player
opens, including autoplay episode transitions; the window flag is still
dropped when the player closes.

Also resolves the reorg TODO markers per triage: hold-to-speed lock
(#1046) will be gesture behavior rather than a setting, metadata
language (#1668) and delete re-authentication (#1924) are rejected, and
always-on-top is player-persisted state, not a Window setting (#1386).

close #1827
close #1810
close #2149
close #931
2026-08-27 16:42:38 +02:00
edde746 c9de78697b feat(settings): reorganize settings into general, appearance, and playback homes
Settings were grouped by screen history rather than by what they govern:
the profile-selection prompt, startup section, force-TV mode, and app
language sat under Appearance, Discord Rich Presence and the companion
remote host hid inside Playback > Behavior, and maximum volume lived
under Seek & Timing.

Introduce a General screen (language, startup, desktop window), regroup
Appearance into display/library/home/navigation/Live TV, split the
Playback monolith into engine, video & display, audio, quality,
subtitles, seek, auto-play & skip, and behavior groups, surface
auto-play next episode in settings, rename the Keyboard Shortcuts
section to Controls (now also hosting the companion remote host), move
Discord Rich Presence to Services > Integrations, and move the
performance-overlay switch to Advanced. Pref keys are unchanged, so
stored values, export/import, and reset behavior are unaffected.

TODO markers record the agreed homes for upcoming settings (#1998,
#2064, #1641, #1769, #2149, #1827, #2138, #1810, #1046, #1924, #1413,
#1668, #1386, #1795).
2026-08-27 16:02:10 +02:00
edde746 9ac8002b53 feat(player): apply separate default quality on cellular connections
On mobile data the single default streaming quality either burns
through the user's data plan or permanently caps quality at home.
Playback start now applies a dedicated cellular default when the
device is on a cellular-only connection, read from the app's existing
single connectivity subscription. The new setting defaults to
following the general default, ships in Settings > Playback for
phones/tablets only, and explicit per-play quality picks still win.

'Metered connection' had been spelled out independently in the offline
provider, the download WiFi-only gate and the sync-rule cooldown.
Rather than add a fourth copy, all four now share
ConnectivityLinkType. Network *presence* is deliberately left alone:
its callers disagree on whether an empty snapshot counts as
connected, so folding that in would change behavior.

showSelectionDialog now returns the picked DialogOption instead of its
raw value so the tile's null-valued 'Same as Default Quality' option
stays distinguishable from dismissing the dialog.

close #2147
2026-08-27 14:14:01 +02:00
edde746 942065e39d fix(plex): honor disabled credits detection when synthesizing chapter markers
When a Plex admin disables credits detection for a show or movie, PMS
strips detected credits markers from its responses, but Plezy's
chapter-title fallback resurrected the skip action from a credits-named
chapter — surfacing a "Next Episode" button (and auto-skip) during
credits the admin asked to leave alone.

Drop credits markers when the owning show/movie carries an explicit
enableCreditsMarkerGeneration=0. Movies read the attribute off the item
already fetched; episodes resolve the grandparent show through the
shared cache-first metadata row, so the lookup normally costs no extra
request and only runs when a credits marker is actually present. Absent
attribute (servers without the feature) and -1 (library default) keep
the fallback intact; lookup failures fail open. The offline cached
extras path applies the same rule from cached rows.

close #2137
2026-08-27 10:16:05 +02:00
edde746 94565b4ee0 feat(library): make grid spacing between posters configurable
The library grid packs posters edge to edge. The grid delegate's cross-
and main-axis spacing were hardcoded to zero, so the only visible gap
came from each card's own 3px padding, and Library Density changed
poster size rather than the space between posters. The result reads
denser than Plex, Jellyfin, or any commercial client, both horizontally
between posters and vertically between a poster and its title.

Add a Grid Spacing setting - Tight, Normal, Spacious (0/6/12px) - below
Library Density. Tight is the default and reproduces the current layout
exactly, so no existing grid moves on update.

The gutter lands in MediaGridDelegate.spacingFor(), already the single
funnel for non-full-bleed grid spacing, so every grid surface picks it
up: library browse, collections, playlists, downloads, and the detail
screens. Square music grids keep their 8px floor. The pref is watched
once in MediaCardSliverLayout - the only MediaGridGeometry.resolve()
call site - so grids re-layout live instead of on restart.

Grid cells grow the poster-to-title gap to 2/4/6px as well; the
Expanded poster absorbs the delta, so the cell keeps its aspect ratio.
Fixed-height hub-row cards keep the historical 2px because their text
band cannot absorb more, and hub-row cell packing opts out of the
setting entirely so shelves stay byte-identical across it.

Full-bleed TV grids are untouched - they already carry an 8-18px
scale-derived gutter - and are opt-in behind tvFullCardLayout, so the
default TV library grid follows the setting like every other surface.

Verified on macOS across all three steps: gutters and title gap grow,
grids re-pack live, and the segmented control reflects and writes the
value.

close #1597
close #2083
2026-08-27 09:21:48 +02:00
edde746 0c5308cfa1 refactor(networking): drop Cronet and NSURLSession for the tuned dart:io client
Plezy carried three native HTTP clients on the assumption that they beat
Dart's own. Benchmarked against real Plex and Jellyfin servers on macOS,
Windows, Linux and three Android devices, two of them do not.

Cronet loses on every request shape the app issues: 8.1 vs 83.8 MiB/s on a LAN
body read, 84 vs 150 req/s on an artwork fan-out, 14.3 vs 10.7 ms on
sequential API calls. It also fails a 60-way fan-out outright with
net::ERR_CACHE_WRITE_FAILURE under the 2 MiB memory cache we configured, and
cost 70-705 ms of CronetEngine.build on first use. Paying that build off the
critical path is the only reason AndroidPlatformHttpClient,
warmUpPlatformHttpClient and the per-request delegate swap existed; all three
go away with it.

CupertinoClient had no measured advantage either, losing the TLS fan-out 44 vs
60 req/s, and no reported issue ever justified it. tvOS already shipped the
dart:io client, so Apple platforms now agree with it.

WinHttpClient stays. WINHTTP_OPTION_IPV6_FAST_FALLBACK (#1128) has no dart:io
equivalent, and it brings the system proxy and the Schannel trust store.

The pool tuning becomes unconditional. It was opt-in behind usePlexApiClient
so generic tracker and auth clients stayed disposable, but every dart:io client
has carried connectionTimeout and forceCloseOnDrainTimeout since #1972, so
tuned and untuned already share shutdown semantics and the flag only cost
throughput: 12 connections per host with a 90s idle measured ~4x the dart:io
default on a 60-way fan-out on Linux and ~2x on Android.

media3-datasource-cronet and cronet-embedded stay. They back ExoPlayer's
CronetDataSource independently of package:cronet_http.

Refs #2140.
2026-08-27 09:21:48 +02:00
edde746 a18ecb5c4a test(watch-together): stop the relay setup tests racing a real handshake
Two relay setup tests failed on CI while the same commit had passed a
few minutes earlier. The harness rewrote every 10-second timer in the
zone to 10 ms, which also compressed the connect deadline of the
recovery that runs once setup retries are exhausted. On a loaded runner
that deadline expired after the relay had upgraded the socket but
before the client sent its first frame, so the recorded connection
carried no messages and shifted the expected sequence; when all three
recovery attempts were starved this way, the recovery never announced
at all.

A reply that never comes is safe to compress, a real loopback handshake
is not, and one zone hook matching on duration cannot tell them apart.
The service now exposes the setup acknowledgement, the release
handshake, and the release acknowledgement as separate budgets, each
still 10 seconds in production, and every test sets only the one it
means to expire. The blunt helper is gone; what remains collapses the
250 ms and 500 ms retry delays, which are waits rather than races.

Verified by reproducing both failure modes under CPU saturation, about
one run in ten, then 30 consecutive clean runs of the file under the
same load and a full suite at 6332 passing.
2026-08-27 09:21:48 +02:00
edde746 f7060478d1 fix(plex): offer User Rating and Plays sorts in home-video libraries
Browsing a Plex home-video / "Other Videos" library under "Show all"
offered no way to sort by your own rating. The sorts Plex advertises for
those sections only cover critic and audience ratings, which unmatched
files never carry, so nothing rating-based was usable.

Plex honors `sort=userRating:desc` and `sort=viewCount:desc` on those
sections without advertising them, and the client already appends both
for movie and TV libraries. Home-video sections are `type="movie"` on the
wire and only differ by `subtype="clip"`, which the library mapper folds
into MediaKind.clip for folder-first grouping and wide cards, so they
were failing the movie/show allow-list. Add clip to it.
2026-08-26 20:28:19 +02:00
edde746 3f03262833 fix(player): recover playback after a lost native-channel handoff
A player whose predecessor had not released the shared native channel
within three seconds skipped its own native dispose and chained its
release onto that predecessor. If the predecessor's teardown never
completed - one hung 4K session was enough - every later player waited
on the chain, failed to initialize, and playback stayed broken with
"Playback could not be started" until the app was killed.

Initialize and dispose now carry the creating instance's token. The
Android plugins remember which token created the current core and
acknowledge a dispose from any other token without touching the core,
so a dispose that lost the ownership race is provably stale and safe to
send. With that guard, a timed-out ownership wait force-disposes
instead of skipping, settles its release unchained, and frees the
channel for the next session; a dispose watchdog answers Dart even if
a native teardown hangs, leaking that one core instead of wedging all
future playback. Commands wait eight seconds (was three) so a slow but
healthy teardown delays the next session instead of failing it.

Verified on a Shield Pro: 38 back-to-back session races at 0.8-2.2s
gaps with zero failures and balanced teardowns, and a deep-link-over-
playback collision whose stale dispose is ignored, after which Back
returns to the still-playing session and Retry starts the new one.
Apple and desktop handlers ignore the token and keep the historical
skip semantics until they gain the guard.
2026-08-26 18:59:28 +02:00
edde746 3c6d398598 feat(player): default Android playback to the mpv backend
With video on the MediaCodec plane, real bitstream passthrough, media3
demuxing, and the GL fallback ladder in place, mpv measures at parity
or better than ExoPlayer on every device class tested (Tegra, Mali,
Amlogic armv7, Adreno; API 28-36; phone, TV, and foldable), including
the two historical Android mpv failure modes: low-end TV playback and
Hi10P.

Installs that never chose a backend move to mpv; a stored ExoPlayer
choice is preserved, and the Player Backend toggle stays user-visible
as the escape hatch. The automatic ExoPlayer-to-mpv runtime fallback
is unchanged.
2026-08-26 18:59:28 +02:00
edde746 8f893e7a67 fix(player): demux Android direct play with media3 again
The in-app FFmpeg container demuxer classified every DTS variant as
plain DTS (profile-blind MIME mapping at the demux boundary), so
DTS-HD MA lost its lossless identity downstream, and it ignored
container display-aspect-ratio overrides. media3's extractors get both
right.

Delete the FFmpeg demuxer (JNI, extractor, and its setting); ExoPlayer
direct play demuxes with media3's DefaultExtractorsFactory again, and
mpv - the Android default - reads container display dimensions itself.

close #2124
close #2115
2026-08-26 18:59:28 +02:00
edde746 465da3e82a feat(audio): bitstream passthrough by default on Android TV
mpv's ao_audiotrack hardcoded stereo IEC61937 frames, which cannot
carry TrueHD MAT or DTS-HD MA 8-channel bursts, and the app fed
audio-spdif an empty list in self-defense because mpv
force-passthroughs every codec named there with no decode fallback.
The mpv path therefore decoded everything, and passthrough had to be
enabled by hand on every install.

The Kotlin audio route probe (AudioOutputPolicy) now feeds mpv a
per-route audio-spdif list, the fork's multichannel IEC61937 patch
(pinned libmpv v1.1.3) provides the burst geometry, and E-AC3, TrueHD
and DTS-HD MA bitstream on the mpv path. Android TV installs with no
stored preference default to passthrough on, on both backends; an
explicit user choice is preserved.

Verified by route probing and mpv logs on Shield and Box R; no AVR was
in the loop, so receiver-side decode is unconfirmed.
2026-08-26 18:59:28 +02:00
edde746 04615ce2fc feat(player): HDR output for software-decoded video on Android
Software-decoded HDR always collapsed to SDR on Android: the EGL
window surface carried no colorspace, so PQ/HLG content that fell back
to software decode rendered through an SDR surface, and Android was
excluded from the hdr-enabled path outright.

The GL vo now requests a BT2020-PQ window surface (fork patch, pinned
libmpv v1.1.3) and Android joins the hdr-enabled path, so software
decode keeps HDR scanout and tone mapping happens only when the
display genuinely cannot show HDR.
2026-08-26 18:59:28 +02:00
edde746 a1c98b9d27 feat(player): render Android mpv video on the MediaCodec plane
Android mpv drew every frame through vo=gpu: an ImageReader/GLES copy
pinned to 8-bit RGB0 with a 100 ms timed wait per frame, which
truncated 10-bit and HDR output, raced acquireLatestImage, and
performed badly on low-end TVs.

Video now scans out on a SurfaceFlinger video plane through the fork's
vo=mediacodec: decoder buffers are queued to the surface at their
target PTS (av_mediacodec_release_buffer_at_time), so 10-bit and HDR
dataspaces reach the display untouched and frame pacing no longer
depends on GL vsync. Subtitles and OSD render on a sibling transparent
surface presented for the same PTS, frame-locked by construction.

The plane takes decoder buffers only, so software-decoded video stays
on a GL vo, with a chain-failure watchdog re-initializing the output
when the plane refuses a stream mid-session. The GL fallback is vo=gpu
- gpu-next breaks the Tegra GLES linker (#2010) - and GpuVoPolicy
selects gpu-next only when Dolby Vision RPU reshaping needs
libplacebo. AV1 film grain is applied in the decoder
(vd-lavc-film-grain=cpu) because the GL raster grain fallback is not
available on this path.

Pins libmpv-android v1.1.3, which carries the fork patches this path
rides on: the vo itself, BT2020-PQ EGL window surfaces, GLES direct
rendering treated as slow (H.264 Hi10P software decode on Tegra went
from 0.3x realtime with wrong colors to 1.0x with correct 10-bit
output), and multichannel IEC61937 for ao_audiotrack.

Verified on Shield Pro (Tegra/GLES), Pixel 7 (Mali), Box R 4K Plus
(Amlogic armv7), and Galaxy Z Fold3 (Adreno): 520 play/teardown cycles
and 3 hours of continuous 4K HDR playback; HDR engagement confirmed
via SurfaceFlinger dataspace BT2020_ITU_PQ.
2026-08-26 18:59:19 +02:00
edde746 85bf948004 fix(macos): keep text and icons legible by pinning the Skia renderer
On macOS 2.17.1 the UI started flashing garbage: text and Material icon
glyphs rendered as striped noise, and a keypress could flash a whole
glyph-atlas texture across the window. 2.17.0 on the same machine was fine.

2.17.1 moved to Flutter 3.47.1, which made Impeller the default macOS
renderer. Plezy is unusually exposed to that switch: MainFlutterWindow
clears the Flutter view to transparent so the mpv CAMetalLayer behind it
stays visible, so whatever Impeller leaves in the presented drawable is
blended onto the screen instead of being hidden under an opaque frame.

Opt out through the Info.plist switch the macOS embedder reads from the
main bundle at launch, so it applies to release builds too. That restores
the renderer every release up to 2.17.0 shipped; keep it until the engine
fixes for the 3.47 macOS Impeller regressions reach stable.

close #2132
2026-08-26 17:16:21 +02:00
edde746 c564635ad9 fix(jellyfin): advertise video codecs from a native hardware-decode probe
A device with no hardware HEVC decoder could still be handed an HEVC
transcode: the device profile advertised a fixed codec list that assumed
every device decodes everything. Prepending AV1 to reach the AV1 encoders
issue #2131 asks for would have made that worse - an Apple TV 4K and every
iPhone before the A17 Pro have no AV1 decoder at all.

Probe the platform instead. Android enumerates MediaCodecList for a
hardware decoder and iOS/tvOS ask VideoToolbox, both feeding one latched
VideoDecodeCapabilities that the device profile reads when it builds its
codec lists. Desktop deliberately answers nothing: a pre-Kaby-Lake Mac has
no hardware HEVC decoder and an M1 no AV1 one, yet both software-decode in
real time, so narrowing there would force transcodes for nothing. An
unanswered or failed probe advertises everything, so the list never
narrows on missing data.

The transcode target becomes av1,hevc,h264 filtered by the probe. Leading
with AV1 is safe because the server rotates codecs its admin has not
enabled ("Allow encoding in HEVC/AV1 format", both off by default) to the
back before picking one, so it costs nothing on a server that will not
emit AV1.

Audio now accepts everything the path can carry. The direct-play profile
drops its AudioCodec list entirely - an omitted list means "any codec" to
Jellyfin - so an audio stream can no longer be what blocks direct play.
The transcode target lists every codec Jellyfin can put in an fMP4
segment, so a video-only transcode copies DTS or TrueHD instead of
re-encoding it. Two limits bound that string: the server validates it
against ^[a-zA-Z0-9\-\._,|]{0,40}$ when it echoes the list into the
transcode URL, so alac does not fit and * is not a wildcard; and omitting
the key is not "accept everything" here the way it is for direct play,
because the server substitutes the source codec and then ships no audio at
all for a source fMP4 cannot carry.

close #2131
2026-08-26 16:53:14 +02:00
edde746 fce4193f7e fix(jellyfin): negotiate video transcodes as fMP4 HLS instead of MPEG-TS
MPEG-TS segments cannot carry AV1, so a Jellyfin server with an AV1
hardware encoder (Intel Arc and similar) could never pick AV1 as the
transcode output no matter what the codec list advertised. Switch the
video TranscodingProfile container from ts to mp4, matching
jellyfin-web's fMP4 HLS behavior; mpv consumes fMP4 HLS on every
platform and the Plex VOD target has shipped it since issue #1859.

close #2131
2026-08-26 14:41:37 +02:00
edde746 628fd21ec3 fix(windows): keep the video visible behind the OSD by pinning the Skia renderer
After 2.17.1 the video went fully black on Windows for as long as the player
UI was on screen and came back the instant it faded out. Audio was never
affected, mpv.conf made no difference, and 2.17.0 on the same machine and
driver was fine.

2.17.1 moved to Flutter 3.47.1, which made Impeller the default Windows
renderer. Plezy is unusually exposed to that switch: the patched engine
presents the UI on a topmost DirectComposition visual that DWM blends over the
mpv video child, so the video is only as visible as the presented frame's
per-pixel alpha says it is. When Impeller's GLES backend gets that alpha wrong,
the OSD's full-screen scrim presents opaque and hides the video outright;
unmounting the controls presents a transparent frame again, which is why the
picture tracked the UI exactly.

Opt out through the embedder Impeller switch that 3.47 added. Unlike
FLUTTER_ENGINE_SWITCHES it applies to release builds, and it restores the
renderer every release up to 2.17.0 shipped without touching the engine patches.

close #2127
2026-08-26 03:15:59 +02:00
edde746 d2c4e8345f fix(player): retry transient stream errors instead of falling back to MPV
During Android direct play, a single dropped connection or network blip
mid-stream kicked an otherwise healthy ExoPlayer session over to the MPV
fallback - on a Shield this showed as random backend switches minutes
into an episode (log pu4ad: "ffmpeg demuxer read failed: -5" with
contentIsMalformed=true, while MPV reopened the same URL fine).

Three defects lined up behind it, all in the 2.17.0 ffmpeg demux path:

- The AVIO read callback turned the input proxy's stored IOException
  (its -1 return) into a bare AVERROR(EIO) without marking javaError, so
  the extractor classified the failure as a malformed container. media3
  never retries a ParserException, so the designed ERR_JAVA ->
  IOException -> load-error-retry path was unreachable. The callback now
  latches javaError for a negative read and fails fast on every later
  read in the same native call, so matroska resync cannot clobber the
  stored message or skip past the failed range.
- A failed refill latches AVIOContext error/eof_reached and avio never
  drives the callback again, so even a correctly classified retry would
  re-fail on the stale error. nativeReadPacket and nativeSeek now clear
  the latch on entry; a genuine end of file (error == 0) is left alone.
- FfmpegRandomAccessSource kept a handle whose read had thrown, and its
  position matched the retried request, so the retry was handed the same
  dead handle. A failed read now drops the handle and the retry reopens.

A transient failure now surfaces as a retryable IOException, media3
reopens the source, and sample delivery resumes gaplessly; persistent
failures still exhaust the retry policy and reach the MPV fallback as
before.

close #2113
2026-08-25 11:15:43 +02:00
edde746andGitHub ae555ed5d7 feat(settings): account preferences, stored on the server instead of the device (#2112)
Preferences that belong to the media-server account had nowhere to live in Plezy. Jellyfin keeps a user's audio/subtitle language, subtitle mode and several library options in `UserConfiguration`; plex.tv keeps the same language choices plus watched indicators and review visibility on the account. Plezy read four of those fields for auto-track selection and could never show or change any of them.

Adds an Account preferences section under Connections. One account edits in place; several show a picker first, scoped to the active profile's own connections so a managed Plex Home user never edits the owner's record. Every row is gated on what the backend can actually store.

It also moves "rewatching in Next Up" onto the account. There is no `UserConfiguration` field for it, but the per-user `DisplayPreferences` store is keyed `(userId, displayPreferencesId, client)` with no device component, so the switch goes there and follows the account.

`AccountRef` keys by account, not `clientScopeId`: MediaBrowser is `{machineId}/{userId}`, Plex is (account, Home user). Writes are patch-shaped because both backends replace whole objects — Jellyfin's `POST /Users/{id}/Configuration` and its `DisplayPreferences` row both reset omitted fields, so each write re-reads, merges only the patched keys, and posts back. Plex takes its changes as query parameters with an empty body, and its `experience` blob and the PMS `/accounts/1` mirror are deliberately untouched.

`AccountPreferencesController` owns a single repository above the profile session, so changing a language in settings reaches the next playback without a restart. Emby is gated out of rewatching through `MediaBrowserDialect.supportsNextUpRewatching`.

close #1910
2026-08-25 08:42:48 +02:00
edde746 779c532fc7 chore(i18n): regenerate german strings after the premiereDate update
de.i18n.json changed in #2106 without a codegen run, so scripts/codegen.sh
--check failed on strings_de.g.dart. No other locale is affected.
2026-08-25 03:11:11 +02:00
edde746 595cd9fe24 feat(seerr): sign in with quick connect and accept schemeless urls
Linking a Seerr instance had two rough edges, both on the Jellyfin path.
The URL step prepended https:// to anything without a scheme, so a
plain-HTTP instance on the LAN — 192.168.1.5:5055, or a bare host on
Seerr's default port — failed with "could not reach" unless the user knew
to type the scheme. And the only way to sign in with a Jellyfin account
was typing a username and password, which on a TV remote is misery.

Schemeless input now expands into candidates that are probed together,
but TLS wins by construction: a plaintext success is held while any https
candidate is still in flight and is accepted only once they have all
failed. The sign-in that follows posts a password to whichever URL wins
here, so a slow-but-working https endpoint has to beat a fast plaintext
one, and the wait is already bounded by the probe timeout. When nothing
answers, the failure that reached a server outranks a transport error, so
"this instance has not completed first-run setup" is not masked by "could
not reach https://..." from a candidate the user never typed.

Quick Connect goes through Seerr's own proxy routes (3.4+): initiate,
then check polled at Seerr's own 2s cadence through the shared
pollWithBackoff — a 404 mid-poll means the secret is gone and is terminal
— then authenticate, which mints the session cookie through the existing
sign-in path. The secret rides in a query string, so it is registered for
log redaction the way the Jellyfin flow registers its own. An instance
that predates the routes 404s the initiate and is told apart from a
generic rejection.

SeerrAuthMethod.quickConnect deliberately stores no secret: silent
re-auth is impossible by construction, so an expired cookie lands in the
existing "no stored credentials" arm, unlinks the session, and the
connect flow asks for a fresh code. The affordance is limited to the
Jellyfin credential form, since Seerr rejects Quick Connect for Emby, and
is not auto-started on TV the way the MediaBrowser form is:
/settings/public exposes no "Quick Connect enabled" flag to gate that on.

The waiting panel and its attempt/cancel bookkeeping moved out of
AddJellyfinScreen into QuickConnectCodePanel and QuickConnectFlowMixin so
both screens share one implementation, and the post-frame focus helper
both forms use moved to AsyncFormStateMixin.
2026-08-25 03:07:14 +02:00
edde746 75279ca196 refactor(discovery): expand server url candidates through one shared helper
Turning what a user typed into URLs worth probing lived inside
JellyfinEndpointDiscovery, next to a private copy of the scheme-detection
regex that url_utils already had. A second backend needs the same rules
with a different default port, and the existing copy carried two latent
defects: input with no host came back unchanged, so a candidate that can
never resolve went to the prober, and a query string survived into the
base URL that request paths are appended to.

expandBaseUrlCandidates takes the ordered guesses a backend wants — a
scheme plus the port to try when the user typed none — and owns the rest.
A typed port beats a guessed one, so host:8096 collapses to one candidate
per scheme and the same guess list covers both bare hosts and hosts with
ports. Candidates are built field by field rather than through
Uri.replace, whose null query means "keep mine", so query and fragment
are dropped for real. Blank input and input with no host expand to
nothing.

JellyfinEndpointDiscovery passes its existing order, so its probe and
persistence behaviour is unchanged, and hasUrlScheme replaces the regex
copy.
2026-08-25 03:07:14 +02:00
BockiandGitHub bd2d19a1c1 Update de.i18n.json (#2106) 2026-08-25 01:21:35 +02:00
github-actions[bot] 66c6b137a5 chore: update cask to 2.17.1 2026-08-24 23:18:29 +00:00
edde746 805632efc1 chore: bump version to 2.17.1 2026-08-25 00:43:37 +02:00
edde746 fe9d9d5e7d test(player): cover saf reads and the demuxer's jni byte source under r8
The random-access demuxer added two surfaces with no gate behind them. A
download stored through SAF arrives as content://, where an index read has to
open a second descriptor while the loader holds one, and the AVIO callbacks
are reached only by name from C++, so R8 may rename them while every debug
check passes -- the shape #1703 shipped with.

FfmpegExtractorSeekTest now runs the cued fixture over a content:// URI
served by a test-only provider, and FfmpegDemuxerReachabilityTest drives
nativeOpen plus a seek through a media3-free byte source so it can run
minified. Wired into the existing R8 reachability target; verified it fails
when the FfmpegDemuxerJni$Input keep rule is removed.
2026-08-24 23:02:23 +02:00
edde746 1995fc6b75 refactor(player): demux through random-access IO instead of unwinding libavformat
Resuming or seeking a large MKV on the Android FFmpeg demux path buffered
for minutes with no error and no fallback. The cause was the seam, not the
container: libavformat's demuxers own their seeking — end-of-file index,
back to the header, binary search — while media3's Extractor is forward
only, so every backward jump had to abort the in-flight libavformat call
with a synthetic IO error and replay the whole open. matroskadec attempts
its deferred Cues parse exactly once per context, so that abort burned the
index for the session and every later seek fell back to libavformat's
linear generic scan, reading the file up to the target.

That protocol had produced a bug of this shape repeatedly (a NULL deref
resuming find_stream_info across an abort, a use-after-free on fallback
teardown, matroskadec resync skipping the keyframe cluster) and it was held
together by four empirical retry budgets whose exhaustion degraded silently
— which is why #2096 looked like an unbounded spinner instead of an error.

Give libavformat what it requires instead. FfmpegRandomAccessSource serves
any absolute position from a second DataSource built by the same factory
media3 uses, cloning the DataSpec media3 opened for the item so Cronet,
download caches, SAF and per-item request headers still apply. Reads that
the loader's ExtractorInput can serve still go through it, so sample
delivery keeps feeding media3's byte accounting, back-pressure and
load-error policy; the extractor nudges the loader to follow the demuxer
with one RESULT_SEEK, which is an optimization that can never stall
playback because the read succeeds either way.

Deleted with the protocol: the synthetic AVERROR_NEED_SEEK unwind, the
24 MB replay cache, the Cues priming seek and its read guard, the sticky
AVIO error clearing, and all four budgets (seekAttempts, stickyRecovers,
MAX_RECONCILES, MAX_OPEN_LOADER_ROUND_TRIPS). Opens run straight through,
seeks are one avformat_seek_file on the loader thread, and an IO failure is
an IOException that reaches media3's retry policy instead of a silent
degradation. The demuxer is now the only component that resolves seeks, so
the extractor's sample-derived seek index is gone too.

Verified on a SEI Robotics Android TV box against Jellyfin: the DV P8.1
28.4 GB MKV resume that started at a 4m28s spinner opens in 1.1 s and
resolves its seek in one call, a mid-playback scrub resolves in 1 ms from
the in-memory index, a 2 GB MKV resume opens in 0.5 s, fresh playback needs
no index read at all, and MP4/AVI still open and deliver. New coverage:
FfmpegRandomAccessSourceTest pins the read/reopen contract, and
FfmpegExtractorSeekTest asserts on-device that a cued seek lands on target
without walking the file and that a cueless file still reaches it.

close #2096
2026-08-24 23:02:23 +02:00
edde746 defb0f4983 fix(player): publish real dolby vision profiles from the ffmpeg demuxer
The demuxer JNI read AV_PKT_DATA_DOVI_CONF as the bit-packed dvcC/dvvC box
layout, but libavformat surfaces the unpacked
AVDOVIDecoderConfigurationRecord — one byte per field. Profile 8 level 6
streams therefore surfaced as "dvh1.04.00" plain HEVC (visible in #2096's
logs): DoviConvertingTrackOutput's profile 7 conversion could never engage,
and profile 8 was routed to the plain HEVC decoder instead of the Dolby
Vision decoder the media3 demux path selects.

Read the struct fields verbatim and mirror media3's DolbyVisionConfig in
Kotlin: recognized profiles publish video/dolby-vision with the
dvhe/dvav/dav1 RFC 6381 codecs string, unrecognized profiles keep the base
codec's format. A DV P8.1 MKV on the FFmpeg path now reports "dvhe.08.10",
mime video/dolby-vision, and takes the DV P8 passthrough path exactly like
the media3 demuxer.
2026-08-24 23:02:23 +02:00
edde746 371eab8637 fix(downloads): stream from the server when a downloaded SAF copy is unreachable
Playing a downloaded movie or episode failed outright once the storage
holding it was gone — an SD card ejected, a USB volume unplugged, the
files deleted from outside the app (issue #2101). The item still played
fine from the server, but Plezy never tried: it committed to the local
copy and surfaced mpv's open failure.

Resolution already refused a missing local copy and let the caller
stream instead, but only for filesystem paths. SAF `content://` URIs
skipped the check on the premise that they are always playable as
written. They are not: an unmounted volume answers
`FileNotFoundException: No root for <volume>`, and a revoked grant is
just as dead, while the row still reads `completed`.

Probe the stored document through SAF before preferring it, so an
unreachable copy resolves to nothing and every consumer degrades the
way a missing file already did — the player streams, and both
external-player entry points launch against the server instead of a
dead URI.

close #2101
2026-08-24 19:27:20 +02:00
edde746 f357be4077 fix(tvos): match Siri Remote navigation to measured native focus-engine physics
Siri Remote navigation felt sluggish and then over-sensitive next to
native tvOS apps (issue #2006): swipes were priced at a fixed travel
per step, a single flick could glide into a second focus step, hard
lifts coasted several extrapolated steps, and rail scrolls snapped in
65-250ms where native glides.

Retuned the whole path against two hardware instrumentation passes on
an Apple TV 4K: committed-move telemetry through an experimental
UIFocusItem bridge (branch feat/tvos-native-focus-bridge), then a
dedicated native probe app logging every touch sample, pan velocity,
engine hint, focus step, and scroll tick across 101 swipe sessions on
160/230/300pt tiles. What the data showed, now encoded:

- step pricing follows geometry: one step costs the focused item's
  extent along the swipe axis plus ~155pt (measured 314/391/410pt on
  160/230/300pt tiles), not a fixed distance. Thresholds derive per
  axis from the primary focus rect, normalized so a wide-flat control
  steps vertically once the finger covers its height. Locked-focus
  rows (hub rows, the TV browse rail) vend their selected card's rect
  through the new LockedFocusRowNode so the row-wide focus node's
  screen-sized rect never prices the step. Scopes, the player's
  catch-all surfaces, and unbuilt cards fall back to a fixed 400pt.
- a lift never coasts more than one step: sessions with lift
  velocities up to ~11400pt/s never produced a second coast step. The
  glide is gated on a sustained drag (two consecutive same-direction
  steps), cancelled by reversal pivots and new touches, so a discrete
  flick moves exactly one item.
- the native 'inertia' feel is the scroll animation, not focus
  physics: the engine's scrollable containers settle over ~450-900ms
  of ease-out. TV rail and hub-row navigation scrolls now retarget a
  500ms easeOutCubic animation per step, so drags and hold-repeats
  chain into one continuous glide that catches up on release.
2026-08-24 13:41:44 +02:00
edde746 0fdc22b4fa fix(linux): make the render-executor completion handoff visible to TSan
GLib's GMutex is a raw futex, so ThreadSanitizer cannot see the
happens-before edge g_main_context_invoke_full provides and fails the
thread lane on plane_render_executor_test. Publish the completion
payload through an explicit release/acquire pair, and suppress the
remaining reports that originate wholly inside libglib's own source
bookkeeping. Races on repository memory still fail the run; verified
0/100 failing TSan runs in an ubuntu:24.04 container (20/20 before).
2026-08-24 12:42:23 +02:00
edde746 fb85bb279a style(android): apply ktlint to the ffmpeg audio csd code
The Native Formatting lane rejects the unbraced multiline if/else in
FfmpegExtractor and the wrapped expression body in FfmpegAudioCsdTest.
2026-08-24 12:42:23 +02:00
edde746andGitHub cc4eff98c0 build: migrate to Flutter 3.47.1 (#2092) 2026-08-24 12:32:05 +02:00
edde746 0fbf2e205c fix(profiles): skip the resume profile prompt during a live companion-remote session
With "Ask for profile on app open" enabled, every screen-off or app
switch on a phone re-pushed the profile picker and PIN on resume, burying
a companion-remote session that survives backgrounding since the
reconnect cycle was made lifecycle-aware. Suppress the resume prompt
while a companion session is live, mirroring the active-playback
exemption — the session already belongs to the profile that started it.

close #2087
2026-08-24 10:06:00 +02:00
edde746 a9f2c1ff99 fix(player): shape ffmpeg demuxer audio extradata into media3 csd layouts
VP9/WebM-origin files stalled at 0ms in ExoPlayer on 2.17.0 and fell
back to MPV after ~40s. The ffmpeg demuxer published raw extradata as
the only initializationData entry; Android's Opus decoders consume
their first three input buffers as OpusHead/codec-delay/seek-pre-roll,
so they ate the first two real packets as configuration and silently
discarded every decoded sample, pinning the audio-driven clock at 0.
Vorbis (unsplit Xiph lacing) and FLAC (unmarked STREAMINFO) had the
same shape divergence.

Shape audio extradata into the layouts media3's own extractors emit
before publishing the track format.

close #2088
2026-08-24 09:36:10 +02:00
github-actions[bot] fe4e53f912 chore: update cask to 2.17.0 2026-08-24 05:28:32 +00:00
edde746 fed572d19e chore: bump version to 2.17.0 2026-08-24 06:16:29 +02:00
edde746 adef523894 chore(build): add a SwiftPM refresh script for stale MPVKit pins
After set_mpvkit_revision.sh moves the MPVKit pin, macOS builds die in the
SwiftPM integration migration with "could not find the commit <sha>": Flutter
runs the macOS Xcode steps with -skipPackageUpdates, and its one fetch-capable
step only ever runs for iOS, so the local mirror never learns the new revision.

scripts/refresh_apple_spm.sh runs a single -resolvePackageDependencies per
platform to update the mirror without touching the tracked locks, with --reset
for an internally inconsistent SourcePackages directory. The header of
set_mpvkit_revision.sh now points at it.
2026-08-24 06:12:06 +02:00
edde746 84bc4b2618 fix(i18n): translate the strings that still reached the UI in English
Non-English users saw English text in a dozen places and blank labels in
sixteen more.

The English came from sites that produce their copy away from the widget
that renders it, which is what the structural hardcoded-string check
cannot see: picture-in-picture refused with a raw literal instead of the
pipErrors.notSupported key that already existed; the two Jellyfin/Emby
auth throws missing display: rendered their developer message on the
add-server form; ServerParsingException.toString() fed its English into
the localized "Failed to load servers" wrapper; Watch Together
interpolated the whole PeerError, so a failed create read "Failed to
create session: PeerError(PeerErrorType.timeout): Timed out creating
session" and join printed its prefix twice; the hub and playlist
continuation footers rendered exception.toString(); shader rows showed an
English title over an already translated subtitle; the player queue fell
back to the raw Dart enum name; a Plex home user with no title showed
"Unknown"; a failed player start showed "Exception: Failed to initialize
player"; and the tvOS top-shelf header was hardcoded in an extension that
has no Flutter engine.

The blanks came from three recent features that added English keys
without translations. clean_translations.py filled all 21 siblings with
empty strings, so the Android TV resolution switch, every Jellyfin/Emby
recording-rule field, the demuxer row, the Companion Remote address
caption and the Seerr blocklist pill rendered nothing at all.

Two fixes are structural rather than key swaps. ContinuationStatusSliver
now takes an errorContext and calls a new non-logging
localizedLoadErrorText, so no future throw can leak through it. lib/mpv
stays free of user-facing copy: it raises a PlayerInitializationException
sentinel and a PlayerError.playerInitFailed cause tag that the player
screen resolves to localized text. The tvOS section title travels in the
shelf payload, additively, so an older cache still renders.
2026-08-24 05:23:05 +02:00
edde746 ead637cc92 ci(linux): build plane_render_executor_test so ctest can run it
Both Linux sanitizer jobs have failed since 974806fe. It registered
plane_render_executor_test with ctest, but the reliability job compiles an
explicit target list and the new target was never added to it, so ctest found
no executable and reported the test as Not Run.
2026-08-24 02:13:32 +02:00
edde746 eed6071b94 test(jellyfin): assert DateCreated on the music latest hub row fields
The cross-server aggregation suite still pinned the music Latest row's
`Fields` to the pre-DateCreated set, so the suite has failed on every commit
since 24d7681d added the field. That commit updated the assertion in
jellyfin_client_urls_test.dart but missed the second copy of the same
expectation here, leaving CI red rather than signalling a real regression.
2026-08-24 02:13:28 +02:00
edde746 6da1f83891 feat(player): switch the display to the video's native resolution on Android TV
Sub-4K content on a 4K TV was always upscaled by the playback device, so the TV's own (usually better) upscaler never received the native signal and could not apply resolution-specific processing.

Adds a Match Content Resolution setting on Android TV: playback picks the smallest display mode that still contains the video — never downscaling it — and rate-matches within that resolution when frame rate matching is also enabled. A resolution-only switch keeps the refresh rate as close to the current one as possible, and the settle watchdog now verifies the requested mode id so such switches still trigger the Android MPV decoder refresh. Transcodes get their target from decoded dimensions on the post-first-frame path. Mode selection is extracted into a pure, JVM-tested DisplayModeSelector.

close #2073
2026-08-24 02:10:35 +02:00
edde746 8b5ee4f3dd fix(subtitles): apply downloaded subtitles instead of polling the stale metadata cache
In-player subtitle search always ended with "Subtitle downloaded, but it
could not be selected": the apply flow polls getVideoPlaybackData for the
new external stream, but the fresh-cache-first fast path (be9197ed) served
the pre-download /library/metadata row for every iteration — playback
start leaves a fresh row, and the first network poll re-stamps it, so the
new stream was never observed and the flow timed out.

Add forceRefresh to PlexClient.getVideoPlaybackData (mirroring
getPlaybackExtras) and pass it from the download poll loop. The forced
fetch still rewrites the cache row, so the subsequent source switch sees
the new track.
2026-08-24 01:52:13 +02:00
edde746 a6cca37174 fix(ui): keep pages scrollable when the wheel lands on a hub row
On Linux the Home page, a library's Recommended tab and movie/show detail
pages could not be scrolled at all, while Browse, Collections, Playlists,
search, downloads and settings scrolled normally. Those three screens are
exactly the ones whose viewport is covered by horizontal hub rows.

A wheel, trackball, trackpoint or button-scroll event expresses one-axis
intent, but the host reports both axes in the same event: on Linux only
touchpad-sourced scrolling becomes a pan/zoom sequence that resolves in the
gesture arena, and everything else arrives as one PointerScrollEvent
carrying whatever dx the device produced. A Scrollable claims a scroll
signal as soon as the delta along its own axis is non-zero, and the deepest
claimant wins the PointerSignalResolver, so a tenth of a pixel of dx handed
the whole event to the horizontal row and the page behind it never moved.

Collapse a scroll signal onto its dominant axis in the binding, before hit
testing - the last point where the delta can still be corrected, because a
Scrollable has already registered with the resolver by the time it sees the
event. Pan/zoom events are left alone, so trackpad panning keeps both axes,
and a horizontal wheel or tilt still scrolls the row it points at.

close #2081
2026-08-24 01:49:43 +02:00
edde746 fff1b3090d build(apple): pin MPVKit by commit instead of by version
MPVKit publishes binaries for every commit on its main branch now, so a
version tag is no longer the only resolvable thing. Pinning the revision
means a fork fix is consumable as soon as its binaries land, with no release
ceremony there and no version bump here.

Pinned at 0097fea015fe, which carries the PiP subtitle fix: the iPadOS
Picture-in-Picture window no longer resizes when SRT subtitles appear and
disappear. Nine pin sites move together -- three project.pbxproj
requirements plus the six SwiftPM locks that check_apple_spm_locks.py keeps
in agreement.

tvos/scripts/wire_mpv.rb no longer hardcodes the version it writes; it reads
the revision out of the tvOS project's committed lock, so re-wiring the
tvOS target cannot silently revert the pin. Its test asserts the shape and
that all nine sites name one commit, rather than a literal sha, so moving
the pin stays one command:

    scripts/set_mpvkit_revision.sh <40-char sha>

close #2078
2026-08-24 01:15:28 +02:00
edde746 c3305d2919 fix(tv): paint the floating sidebar panel over content
In TV mode the sidebar menu floated unreadably on top of the home rows,
the artwork and the settings list — two overlapping sets of text with no
panel behind either.

The rail's surface is transparent on TV so the full-bleed backdrop
continues behind a docked rail, which is safe because the shell displaces
content around it. 2.16.0 turned hover/touch expansion into an M3E modal
panel that overlays content at the collapsed offset instead of pushing
it, so there the rail painted nothing and content showed straight
through the menu.

Keep the transparency rule for every docked shape and paint the surface
whenever the rail floats, reusing the predicate that already gates the
overlay corner radius and edge shadow. The fade now shares the width
morph's duration and curve, so a shorter fade cannot strand a fully
grown, fully transparent panel over the content mid-collapse.

Reproducing needs Force TV mode plus a pointer, which is why this
surfaced on a SteamOS box driving a TV and never on Android TV's D-pad
path.

close #2079
2026-08-24 01:15:28 +02:00
edde746 b457290a6b fix(player): stop the Dolby passthrough buzz after 30-40 minutes via MPVKit 1.0.26
With Audio Passthrough on, (E-)AC-3 Direct Play on Apple TV degraded
into a repeating buzz after roughly half an hour and never recovered
(a 31.25 Hz comb: one stale 32 ms frame looping). During preroll the
system's Dolby pipeline probes the fake endless resource at a fixed
~183 MiB offset; the AO satisfied it with fabricated copies of the
latest access unit, and CoreMedia cached that range by stream offset
and planned its sequential reads around it. Once playback reached the
cached bytes (33 min at 768 kb/s, 40 min at 640 kb/s) it played the
fabricated frames, and its next read landed past the write head, where
the loader kept fabricating frames forever. Seeks rebuild the item at
offset zero, which is why exit/resume bought another 30-40 minutes.

MPVKit 1.0.26 refuses loader reads past the write head instead of
fabricating data; the pipeline falls back to a plain sequential read
from the write head and prerolls normally with nothing poisonous
cached.

Verified on an Apple TV 4K gen 3 with an HDMI capture rig: the 1.0.25
sink audibly and loggably degrades at stream byte 0x0B770000 (8.3 min
into a 3072 kb/s accelerant stream, 40 min at 640 kb/s), while the
1.0.26 sink crosses the same byte with continuous audio on both the
accelerated stream and a full 40-minute 640 kb/s Plex Direct Play soak
through Plezy itself.

close #1776
2026-08-24 01:15:28 +02:00
edde746 a11da3fec8 feat(livetv): record live TV on Jellyfin and Emby via the timer APIs
Jellyfin and Emby users had no way to record live TV from Plezy at all: no
record button in the EPG guide's program menu, and nothing in the recordings
UI, because every recording surface was gated behind a Plex-only DVR adapter.

The recording surfaces are now backed by a MediaBrowser DVR adapter that
synthesizes the neutral (Plex-shaped) payload models from the timer APIs:

- Template comes from `GET /LiveTv/Timers/Defaults?programId=`, offering a
  "Record Episode" entry and, for series airings, "Record Series". The
  defaults DTO travels JSON-encoded in the template's opaque `parameters`
  and setting ids are DTO field names, so the existing template-driven
  record-options sheet renders and round-trips them unchanged.
- Create POSTs the mutated defaults whole to `/LiveTv/Timers` or
  `/LiveTv/SeriesTimers`; a duplicate one-off create answers 400, which the
  adapter rethrows as `RecordingConflictException` so the sheet can show
  "Already scheduled" without a backend check.
- Scheduled recordings read `/LiveTv/Timers` minus `Cancelled`/`Completed`
  tombstones, rules read `/LiveTv/SeriesTimers` with their child timers
  nested. Rule keys carry a `timer:`/`series:` prefix so cancel, edit and
  delete dispatch to the right timer space inside the adapter.

Guide programs now carry their recording state: the program id doubles as the
record seed, and `TimerId`/`SeriesTimerId` become the rule keys that drive the
guide's scheduled dot and the Manage action. The series key is stamped only
when an airing actually records, so an episode a series rule skips does not
show a false indicator.

Three neutrality fixes on the shared UI: the record-options sheet only demands
a target library when the template declares one (MediaBrowser records into its
own configured folder), and "Re-evaluate rules" is hidden unless a connected
DVR supports it, since only Plex has that endpoint.

`fetchDvrs` deliberately stays empty so the synthesized per-server Live TV
identity that channel fetches, favorites and playback key off is preserved.

Verified end-to-end against a disposable jellyfin/jellyfin:10.11.11 container
with an M3U tuner and XMLTV guide, driven through the real client: template,
create, duplicate conflict, cancel, series create with child grabs, edit
round-trip and delete.

close #1645
2026-08-24 00:08:11 +02:00
edde746 99c21ce6ae fix(remote): stop companion pairing hanging when a host address is unreachable
Tapping a discovered desktop in the phone's companion remote did nothing:
the device list emptied to "No devices found on your network" and no
connection was ever made. Manual IP:port entry silently did nothing too.

A host advertises every local IPv4 address, so a PC with virtual adapters
(WSL, Hyper-V) broadcasts addresses the phone cannot route to. The client
races them all, and cleanup of the losing candidates awaited
`sink.close()` on channels that never connected. That future never
completes in web_socket_channel: the close future waits on the local
stream's listener, which is only attached on the connect-success path. So
the race never finished, the winner was never joined, and the flow just
stopped with no error.

Cleanup now tracks whether a candidate ever connected: unconnected probes
get a deferred close armed on `ready` settling instead of a blocking
await, and they skip the terminal drain since they hold no host admission
slot. The managed join gets a real connect timeout that surfaces as a
typed timeout error, and disconnect during a pending connect closes the
socket once the connect settles rather than blocking on it.

Two paper cuts around the same flow: a failed attempt now restarts
discovery instead of stranding the cleared list on "No devices found",
and the desktop's server card shows its listen addresses so manual entry
is not guesswork.

close #2077
2026-08-24 00:08:10 +02:00
edde746 5b6016d88b fix(player): strip mpv.conf-style quotes from custom config values
A quoted value in the mpv.conf settings screen, copied verbatim from a
real mpv.conf (sub-font = 'NetflixSans-Bold'), reached mpv_set_property
with the quotes included: a string property silently selected a
nonexistent font family and fell back to the bundled font, and a
numeric property failed mpv's parse and was only logged. Either way the
line did nothing. mpv's own config-file parser strips one pair of
matching quotes around the whole value; parseMpvConfigText now does the
same before the startup pass applies the entries.

close #2025
2026-08-24 00:08:10 +02:00
edde746 6aaea847a7 fix(tv): stop dropping more than half the frames on D-pad browse
On a 32-bit Amlogic TV box, 57% of UI frames while moving focus along a rail
missed the 16.68 ms budget, and the median frame was already over it at 20.7 ms.
The GPU was idle throughout (raster p90 9.1 ms, zero frames over budget) -- all
of it was main-isolate work, split roughly evenly between layout and semantics.

Five separate causes, all measured:

- The horizontal rail used `itemExtentBuilder`, so `RenderSliverVariedExtentList`
  walked every preceding index on each realized child, in every layout pass, and
  re-resolved the trailing slot inside the closure. Pinning the trailing cell to
  the card extent makes the list uniform, which restores O(1) offset, index and
  max-extent math.
- The sidebar-expand tween wrapped the whole shell with a `LayoutBuilder` inside
  its builder, so ~15 ticks per focus flip rebuilt `SideNavigationRail` -- and its
  non-virtualized child list -- during the layout phase. The tween now wraps only
  the content `Positioned`, matching `SideNavigationBleedBuilder`.
- Each nav item crossfaded through two `Opacity` subtrees, i.e. 14-18 offscreen
  save layers per frame for the whole 250 ms morph. It now fades colour alpha on
  the leaf, the same substitution `AnimatedDimScrim` already documents.
- `HorizontalScrollWithArrows` kept a scroll listener on platforms where its arrow
  chrome is compiled out, so crossing either scroll boundary `setState`d a whole
  rail row of cards. Two full-row rebuild storms per traversal, for arrows that
  cannot appear.
- The rail's semantic proxy rebuilt its label and six closures on every
  `_RailFocusModel` notification, including vertical-scroll flips.

Also: one merged listener per `SettingsBuilder` instead of six, and the media card
semantic label is cached rather than rebuilt and then discarded by the rail's
`ExcludeSemantics`.

Measured on the device, median of three runs: frames over budget 120/212 -> 32/246,
total UI-thread work 4067 ms -> 1845 ms, layout p90 18.2 -> 8.1 ms, build p90
7.95 -> 2.42 ms. The sidebar scenario went from 121/148 frames over budget to
32/184.
2026-08-23 18:13:39 +02:00
edde746 a615ec6b97 test(plex): pin that hydration installs no live machinery
The offline guarantee rests on hydration being genuinely network-free, not just
on the call sites picking the right entry point. Assert it directly: a hydrated
service must not react to a connection row appearing afterwards — which is what
the boot-time legacy migration does — and `start()` must then pick that row up,
proving the watch belongs to the live side.

Device verification of the airplane-mode cold start is not included: it needs
physical access to re-enable the test box's network. This test covers the same
invariant deterministically.
2026-08-23 18:13:39 +02:00
edde746 c4059d0ead fix(startup): stop Cronet and Plex Home from blocking time-to-interactive
Two cold-start findings from the same pass. They share a call site in
`MainScreen`'s post-frame block, so they land together.

## Cronet was 33% of time-to-interactive

`createPlatformClient()` built the shared `CronetEngine` inline, so whichever
consumer happened to create the first HTTP client paid for it — and that landed
between `database_ready` and `credentials_loaded`, i.e. squarely on the path to
the first usable screen.

Measured on the Amlogic SC2 box, phase marks relative to `dart_main`, by
temporarily forcing the existing `_cronetBroken` fallback so no engine is ever
built:

| phase | engine built inline | engine never built |
|---|---|---|
| database_ready | +455 | +456 |
| credentials_loaded | +1171 | +703 |
| binding_settled | +1331 | +827 |
| main_screen | +1394 | +932 |

So ~462 ms, fully serial. Logcat shows where it goes: `DynamiteModule
loadModule2NoCrashUtils` then `HttpFlagsLoader` reading
`com.google.android.gms/app_httpflags/flags.binarypb`. The cause is provider
*enumeration*, not selection — `CronetEngine.Builder(Context)` calls
`isEnabled()` on every registered provider, and `PlayServicesCronetProvider`
answers that by installing the Play services Dynamite module. `play-services-cronet`
arrives transitively through `media3-datasource-cronet`, and `package:cronet_http`
offers no way to choose a provider, so the only lever available in Dart is *when*
the cost is paid.

Android's `createPlatformClient()` now returns a client that resolves its
delegate per request: the tuned IOClient that already backstops a broken Cronet
until the shared engine exists, Cronet afterwards. Per-request matters — a
`MediaServerHttpClient` builds its client in a constructor initializer and lives
for the process, so deciding once at construction would have pinned primary
media-server traffic to HTTP/1.1 forever, which is a silent steady-state
regression rather than a fix. `warmUpPlatformHttpClient()` then builds the engine
from `MainScreen`'s post-frame block.

Result: `main_screen` +1394 -> +915 ms, and logcat carries both client lines
(`IOClient (Android fallback)` then `CronetClient`), proving the swap. The build
now runs from +1023 to +1419, entirely after the first screen, and produces no
Choreographer or Davey report — the UI is static waiting on hub content there, so
there are no frames to drop.

## Plex Home refresh raced the offline decision

`PlexHomeService.start()` conflated disk hydration with going live: it decoded
the cached `plex_home_users_*` entries *and* subscribed to connection changes,
installed a refresh timer and fired `_refreshAll()`. It was invoked straight from
a provider `create:`, so on a box with no network — or the flaky 2.4 GHz Wi-Fi
these devices typically have — it started requests that would time out during the
exact window the startup gate needs. Its immediate neighbour
`ActiveProfileBinder` is explicitly not auto-started for this reason and says so
in a comment; the same argument applied here and had simply not been followed.

`start()` is now the live/network entry point and `hydrate()` is the disk-only
half, coalesced and lifecycle-guarded like `start()` already was. The provider
`create:` hydrates; `_reloadSnapshot` and `reloadFromStorage` hydrate; the borrow
picker hydrates, because it reads `current` immediately and is reachable while
offline. Only `MainScreen` goes live, gated on `!_isOffline`, with
`_handleOfflineStatusChanged` picking it up if the session later regains network —
otherwise an airplane-mode launch would never refresh Plex Home again.

Hydration still `_emit()`s, so `stream`'s replay contract holds even when the
network side never starts, which is what keeps a late listener behind a
`combineLatest` off a permanent spinner.
2026-08-23 18:13:39 +02:00
edde746 f95465067e chore(tools): add the on-device frame and startup benchmark harness
The measurements behind the preceding commits needed a repeatable way to drive a
real Android TV box and read both sides of the frame. `dumpsys gfxinfo` alone is
not enough (it sees the HWUI composite, not Flutter's UI and raster threads), and
DevTools is not scriptable.

- `vmclient.mjs` -- Dart VM Service client over WebSocket, plus percentile and
  timeline helpers and a CPU self/total-time reducer over `getCpuSamples`.
- `scenarios.mjs` -- repeatable D-pad workloads. Keys are sent as one batched
  `input keyevent` invocation per burst, because a separate invocation per key
  costs more on the device than the interaction being measured.
- `bench.mjs` -- runs a scenario and correlates Flutter's own frame phases
  (`Animator::BeginFrame`, LAYOUT, SEMANTICS, BUILD, PAINT, `Rasterizer::DoDraw`)
  with HWUI framestats, reporting medians over repeats.
- `profile.mjs` -- CPU self/total time by function plus an allocation profile.
- `launch.sh` -- cold-launches the profile build, sets up its own port forward and
  prints a host-reachable VM Service URI. Passes `--ez enable-dart-profiling`,
  which only `flutter run` supplies by default, and wakes the display first
  because `am start -W` silently reports no `TotalTime` when the screen is off.

Not referenced by `lib/` and not packaged; `tools/` is outside the APK.
2026-08-23 18:13:39 +02:00
edde746 e6a0840fbe fix(player): stop rebuilding the whole controls tree on every tick
Nothing sat between the full-screen `RasterizedGradient` scrim and the
position-driven leaves, so `markNeedsPaint` from the timeline slider walked past
the gradient and re-rasterized the entire chrome -- top bar, button row,
timestamps, timeline -- on every 250 ms position tick. That also partly defeated
`RasterizedGradient`, which exists because Skia gradients cost ~10 ms per
full-screen pass on this GPU class.

Around that, four things drove root `setState` calls that only needed to change a
leaf:

- Held D-pad seek called a root `setState` per key repeat, even when the readout
  was already visible in the same direction and only the accumulated seconds had
  changed. The seek amount now flows through a `ValueNotifier` that
  `DoubleTapFeedback` reads, so a burst updates one `Text`.
- `DoubleTapFeedback`'s drift chevron ran `..repeat()` with no stop condition, and
  kept ticking at 60 Hz for the ~300 ms the readout spends at zero opacity after
  every burst. The controller is now gated on visibility.
- The auto-skip countdown ran a 5 Hz timer that root-`setState`d the controls tree
  for the whole intro/credits window, to animate one progress ring.
- The play-next and still-watching countdowns root-`setState`d the player screen
  once a second, which re-created `PlexVideoControls` with its ~50 props and
  rebuilt the entire chrome to change one digit. Prompt open/close deliberately
  stays on the state path, because `playNextFocusNode` is threaded through those
  props and D-pad focus depends on it.

Two of the four position subscribers existed only to recompute pointer-hover
tooltips that a D-pad viewer never sees, rebuilding a button subtree 4x/s and
rescanning the chapter list each time; the "ends at" readout reformatted a string
4x/s for a value that changes once a minute. All three now dedupe.

Finally, the buffer path did two sequential `copyWith` calls on a 15-field
`PlayerState` and handed `BufferRangePainter` a freshly allocated list every tick.
`List` has no value equality, so `shouldRepaint` was unconditionally true.

Measured on device during playback with the chrome raised: 6 of 344 UI frames over
budget, p50 4.39 ms, layout p90 1.09 ms. During a held D-pad seek -- the worst
frame-time window on the TV path, because the readout and the decoder flush land in
the same frames -- 1 of 354 frames over budget, p50 4.28 ms, zero raster frames over
budget.
2026-08-23 18:13:39 +02:00
edde746 cb55134cef fix(startup): move optional work off the launch gate
Cold start on the target TV box reaches its first frame 21 ms after `dart_main`,
so nothing Dart-side gates the splash. Everything below is on the path to the
first *useful* frame, which is a strictly serial chain and where the viewer
actually waits.

- `monoTheme` is a pure function of two bools that builds a full `ColorScheme`, an
  applied-and-copied 15-style `TextTheme`, ~14 sub-themes and then clones the whole
  `ThemeData` again. It was rebuilt five times per cold start, two of them before
  `runApp`, and twice more per app-shell rebuild. It is memoized now, keyed by
  palette plus `TargetPlatform` -- the platform matters because `ThemeData()`
  derives tap target size, visual density and typography from
  `defaultTargetPlatform`, so a palette-only key would be wrong under a debug or
  test platform override.
- `initializeDateFormatting` ignores its locale argument and builds CLDR symbols
  and patterns for all 121 locales synchronously. It blocked the gate ahead of the
  database open for data that only content screens use.
- `DownloadStorageService.initialize` ended in a `path_provider` round trip plus
  mkdir at the tail of the gate, contradicting the comment above it that already
  explained offline artwork is not a launch requirement.
- `recoverInterruptedDownloads()` and `TrackerCoordinator.initialize()` ran from
  `initState` of the widget whose first build produces the first app frame, and
  the RSS watchdog installed a periodic timer there whose first useful sample is
  15 s away regardless.
- `CredentialVault` decrypted every token with pure-Dart AES-GCM on the main
  isolate, uncached, on every registry read and on every Drift re-emit -- and the
  binder writes tokens during the startup sweep, so writes re-triggered reads.
  Decryption is memoized by ciphertext, with `invalidateCache()` wired into the
  preference-store repair path so a repaired install cannot serve stale plaintext.
- `reloadFromStorage` now coalesces in-flight callers. The two serial awaits around
  the legacy migration are deliberately not merged; only genuinely concurrent
  callers share a snapshot.
- `_sameConnections` ran two `jsonEncode` calls per connection on every Drift emit
  purely to compare, allocating two maps and two strings each time.
- The splash rendered one `CircularProgressIndicator` per pending server on top of
  the aggregate one, so N+1 tickers scheduled a frame every vsync for the whole of
  `awaitBindingSettle` -- competing with the startup work they were reporting on.

Measured on device in a settled dexopt state: time to `main_screen` 1495 -> 1400 ms,
`credentials_loaded` 1238 -> 1128 ms, `database_ready` 501 -> 443 ms. First frame is
unchanged at ~18 ms, as expected.
2026-08-23 18:13:39 +02:00
edde746 5d83d4833c fix(images): stop decoding artwork nothing ever displays
The image pipeline funnels through `MediaImageHelper.serverArtworkProvider`, which
sizes the request, bounds the decode and namespaces the disk key. Five places
escaped that funnel, and on the reduced tier they compete for a 64 MiB image cache.

- Jellyfin trickplay prefetch built a bare `CachedNetworkImageProvider` and called
  `resolve()` on it, fully decoding a sprite sheet -- roughly 22 MiB of RGBA for a
  10x10 grid of 320-wide tiles. None of it was ever painted: the render path wraps
  the same provider in `ResizeImage`, so it decodes again under a different cache
  key. The comment already said the intent was only to warm the disk cache, so it
  now does exactly that through the cache manager and resolves no image stream.
- `CyclingMediaBackdrop` re-fetched and re-decoded a full-screen backdrop every
  10 s forever, with no `DevicePerformance` term in `_canRotate` even though its
  own fade duration is tier-gated. At the reduced tier's 1280x720 art cap that is
  3.52 MiB per rotation, ~7 MiB live across the crossfade, churning while the
  viewer sits still and evicting the rail posters behind it. The fade is already
  zero-duration there, so the rotation bought variety and nothing else.
- Catalog detail passed `item.posterUrl`/`backdropUrl` with no client, which
  `getOptimizedImageUrl` deliberately returns unmodified -- so a 40x60 slot pulled
  a 600x900 TMDB asset and a 320-tall backdrop pulled 1920x800. `posterFor`/
  `backdropFor` already existed for this; the sites now use them.
- The season strip, the Live TV programme sheet and the profile avatar built
  `CachedNetworkImage` directly, keeping the sized request but losing the
  `plex_optimized_<sha1>` disk key, so the same artwork was cached twice and
  re-downloaded on detail open. The season strip also discarded its height bound.

Sources without published variants (Trakt, AniList, MAL, MDBList) still fall back
to the base URL.
2026-08-23 17:51:27 +02:00
edde746 f2bf43a8bc fix(windows): restore window placement onto a live monitor without a blank flash
The remembered window placement restored invisible when its monitor was
gone (undocked laptop, powered-off TV), briefly flashed a blank window at
the restored spot before the first Flutter frame, and could lose the
maximized state: the exit path hides the window before a multi-second
teardown, so a debounced save landing in that gap recorded SW_HIDE, and a
window closed while minimized-from-maximized restored as a normal window.

Validate the saved rect against current monitors and keep only the size on
a miss, apply the placement with SW_HIDE so the first-frame callback stays
the single show, skip persisting while the window is hidden, and honor
WPF_RESTORETOMAXIMIZED when deciding to relaunch maximized.
2026-08-23 10:57:42 +02:00
edde746 b4b36c7e18 style(native): clang-format the mpv executor test, display-mode manager, and demuxer policy 2026-08-23 10:30:43 +02:00
edde746 be01631cab chore(ratings): delete the unused MediaRatingBadgeGroup pill
The detail hero builds its own pill around InlineRatingBadges since the
hero-chip rework, leaving MediaRatingBadgeGroup without a caller and the
unused-code check red. Remove it and inline the style helper its removal
left with one call site.
2026-08-23 10:30:43 +02:00
edde746 02a5f8ad2c fix(settings): pass the connection dialect when listing known servers in discovery
PR #1666 merged without compiling: it maps existing connections into the
add-server discovered list, but DiscoveredJellyfinServer gained a required
dialect with the Emby backend. Carry the connection's dialect through and
list only connections matching the screen's dialect, so the Add Emby screen
does not offer existing Jellyfin servers.
2026-08-23 10:30:36 +02:00
edde746 0964ab8ba2 feat(libraries): open grouping, filters, and sort as anchored menus on desktop
The three browse chips opened bottom sheets on every form factor. On
desktop platforms they now anchor dropdown popups to the chip: grouping
is a radio menu, sort shows the direction on the active field
(re-selecting toggles it) plus Clear, and filters use a two-level menu
with per-category values and an All row to clear one category. Phones
and TV keep the existing sheets.
2026-08-23 10:12:27 +02:00
edde746 89b8af62ea fix(settings): use background focus chrome on the add connection cards
The backend cards drew the outline focus border; the wrapper now sits
inside the opaque Material with useBackgroundFocus so the fill paints
above the surface, matching the other settings surfaces.
2026-08-23 10:12:27 +02:00
edde746 5842d9c1ec fix(profile): replace the profile tile chips with inline metadata
The Active badge and connection chips used opaque primaryContainer /
surfaceContainerHighest - both resolve to the card surface color in the
mono scheme, so they punched dark holes in the focused tile's background
highlight, and boxed pills fight that fill however they are tinted. The
Active badge becomes a muted check icon + label next to the name, and
connection chips become plain muted icon + text entries, matching the
app's other meta rows.
2026-08-23 10:12:27 +02:00
edde746 07463eea04 fix(explore): keep the page at the top when a tab switch focuses a hub
Switching to the Explore tab hands focus to the first hub, and
HubSection unconditionally ran Scrollable.ensureVisible, scrolling the
app bar and search field off-screen in touch mode. The scroll is now
gated on keyboard/D-pad input mode, mirroring FocusableWrapper's
autoScroll.
2026-08-23 10:12:27 +02:00
edde746 627374d4b5 fix(detail): fit hero chips on one row and even out the mobile sections
The hero metadata strip wrapped to a second run, leaving the Rate chip
alone on its own line (or clipping it away on short heroes). The strip
now measures chips and sheds them by usefulness - scores pill first,
then quality labels, edition, certification, runtime - never the year
or the interactive Rate chip, mirroring the TV FittedMetadataLine.

Episode rows replace the 'E0' primary-container chip with an inline
'3. Title' prefix that mirrors the server-provided number, including a
genuine episode 0. Phone section gaps drop from 24px to 12px so Cast,
Extras, and the related hubs share one rhythm; TV keeps its own values.
2026-08-23 10:12:27 +02:00
edde746 c4b043cba9 fix(ui): present the library switcher and profile menu as bottom sheets on mobile
Both anchored popups were small tap targets on phones. AppMenuButton
gains an opt-in adaptiveSheet flag that routes through
showAdaptiveAppMenu: full-width, untitled sheet rows on touch platforms
(phones plus Android TV / tvOS), the same anchored popup on desktop.
2026-08-23 10:12:26 +02:00
edde746 aa9118a799 fix(tv): hold the hub focus glow while the rail scrolls vertically
Moving UP between hubs showed the focused card's glow immediately: the
glow paints in the root overlay, unclipped by the rail viewport, so it
flashed over the spotlight while the target row was still offscreen.
The rail now suppresses only the glow for the 250 ms vertical scroll
and lets it fade in once the row settles. FocusGlowOverlay defers
attached-portal shows out of build, which OverlayPortalController
asserts against.
2026-08-23 10:12:26 +02:00
edde746 fe954eef5f fix(profile): use background focus chrome on the profile screens
Profile tiles and buttons drew the outline focus border while every
other settings surface highlights with a background fill. Tiles nest
the FocusableWrapper inside the Card so the fill paints above the
opaque card surface; buttons opt into useBackgroundFocus.
2026-08-23 10:12:26 +02:00
edde746 66d0ef054e fix(auth): lay out the plex QR retry and cancel buttons inline on TV
The QR sign-in screen stacked Retry above Cancel with intrinsic widths,
reading as sparse on a TV canvas and pushing Cancel off the bottom edge.
Both wait states now share one centered row, matching the player's
initialization-error surface.
2026-08-23 10:12:26 +02:00
Thomas LupinandGitHub 8f13a56e1a Add existing Jellyfin servers to discovered servers (#1666) 2026-08-23 09:29:04 +02:00
edde746 8061c4f5f2 docs(contributing): require AI-assisted PRs to disclose models used 2026-08-23 09:19:55 +02:00
edde746 802d47e980 fix(windows): preserve Dynamic Refresh Rate when restoring display mode
On a Dynamic Refresh Rate display (e.g. Surface 120Hz panels), stopping
playback with Match Refresh Rate enabled left Windows pinned to a fixed
60Hz with DRR disabled: the legacy EnumDisplaySettingsW capture only sees
the DRR base rate, and a DEVMODE ChangeDisplaySettingsExW restore cannot
express the CCD-level DISPLAYCONFIG_PATH_BOOST_REFRESH_RATE selection.

Capture a virtual-refresh-rate-aware QueryDisplayConfig snapshot of the
topology before the first display mutation and restore it through
SetDisplayConfig (saving to the database to repair the 24/48/60Hz
registry-workaround write-back), keeping the DEVMODE path as fallback.
The HDR toggle mode dances re-apply the same kind of snapshot, and crash
recovery returns to the persisted display configuration via
SDC_USE_DATABASE_CURRENT, verified against the recorded mode before the
legacy restore takes over.

close #2055
2026-08-23 07:34:56 +02:00
edde746 1a9d2686c9 fix(tv): declutter the detail page with a slimmer rail and spaced hero
The TV media detail page felt cramped on 1080p TVs (540 logical px): the
bottom rail's title strip, card label bands, and next-hub peek consumed
nearly half the screen and cut the next hub's posters mid-card at the
screen edge, while the hero packed logo, metadata, genres, summary, and
action row into 5-10 px gaps against the back arrow, shedding summary
lines to fit.

Slim the shared rail metrics (hub strip 36->30, next-hub peek 30->20,
label band 42->36, person labels 58->52, height slack 14->10) and the
detail page's rail card scale (0.8->0.72), then spend the freed height
on the hero: larger gaps between metadata/genres/summary/actions, a top
offset that clears the back button, and an info column widened from 57%
to 60% of the screen. Movie and show details now keep three spaced
summary lines, and the wider metadata line fits one more rating badge
before shedding.

The #1893 metadata-line regression test pinned the exact badge-shed
count at its test viewport; it now asserts rendered badges stay fully
on screen while keeping the quality-label guards.
2026-08-23 07:08:27 +02:00
edde746 95800d8a72 fix(tv): open a full details sheet from the detail hero info block
On TV the detail hero caps the description at three lines with no way to
read the rest, and the fitted metadata line sheds rating badges and
quality labels when they do not fit, leaving that information
unreachable by D-pad.

The hero information block is now a focusable target: D-pad up from the
action row lands on it, and select (or tap) opens a sheet with the
complete metadata fields, every rating badge, the genres, and the
untruncated description. Long descriptions page with D-pad up/down.

close #2042
2026-08-23 05:51:36 +02:00
edde746 3f55cc461e fix(player): show audio codec and bitrate in the performance overlay on ExoPlayer
The Android performance overlay showed only sample rate and channels for
EAC3, FLAC, DTS, TrueHD, and Opus tracks. The overlay reads the codec
from media3's Format.codecs, an RFC 6381 string only MP4/HLS provide
(hence AAC working), and the bitrate from Format.bitrate, which Matroska
carries only when the muxer wrote BPS statistics tags.

Fall back to the already-transmitted sample MIME type for the codec name
(audio and video), and measure the audio bitrate in the FFmpeg demuxer
from packet sizes over their pts span — the same source mpv uses for its
audio-bitrate property — when the container declares none.

close #2063
2026-08-23 03:44:45 +02:00
edde746 c201bc2f03 feat(player): default every container to the ffmpeg demuxer
The Auto demuxer mode routed only media3's weak container families
(AVI, ASF/WMV, MPEG-PS, Matroska/WebM) through FFmpeg and kept MP4/TS
on media3's extractors, with a second any-container FFmpeg instance
behind media3's list. With the goal of fully switching to the ffmpeg
demuxer, the split served no purpose and the catch-all could never add
coverage once the primary accepts everything.

Collapse the preference to two modes: FFmpeg (default), which demuxes
every progressive container ahead of media3's list, and media3 only as
the user-facing escape hatch in case a file misbehaves. media3's
extractors stay behind FFmpeg, so anything FFmpeg cannot sniff still
reaches them. The catch-all role and the Auto container list are
removed; unknown persisted wire values (including the retired "auto")
resolve to FFmpeg.

Verified on a Pixel 7: MP4, TS, and MKV all demux through FFmpeg under
the default ("sniff accepted mov,mp4 / mpegts / matroska,webm") with
forward and backward seeks landing; JVM suites and analyzer pass.
2026-08-23 01:42:36 +02:00
edde746 75c095a5b2 feat(player): demux direct-played containers with ffmpeg on Android
Direct play on Android kept accumulating container patches: AVI with
XviD packed-bitstream timestamps and missing VOL csd played broken,
ASF/WMV and MPEG-PS/VOB had no media3 extractor at all, and MKV needed
a custom extractor stack for zlib-compressed subtitles, LOAS/LATM
audio, cueless seeking, and font attachments.

Demux progressive containers with libavformat behind media3's
extractor API. An AVIO bridge serves libavformat from the
ExtractorInput: every position divergence defers into a RESULT_SEEK
round trip, header reads replay from a block cache while
avformat_open_input restarts, and avformat_seek_file executes seeks
with bounded loader round trips. Packets feed media3's TrackOutputs,
so decoders, passthrough carriers, Dolby Vision RPU/EL conversion
(dvh1 codecs string surfaced from DOVI side data), and the subtitle
pipeline are untouched: embedded fonts feed AssHandler over JNI, ASS
reaches libass as per-sample dialogue, SRT/VTT render as cues, VobSub
maps through media3's VobsubParser, and LOAS/LATM AAC unwraps via
LatmTrackOutput.

Under the default Auto preference FFmpeg demuxes AVI, ASF/WMV,
MPEG-PS, and Matroska/WebM and sits behind media3's list as an
any-container fallback; MP4/TS keep media3's extractors. A playback
setting exposes auto / FFmpeg first / media3 only, and the JNI
load-failure path falls back to stock media3. The custom Matroska
extractor stack and its reflection keeps are retired.

Verified on Pixel 7 (API 36), Box R 4K Plus TV (API 34), and SHIELD
TV (API 30): instrumentation playback suites, the minified R8
reachability gate, and an on-device container matrix with forward and
backward seek landings plus visual subtitle checks.

close #2052
2026-08-23 01:22:24 +02:00
edde746 974806fe80 fix(linux): render the mpv video plane off the GTK main thread
The player UI was choppy and slow while video played, and scrub-bar
thumbnails rarely appeared until the video was paused (worst with 4K
HDR content, whose per-frame tone-map render is expensive). The cause:
mpv's render and the plane's eglSwapBuffers ran on the GTK main thread,
which also rasters Flutter's UI and dispatches input, so every UI
repaint and pointer event waited out the video frame render.

Move the render + swap onto a dedicated plane render thread
(PlaneRenderExecutor). All Wayland protocol state stays on the main
thread: Present() splits into PreparePresent() (gates + frame-callback
request) and CompletePresent() (first-frame scale flush, ack watchdog,
mid-flight hide/rect-loss re-detach). The plugin serializes one job at
a time, defers rect application and HDR transaction starts to the job
completion so a resize never races the swap and a staged colour
transition can never pair an old-colour buffer with a new description,
and drains the worker before disposal - which is what lets
RenderToSurface render without holding native_mutex_. A worker wedged
inside a driver call is abandoned after a bounded wait and the
session's player and plane are deliberately leaked instead of freed
under it. PLEZY_PLANE_RENDER_MAIN_THREAD=1 restores the old inline
behaviour as a temporary escape hatch.

Measured in a headless-sway container with a 4K test file (llvmpipe
inflates render cost the way DV tone-mapping does on real hardware):
idle-playing UI commits went from ~354 ms to the keep-alive's ~100 ms,
and pointer reads from ~185 ms bursts back to input rate; the #2067
hide/backoff/recover log signature is byte-identical.

close #2057
2026-08-23 00:13:43 +02:00
edde746 6f64ca2952 fix(linux): recover the wayland video plane after the compositor stops acking frames
Switching workspaces on KDE or a wlroots compositor hides the toplevel
without any GTK visibility change, and the compositor stops answering
the video plane's frame callbacks. Once the ack watchdog spent its miss
budget it stopped dead: the giveup destroyed the only outstanding
wl_callback, mpv's edge-triggered redraw latch was already saturated by
a render that bailed on frame_pending(), and no visibility change ever
comes - so video stayed frozen on the last buffer until a resize or
fullscreen toggle, while audio kept playing.

Back off to a slow re-present timer instead of stopping. A present only
happens when mpv actually has a new frame, so a hidden playing plane
settles at one commit per ~1.5 s and recovers within a second of being
shown again; a paused hidden plane goes dormant and is revived by mpv's
next update edge.

close #2067
2026-08-22 15:31:34 +02:00
edde746 a9a7498991 fix(plex): remove comma-containing tags one request per tag
Plex's tag.tag- removes comma separated tags and has no escape syntax, so
removing a tag containing a literal comma ('Action, Comedy') split it at the
separator and could over-remove siblings named 'Action' or 'Comedy'.

Fields whose removals contain a comma now defer to one removal per request
after the main edit; every request restates the kept tags and the lock, so
the sequence converges regardless of order. Removals without commas keep the
exact single-request wire shape.
2026-08-21 19:23:45 +02:00
edde746 37446e2d8e fix(android): fail loud on non-literal JVM reflection in the shrinker check
The JVM-reflection scan only recognized string-literal lookups, so a
Class.forName or getDeclaredField written with a constant, variable, or
concatenated name was silently skipped and a release build could lose the
member while the check stayed green — inverting the fail-loud behavior the
checker applies to every native lookup it cannot trace.

Unclaimed reflective occurrences now error like the cannot-trace paths, and
the forName pattern requires the closing paren so a concatenated argument is
not half-claimed as a bare literal prefix. Production reflection stays
all-literal, so repository validation is unchanged.
2026-08-21 19:23:45 +02:00
edde746 72f68bdfa7 fix(player): mark chrome opaque only after the fade-in completes
Hiding the chrome in the frame between the post-frame opaque mark and the
next build trusted an opaque flag the renderer never realized: hide() kept
controlsPresented while the fade-in target never rendered, so no fade-out
ran, markControlsHidden never arrived, and Back/Escape stayed swallowed
until a later show/hide cycle repaired the flag.

The controller's opaque flag now follows the real fade-in completion via
AnimatedOpacity.onEnd, so any hide it observes can rely on a fade-out that
will actually run. Branches that mount the chrome directly at full opacity
keep marking immediately, since those insertions fire no onEnd.
2026-08-21 19:23:45 +02:00
edde746 24d7681d92 fix(jellyfin): request DateCreated on album hub rows so Date Added sorts work
The Latest Albums see-all sheet offers a Date Added sort, but its rows were
requested without DateCreated, so addedAt mapped null and the sort silently
compared nulls — the same gap the earlier DateCreated work closed for catalog
and hub rows. DateCreated is a direct dto property, not one of the per-row
COUNT fields that motivated this set's slimness (#1552), so the cost profile
of these folder-dto requests is unchanged.
2026-08-21 19:23:44 +02:00
edde746 595a846bb9 fix(tv): clear stale back-suppressor arming when the next back press arrives
Backing out of a focused text field on TV fires onBack on KeyDown and arms
BackKeyUpSuppressor so the orphaned KeyUp cannot run a second back. When the
closing IME session swallowed that KeyUp entirely, the armed state persisted
and silently consumed the next back press anywhere in the app.

A matching KeyDown now proves the suppressed press ended without its KeyUp
reaching us: the arming clears and the fresh press acts normally. The select
suppressor keeps consuming KeyDowns because the hotkey recorder arms against
the very KeyDown it re-dispatches; KeyRepeat while armed is still consumed.
2026-08-21 19:23:44 +02:00
edde746 7652d060e2 fix(trackers): purge queued writes on session invalidation and lock-order the fallback sweep
Queued tracker writes still replayed through the wrong account when the session died by token expiry instead of explicit disconnect: the auth-failure teardown cleared the store and rebound null but never purged the service's retry queue, so rows queued under account A replayed through whichever account connected next. The invalidation callback now purges like the disconnect path, after the rebind so an in-flight failure is dropped by the account-binding check instead of re-queueing behind the purge.

Narrower second hole in the same invariant: removeService swept the in-memory fallback outside the queue lock, so an enqueue whose persist failed while a disconnect raced it re-buffered the row after the sweep and the next flush resurrected it. The fallback add and the fallback sweep both run inside the queue lock now, so lock-slot order covers the buffered store the same way it already covered the persisted one.
2026-08-21 19:23:44 +02:00
edde746 7fc559e64b fix(downloads): resolve offline detail metadata through the active profile scope
A shared physical download created under MediaBrowser user A could replace user B's offline detail metadata with A's watch position and token-stamped image URLs: lookupOfflineMetadata resolved via the download creator's clientScopeId. It now resolves the active profile's persisted scope like every other profile-visible read; a profile without its own cached row falls back to the lightweight seed metadata.
2026-08-21 19:23:44 +02:00
edde746 ed1d0f1b10 fix(profiles): require the target profile's PIN before managing or deleting it from the picker
Long-pressing a PIN-protected local profile in the picker offered Manage and Delete with no verification, so any user could open its detail screen, clear its PIN, or delete it outright. Both actions now verify the target's PIN first (active profile and Plex Home profiles keep their existing flows).
2026-08-21 19:23:44 +02:00
edde746 5591a0094d fix(windows): key HDR restore to the recorded display and hand off after a monitor move
HDR state was recorded for the display playback started on, but the restore gate queried whichever monitor the window sat on at exit; moving the window to another monitor could skip the restore, clear the change flag, and delete the recovery record, leaving the original display stuck in HDR. The gate and any repeat toggle now resolve the recorded target.

A repeat SetHDREnabled issued after the window moved also stayed pinned to the recorded display: playback moved from HDR monitor A to monitor B re-toggled A, returned success, and left B untouched even though the Dart caller had probed B. With a change live, the operation now restores the recorded display first (retiring its recovery record exactly as a normal restore) and proceeds as a fresh change on the current monitor. If that restore fails the call refuses and keeps the old record so no display diverges from its recovery state; if the current monitor cannot be determined it stays pinned to the recorded display.
2026-08-21 19:23:43 +02:00
edde746 6ab46ced54 fix(relay): claim OAuth callbacks before the code exchange and bound poster and poll traffic per IP
Two callbacks with the same state could both exchange the authorization code upstream (concurrently or by replay); the session is now atomically claimed under the proxy lock before the exchange.

GET /posters/ and the /auth/result long-poll had no per-IP limiting or concurrency bound, and every poster lookup serialized through an exclusive store lock; both endpoints now use the established limiter and non-expired hits take a read lock. The limiter also tracks active transfers per IP with caps below the global limits (4 for fetches, 2 for uploads), because one unauthenticated client could otherwise take all 16 global poster-fetch slots and hold them through slow ServeContent reads, starving everyone else with 429s; concurrency checks precede bucket charges so a capped denial consumes no admission tokens.

/auth/result gets its own per-IP budget instead of sharing /auth/start's burst-3 bucket, where two concurrent NAT'd sign-ins 429'd on the fourth request. It is charged only after the poll secret validates (bogus requests keep the generic 410 and cost nothing), denials carry an honest Retry-After, and the Dart poller - which treated 429 as terminal and abandoned a valid session - retries them until the session's 10-minute lifetime expires.
2026-08-21 19:23:43 +02:00
edde746 a029b1a7c8 fix(seerr): decode media status per product and model failed/completed request states
Jellyseerr shifts MediaStatus codes 6/7 relative to Overseerr (6=blocklisted, 7=deleted vs 6=deleted), and the shared unconditional mapping misread both. The product is now detected from the presence of mediaServerType in /settings/public, persisted on the session, and used to resolve raw wire codes; blocklisted titles are shown as non-requestable.

Request statuses failed(4) and completed(5) previously decoded as pending, blocking re-requests and mislabeling failures; both are now modeled and active requests are defined positively as pending or approved. Seerr also marks a request Failed on arr-push failure while leaving the media status Processing, and precedence checked processing first, so failed titles rendered as Processing and the request sheet kept blocking re-requests; a failed request with no live pending/approved request now wins over stale pipeline status in both the catalog state and the sheet's blocked labels.

Reauthentication completing from a stale session snapshot wholesale-replaced the session and could downgrade a concurrently detected product discriminator back to unknown permanently (the settings cache never reapplies it); adoption now merges the known product.
2026-08-21 19:23:42 +02:00
edde746 ca7f90d1bd fix(widgets): dismiss the file-info spinner when the launching card unmounts
The non-dismissible file-info loading dialog was popped only from the card's own context; if a list refresh removed the card mid-fetch, both pop sites were skipped and the modal stuck forever. The spinner is now owned by ScopedLoadingDialogController and dismissed in a finally.
2026-08-21 19:23:42 +02:00
edde746 4fcb221643 fix(downloads): repair recovery paths, queue stalls, resume coverage, deletion fan-out, and aggregate status
Post-restart completion recovery joined directory/filename, losing the base-directory component the Task constructor strips on custom roots. An unresolvable queue head (offline server) broke out of the drain loop, stalling every other queued download; the drain now excludes it and continues. The download tree also read all-cancelled or partial containers as completed.

The queued-download resume was a one-shot on the first online client, so a persisted row skipped because its server was offline stayed queued until restart. The resume now re-fires whenever a server comes online that the last resume did not cover (including reconnects), and a resume landing mid-drain re-drives the pass instead of being swallowed by the processing guard.

Deleting an episode fanned out one network playback-extras request per sibling row; the reference scan is now cache-only, retaining thumbnails when a sibling cannot be resolved. Season/show deletion removes rows sequentially, so that conservative retention would have counted siblings queued in the same batch - a sibling, or the container row whose extras cache is always a miss, made every episode retain its thumbnails and orphaned the files once the batch's rows were gone. The fan-out threads the batch's rating keys through so rows scheduled to disappear neither retain thumbnails nor contribute in-use paths; genuinely surviving rows still trigger retention.
2026-08-21 19:23:42 +02:00
edde746 0f5cd11c08 fix(screens): claim the mandatory profile picker before awaiting and skip the full-screen loader after playback
The mandatory profile picker checked its re-entry flag before several awaits, so an initialization notification could stack two requireSelection routes; the flag is now claimed before the first await and the late-profiles edge only fires on a real transition. Returning from playback also reran the full metadata loader, replacing the whole detail screen with a spinner and resetting the selected season; playback returns now use the non-loading watch-state refresh.
2026-08-21 19:23:41 +02:00
edde746 7d0e04bcc0 fix(player): retire never-faded chrome immediately and display sync offsets through their scope
A show/hide inside one frame left the chrome flagged presented with no fade to clear it, so back and Escape did nothing until a later full cycle repaired the flag; hide now retires presentation directly when the chrome never became opaque. The sync-offset rows and slider seed also read the global pref while writes and the player used the scoped store, so a title/library-scoped offset displayed as 0ms and the first slider tap jumped from the wrong baseline.
2026-08-21 19:23:41 +02:00
edde746 09e0b06e49 fix(tv): unbreak collapsed-rail D-pad traversal, action-bar focus survival, and text-field back handling
With the rail collapsed and Libraries expanded, DOWN from the header landed on a mounted but focus-excluded library node and was swallowed, trapping traversal; the focus order now matches the render exclusion and traversal scans past non-focusable candidates.

An action bar rebuilding on count change disposed every node, silently dropping focus and never notifying the TV host; bindings are now reused by stable identity (external focus node, else debugLabel) and the transition is reported. Positional reuse remains the only option for an unlabeled action, but it applies only while the action-list shape is provably unchanged - catalog detail enrichment inserting Request before a focused Trailer used to hand Trailer's focused binding, focus ring and next Select included, to Request. Those actions also carry stable debugLabels so their focus survives enrichment.

The text field consumed back on KeyDown outside the shared handler, letting one press act twice. It now marks the back coordinator like handleBackKeyAction does and keeps the down-only shape solely on TV, where the closing IME session swallows the matching KeyUp. Because onBack can move focus (empty search field -> sidebar), the orphaned KeyUp would otherwise drive app-level back on the new focus chain, so the field arms BackKeyUpSuppressor; the suppressor gained a hardware-level KeyUp observer that clears the armed state in a microtask after the press ends, removing the long-documented pinning hazard where an unconsumed KeyUp left it swallowing the next press.
2026-08-21 19:23:41 +02:00
edde746 5c08862194 fix(trackers): purge queued writes on disconnect, evict stale anime snapshots, and cancel dismissed auth dialogs
Queued tracker writes carried no account identity, so rows created under account A replayed against account B after a reconnect; explicit disconnect now purges that service's queue. An in-flight markWatched/reconcile that failed after the purge was re-enqueued anyway (the write scope only tracked profile generation) and replayed into whichever account connected next: Tracker.accountBinding (client identity, rebound synchronously on every disconnect) is captured before each write and re-checked before queueing a retry, and because the check sits in the same synchronous segment as the enqueue, a row that passes it is claimed ahead of the purge in the queue mutex and is still removed by it.

The memoized anime-list snapshot survived writes, so sequential rewatch updates computed from pre-write state; successful writes now evict the entry.

A device-code dialog dismissed by system back never cancelled the poll (blocking new attempts until the deadline), and a user-cancelled sign-in showed the connection-failed snackbar; both now route through one cancel path.
2026-08-21 19:23:41 +02:00
edde746 de91db47c7 fix(player): keep progress reporting and live sessions alive across failed retries, re-arm the sleep timer on prompt dismissal
A Jellyfin live retry that failed before open stop-reported the still-current session (recover returns the receiver), killing /Sessions/Playing for the rest of the session; the discard now skips a recovered session identical to the current one. An in-place reload failing before the open boundary left the progress tracker disposed and nulled, so the resumed stream never reported again and the exit flush was skipped; the re-wire now also runs on the rollback path against the restored metadata. Dismissing the Still Watching prompt via back or next also never re-armed the sleep timer; it now counts as the same acknowledgement as Continue.
2026-08-21 19:23:40 +02:00
edde746 d7422c81cb fix(providers): keep reconnects, retained libraries, and Discord presence alive after failures
Companion-remote reconnects derived their intent from a session status the peer overwrites mid-join, so a failed reconnect attempt often never rescheduled; the attempt now carries its own intent flag.

Library loads dropped retained state on failure. A delta load that failed for every requested server removed their libraries while adding nothing, and an in-place refresh where one server succeeded and another timed out replaced the whole list with only the successful response, wiping the failed server's sidebar entries even though it stayed out of the loaded set. Both paths now key retention to the servers that actually responded: unreachable servers keep their entries and are refetched on the next status emission, removed servers still drop.

Discord RPC kept the dead client after a disconnect, making every 30s reconnect a no-op for the rest of the session; disconnect now tears the client down so the timer builds a fresh one. Rapid disable/enable while a connect was still initializing also let the old client's failure dispose the fresh one, so each attempt binds its listeners and cleanup to its own client instance and stands down when it is no longer current.
2026-08-21 19:23:40 +02:00
edde746 da21481ff3 fix(android): keep the reflected media3 MatroskaExtractor fields under R8
AssMatroskaExtractor and MatroskaLatmSupport reflect MatroskaExtractor's private extractorOutput/subtitleSample fields by name, but no keep rule covered them: R8 renames the fields and every MKV direct-play in a release build fails constructing the extractor. Adds the keepclassmembernames rule (descriptors verified against media3 1.11.0 in the Gradle cache) and extends check_shrinker_rules.py to scan Kotlin/Java reflection across all android src/main roots including libass.
2026-08-21 19:23:40 +02:00
edde746 e5dc9c3f89 fix(networking): surface cancelled responses as cancellation and stop crediting a failed Plex hub fetch
A response cancelled before or during body consumption completed as a successful empty body, so cancellation-triggered aggregation could overwrite valid state and a cancelled download could commit an empty file. The managed client now delivers an abort error, and a request whose own abort has fired classifies secondary teardown errors as cancelled (timeouts keep their type). A Plex server whose /hubs leg failed was also counted as succeeded when only the optional music leg returned, letting Discover replace good hubs with a music-only result.
2026-08-21 19:23:40 +02:00
edde746 d7500c25c1 fix(plex): stop double-encoding removed tags and surfacing failures as empty lists
Removing a tag containing a space or symbol silently did nothing: the removed values were pre-encoded and the transport encoded them again, so Plex matched nothing while the UI showed the tag gone. Folder listings and the shared list wrapper also converted every transport failure (401, 500, timeout) into a successful empty list, so an unreachable server rendered 'no folders'/'no results' with no retry while Jellyfin surfaced an error. Failures now propagate to the existing error paths, and the match screen gained one.
2026-08-21 19:23:40 +02:00
edde746 d1ccd236fd fix(gamepad): release held-direction state when a controller disconnects
Disconnecting a gamepad while holding a D-pad direction or a deflected stick left the synthetic key repeat running forever, since only window blur tore that state down. The disconnect event now runs the same teardown: stop repeats, release held keys, clear pressed/suppressed sets and stick latches.
2026-08-21 19:23:40 +02:00
edde746 5961bf8881 fix(settings): reject blank intro/credits patterns and ignore stored blanks
A cleared skip-marker regex saved as an empty pattern, and RegExp('') matches every chapter title: all synthetic markers became intros or credits, and an end-of-file credits marker could auto-advance the episode. Blank input is now rejected at both validation and save, and the chapter fallback treats already-persisted blank patterns as absent.
2026-08-21 19:23:40 +02:00
edde746 0a75e2345e fix(jellyfin): request DateCreated on list rows, sync ProductionYear on date edits, and window the EPG on overlap
Jellyfin gates DateCreated behind explicit Fields, so browse/hub rows mapped addedAt as null: the Date Added sort was a no-op and unplayed Next Up rows sorted dead last in merged Continue Watching. Both base field sets now request it.

Editing a release date re-posted the full DTO with the stale ProductionYear; the year now follows the edited date and clears with it.

The guide requested programmes by MinStartDate, dropping anything already airing; the lower bound is now MinEndDate so overlapping programmes stay in the window.
2026-08-21 19:23:39 +02:00
edde746 70ffe8ff15 fix(player): mirror ExoPlayer rate into PlayerState and keep secondary subtitles out of the primary selection
On the default Android ExoPlayer backend the native core never emits a speed property, so PlayerState.rate stayed at 1.0 forever: the speed sheet checkmark, keyboard speed stepping, long-press 2x restore, and media-session rate all computed from a stale 1.0. setRate now mirrors its value into state like setVolume already did.

On mpv backends, a selected --secondary-sid subtitle later in track-list order overwrote the primary selection because parsing ignored main-selection; the track sheet then badged the secondary as primary and replaced the user's primary on tap. parseTrackList now treats main-selection 0/absent as primary and 1 as the secondary selection.
2026-08-21 19:23:39 +02:00
edde746 938ddc5942 fix(startup): build the repair dialogs below the bootstrap MaterialApp
Tapping Repair on the startup-failure screen always threw: the repair flow received the gate State's own context, which has no Navigator, MaterialLocalizations, or ScaffoldMessenger, so both the confirm dialog and the fallback error snackbar raised instead of rendering. Thread the bootstrap home builder's context (below the MaterialApp) into the repair flow and its failure snackbar.
2026-08-21 19:23:39 +02:00
edde746 ec530c6713 fix(jellyfin): refuse ambiguous bare-scope cache resolution across users
With two profiles bound to two Jellyfin/Emby users on one server, a legacy bare machine-id lookup (offline downloads, cached playback metadata) could resolve another user's cache row, serving their resume position and token-stamped image URLs. Mirror the write-path guard: when the bare scope matches more than one user, log and return nothing.
2026-08-21 19:23:39 +02:00
edde746 a53041a352 fix(playback): match preferred track language by ISO variation, not string prefix
A 2-letter preferred language (es, ar, ru, ...) prefix-matched unrelated 3-letter track codes (est, arm, rum), so profile-based audio/subtitle selection could pick a wrong-language track whenever it preceded the wanted one in container order. Route the matcher through languageMatches, which compares exact codes, region variants, and ISO-639 variations.
2026-08-21 19:23:39 +02:00
294419109b feat(player): dismiss the skip prompt on Back instead of exiting (#2049)
While a Skip Intro / Skip Credits prompt is up and the chrome is down,
Back walked the screen's staged chain and exited playback. On a remote
nothing else means "no thanks": left/right seek, OK takes the skip,
up/down raises the OSD. Declining an intro cost you the episode.

Adds a stage for it alongside the sheet and content-strip stages that
already run locally in the player controls. Gated on the same condition
as Select's skip path, off on phones (#1938), off without canControl,
and off while a screen-level prompt owns the key.

The claim is latched for the whole press: handleBackKeyAction acts on
the key-up, and the button's own 7s auto-dismiss can fire in between.

Co-authored-by: cajunflavoredbob <cajunflavoredbob@users.noreply.github.com>
2026-08-21 08:48:44 +02:00
edde746 61268fab73 fix(livetv): derive recording state from grid subscription attributes
Recording indicators never appeared in the EPG and the program sheet kept
offering "Record" for already-subscribed programmes, so rules were created
repeatedly (nine duplicate subscriptions in the linked report). Two defects,
both confirmed against the official web client bundle:

- The sheet's scheduled-state check called
  /media/providers/<identifier>/media/subscriptions/mapping/<ratingKey>,
  which 404s: PMS mounts that route under the numeric MediaProvider id from
  /media/providers. The check failed instantly and unconditionally on every
  platform, so the button always read "Record".
- The guide derived its dot solely from cross-matching grab metadata, and
  the grab refresh issued right after scheduling raced the server
  materializing the grab, wiping the optimistic key before one frame showed.

The grid response already tags subscribed airings with subscriptionID /
grandparentSubscriptionID - the signal the official client renders from.
LiveTvProgram now carries those attributes; the guide checks them first
(grab matching stays as the secondary signal) and keeps local
schedule/cancel actions authoritative until the next grid load. The sheet
resolves Record vs Manage from the tagged rule key without a network call,
falling back to the fixed numeric-id mapping route for untagged airings.
Grab parsing also accepts the nested airing under "Video", which PMS uses
for every non-scheduled grab status in JSON.

close #2009
2026-08-21 07:44:27 +02:00
edde746 8b7917fcc4 chore: bump version to 2.16.2 2026-08-21 07:34:28 +02:00
edde746 2563d624ca fix(player): stop periodic audio dropouts during Dolby passthrough via MPVKit 1.0.25
With Audio Passthrough on, every (E-)AC-3 track on Apple TV dropped
100-220ms of audio every 1.79s. The system pipeline behind the
compressed AVPlayer path reads unboundedly far ahead of the playhead
and consumes its buffer in fixed ~1.8s quanta; the AO's 2s feed lead
meant each refill overran the write head and the renderer skipped the
missing audio to stay on clock. Bitrate- and route-independent, and
invisible to the AO: item status, time control, and the feed margin
all stayed clean while the sink output gapped (#1300, #1776).

MPVKit 1.0.25 feeds the elementary stream 8s ahead of the observed
playhead -- 4x the pipeline's refill quantum -- sizes the ES window
from the configured lead, exposes it as
--ao-avfoundation-compressed-lead, and keeps waiting during preroll
while a slow source (a realtime-pinned server transcode) is still
making priming progress instead of abandoning Atmos for PCM.

Verified on an Apple TV 4K gen 3 with an HDMI audio capture rig
against EAC3 768k and 640k streams: 21 dropouts/min on 2.15.0, zero
across 10.7 minutes with the new lead; a 997Hz sine encoded as EAC3
through the full passthrough path is statistically identical to
first-party AVKit playback of the same tone; a rate-limited server at
0.95x realtime now prerolls late on the compressed path instead of
downgrading, and once the lead is filled mpv's cache pauses absorb
the deficit with the margin intact.
2026-08-21 07:30:41 +02:00
edde746 54af977f39 fix(library): refetch content tabs when the app resumes from a long backgrounding
Opening Plezy on a TV box resumes the resident process rather than
cold-starting it, so the Libraries grid kept showing the in-memory
content from the previous session -- hours stale -- until the user
switched libraries and back. Nothing on the resume path refreshed tab
content.

MainScreen now latches genuine backgrounding and, on a resume more than
five minutes later, refreshes LibrariesProvider and sweeps the content
tabs through each screen's in-place Refreshable.refresh() -- skipped
while offline, before startup priming, during playback, or with no
connected servers. LibrariesScreen.refresh() now refetches the selected
library's loaded tabs (the toolbar refresh action) instead of
re-selecting the saved library, which never reloaded them because tab
widgets only reload when the library's globalKey changes.

close #2043
2026-08-20 18:19:03 +02:00
edde746 21f48382bc fix(hubs): derive wide hub-row cards from the grid's widening scheme
A continue-watching episode card was 180dp on home but 232dp in the
grid behind "see all" at 480dp: hub rows widened the resolved poster
cell (x1.5) while grids widen the max extent (x1.8) before the integral
column packing, and the TV shelf multiplied the rail's tall card by the
same 1.5. Rows now adopt the grid's packed wide cell via
MediaGridDelegate.wideCellWidth, the TV shelf passes the hub's wide
flag to TvBrowseRailLayout.cardWidthFor, and the single widening
scheme is stated in MediaGridDelegate. Grids are untouched.
2026-08-20 14:49:33 +02:00
edde746 424c14a344 fix(tv): size HubSection shelf cards with the browse rail formula
Live TV "What's On" and catalog related rows are the two TV surfaces
without a TvBrowseRail path; HubSection's own clamp ([210, 340],
unscaled) rendered ~40% larger cards than every neighboring rail and
gave 720p TVs the same 210dp floor as 4K. Delegate the shelf card
width to TvBrowseRailLayout.cardWidthFor so the clamps scale and match
the rails.
2026-08-20 14:34:39 +02:00
edde746 fcb167e661 fix(library): size hub detail posters like home rows and library grids
Home hub rows showed ~3 large posters per row while the hub's "see all"
page packed 5 small ones on the same 360dp phone. Hub detail was the
only surface on the padding-aware target-count formula, which resolves
ceil(lerp(5, 2, f)) columns regardless of screen width (and 9+ columns
on TV). Drop the flag so hub detail shares the fixed-extent formula
with every other grid, and delete the now-unused
getMaxCrossAxisExtentWithPadding and its usePaddingAware plumbing.

close #2039
2026-08-20 14:34:27 +02:00
edde746 32b3fb64a2 fix(linux): ship gio-launch-desktop so the bundled libgio can launch URLs
Root cause of the broken 'Sign in with Plex' and update links on
portable builds: the bundle ships Ubuntu's libgio, whose compiled-in
helper path (/usr/lib/x86_64-linux-gnu/glib-2.0/gio-launch-desktop)
exists only on Debian-family hosts. glib then falls back to a bare PATH
search, and distros like Fedora keep the helper in /usr/libexec outside
PATH, so every URL/desktop-file spawn failed. Installing the RPM masked
it only because system glib is built with the right path.

Bundle the build host's gio-launch-desktop next to the libgio it was
built with (bundle-libs.sh now fails the build if libgio is bundled and
the helper cannot be found) and export GIO_LAUNCH_DESKTOP from plezy.sh,
which glib checks before its compiled-in path. Covers the tarball and
the deb/rpm/pacman packages alike, since they all ship the same bundle
and launch through the wrapper.

close #1477
2026-08-20 13:31:16 +02:00
edde746 71cbb83c06 fix(player): keep a play/pause tap from crashing on a torn-down player
Transport from the controls layer ran unawaited with no error handling:
a tap racing player teardown (NOT_INITIALIZED on Android) or a wedged
mpv event queue (SET_PROPERTY_FAILED on Windows) crashed the app. The
controls path now tolerates failures the same way the remote transport
path one function above already does.
2026-08-20 13:31:03 +02:00
edde746 33d80b6d0e fix(companion): keep LAN discovery from emitting into a closed hosts stream
The most frequent Dart crash in production: CompanionRemoteProvider's
async crypto rebuild can call stopListening() on a discovery service
that was already disposed, and _emitHosts() then threw 'Bad state:
Cannot add new events after calling close'. Emitting after dispose is
now a no-op.
2026-08-20 13:31:03 +02:00
edde746 a9cbb72c63 chore(server): bump bugs image to sha-c996cf3
Deployed 2026-08-20. Adds dartsymbolmap chunk-upload support and
crashpad minidump ingestion; fixes the method-scoped SPA fallback
that 405'd every non-GET API request.

Old: sha-319e0eb@sha256:1e5a2d8ab80e703de4a8a8b15d858ce931609e2226bf1e6d04979c0ca52a3005
New: sha-c996cf3@sha256:540d985c51f953704c8b97c6c568d0ffc107b91223dd5279136cce1c5522598b
Index verified on two hosts; linux/amd64 + linux/arm64 present.
Migration 18 (event_attachments) rehearsed on a cloned DB copy.
Rollback: prior digest + /root/bugs-db-backup-20260820-082218 on the host.
2026-08-20 10:31:06 +02:00
edde746 7c496413f8 fix(remote): survive app backgrounding by guarding the reconnect cycle and retrying on resume
Backgrounding the Android app or locking the screen near-always dumped the
companion remote back to the device-selection page, forcing a manual
re-connect. Three defects combined: the peer's trailing disconnected status
event knocked the session out of reconnecting and broke the retry chain, the
bounded backoff budget (~31s) burned out against restricted background
networking before the user returned, and nothing retried on resume.

The provider now ignores stale peer status/error events while a reconnect
cycle is active, defers retries while backgrounded instead of consuming the
budget, and on resume retries immediately with a fresh budget - or pings a
nominally-connected session so a dead socket fails into the reconnect path
right away. Authenticated socket errors in the peer now surface as
disconnects like clean closes, keeping both terminal signals on the
reconnect path.

close #2035
2026-08-20 07:10:51 +02:00
edde746 04673a8c8a fix(library): render Plex home videos with 16:9 thumbnails instead of cropped posters
Plex "Other Videos" libraries returned items as type=movie with
subtype=clip, which mapped to MediaKind.movie and rendered 2:3 poster
cards that cropped the generated 16:9 video-frame thumbs.

Items keep the movie kind so downloads, add-to, delete-from-server, and
detail navigation stay available, but subtype=clip now renders wide with
the thumb-first artwork clips already use. Sections marked subtype=clip
in /media/providers map to the clip library kind, giving Plex home-video
libraries the same folder-first grouping and wide grid cells as
MediaBrowser homevideos views. Wide-only hubs also keep 16:9 cards in
the poster episode modes, matching the TV rail's gate.

close #2036
2026-08-20 05:44:08 +02:00
edde746 958c27350d feat(navigation): open settings with Cmd+, / Ctrl+, on desktop
Pressing Cmd+, on macOS did nothing: the stock Flutter template left a
disabled Preferences menu item holding the key equivalent, and nothing
in the app handled the chord.

MainScreen now handles Cmd+, (macOS) / Ctrl+, (Windows/Linux) beside
the existing Cmd+F search shortcut, reusing its tab-aware open path. A
SettingsShortcut fallback above the profile navigator covers pushed
content routes, pushing a named settings route; a navigator observer
blocks the chord while settings is already in the stack, and the video
player route keeps ownership of the keyboard. The dead xib menu item
is removed.

close #1909
2026-08-20 05:28:37 +02:00
edde746 591f33aa2c chore: bump version to 2.16.1 2026-08-20 04:21:15 +02:00
edde746 dcf2314d9d fix(player): interpolate the media-controls suspend flag in lifecycle log
The controller extraction left a bare $_mediaControls.suspendedForTvBackground
in the lifecycle diagnostic string, so the line logged the controller
instance instead of the boolean it exists to surface during TV
background-suspend debugging.
2026-08-20 03:30:07 +02:00
edde746 4c74d6a1d5 chore(player): latch TV background suspend state in one owned object
The Android TV background suspend (#1911) kept its grace timer, the
suspended latch, and four pre-stop position/track fields loose on the
State, with the latch/rollback/consume invariants enforced only by
convention across three lifecycle methods and the redelivery loop.
Move them into TvBackgroundSuspendState: latch() sets the snapshot and
the suspended flag together, clear() rolls both back when the native
stop fails, and consumeForRestore() drops the suspended latch before
handing the snapshot to the restore reload — the ordering the bounded
stop-report redelivery depends on. Pure eligibility predicates stay in
tv_background_suspend_policy.dart; orchestration stays in the
lifecycle part.
2026-08-20 03:08:43 +02:00
edde746 5842d30ae8 chore(player): route all live-session mutations through the live part
The live fallback ladder, retry latch, timeline suspend/resume, and
exit-on-resume flags were poked directly from the error handler, the
play-intent path, the playing-state listener, and lifecycle handling.
Give the live part named operations (_beginLiveLadderRetry,
_retryLiveStreamForPlayIntent, _resetLiveLadderOnPlaybackRestart,
_stopLiveSessionForTvBackground, _consumeLiveExitOnResume) and move
the timeline suspend/resume helpers over from lifecycle, so
LiveTvSessionState is mutated only by live_tv.dart and the initial
tune in the start composition root.
2026-08-20 03:04:14 +02:00
edde746 5e19d9dad4 chore(player): give the episode vertical an owned session-state object
Adjacency, loading flags, the Play Next prompt/countdown, the
transient-retry budget (#1867), the completion latch, and the per-
screen adjacency loader were thirteen loose State fields written by
the episode parts, the reload engine, and the stream listeners. Move
them into EpisodeSessionState — the episode analog of
LiveTvSessionState — so the vertical's mutable state has one home and
the reload engine's touch points (clear prompt on open, reset
adjacency and retry budget on swap, record failure reason) are visible
as writes to one object. Logic is unchanged; the screen disposes the
state object instead of the raw timer.
2026-08-20 03:00:27 +02:00
edde746 b0b4d5d6db chore(player): extract spurious-EOF recovery into an owned helper
The dead-stream recovery budget, its progress-based refill, and the
parked latch (#1520) were four State fields written from the commit
chokepoint, the position listener, the reload engine, seeking, and the
transport-intent handlers. Move the state machine into
SpuriousEofRecovery with explicit verbs (interceptEof, retry,
clearPark, resetBudget, onPositionAdvanced); the reload call rides one
injected callback that fills the common in-place-reload arguments. The
reload outcome enum becomes the public MediaReloadOutcome so owned
helpers outside the screen library can consume it.
2026-08-20 02:55:08 +02:00
edde746 a55ec642b3 chore(player): move the transition lock and generation into a gate object
The mutually-exclusive playback transition state, its lease identity,
the idle completer, and the playback generation counter were four State
fields manipulated by centralized screen methods. Move them verbatim
into PlaybackTransitionGate (tryAcquire/owns/advance/release/forceIdle/
waitForIdle/beginGeneration) so lease discipline is enforced by one
type and parts can no longer touch the raw fields. The transition enum
and lease type become public in the gate's library; leases are only
mintable through tryAcquire.
2026-08-20 02:50:18 +02:00
edde746 aedca9b416 chore(player): centralize first-frame readiness in FirstFrameGate
_hasRenderedFirstFrame had five writer files with hand-rolled
snapshot/restore pairs in the reload and channel-zap rollbacks, and the
paired _hasFirstFrame ValueNotifier was reset independently along the
open path. Move both flags into FirstFrameGate with explicit verbs —
markReady, resetUiForOpen, resetRenderedForAttempt, reset,
forceUiReadyOnFailure, snapshot/restore — so the UI-vs-reporting
asymmetry and the transactional rollbacks are enforced by one type.
The uiReady notifier keeps its identity across attempts; the video
surface, controls, and buffering overlay hold it by reference.
Unit-tests the gate's verb semantics.
2026-08-20 02:45:53 +02:00
edde746 d9a5fb034e chore(player): extract shader and zoom orchestration into a controller
Shader preset application, ambient lighting enable/restore/toggle, and
video zoom/boxfit lived as an extension reading per-attempt services
off the player State. Move them into VisualEffectsController, a plain
State-owned helper; the shader, ambient-lighting, and video-filter
services are injected as late-bound getters because all three are
re-created per playback attempt and nulled in teardown. Rebuilds keep
flowing through the single requestRebuild callback.
2026-08-20 02:40:30 +02:00
edde746 92cc49a265 chore(player): extract companion remote wiring into an owned binding
The CompanionRemoteReceiver callback install/uninstall, home-fallback
save/restore, provider sync handle, and receipt-time volume/seek
dispatch lived on the player State. Move them into
CompanionRemoteBinding, a plain State-owned helper: the binding
instance replaces the State as the receiver's playerOwner token with
identical identical()-guard semantics, and the provider is captured at
bind time because context.read can fail during dispose. Subtitle/audio
cycling stays on the State — the drain loop is bound to the playback
transition lease — and is passed in as callbacks.
2026-08-20 02:30:41 +02:00
edde746 1e83e4e6c2 chore(player): extract OS media-controls adapter into an owned controller
The Android TV background suspension latch, availability policy, and
resume/rewind restore logic lived as an extension on the 149-field
player State, with the suspension flag read and reset from three other
parts. Move them into MediaControlsScreenController, a plain
State-owned helper following the established player pattern: the
manager, player, and current item are injected as late-bound getters
because they are re-created per playback attempt. The controller now
solely owns the suspension latch; teardown clears it via
resetSuspension() instead of writing the State field directly.
2026-08-20 02:25:16 +02:00
edde746 e71580def9 chore(player): move the in-place reload engine into its own part
episode_navigation.dart fused two responsibilities: the episode
next/previous vertical and the screen's generic in-place media
transition engine (_switchPlaybackSource, _performPlaybackSourceSwitch,
_selectSourceSubtitleLocally, _reloadMediaInPlace,
_reapplyScopedPlayerPrefsForItemChange), which lifecycle restore,
spurious-EOF recovery, Watch Together, and the companion remote also
drive. Move the engine and deferTranscodeSubtitleSelection verbatim
into playback_reload.dart so the episode part contains only the
episode feature. No code changes beyond the file split.
2026-08-20 02:16:12 +02:00
edde746 2f47ed23cd chore: dedupe resolution display labels and fold single-use helpers
Two private formatters mapped the canonical server resolution label to
display text (media_quality_labels, media_version) with edge-case
drift, and several single-consumer helpers added indirection without
callers:

- add shared resolutionDisplayLabel in resolution_label.dart and
  migrate MediaVersion.displayLabel and the quality-label builder to it
- drop the resolutionLabelFromHeight compat re-export from
  jellyfin_mappers (no remaining consumers) and its stale doc note
- delete TraktCatalogSource.membershipKeysFor, byte-identical to the
  CatalogWatchlistMachinery default
- derive the rating sheet backend label from
  MediaBrowserDialect.productName instead of a hardcoded switch
- inline EndpointFailoverManager into failover_http_client.dart, its
  only importer, and remove endpoint_failover_interceptor.dart
2026-08-20 02:01:12 +02:00
edde746 b66eec827d fix(trackers): use the shared refresh timeout for MAL token refresh
MAL token refresh waited on the general 20s request timeout while the
Trakt and MDBList refresh paths use the dedicated 15s refresh timeout,
so a hung refresh held the 401 retry longer on MAL than on its
siblings. Align MAL with the shared refreshTimeout.
2026-08-20 01:59:00 +02:00
edde746 df0d71e6f8 fix(auth): let the Plex QR and browser waits cancel back to the sign-in actions
Google Play rejected 2.16.0 (versionCode 142) for an Android Automotive
navigation dead end: on a car, "Sign in with Plex" resolves to the
in-app QR wait, which offered only Retry — and the AAOS system bar has
no back button, so a touch user could not leave the screen without
killing the app. Add a Cancel action to the QR and browser-polling
states that aborts the attempt and returns to the initial sign-in
actions on every platform.

Verified on an API 34 Automotive emulator: Cancel returns to the
landing with the Jellyfin/Emby paths reachable.
2026-08-20 01:11:23 +02:00
BockiandGitHub 088886bfb6 Add Emby as option in issue and feature templates (#2014) 2026-08-20 00:30:57 +02:00
edde746 e0122feb2b fix(release): address the Amazon submission API by app id instead of package name
The App Submission API stopped resolving apps by package name and now
returns 400 "No app found with the entered Inputs"; it requires the
amzn1.devportal.mobileapp app id from the console URL. Read the id from
AMAZON_APPSTORE_APP_ID, validate it in preflight, and keep the package
name for console-facing messages.
2026-08-20 00:29:21 +02:00
github-actions[bot] 08a3a61c2a chore: update cask to 2.16.0 2026-08-19 22:27:04 +00:00
edde746 4cc8b4c0d9 chore: bump version to 2.16.0 2026-08-19 23:42:07 +02:00
edde746 7a4cdc8b5e fix(player): pin loudnorm output to 48 kHz float to stop startup audio stutter
Audio Normalization on the mpv path made every video start with stuttering
audio on Linux: dynamic-mode loudnorm always outputs float64 at 192 kHz, so
the AO opened at f64/192k and PipeWire had to convert/resample on the
deadline-critical path (~4x the per-cycle DSP work) while playback startup
load was still settling. Appending mpv's native format filter pins the
chain back to 48 kHz float, so the conversion happens once on the buffered
decode side and the AO opens a normal stream. Integrated loudness output is
unchanged (-14 LUFS, verified via ebur128). mpv's own format filter is used
instead of lavfi aformat so the fix does not depend on which lavfi filters
each platform's bundled ffmpeg compiles in.

Addresses the normalization half of #1720; the residual startup
micro-stutter with normalization disabled is a separate regression.
2026-08-19 23:25:59 +02:00
edde746 20896a3d48 fix(player): keep the wake-time profile picker responsive on Android TV
Sleeping the device mid-video with "Ask for profile on app open" enabled
left the app wedged on an unresponsive Choose Profile screen (Nvidia
Shield). The picker is pushed on the root navigator, but the player's
focus self-heal only consulted its own nested profile-session route, so
it yanked D-pad focus back behind the picker whenever it lost it.

Route currency now walks every enclosing navigator (isRouteChainCurrent)
before the player reclaims focus, primes loading-phase navigation focus,
or claims the surface on window focus. The resume-time prompt is also
skipped entirely while a video player is active: waking mid-stream
resumes the stream instead of stacking the picker over the session.

close #2034
2026-08-19 23:08:32 +02:00
edde746 fc96ddc1ab style(android): fold initialVideoOutput body onto its signature per ktlint 2026-08-19 23:06:08 +02:00
edde746 4522f42bbf fix(focus): reveal focused items only during keyboard/D-pad sessions
Closing an episode context menu (or its Rate / File Info sheets) on a
show opened from a Home section scrolled the detail page back to the
top, and on shows with many seasons jumped the season selector back to
the entered-from season. The Home path parks invisible focus on the
initial episode/season target; dismissing the menu restored focus to
that parked node, whose focus-gain auto-scroll then yanked the viewport.

Focus chrome is already keyboard-mode-only, so make the focus-gain
reveal match: FocusableWrapper, FocusableChipStateMixin, and
FocusableTileStateMixin now scroll into view only during keyboard/D-pad
sessions. The gate reads the tracker's live state (new
InputModeTracker.currentMode) because the inherited provider is one
frame stale on the first navigation key of a session. The touch OSK
search submit keeps its jump-to-results via an explicit reveal, matching
the existing pointer-mode convention of pairing requestFocus with an
explicit scroll.

close #2031
2026-08-19 22:38:18 +02:00
edde746 a4b88df965 fix(explore): show Seerr request once the detail fetch resolves a tmdb id
Plex Discover's hub, search, and related endpoints ignore includeGuids,
so items opened from those rows carried no tmdb id and the Request
action never appeared — only watchlist items (whose endpoint does
return Guids) could be requested. The gate was frozen in initState from
the row item; it now reads the detail-enriched item, whose metadata
fetch does bring the tmdb id.

close #1959
2026-08-19 20:54:00 +02:00
edde746 810ef002ad fix(player): show source track audio in stats during passthrough
When mpv bitstreams (audio-spdif), audio-params describe the IEC 61937
carrier - 192 kHz "stereo" for E-AC-3 - so the performance overlay told
users their 5.1 track was playing as 2ch stereo. Every recent "EAC3
downgraded to PCM" report in #1300 reads back this string while the
receiver route stays healthy.

Show the source track's channel layout and sample rate instead, plus an
explicit Passthrough row naming the bitstreamed codec, on both the
mpv-channel and Android mpv-fallback stats paths.
2026-08-19 20:14:48 +02:00
edde746 cb900c255a fix(trackers): preserve AniList/MAL rewatch status when scrobbling
Finishing an episode of a show set to rewatching stomped the entry back
to watching. The scrobble write now reads the entry's status and rewatch
count in the same request as the episode count, keeps REPEATING /
is_rewatching entries rewatching, starts a rewatch when progress lands on
a completed entry, and bumps the rewatch count when a rewatch completes.

close #2026
2026-08-19 19:34:04 +02:00
edde746 43ab083cda fix(tvos): match Siri Remote swipe physics to measured native focus engine
Swipe navigation felt sluggish next to native tvOS apps: Plezy priced a
focus step at 0.55x the focused item's extent, throttled repeats to 140ms,
and stopped dead on finger lift - the inverse of the native engine's feel.

Retuned AppleTvRemoteTouchService to on-device measurements of the native
focus engine (issue #2006):
- one focus step per fixed 400pt of touch travel; drop item-extent scaling
  (measured step distance was identical across a 230pt and a 345pt axis)
- repeat cadence 140ms -> 60ms (native median)
- fast lifts glide one or two extra steps (>=2000 / >=8000 pt/s) within
  ~130ms of the lift; reversal pivots and new touches cancel the glide
2026-08-19 18:26:30 +02:00
edde746 3fb90a4948 fix(images): fetch full-resolution tile artwork on low-end hardware
Posters and episode thumbnails looked noticeably soft on Fire TV sticks and
similar boxes: the auto-detected reduced tier capped artwork DPR at 1.5 and
tightened tile decode caps, so every tile was fetched at 56% of its pixels
and upscaled twice on large 4K panels.

Drop the reduced-tier DPR cap and the poster/square/thumb decode caps so
tiles fetch and decode at full TV density on every tier; raise the reduced
image-cache budget to the 64MB TV baseline to absorb the larger tiles.
Backdrops keep their scrim-masked ~720p reduced caps, and the display budget
factor stays pinned to 1.0 there, so the low-RAM art ceiling is unchanged.

close #2020
2026-08-19 13:16:36 +02:00
edde746 65713858ea fix(tvos): open the sign-in keyboard after fast server probes instead of freezing remote input
Adding an Emby server on Apple TV locked the app up after entering the
URL: the server probe answered inside the URL keyboard's dismissal
animation, so the username field's system keyboard silently never
presented while its editing session kept ownership of every remote
press — leaving only Menu, which suspends the app. Jellyfin was
unaffected in practice because Quick Connect skips the username focus.

Engine 3.44.0+6 defers first-responder takes until the in-flight
keyboard presentation clears and routes remote presses to the engine
whenever no keyboard is actually on screen, so the session can no
longer strand the user.

close #2011
2026-08-19 12:57:15 +02:00
edde746 744e72d76b fix(player): stop continuous Dolby Direct Play judder via MPVKit 1.0.23
Direct Play of any (E-)AC-3 track on Apple TV developed persistent
micro-stutter: mpv's audio clock was derived from es_pts on the
compressed path, which is credited a whole 32 ms burst the moment a
payload lands, sawtoothing the clock on a ~0.8 s cycle that video
retires as visible skip/hold pairs. AAC content was unaffected, which
is why the symptom tracked Dolby audio and survived every VO-side fix.

MPVKit 1.0.23 measures the clock from IEC samples actually handed to
ao_read_data instead. Verified with an HDMI capture rig against the
CI-built binary: EAC3 display cadence is now statistically identical
to AAC (was 47.6 skips/min plus 453 multi-frame holds over 38 min).

close #1776
2026-08-19 12:57:15 +02:00
edde746 761303de11 fix(subtitles): render zlib-compressed embedded MKV subtitles on the ExoPlayer path
Embedded subtitles on mkvmerge-muxed files with compressed subtitle tracks
(the anime-release convention, reported against AV1 encodes) never rendered:
the track selected fine but nothing ever appeared on screen.

Two defects compounded. ContentCompAlgo 0 (zlib) is the Matroska default
value, so mkvmerge omits the element and the explicit-value detection never
engaged - media3 ignores an empty ContentCompression and silently emits
compressed samples. And for text subtitle tracks TrackOutput-level inflation
can never work: MatroskaExtractor prepends the plaintext timecode prefix to
the still-compressed payload and truncates the sample at the first NUL byte
before any TrackOutput runs, while AssTrackOutput feeds that same internal
buffer to libass, which then parses zero events and reports every frame as a
changed empty render.

Treat the presence of ContentCompression as zlib until an explicit
ContentCompAlgo says otherwise, and for SRT/ASS/SSA/VTT tracks inflate the
block frame payload before the parent's subtitle sample assembly, leaving the
TrackOutput wrapper to the formats it can actually handle. Blocks that are
laced, corrupt, or over-bound pass through byte-identical. The detection fix
also makes the existing whole-sample TrackOutput inflation engage for
PGS/VobSub zlib tracks, which media3 does not truncate.

Verified with mkvmerge zlib/plain fixture extraction tests and end-to-end on
an API 36 emulator against a Jellyfin direct-play mux mirroring the reported
file.

close #2023
close #2022
2026-08-19 12:34:40 +02:00
edde746 4a1111f435 feat(navigation): restyle sidebar as M3 Expressive navigation rail
The custom sidebar read as an ad-hoc widget: collapsed rows were the
expanded layout clipped to the strip, the libraries tree used a
staircase of indents and mixed row heights, and hover expansion pushed
the whole content area sideways.

Rebuild the rail on M3 Expressive geometry: collapsed destinations are
icon-only 56x32 pills centered in an 80px strip (48px icon-only on TV),
expanded rows are fixed-height destinations with a full-width stadium
indicator, and the two layouts crossfade/lerp during the width morph
instead of clipping. The libraries section is flattened into full-width
destination rows under a chevron header at standard destination
metrics, hover/touch expansion overlays content as a rounded, shadowed
panel over a dimmed scrim instead of pushing it, and rail width, item
morphs, content translate, and bleed all share one duration/curve.
2026-08-19 09:11:18 +02:00
edde746 4b6533d25b fix(linux): stop the HDR watchdog from firing after synchronous no-op transactions
On a Wayland HDR session, colors flickered between HDR and washed-out SDR every ~5 seconds: the mpv-leg timeout in apply_hdr_state was armed after SetHdrOutput returned, so a synchronous reply (the no-op short-circuit that runs on every playback restart and re-describe) orphaned the timer. Five seconds later it fired against a healthy plane and withdrew the live HDR image description; the next re-apply re-attached it and armed the next orphan.

Arm the timeout only while the reply is genuinely outstanding. An asynchronous reply still removes it, and a genuinely wedged core is still bounded.

Verified in a headless-sway Docker repro against the same PQ/BT.2020 file: 2.15.0 logs the false 'mpv never answered the output colour-space switch' warning 5 s after plane bring-up and again after source recognition; the fixed build logs none across bring-up, HDR playback, and seeks.

close #2016
2026-08-19 06:07:25 +02:00
edde746 05ef93c55b fix(player): keep gpu-next off the Android hardware-decode path
HEVC files played through the mpv backend on the Nvidia Shield show a
solid blue screen with audio: under hwdec=mediacodec, gpu-next samples
the decoder output as a samplerExternalOES that libplacebo declares in
both shader stages, and the Tegra GLES linker rejects the pair ("struct
type mismatch between shaders for uniform"), failing every frame. The
in-chain gpu fallback never engages because gpu-next initializes fine,
and mpv/libplacebo master reproduce it unchanged.

DV reshaping — the reason gpu-next exists on Android — only happens
under software decode, so offer gpu-next exactly there and keep the
legacy gpu VO for hardware sessions on both the primary mpv backend and
the ExoPlayer fallback core.

close #2010
2026-08-18 23:21:19 +02:00
edde746 8d2eca42d4 feat(search): filter search results by media type
Searching a name shared by a movie, a show, and audio drowns the wanted
item in episode and track rows. The search screen now offers kind chips
(All, Movies, TV Shows, ...) above the results; chips derive from the
pre-rank candidate pool, and selecting one re-ranks that kind's
candidates with the full display budget, so a kind crowded out of the
trimmed All view still surfaces everything the servers returned for it.
Chip switches never refetch, and the filter falls back to All when a
refined query no longer returns its kind.

close #2001
2026-08-18 20:58:35 +02:00
edde746 0f3d06668f fix(jellyfin): read Emby playback shelves from the hide-aware resume route
Removing an item from Continue Watching on Emby posts HideFromResume,
which only the dedicated /Users/{uid}/Items/Resume route honors: the
IsResumable /Items query and the per-series /Shows/NextUp lookups kept
returning hidden rows, so removed items blipped back on every refresh.

Emby's dedicated route conflates both shelves (in-progress items plus
one zero-position next episode per started series), so every playback
surface now reads one hide-aware window from it and splits the rows by
PlaybackPositionTicks: positive rows feed Continue Watching, zero-
position episode rows feed Next Up. The 1+N per-series Next Up
reconstruction is deleted; one recency scan still supplies the play
dates and the NextUpDateCutoff window. Jellyfin request strings are
unchanged.

close #2003
2026-08-18 20:58:35 +02:00
edde746 7131be4cc0 fix(plex): request native-size artwork instead of server-side upscales
Browsing artwork showed PMS PhotoTranscoder log lines flagged
"upscaled: 1" on every request. The flag merely echoes the upscale=1
query param Plezy sent on every cover request (PMS prints it before
locating the source, including on cache hits and pure downscales), but
the param had a real cost: whenever the requested box exceeded the
source — hero art at the 4K display budget (3840x2160 requests against
the near-universal 1920x1080 agent art), portrait backdrops on >1080p
phones — PMS genuinely enlarged the image server-side. Verified against
PMS 1.43: ~2.5x the transcode time and transfer bytes for zero rendered
detail, since the client covers the slot on the GPU regardless and the
fit-policy decode bounds never enlarge.

Send upscale=0 on cover requests too: downscale output is byte-identical
and oversized requests now return the native image. Jellyfin needs no
change — MaxWidth/MaxHeight never enlarge.

close #1975
2026-08-18 19:47:52 +02:00
edde746 436fd7d2d5 fix(desktop): hide the window before exit teardown and keep shutdown out of live UI
Closing the window now runs a graceful exit (so trackers get their
terminal scrobble), but the teardown kept the window on screen for
seconds while screens visibly emptied as servers disconnected.

Hide the window as the first step of exit teardown, bounded so a
stalled platform channel cannot hold an already-accepted exit open, and
cover every graceful-exit entry (window X, Cmd+Q, OS-initiated), not
just the close button. Add a terminal MultiServerManager.shutdown() that
closes the status streams before draining clients: the still-mounted
widget tree must never observe an "all servers gone" snapshot mid-exit,
which would flip the app into offline UI and dismantle screens (and
with it the teardown-driven AppLifecycleListener used-after-dispose
assert). A health result landing after shutdown is a silent no-op.

Supersedes the flag-based approach in #1999.
2026-08-18 19:38:30 +02:00
edde746 c198bab04c fix(tv): keep focus on the played item when continue watching reorders
Exiting the player after enough progress moved the played item to the front of Continue Watching left D-pad focus at its old position, now occupied by a completely different item.

TvBrowseRail and HubSection now remap the focused index to follow the focused item identity when a hub reorders underneath it, falling back to the same series replacement entry when a finished episode is swapped for the next one, and HubSection focus memory is remapped so re-entering the row lands on the same item.

close #1987
2026-08-18 19:27:00 +02:00
edde746 2a6f752860 fix(release): make multi-channel deployment resumable 2026-08-18 18:00:52 +02:00
github-actions[bot] 16c0e00302 chore: update cask to 2.15.0 2026-08-18 15:05:13 +00:00
edde746 6d75e58f52 chore: bump version to 2.15.0 2026-08-18 14:50:24 +02:00
edde746 ad1a12c998 fix(release): reset fresh state and preserve deferred phases 2026-08-18 14:45:32 +02:00
edde746 9fe6dbe9f2 fix(explore): add MDBList watchlist source
Connected MDBList accounts were omitted from Explore, so their watchlists could not be selected or displayed. Register the profile-scoped MDBList client as a catalog source with watchlist mutations and search.

close #1888
2026-08-18 13:13:06 +02:00
edde746 304d8a5e33 fix(plex): keep relay out of the phase-1 race, preferred persistence, and pinned sessions
A relay connection can win the phase-1 race (plex.tv edge answers fast),
gets saved as the preferred endpoint, and the cached URL then wins the
deterministic head-start probe at every bind — pinning future sessions to
relay's 2 Mbps cap even after direct connectivity returns, surfacing as
HTTP 500s on Original quality. A session that lands on relay legitimately
(direct down at connect time) stays there all evening: re-optimization
only fired on connectivity events.

Relay is now a fallback tier in the race: all probes still start at once,
but a relay success is held until every direct candidate has failed, and a
cached relay URL gets no head start. A single persist gate refuses relay
at all four endpoint-save sites, classified against both the live server
and the connect-time capture so rotated relay URIs cannot slip through.
While the active endpoint is relay, a bounded-backoff re-probe (30s/60s/
120s) re-races the candidates so a returning direct endpoint promotes
away without a restart.
2026-08-18 09:23:04 +02:00
edde746 986237491f fix(i18n): fill missing translations and remove unused keys 2026-08-18 08:41:13 +02:00
edde746 35eef09f72 fix(tvos): present video on the host clock instead of the media timebase
Direct Play on Apple TV develops recurring micro-stutter that worsens
the longer playback runs and clears temporarily on pause/play
(issue #1776). Since 2.4 the avfoundation VO has presented frames
against a media-time CMTimebase anchored and rate-servoed to follow
mpv's audio-slaved schedule; clock skew between the two domains can
only be retired by rate slewing or a re-anchor snap that retimes every
queued frame at once. The media timebase exists for PiP, which tvOS
does not have.

Bump MPVKit to 1.0.22 and opt tvOS into its new
avfoundation-presentation=host mode: samples carry mpv's scheduled
display time against a free-running host-clock timebase, so drift is
absorbed per frame inside mpv and no timing state accumulates in the
VO. The queue lead returns to 128ms; 500ms only dampened media-mode
snaps and quadrupled their blast radius. 1.0.22 also paces the
compressed-passthrough feed off the most-advanced playhead reading,
fixing the periodic audio dropouts passthrough users reported on 2.14.
2026-08-18 08:38:46 +02:00
edde746 8461e6ba5f feat(detail): split play button with version picker segment when multiple versions exist
There was no way to tell from the detail screen that a movie or episode
has multiple versions (theatrical/extended cuts, 1080p/4K encodes); the
only entry point was the hidden Play Version item in the overflow menu.

The Play button now becomes a Material 3 Expressive split button when
the item carries more than one version and its server is reachable: the
main segment keeps plain Play (which already resumes the remembered
version), and a narrower chevron segment runs the existing Play Version
flow (version picker, quality picker when the backend can transcode,
preference save). The flow itself is extracted from the context menu
into a shared promptAndPlayVersion helper, and FocusableActionBar gains
per-action spacingBefore so the joined pair can sit tighter than the
rest of the row. Transcode-only quality picking stays in the overflow
menu so the chevron keeps signaling a real version choice.

close #1881
2026-08-18 07:41:54 +02:00
edde746 93d3ec65e2 fix(exoplayer): decode DTS with FFmpeg when the stream cannot bitstream
DTS-HD files play silently on the Onn 4K Plus: DTS decode is license-gated
in its firmware, so c2.amlogic.audio.decoder.dtshd initialises, drains and
advances the playback position while rendering silence. Route DTS-family
decode to the bundled FFmpeg decoder whenever the track will actually be
decoded - passthrough off, downmix, normalization, a failure block, or a
route that cannot bitstream DTS in any shape. Bitstream-capable routes are
untouched: media3 selects direct output before it ever consults the decoder
list, so raw passthrough, the IEC 61937 carrier and the tunneling gate keep
their exact behavior. Kodi ships the same policy as its only configuration:
its MediaCodec audio whitelist is empty and DTS always decodes in FFmpeg.

close #1995
2026-08-18 06:28:28 +02:00
edde746 35dce90ea9 feat(player): persist player-sheet changes at a configurable scope
Changing playback speed, shader preset, aspect ratio, or a sync offset in
the player always rewrote the global default, so a show watched at 1.5x
forced 1.5x onto movies, an Anime4K pick followed the user into
live-action libraries, and a file-specific subtitle offset leaked onto the
next title.

Each of those settings now has a scope under Settings > Video Playback >
Remember Player Changes: don't save, everywhere (default, pre-existing
behavior), per library, or per show/movie. Player writes route through the
configured scope; playback start and in-place item changes resolve the
value for the current item, falling back to the global default. Items
without the needed identity (live TV placeholders, Jellyfin/Emby downloads
without a stamped library) keep the global behavior. Resolution consults
only the configured scope, so entries saved under a previous scope become
inert instead of shadowing the new one.

close #1984
close #1322
close #1616
2026-08-18 06:09:11 +02:00
edde746 483691d43a feat(player): surface skip forward/back on the iOS and tvOS lock screen and remote
On iOS and Apple TV the lock screen, Control Center, and iPhone remote card only offered previous/next track for video, so the transport buttons restarted the episode or jumped to the next one instead of skipping a few seconds.

MediaControlsManager suppressed the MPRemoteCommandCenter skip commands on all Darwin platforms because they displace the next/previous buttons — the right call for music, the wrong one for video. The suppression is now a per-surface policy: the video player opts in with preferSkipOverTrackButtons and advertises the in-player small-skip step (seekTimeSmall, default 10s) via setSkipIntervals, while music keeps next/previous as its lock-screen transport. Skip events already routed through MediaControlRouter to _seekRelative on every platform, so the OS-echoed interval drives the actual seek.

close #1994
2026-08-18 04:06:11 +02:00
edde746 b4a84c6a28 fix(profiles): don't re-prompt for profile when a system overlay closes
On Fire TV, invoking Alexa and dismissing its overlay popped the profile
picker over a still-playing session: MainScreen treated every resumed
lifecycle event as an app open and re-applied "ask for profile on open".
The Alexa overlay only produces inactive -> resumed, which the handler
could not tell apart from a real return to the foreground.

Track the deepest lifecycle state since the last resume in a small gate
(ProfileSelectionResumeGate): only a genuine backgrounding (hidden,
paused, or detached) arms the prompt for the next resume. This also
keeps iOS working, where returning from the background arrives as
hidden -> inactive -> resumed.

close #1990
2026-08-18 02:09:28 +02:00
edde746 c5e7ce648b fix(player): gate audio passthrough on the IEC 61937 shapes each backend opens
On Shield Experience 8.x (API 28) ExoPlayer force-decoded TrueHD to
multi-channel PCM, and enabling passthrough on the mpv backend made every
non-AAC file wedge on an infinite buffering spinner with no audio pipeline
at all.

Two defects behind one symptom pair:

- The MAT/DTS-HD carrier oracle stopped at API 29 because
  AudioTrack.isDirectPlaybackSupported does not exist below it, so API 24-28
  never offered the carrier even on routes that genuinely bitstream it. Below
  API 29 the HDMI AudioDeviceInfo is the only vouching signal, so the carrier
  is now offered when an HDMI output explicitly advertises IEC 61937 at
  192kHz/8ch; unspecified (empty) capability arrays deliberately do not
  count, because an unvouched IEC track that initialises without being
  bitstreamed renders as full-scale noise. A route that advertises and still
  refuses the track fails AudioTrack init into the existing force-decode
  recovery.

- The mpv audio-spdif list was gated on the raw encodings the route
  advertises, but mpv's audiotrack AO opens every spdif format as a stereo
  ENCODING_IEC61937 track clamped to the 48kHz mixer rate. E-AC3, TrueHD and
  DTS-HD MA structurally cannot survive that shape, and a route can advertise
  raw encodings while its HAL takes no IEC track at all - naming any codec
  there leaves mpv's audio chain stuck before AO init (reproduced on a Shield:
  spdif_ac3 selected, no AudioTrack ever opened, playback never starts). The
  list is now capped to ac3,dts and additionally gated on the route accepting
  the stereo IEC shape, using the same tiered oracle as the carrier. The
  primary mpv backend previously wrote a hardcoded five-codec list from Dart;
  it now asks the plugin to derive the value from the audio route, like the
  ExoPlayer fallback already did.

Verified on a Shield (API 30) with a full-capability EDID: TrueHD rides the
carrier and survives speed transitions (instrumentation), and an E-AC3 title
that previously wedged under mpv+passthrough now decodes and plays with
audio-spdif=ac3,dts.

close #1991
2026-08-17 23:34:05 +02:00
edde746 7cfd68c491 test(player): match the renamed carrier diagnostic in the mismatch regression
The rate-mismatch regression greps the audio diagnostics for the literal
'MAT/IEC 61937 carrier', but 658469f9 reworded the sink's engage message to
'TrueHD (MAT) via IEC 61937 carrier' when DTS-HD joined the carrier. The test
self-skips on carrier-less CI emulators, so the rot only surfaces on real
hardware, where the fallback behaves correctly and the assertion still fails.
Match the shared 'via IEC 61937 carrier' fragment both codecs emit.
2026-08-17 23:33:35 +02:00
edde746 137f2a0e95 merge: music-library polish and Live TV guide day navigation
Brings in the feedback-driven fixes: user-assigned Plex playlist
posters, square music-grid gutters, grouped artist discography
(albums/singles & EPs/live/compilations for Plex), and the guide
day-jump rework (mounted reloads, immediate day apply, focus
retention).
2026-08-17 23:03:24 +02:00
edde746 1bdeca3b5f fix(libraries): give square music grids an inter-card gutter
Square-card (music) grids had zero delegate spacing - the only
separation was each card's internal 3px padding, and square shapes are
excluded from the full-card spacing path, so playlist and album tiles
sat nearly edge to edge. Square grids now get an 8px cross/main gutter
(automotive keeps its larger spacing); poster, list, and full-card
layouts are unchanged.
2026-08-17 22:44:12 +02:00
edde746 cff6666219 feat(music): group artist discography into albums, singles & EPs, live, and compilations
Artist pages showed one flat album grid, unlike Plex's own clients.
Plex listing rows never carry Format/Subformat tags (even with
resolveTags=1), so fetchArtistDiscography follows the unchanged album
listing with one batched /library/metadata/{ids} request - whose rows
do include the tags - and classifies each album individually
(EP/Single, then live, then compilation, case-insensitively). A failed
tag fetch degrades to the flat list, and single-album artists skip the
lookup entirely. Jellyfin/Emby carry no album taxonomy on the wire and
return a single albums group.

The artist screen renders one titled section per non-empty group
(single-group artists keep the flat grid), with the grid focus index
space offset per section so D-pad traversal crosses section
boundaries.
2026-08-17 22:44:12 +02:00
edde746 b0798cde9f fix(plex): backfill show logos on continue-watching rows missing them
PMS versions before the ~1.43 hub refresh omit a show's inherited clearLogo
image from episode/season hub rows, so the Discover hero fell back to the
title for TV series while movies (which carry their own logo) and the show's
detail page (which reads the show metadata directly) kept theirs.

Resolve the missing owners' logos in one bulk /library/metadata request
(comma-joined rating keys) and stamp them onto the rows, mirroring the
grandparent lookup Plex Web performs. Best-effort: a failed lookup never
fails the shelf and is retried on the next refresh.
2026-08-17 21:46:12 +02:00
edde746 417f3a5e36 fix(livetv): keep the guide mounted during reloads and apply day picks immediately
The guide replaced itself with a bare spinner on every window change,
unmounting the day-picker anchor and the guide focus node - after one
day or time change the pickers silently no-oped and the remote went
dead. Picking a day also applied nothing by itself: the window only
moved after the second (time-slot) menu, so backing out of it read as
'the day picker does not work'.

The grid now stays mounted during in-session reloads behind a light
loading overlay, a day pick re-anchors the window immediately (the slot
menu is an optional refinement), D-pad SELECT arms the key-up
suppressor before opening the menu, and the day chip uses the existing
'Tomorrow' translation.
2026-08-17 21:36:35 +02:00
edde746 d4d44e6c72 fix(music): show user-assigned Plex playlist poster instead of the auto composite
Plex emits an auto-generated composite mosaic for every playlist, so the
displayImagePath fallback order (composite first) meant a poster the user
assigned in Plex could never appear. Prefer thumbPath and fall back to the
composite; no-op for Jellyfin/Emby, which never set a composite.
2026-08-17 20:59:13 +02:00
edde746 658469f954 feat(player): bitstream DTS-HD MA through the IEC 61937 carrier on Android
Fire TV Stick 4K Max (and other Fire OS devices) advertise ENCODING_DTS_HD on
the HDMI route but only implement the DTS-HD basic profile, so media3's raw
path builds an AudioTrack that drains normally while the receiver hears
silence. The same routes do bitstream the 192kHz/7.1 ENCODING_IEC61937 carrier
TrueHD already rides, so DTS-HD MA access units are now packed into DTS type IV
bursts (a port of FFmpeg's spdif_header_dts4 at the 768kHz HD rate, the same
bytes Kodi's IEC packer produces) and played through that carrier.

The TrueHD MAT carrier sink is generalized into IecCarrierSink with one
IecCarrierPacker per codec. While the carrier route exists DTS-HD is binary -
the carrier or decoded PCM, never the lying raw path; routes without the
carrier keep the pre-carrier raw behavior. Master Audio peaks the carrier
cannot hold strip to the always-fitting core substream for ~60s, exactly as
FFmpeg does, and the packer output is pinned byte-for-byte against FFmpeg
spdif golden fixtures.

close #1988
2026-08-17 20:58:04 +02:00
edde746 efd33b3a4e fix(database): restore api_cache.cached_at read by the playback freshness gate
Main stopped compiling: the v21 column drop treated cached_at as
never-read, but the fresh-cache-first playback metadata gate
(ApiCacheSingleton.getIfFresh, from the playback start-latency fix)
reads it on every Plex and Jellyfin playback start, and a later
cleanup removed the put() stamp the gate depends on.

Reinstate the column, keep the v21 migration to the connections
half only (it never shipped in a release), restore the explicit
put() timestamp - on conflict the upsert only updates the
companion's columns, so without it a refreshed row would keep its
original write time and read as permanently stale - and copy
cached_at through the pinned-metadata rescope statement again. The
v21 migration test now pins that api_cache is left untouched.
2026-08-17 20:47:40 +02:00
edde746 86498547ba fix(plex): burn Live TV DVB subtitles on explicit selection
Plex Live TV lost DVB subtitles when 2.10 moved the live path to HLS
(#1983): the transcode starts with subtitles=none, which drops a
tuner's bitmap subtitle streams from the output entirely - unlike
in-band CEA captions, they are separate elementary streams.

The tune response now surfaces the part's embedded bitmap subtitle
streams as selectable tracks in the player's subtitle menu. Picking one
points the part's server-side selection at that stream and rebuilds the
live transcode with subtitles=burn, preserving the time-shift position.
Off stays the default so tuner captions are never auto-burned (#1590),
and channels without bitmap streams keep the native track list. The
selection survives stream recovery by re-mapping onto the re-tuned
session's streams and resets on channel zap. Jellyfin live sessions
record subtitle selection as intentionally unsupported: their one
negotiated URL has no rebuild to deliver it through.
2026-08-17 20:20:20 +02:00
edde746 5fe1e6dc65 refactor(ui): delete unwired log output, dead notifier filters, and never-passed widget params
MemoryLogOutput extended LogOutput but was never wired as a Logger output (storage happens in the printer); DeletionNotifier/WatchStateNotifier's forServer/forItem filtered streams and WatchStateEvent.mediaType had no production consumers (tests now filter .stream directly); context.hiddenLibraries/profileSettings and toPlexUrl had zero call sites; MonoTokens.splashFactory was never read; OptimizedMediaImage's enableTranscoding/cacheKey chains, FocusableMediaCard.width/height/forceGridMode, TvBrowseRail's constant-zero gap functions, and media_image_helper's scaleFactor were never varied by any caller. The sha1 LRU stays (rebuild-hot artwork URLs); TvRailTrailing.none and the mono-theme copyWith stay live (lerp delegates to copyWith). Also carries the MusicPlayContext.id argument drops in the music screens and remaining sweep test updates.
2026-08-17 19:02:25 +02:00
edde746 1df47ed8e1 refactor(watch-together): remove the unconstructable disconnected state and write-only session surface
Participant.lastKnownPosition had zero reads or writes; SessionState.disconnected was never constructed, making isInSession's comparison tautological (now _session != null); the session indicator's onLeaveSession callback had no production passer; enterRoom's bool was awaited and discarded. Music engine: MusicPlayContext.id and sleepTimerEndsAt were write-only, and the coordinator constructor seam was never injected.
2026-08-17 19:02:25 +02:00
edde746 a7527718df refactor(services): delete dead branches, write-only fields, and test-only cache/service surface
plex_client.selectStreams' allParts=false branch, download_manager's both-branches-true conditional and unscoped getAllPinnedMetadata tail, playback_source_resolver.preferOffline, and update_service's unreachable catches had no reachable path; PlaybackSession.result/streamHeaders, PlaybackContext.clientScopeId, FileInfoStreams.audioStream, PrefsRepairOutcome.settingsReset/sessionsSalvaged, and JellyfinLiveSessionTracker.playSessionId were write-only; PlexConnection.directUrl, PlexServer.isOnline plus its parse-and-persist presence field, SafStorageService.createDirectory, FullscreenStateManager.stopMonitoring/dispose, the play_queue_launcher re-export shim, track-selection's constant params, and PlexApiCache.unpinForOffline/isPinnedRatingKey (matching the earlier Jellyfin removal) were dead API.
2026-08-17 19:02:25 +02:00
edde746 7cd5bb64bb refactor(player): remove dead completion-latch channels, unreachable settings states, and unread DV stats
classifyPosition's return enum was discarded by its only production caller (rearm is the side effect that matters); the latch's tolerance/retry knobs were never tuned; _loadAdjacentEpisodes' result was unread by all three callers; countsAsApplied carried a subsumed disjunct and _syncMediaControlsAvailability a stale-generation guard with no suspension point before it; _SettingsView.audioSync/subtitleSync could never be current (both routes early-return into the sync bar); PerformanceStats.dvRpuOutputTooSmall/dvPlaybackReason and ContentStrip.chaptersLoaded were written but never read.
2026-08-17 19:02:24 +02:00
edde746 b38df008ec refactor(screens): delete never-passed knobs, dead enum values, and the unconsumed context-menu onTap
plex_pin_auth_flow's QR knobs, ProfileNameField's navigation params, MusicDetailHeader.wideArtworkSize, and _buildReorderableList's bool were never passed; DownloadType.manage was never constructed; MediaContextMenu.onTap was declared but never invoked — removed with its four card passes (each card's own gesture handlers stay); the pin dialog's obscure chain was always true and _PinKey.label's icon branches unreachable; libraries_screen._isInitialLoad was write-only; LiveTvActionsMixin loses dead findChannel (the generic parameter stays — required by the on-clause, the report was wrong); add_jellyfin's focus-map removal branch ran only against an empty map; the recommended tab's hub-key null fallback was dead behind _ensureHubKeys. media_card also loses its always-false seasonal-rank comparison from the CatalogRankScope removal.
2026-08-17 19:02:24 +02:00
edde746 ceab5a5b59 refactor(providers): remove the unreachable init fallback, unread load results, and dead refresh surface
hidden_libraries' constructor always seeds _initFuture, so ensureInitialized's ?? _initialize() fallback could never run (field now late final); _loadLibrariesInternal returned a bool no caller read; OfflineModeProvider.refresh() had zero call sites; ExploreScreen's Refreshable application was dispatched by nobody (only the discover tab and library tabs are dispatched); the discover null-serverId branch stays — the TV spotlight resolver passes null items during initial load.
2026-08-17 19:02:24 +02:00
edde746 6eb0805f8d refactor(profiles): delete dead client accessors, the write-only focus aspect, and test-only registry API
getServerBoundPlexClient/getClientForLibrary existed only for their own unit tests; MetadataEditAdapter.backend and Plex's unreachable prefKey fallback and music-kind branches had no production path (edit is double-gated on supportsKind); MainScreenFocusScope's focus aspect, isSidebarFocused, and focusContent were write-only; resolveActivePlexIdentity.preferredAccount was never passed; ProfileRegistry.get was unused outside tests — its removal exposed a stale test contract, now pinned correctly: list() deliberately never serves plex_home rows.
2026-08-17 19:02:24 +02:00
edde746 a33c423985 refactor(models): stop parsing wire fields and enum members nothing consumes
Parse-only DTO surface deleted across trackers and catalog models: quality-preset storageKey/fromStorage round-trips (persistence uses EnumPref on .name), PlexHome's placeholder identity fields (id stays — deriveHomeSecret reads it), SeerrUser.email/avatar, SimklSearchResult.endpointType, SimklDetail.type, SimklAllItemsEntry.status/isShow, TraktCatalogEntry.rank, CatalogItem.relevance, and the never-produced CatalogRankScope.favorited/.seasonal members with their label arms. Tracker root: OAuthProxyStart.expiresIn, TrackerSession.scope/isExpired, copyWith slimmed to its one real parameter, TrackerHttpClient.service. TrackerAccountStore.service and the trackerAccountStore() alias are live (persisted-blob validation, callers) and stay.
2026-08-17 19:02:24 +02:00
edde746 1a26b0dd08 refactor(media): delete write-only item fields, dead copyWith/getters, and the unread live-TV activity wrapper
PlexMediaItem.subtitleMode/extraType were mapped from DTOs and never read (subtype stays — the detail screen's trailer picker destructures it); MediaPlaylist.copyWith, PagedMediaListState.mapItems, isMusicContent/isCollection, and MediaHub.copyWith's eight never-passed params had zero call sites; LiveTvActivityResult wrapped reloadGuide results nobody unwrapped (now Future<void>); PlayerLogLevel.none was unreachable — nothing parses or produces it; MediaSourceInfo.getPartId() was an accessor over its own public field.
2026-08-17 19:02:23 +02:00
edde746 4cc065b73a refactor(focus): delete never-selected auto-open behaviors and never-passed focus params
TvTextInputAutoOpenBehavior.onFocus/.onFirstFocus were handled by both TV-keyboard state machines but selected by no caller; FocusableWrapper.longPressDuration duplicated the controller's own 500ms default; FocusableActionBar.mainAxisSize was never passed; FocusableActionBuildState carried focusNode/isFocused/isKeyboardMode that no builder reads (AGENTS.md updated to document the surviving showFocus/animationDuration pair). includeFocusSemantics stays — focusable_media_card passes it.
2026-08-17 19:02:23 +02:00
edde746 071ae8e1c2 refactor(database): drop the never-read connections.isDefault and api_cache.cached_at columns
connections.isDefault was maintained by three write paths (upsert preservation, remove-promotion, setDefault) that no production code ever read back; api_cache.cached_at was documented 'optional future use' and written on every cache store. Both columns are dropped in a v21 migration with row-preservation coverage; the dead write machinery, recordAuthSuccess, updateSyncRuleLastExecuted, getDownloadOwnerCount, and OfflineActionType.fromId (rejection semantics live in the sync service's explicit switch) go with them.

Recovery-image compatibility: committed tvOS snapshots written by older builds still carry isDefault in connections rows, and the restore decoder deliberately rejects rows that do not round-trip exactly. A retired-columns allowlist now strips such keys before the strict check, so pre-retirement images stay restorable — the legacy-plaintext restore test caught this and now pins it. _bindServerStatusListener in main.dart also loses its unused provider param and resolver indirection.
2026-08-17 19:02:23 +02:00
edde746 7658587584 refactor(player): one subscription list, bool play-pause focus request, one desktop click contract, one sync-offset layout
The screen's player stream subscriptions were enumerated by hand in four places (re-wire, rollback, dispose, plus a parallel nulling list) kept in sync only by prose — _cancelPlayerStreamSubscriptions is now the single cancel-and-null authority, living beside the fields. PlayerChromeFocusTarget was a one-value enum with request/consume plumbing, now a bool with identical post-frame consumption timing. The desktop tap and controls-overlay tap duplicated the click-toggles-playback/double-click-fullscreen contract around shared state, now one helper. SyncOffsetControl shipped two layouts of which production only ever rendered compact — the full layout existed solely for tests, which now cover the shipped layout. TrackControlsState's never-non-null onLoadSeekTimes/onSyncOffsetChanged sheet-compat callbacks are gone.
2026-08-17 19:02:23 +02:00
edde746 49fce5ace9 fix(player): keep right-arrow alive on the last control when rotation and screen lock are both visible
_getButtonCount re-implemented every button-visibility condition from build() and had already drifted: the screen-lock button incremented the built index but was never counted, so with rotation lock and screen lock both visible the reported total was one short and arrowRight on the last button silently died. Navigation now bounds against the actual built list, so there is no condition table left to drift; the dead onLoadSeekTimes sheet-compat callback invocation goes with it.
2026-08-17 19:02:22 +02:00
edde746 057ff98ec1 refactor(ui): delete never-passed widget parameters and unreachable surfaces
Grep-verified dead surface across shared widgets: the app-menu system's minWidth/maxWidth/childPadding/alignmentOffset knobs threaded through four layers with no caller ever passing them; FocusableListTile's suppressInitialSelect/hoverColor/textColor/iconColor machinery (~55 lines) reachable by no call site; OptimizedMediaImage.playlist with zero constructions; TvSpotlightBackground's primary-action button that neither caller can render; MediaGridDelegate.createDelegate whose only caller was a test (MediaGridGeometry.resolve is the single delegate composition now); and the CustomAppBar->Config->DesktopTopBar chain collapsed onto DesktopSliverAppBar with its ~11 never-passed passthrough params (snap kept — real callers pass it).
2026-08-17 19:02:22 +02:00
edde746 00a6e056b0 refactor(plex): drop the test-only raw-JSON mapper flavours and title obfuscation branches
PlexMappers advertised a parse-and-map FromJson flavour of every mapper 'for callers that haven't already parsed a DTO' — no such production caller exists; every call site uses the DTO-typed flavour. Tests now parse the DTO and map it, preserving every assertion. The kBlurArtwork JSON-walking branches in the DTO factories (title/summary vowel rotation on the decode hot path) are deleted with the flag's title half.
2026-08-17 19:02:22 +02:00
edde746 78fa2c29e3 refactor(input): compile the disabled diagnostics and screenshot-blur subsystems out of normal builds
TextInputDiagnostics.enabled and kBlurArtwork were mutable/const-false flags nothing ever set, yet the diagnostics side eagerly built log strings on the gamepad and key-simulator hot paths on every event. Both flags are now const bool.fromEnvironment (PLEZY_TEXT_INPUT_DIAGNOSTICS / PLEZY_BLUR_ARTWORK) so the branches const-fold away, every eager interpolation sits behind a guard, and screenshot blurring stays one dart-define away. The vowel-rotation title obfuscation had no consumer need beyond artwork blur and is gone.
2026-08-17 19:02:22 +02:00
edde746 0e1af9faaf refactor(watch-together): flat engine callbacks instead of bundle classes
HostCoordinatorCallbacks and GuestReconcilerCallbacks existed only to be unpacked by the controller through ten forwarding lambdas into its own flat fields. The engines now take individual nullable callbacks; the controller keeps its late-binding lambdas (the provider assigns the public fields after construction), and the test harnesses forward the callbacks they exercise.
2026-08-17 19:02:22 +02:00
edde746 99b0528623 refactor(settings): drop the orphaned mute-toggle helper
SettingsService.resolveMuteToggle had zero production callers — the live mute policy moved to VideoVolumeController.toggleMute long ago, leaving two diverged implementations of the same rule. The two TV-aware pref defaults in the same file now read through the PlatformDetector facade like the rest of the app.
2026-08-17 19:02:22 +02:00
edde746 f5c7b95b02 refactor(tv): read TV detection through the PlatformDetector facade everywhere
TV state had two interchangeable entry points — PlatformDetector.isTV/isAppleTV and the raw TvDetectionService.*Sync accessors — with call sites split arbitrarily between them. App code now goes through the facade; the raw accessors document that they exist for the facade and tests.
2026-08-17 19:02:21 +02:00
edde746 d78a7d925e refactor(trackers): single-client Trakt refresh, distinct Simkl coalescer names
TraktClient's static per-refresh-token coalescer, initiating-vs-joiner branches, session-adoption identity checks, and both updateSession push methods defended a multi-client world production never creates — the one long-lived client is shared via TrackersProvider, and the two throwaway clients never refresh. Refresh now matches MalClient/MdblistClient's instance-coalescer shape. Simkl's _watchlistLoad field shadowed the identically-named coalescer on the mixin it applies (legal today, a trap on any future library merge) — renamed with comments distinguishing the two caches.
2026-08-17 19:02:21 +02:00
edde746 62c25e493e refactor(settings): drop the dormant manager-registration branch and the duplicate Plex add-account error surface
persistAndBindConnection's addToManager/visibleServerId parameters and post-commit manager phase had no production caller (the Jellyfin flow defers runtime pickup to the profile binder) — the function is void now. A failed Plex account add threw a StateError that PlexPinAuthFlow re-rendered as a raw 'Bad state:' string beside the already-rendered inline error; the flow's normal return already stops the spinner, so the inline error is the single surface.
2026-08-17 19:02:21 +02:00
edde746 e543f417ce refactor(profiles): one initial-focus mechanism and one end-session/recover scaffold
The profile picker requested first-tile focus twice (FocusableWrapper.autofocus plus a one-shot post-frame requestFocus for the same node) — autofocus alone remains, verified by the picker's D-pad tests. The end-session/try/catch-resume skeleton was copied across deleteProfile, the Plex sign-out, and connection removal; withEndedProfileSession now owns the pause/recover scaffolding while each flow keeps its own success-path resume decision and error policy.
2026-08-17 19:02:21 +02:00
edde746 4c2f533eef refactor(music): share the playlist play/download/delete flows between the context menu and the detail screens
The audio-playlist play flow, the playlist download flow (including its inline MediaItem synthesis), the delete-with-confirm flow, and the fetch-artist-then-navigate flow each existed twice — once in MediaContextMenu and once in the playlist/album/now-playing screens, with 'Match PlaylistDetailScreen' comments standing in for shared code. They now live in music_navigation.dart and download_utils.dart with per-caller strings preserved; the menu's collection/playlist download handlers fold into one parameterized handler, its duplicated sync/download menu tree is built once, and the generic picker dialogs move to collection_picker_dialog.dart (pure move).
2026-08-17 19:02:21 +02:00
edde746 fb048097ab refactor(livetv): one refresh-gating mixin, one multi-server iteration helper, simpler recordings coalescer
The pause/resume/ticker state machine (three gates, lifecycle observer, TickerMode subscription, timer sync) was triplicated across the What's On, Recordings, and Guide tabs — now LiveTvRefreshMixin, with the guide's drift catch-up layered on its hooks and the lifecycle test asserting the same contract against the shared implementation. Six hand-rolled multi-server loops share forEachLiveTvServer (the channel/favorites loaders deliberately iterate per DVR entry and say so). Recordings' Completer-based load drain became the same whenComplete coalescing shape the screen's channel loader already uses.
2026-08-17 19:02:20 +02:00
edde746 4eb3ab4632 refactor(libraries): inline the one-caller filter/sort loader, drop the dead ItemUpdatable hookup, one grouping sheet
LibraryFilterSortLoader had one call site that constructed it with a constant client resolver and bypassed it for MediaBrowser anyway; the Plex branch now loads both futures inline with types instead of casts. LibrariesScreen's ItemUpdatable application ended in an empty no-op that would have burnt a network fetch had anything ever called it. The chips-bar grouping sheet re-built the browse-options grouping page's chrome by hand; both paths now render the same BottomSheetPageScaffold page.
2026-08-17 19:02:20 +02:00
edde746 a910aa95cb refactor(tvos): publish menu passthrough directly, trim untuned remote-touch knobs
TvosMenuPolicyPublisher batched an idempotent fire-and-forget publish behind a transaction-depth counter that could never exceed one across its three non-nesting call sites — the call sites now publish directly and the pure predicate keeps its test coverage. AppleTvRemoteTouchService exposed 14 injectable knobs of which only six are exercised anywhere (verified per knob); the other eight are private constants or internal construction now.
2026-08-17 19:02:20 +02:00
edde746 3703ac47c3 refactor(explore): share the catalog enum-to-label mappings
The catalog detail screen and the card badges each kept their own enum-to-i18n switches; the genuinely shared mappings (season name, rank scope, request state, status/format/relation labels) now live in catalog_labels.dart, while badge precedence and the deliberately different availability/4k wording stay local with comments naming the divergence.
2026-08-17 19:02:20 +02:00
edde746 c390e0fb0c refactor(detail): share the season-download filter and the download-retry pipeline
The downloaded-episodes-for-a-season filter+sort was written out three times in media_detail_screen (with drifting show-id expressions, preserved per call site), and the failed/cancelled download branches in the action buttons duplicated the same six-step retry pipeline verbatim. One helper each.
2026-08-17 19:02:20 +02:00
edde746 3665d416c4 refactor(providers): deduped peer disposal, hoisted discover outcome tail, live server-connection getter
CompanionRemoteProvider memoized peer disposals in an Expando even though CompanionRemotePeerService.dispose() already dedups concurrent and repeat calls — the wrapper now only keeps cleanup failures from escaping teardown, and the test fake mirrors the service's idempotent-dispose contract. DiscoverProvider._loadOnce carried the same outcome/generation/boundary tail copy-pasted in three branches, now one local settlePassOutcome. OfflineModeProvider cached _hasServerConnection in five write sites when it always equalled a two-term expression — now a live getter.
2026-08-17 19:02:20 +02:00
edde746 2e1a7130fc refactor(downloads): one auto-remove-watched core, trimmed offline-watch provider, shared focus-restore mixin
The auto-remove-watched-downloads rule existed twice (DownloadProvider's sweep and OfflineWatchProvider's single-item copy) — the kind/completed/delete/title core now lives once on DownloadProvider, with the watched judgment staying per caller because the offline path fires before metadata can reflect a local mark. OfflineWatchProvider drops five members with no production callers (isSyncing, getPendingSyncCount, isWatched, getViewOffset, getEpisodesWithWatchStatus) plus the sync-service listener that only served them. The downloads screen's three verbatim 'suppressAutoFocus flipped — focus the first item' didUpdateWidget blocks are now one mixin.
2026-08-17 19:02:20 +02:00
edde746 55382deaf9 refactor(android): drop the dead mpv-command emulation on the ExoPlayer backend
PlayerAndroid.command() emulated four mpv commands ('loadfile', 'seek', 'stop', 'sub-add') that no caller ever sends through the interface, while the commands actually dispatched ('change-list', 'drop-buffers', 'sub-seek', 'screenshot') fell into the default branch and vanished. The override is now a documented no-op, which is what every dispatched command already observed.
2026-08-17 19:02:19 +02:00
edde746 4436efea72 refactor(models): drop parse-only wire fields nothing reads
Four model surfaces parsed, coerced, and re-serialized data with zero readers: PlayQueueResponse's selectedItemIndex/offset/sourceURI/version (version stays as a parse-time validity gate), PlexUserProfile's seven non-track-selection account fields, MediaSubscriptionCreateRequest's hints/params/providers, and the whole CatalogPlayState pipeline (parsed by the Plex catalog source, merged and round-tripped on every CatalogItem, read by nobody).
2026-08-17 19:02:19 +02:00
edde746 8e9c81fe47 refactor(media): plain LocalPlayQueue, trimmed MediaItem factory, one library-content entry point
PlayQueue was a freezed union whose Plex variant was never constructed (server queues flow through PlayQueueResponse), whose pattern getters had zero call sites, and whose backendId was written but never read — it is now a plain four-field LocalPlayQueue. The MediaItem compatibility factory re-listed the entire ~65-field union surface twice while every caller passes at most 22 fields; it now declares exactly that union. fetchLibraryContent had zero production callers (the UI pages through fetchLibraryPagedContent), so the interface method and both implementations are gone, with Jellyfin's drain folded into its paged entry point.
2026-08-17 19:02:19 +02:00
edde746 093c0596f1 refactor(jellyfin): declare shared client internals once, make live-TV negotiation private
Two part mixins re-declared members owned by siblings (five playback methods with full 17-parameter signatures, _safeFetchItemsArray with four lint suppressions), violating jellyfin_client.dart's own 'declared exactly once' contract — they now live on _JellyfinClientInternals, with _safeFetchItemsArray declared as its positional core so no suppressions survive. LiveTvSupport.resolveStreamUrl's only caller anywhere was Jellyfin's own startPlayback, so it is now a private negotiation step and Plex drops its permanent null stub; the negotiation tests observe the same contract through startPlayback and the heartbeat wire. JellyfinApiCache's unpinForOffline/isPinnedItemId (zero callers, kept only for Plex symmetry) are gone, as are MediaSubscriptionCreateRequest's never-populated hints/params/providers expansions in the Plex live-TV serializer.
2026-08-17 19:02:19 +02:00
edde746 908b4a8dac refactor(database): serialize durable mutations through one queue, keep only guarded watch-action mutators
Every identity/pending mutation nested a per-instance SerialFutureQueue inside the static tvOS-recovery queue, so the per-instance layer added no serialization domain (reentrancy is already prevented by the durability Zone check). The unguarded updateSyncAttempt/deleteWatchAction pair had zero production callers — the sync service deliberately uses the revision-guarded variants.

Tests migrated to the IfUnchanged pair by passing the row's current revision.
2026-08-17 19:02:18 +02:00
edde746 8033a308ce refactor(connection): drop dead status/kind enums, share the Plex account build pipeline
Connection.status was write-only health state (only the Jellyfin refresh wrote it, nothing read it — MultiServerManager owns real server status), ConnectionKind duplicated MediaBackend line for line, the token-to-PlexAccountConnection pipeline existed three times (sign-in, dev-token seed, legacy migration) with drifting label/dedup policy, and JellyfinConnectionAuthService.validate/refresh/signOut had no production callers.

Connection.kind is now MediaBackend (persisted 'plex'/'jellyfin'/'emby' strings are identical, no migration); buildPlexAccountConnection in plex_account_setup.dart owns identity resolution with the three callers keeping only their genuine deltas; the test-only auth trio and its jellyfinSignOut timeout constant are gone.
2026-08-17 19:02:18 +02:00
edde746 68c328b469 feat(search): label results with their source server and library
One server with overlapping libraries (movies in both an HD and a 4K
library, shows duplicated per language) returns search results that
cannot be told apart, forcing users to open each copy to find the
right one (#1970).

Each search row now carries a source line under the summary: backend
icon, server name, and library name, shown whenever the owning server
has more than one library. Plex rows name their section inline, with
sectionKey-only rows back-filled from the loaded libraries; Jellyfin
and Emby send no library field on search hits, so search always runs
the per-library scoped fan-out that previously only served
hidden-library exclusion and stamps every hit with its library. The
Jellyfin detail lookup adds a best-effort /Items/{id}/Ancestors stamp
so full metadata stays attributed, row refreshes merge instead of
dropping the stamp, and the mapper no longer misreads SeriesStudio or
ParentId as library identity.

Episode rows trade one summary line for the source line so the
wide-thumb row keeps its height, and the badge paints slightly below
the line-box center to sit on the text's optical middle.

close #1970
2026-08-17 17:13:26 +02:00
edde746 01f04eda42 fix(ui): show loading feedback while play actions fetch
Several Play entry points gave no feedback while their network round
trips ran: a show or season Play button silently awaited a seasons
fetch (with a 10 s completer window) and a first-episode fetch, and
Plex collection/playlist launches showed no spinner at all. Where a
spinner did exist, the first request was gated on the dialog's first
frame instead of running concurrently with it.

Extract executeWithLoading's dialog plumbing into
ScopedLoadingDialogController (mount-aware dismissal, idempotent,
never pops a foreign route) and reuse it for the show/season Play
path. Start the launcher operation before awaiting the dialog frame so
the first round trip overlaps the render, and show the loading
indicator for Plex list launches too.
2026-08-17 13:47:00 +02:00
edde746 0f016e4e13 fix(player): start the playback fetch before player construction
The playback data resolve — the one network request that must land
before open() — was kicked off only after the SharedPreferences load,
the Windows display-mode sync, the music-session teardown in
claimVideo(), Player construction, and (Android/Exo) a native
setLogLevel, so none of that setup overlapped the round trip.

Move the kickoff to immediately after the settings reads; the resolve
depends only on settings and provider lookups, so display sync, player
construction, and the whole mpv property chain now hide behind the
network latency instead of preceding it.

Also remove redundant work elsewhere on the start path: memoize
PlayerAndroid.getHeapSize (asked again on every open for an immutable
device value), skip the ten subtitle-style settings reads on mpv
backends where setSubtitleStyle is a no-op, and stop navigateToVideoPlayer
awaiting SettingsService.getInstance twice per launch — the external-player
read now sits behind the supportsExternalPlayers guard.
2026-08-17 13:46:51 +02:00
edde746 953acedcab fix(player): pipeline mpv http-header commands at open
Every mpv open rebuilt the HTTP header list with one awaited channel
round trip per change-list command — with Plex's 9-13 identity headers
that is ~12 serialized round trips sitting between the playback resolve
landing and loadfile, on every mpv backend.

Dispatch the clr and append commands without awaiting between sends and
await them together: the method channel delivers messages in send order
and the native side executes them in arrival order, so the
clr-before-append contract holds while the latency collapses to one
round trip. Failures still propagate out of open() unswallowed.
2026-08-17 13:46:41 +02:00
edde746 be9197eda6 fix(playback): serve playback metadata from fresh cache instead of refetching
Videos take noticeably long to start. On Plex, tapping Play refetched
/library/metadata/{id} network-first even though the detail screen wrote
a strict superset of that exact payload under the same cache key seconds
earlier. On Jellyfin/Emby, playback start issued a full-detail item GET
before the PlaybackInfo negotiation, and the video controls issued the
same heavy GET again while the stream was opening (#1784) — the most
expensive queries a small home server serves, paid two to three times
per start.

Add ApiCache.getIfFresh over the existing cachedAt column and serve
rows younger than playbackMetadataCacheFreshness (5 min) without a
round trip. Plex guards with the strict stream-detail check
(_plexMetadataHasStreamDetail) so a thin row written by
getPlaybackExtras' lean fetch still goes to the network; Jellyfin's
row has a single full-shape writer, so fetchPlaybackBundle and
fetchPlaybackExtras share the new fetchItemFreshCacheFirst. Any miss,
stale, thin, or malformed row falls through to the unchanged
network-first path, and offline behavior is untouched.
2026-08-17 13:46:33 +02:00
edde746 a2b3377d91 fix(libraries): stop d-pad up snapping collection and playlist grids to top
On TV, pressing UP in the library Collections or Playlists grid snapped
the list back to the top and dropped focus on the tab chips, making long
lists impossible to navigate. Default directional focus traversal scrolls
the found card into view via Scrollable.ensureVisible, whose
outer-scrollable pass routes through the NestedScrollView coordinator and
resets the inner grid position to zero on every UP press.

Give the shared paginated card grid explicit per-card d-pad navigation,
matching the browse tab: managed per-index focus nodes, row/column moves
that request focus directly, first-row UP to the tab bar, and
first-column LEFT to the sidebar. Focus changes now scroll only through
FocusableWrapper's delta-based auto-scroll.

close #1977
2026-08-17 08:58:00 +02:00
edde746 e1b488f860 fix(lifecycle): force-close IOClients stuck in unabortable TCP connects
tvOS logs flood with "HTTP client drain timed out" / "close deferred"
warning pairs after every Plex endpoint race, and each sweep leaks the
losing probes' sockets for the OS connect timeout (~75 s of SYN
retries on Darwin).

A request stuck in TCP connect cannot be aborted: package:http's
IOClient only registers the abort handler once openUrl completes, so
the graceful drain never finishes and ManagedHttpClient defers the
inner close that would have reclaimed the socket.

Fix at both layers: every IOClient now gets an explicit
HttpClient.connectionTimeout matching MediaServerTimeouts.connect, and
ManagedHttpClient gains an opt-in forceCloseOnDrainTimeout escalation
used by all dart:io-backed clients — close(force: true) promptly fails
in-flight requests, unlike the native-callback clients (CupertinoClient)
the deferral exists for.

close #1972
2026-08-17 08:08:45 +02:00
edde746 a79084b0a5 chore(player): link upstream issue androidx/media#3377 in seek workaround 2026-08-17 04:47:06 +02:00
edde746 75704c7a9b test(player): cover tracks-after-clusters MKV seeking on device
Canary asserts stock media3 1.11.0 still reports these files unseekable
and snaps seeks to the start — when a media3 upgrade makes it fail, the
TrackAwareSeekMap repair in CuelessSeekExtractorWrapper can be retired.
The second test drives the production wrapper stack and requires the
seek to hold.
2026-08-17 04:47:06 +02:00
edde746 f2ce587a85 fix(player): seek via per-track cues in MKV files with Tracks after Clusters
media3 1.11.0 builds the Matroska seek map while parsing Cues, which for
files whose Tracks element follows the Clusters is before any track is
known — the map permanently reports unseekable and ExoPlayer coerces
every seek to t=0, snapping playback to the start. Route seeks through
TrackAwareSeekMap's per-track cue lookups using the track IDs observed
on the extractor output.
2026-08-17 04:39:59 +02:00
edde746 947fddf540 fix(ci): resolve the repository root after the symbols script moved
The scripts reorganization moved upload_symbols.dart from scripts/ into
scripts/release/ but kept the single-.parent root resolution, so the
script searched scripts/build and scripts/debug-info and every CI symbol
upload failed with "no symbols found". The sibling checks scripts were
updated to .parent.parent in the same move; match them.
2026-08-17 02:46:36 +02:00
edde746 50a9365be8 fix(linux): keep the Wayland display away from mpv on software GL
On a Wayland session whose compositor hands clients no GPU device
(Cinnamon/Muffin 6.6.3 on Mint 22.3), Mesa falls back to llvmpipe and
libva-wayland's vaInitialize segfaults inside mpv_render_context_create
the moment mpv is given the wl_display - the app silently closes when
playback starts. 2.14 was the first release to hit this because its
bundled libmpv is the first with VAAPI compiled in, and the device init
runs eagerly at render-context creation, so the hardware-decoding
toggle cannot avoid it.

Skip MPV_RENDER_PARAM_WL_DISPLAY when GL_RENDERER names a software
rasterizer: zero-copy Wayland interop does not exist on llvmpipe anyway,
and mpv's hwdec=auto still reaches the GPU through a DRM render node,
which works even on these sessions. Accelerated sessions keep the
zero-copy handoff unchanged. Verified in a container against Muffin and
weston on llvmpipe: the handle is withheld and playback works.
2026-08-17 02:20:43 +02:00
edde746 06ecba5fb5 fix(player): render Dolby Vision via gpu-next on the Android mpv backend
Dolby Vision Profile 5 files play with pink and purple colors on Android
devices without DV support (#1902): vo=gpu cannot apply DV RPU reshaping,
so the raw IPTPQc2 base layer reaches the screen. The shipped libmpv AAR
builds mpv 0.41 with libplacebo, where gpu-next is the upstream default VO
and reshapes DV correctly.

Prefer vo=gpu-next with an explicit vo=gpu fallback on both the primary
mpv backend and the ExoPlayer failure-fallback path, drop the
vd-lavc-film-grain=cpu override so film grain applies on the GPU under
gpu-next, and report current-vo in player stats.

Verified on a Pixel 7 (no DV display or decoder): gpu-next initializes on
Mali-G710/GLES 3.2, SDR hardware decode is unchanged, and a 4K DV stream
decodes to dolbyvision/bt.2020/pq with correct colors under software
decode. Reshaping still needs software decode: FFmpeg 8.0's mediacodec
wrapper exports no DOVI side data, so hardware-decoded DV keeps playing
the base layer untouched.
2026-08-17 01:41:46 +02:00
edde746 096e285ab0 fix(ui): center sheet back button hover circle on the arrow
Hovering the back button in bottom sheet headers drew the circular
highlight 12px right of the arrow: the 48px hit target was positioned
from the stack's padded origin while the glyph sits flush at the
leading content edge. Move the horizontal padding onto the header row
and position the target so the InkResponse box centers on the glyph.
2026-08-17 01:41:46 +02:00
edde746 aeb6108654 feat(scripts): add the deploy.py multi-channel release pipeline
One command releases to Play, Amazon, App Store Connect (iOS + tvOS), the GitHub build farm, Microsoft Store, and the GitHub release + cask, with checkpointed resume. Replaces the fastlane release flow; first used for 2.14.0.
2026-08-17 01:40:54 +02:00
edde746 f622ba8efe chore(scripts): group scripts into checks, codegen, maestro and release subdirectories
scripts/ had ~80 flat files. Entry points (ci_*.sh, codegen.sh, run_tests.sh, format_native.sh, setup_hooks.sh, upload-symbols.*) and the shared pubspec_version.py stay at the root; checkers, generators, maestro tooling and release tooling move into subdirectories with their tests. Updated every reference: workflow steps, guard-test glob, Docker COPY paths and .dockerignore whitelist, website audit path, dart test imports, and regenerated the five outputs whose headers embed generator paths.
2026-08-17 01:40:54 +02:00
edde746 e47b4e0a73 fix(macos): fall back to AVFoundation audio when CoreAudio fails to open
On macOS 27 beta, CoreAudio rejects ao_coreaudio's channel-layout setup
with paramErr (-50), and since 2.14.0 pinned ao=coreaudio as the only
output, the failed init left every video playing with no audio and no
selectable audio track. Append avfoundation as the fallback, mirroring
upstream mpv's macOS probe order: every format still opens through the
HAL-backed CoreAudio path when it works, and the fallback only engages
when CoreAudio's init fails outright.

close #1964
2026-08-16 22:40:53 +02:00
edde746 9dd8aa4679 fix(macos): remove the audio passthrough option
Enabling audio passthrough on macOS 2.14.0 silenced every AC3/EAC3/DTS
item: the macOS player now pins ao=coreaudio, where audio-spdif redirects
to coreaudio_exclusive. That needs an IEC61937-capable device Mac setups
essentially never have, and with a restricted ao list mpv has no PCM
fallback, so the failed AO init stalls playback with no audio. The toggle
never delivered real bitstreaming on macOS anyway (2.13 decoded through
AVPlayer), so stop offering and applying it there.
2026-08-16 22:40:53 +02:00
edde746 3f6e4c0716 fix(windows): render black letterbox bars in HDR via newer bundled libmpv
With HDR playback enabled on Windows, letterbox bars rendered dark gray
instead of black on HDR displays, for both SDR and HDR content. The
bundled libmpv (20251228-git-a58dd8a) carries a libplacebo that maps the
gpu-next background clear color through the display's reported black
point in HDR mode; libplacebo ff2799a67 (2026-01-07) fixes it by using
infinite contrast for the background. The pin had already been past the
fix (20260303) but was downgraded to 20251228 when downloads moved to
SourceForge.

Bump to 20260809-git-dd5d17d328 (mpv v0.41.0-920, libplacebo v7.371.0),
verified to contain the fix commit.

close #1965
2026-08-16 22:40:52 +02:00
edde746 49c117db83 fix(music): open the gapless next track ahead of the boundary
Gapless playback still gapped between tracks on network streams: mpv
only opened the armed next track's stream at the moment the current one
ended, so any server whose connect+probe outlasts the audio output's
buffered tail (~0.5s) - remote Plex over TLS, a transcode session
starting up - produced an audible dropout at every transition.

Enable mpv's prefetch-playlist when arming a network track so the open
happens while the current track still plays. Measured on a Pixel 7 the
boundary goes from 60-233ms of inline network work to 9-16ms with no
network activity at all; a failed or superseded prefetch falls back to
the old boundary open. Local fdclose:// arms keep prefetch off: an
early open would consume the fd while playlist-pos still reads 0,
breaking _clearArmedNext's "provably never opened" close proof.

close #1869
2026-08-16 22:40:52 +02:00
github-actions[bot] d77836ef22 chore: update cask to 2.14.0 2026-08-16 16:38:32 +00:00
edde746 92b0524edb chore: bump version to 2.14.0 2026-08-16 17:00:37 +02:00
edde746 bb95d54bac style(android): fix ktlint violations in PgsCompositionParser 2026-08-16 16:57:27 +02:00
Aldo BarrerasandGitHub 36b2549506 Add loudnorm to enabled ffmpeg filters. (#1958) 2026-08-16 16:48:29 +02:00
edde746 9c6fcd2625 refactor(player): share one playback-open orchestration between start and reload
_startPlayback and _reloadMediaInPlace each inlined the same ~180-line open sequence around the playback_open.dart helpers — frame-rate prep, display priming, startup gate, external-subtitle plan, open, track manager build, track apply, gate release — with comments instructing that the two copies be kept in sync, and they had already drifted (live _isTranscoding vs result.isTranscoding, Watch Together attach vs detach/reattach).

The sequence now lives once in _openResolvedMedia; the genuine divergences are explicit parameters and caller hooks (transcoding source, WT handling, session-commit boundary, automotive start deferral, resume timing), so a future change to open sequencing lands in both flows by construction. Every await boundary and staleness guard keeps its original position in both flows.
2026-08-16 16:48:02 +02:00
edde746 24f63a63c5 refactor(libraries): make loadItems the single library-tab load hook
BaseLibraryTabState documented an abstract loadData() that every tab "must implement", but three of the four tabs override loadItems() entirely and carried never-invoked empty loadData stubs; only the recommended tab exercised the contract, so the class docs described an extension surface that did not exist.

loadItems() is now the one overridable hook, and the shared load transaction (generation tracking, localized error mapping, post-frame onDataLoaded) lives once in the protected runLoadTransaction helper that the recommended tab and the focus tests route through. No tab's load behavior changes.
2026-08-16 16:48:02 +02:00
edde746 364cdea59b refactor(libraries): show server labels with one policy in the picker and the dropdown
The library quick picker and the libraries dropdown each hand-rolled their own BackendBadge + server-name label rendering with divergent show-when policies: the picker only labeled libraries whose titles collided, so a uniquely-titled library on a multi-server list showed its server in the dropdown but not in the picker.

Both surfaces now share library_server_label.dart — one label widget, one grouping loop over groupLibrariesByFirstAppearance, and one policy: group headers whenever the visible list spans more than one server, per-row labels only in ungrouped lists. The picker's duplicate-title heuristic is gone; its test now pins the unified policy.
2026-08-16 16:48:02 +02:00
edde746 ab199b04cd refactor(profiles): resolve the active profile's Plex token through one shared helper
The job "which Plex token represents the active profile right now" was implemented three times against the same registries — the Discover session supplier, the Seerr token supplier, and UserProfileProvider's settings refresh — and the copies had already diverged on whether a Plex Home profile may fall back to the account token.

resolveActivePlexToken in lib/profiles/active_plex_token.dart now owns the policy: the per-user ProfileConnection token wins when present, else the account-owner token, with an explicit allowAccountTokenForHomeUser flag (true for Discover/Seerr, false for the settings refresh, which must not impersonate the owner). The three call sites keep only their genuine differences.
2026-08-16 16:48:02 +02:00
edde746 ef2ab13abd refactor(profiles): render the profile picker from ActiveProfileProvider
profiles_view.dart rebuilt the exact merged-profile view ActiveProfileProvider already computes — the same four source streams, the same merge/avatar derivation, plus a hand-rolled combineLatest4 — and the profile switch screen was its only consumer while already reading the provider for activeId.

The screen now renders from the provider (new connectionsByProfile/connectionsById/plexHomeByConnectionId getters) and gates loading on provider initialization; visibleProfileConnections moved to profile_merge.dart for profile_detail_screen; profiles_view.dart is deleted. The switch-screen tests initialize the provider up front like boot does, using a timer-less PlexHomeService subclass so start()'s periodic refresh timer cannot trip the widget-test pending-timer invariant; the deleted pipeline's merge assertions were ported to profile_merge_test and active_profile_provider_test.
2026-08-16 16:48:02 +02:00
edde746 fc061dc38d refactor(media): merge the two MediaStreamKind enums into one shared enum
lib/media declared two different enums named MediaStreamKind — a 4-value one in media_stream.dart and a 7-value one in media_file_info.dart — so any file importing both libraries silently picked one by import order.

media_stream.dart's enum now carries the full member set (image/data/lyric added before unknown; the original four ordinals are preserved) and media_file_info.dart re-exports it instead of declaring its own.
2026-08-16 16:48:01 +02:00
edde746 58b510a6c4 fix(music): handle hardware media keys while the app is foreground on Android
Media buttons on HID remotes (USB/Bluetooth keyboards, common on Android
TV) are delivered as key events to the focused window instead of the
MediaSession, so they only worked while the app was backgrounded. A
global handler now routes play/pause, next/previous, stop, and
fast-forward/rewind to the live music session anywhere in the app and
consumes the key burst, so a press can neither leak to Android's
fallback MediaSession dispatch nor start a focused library item. Same
lifecycle as the OS media session; video playback never coexists with it
because claiming video disposes the music session first.

close #1948
2026-08-16 16:47:06 +02:00
edde746 ec605fd8b7 fix(downloads): keep the parallel download limit intact on slow networks
On a slow connection a queued batch of episodes would end up
downloading all at once instead of one at a time. Every download that
hit Android's 9-minute background task limit re-enqueued its
continuation outside the native holding queue's accounting while the
interrupted run freed a slot, permanently raising the effective
concurrency; the notification Resume action leaked the same way on
both Android and iOS.

Pins background_downloader to a fork revision that routes timeout and
notification resumes through the holding queue, only adjusts its
counters for tasks the queue actually promoted, and periodically
recalculates Android queue state the way iOS already did.

close #1955
2026-08-16 16:22:03 +02:00
edde746 25b2939f0a fix(player): stop same-day Specials from hijacking up next
close #1952

Shows whose Season 0 holds aftershow featurettes (e.g. House of the
Dragon "Inside the Episode") share air dates with the episodes they
accompany, so the air-date interleave from #1416 queued them between
regular episodes: playing S03E04 offered S00E76/S00E84 as up next.

Air date alone cannot separate canon Specials from featurettes, so
Specials placement is now a three-way preference, defaulting to
"follow server order":

- respectServer: Plex keeps its server-built /allLeaves queue (aired
  order, Specials interleaved, as before); the Jellyfin queue now
  preserves the /Shows/{id}/Episodes response order, which is
  Jellyfin's native watch order — Specials placed only via explicit
  AirsBefore* metadata per the server-wide DisplaySpecialsWithinSeasons
  setting (the endpoint ignores SortBy except Random). Client-side
  selections with no server order to respect (offline next/prev,
  download "next N", offline OnDeck) fall back to Specials-last.
- airDate: the #1416 aired interleave on every surface.
- specialsLast: Specials strictly after the regular seasons (#1414);
  Plex builds its show queue from /children.
2026-08-16 15:31:47 +02:00
edde746 a7354cd3b6 fix(android): render every PGS composition object in ExoPlayer
PGS subtitles vanished or displaced each other when a display set put two
images on screen at once (dialogue plus a sign or song caption), and
palette-only fade updates blanked the subtitle entirely. media3's PgsParser
keeps one bitmap buffer and only the first composition object's coordinates,
and it discards all state between display sets.

Replace it with PgsCompositionParser, a port of FFmpeg's pgssubdec model:
epoch-scoped object/palette caches keyed by id, in-place palette updates,
one cue per composition object reference, and limited-range BT.709/BT.601
color conversion selected by plane height.

close #1953
2026-08-16 14:03:51 +02:00
edde746 eaccef33dc fix(subtitles): clear a displayed ASS cue immediately when subtitles are disabled
Turning subtitles off (or hiding them) while an ASS/SSA cue was on screen left
that cue painted until its natural end time on the ExoPlayer backend: AssHandler
nulls the libass track, after which every render returns null, no payload ever
reaches the GL thread again, and the overlay keeps its last swapped atlas. The
existing invalidateSubtitles() call from the #1387 fix could never repaint it.

The atlas pipeline now detects a trackless render request and hands the GL
thread one zero-quad payload, which clears and swaps a transparent frame. The
clear is keyed on the renderer state generation so one dropped as stale is
retried, and it self-heals from per-video-frame requests while playing; the
existing invalidate on the disable transition covers the paused case.

close #1884
2026-08-16 12:42:04 +02:00
edde746 2ff3b350ae feat(player): give sync delay sliders 50ms steps over a ±10s range
The sync delay slider spanned ±60s with 100ms steps, making fine
adjustment between e.g. 100ms and 200ms impractical on touch and mouse.
The slider now covers ±10s at 50ms per step (taps and D-pad included),
while the +/- step buttons still reach the ±60s absolute limit via
long-press, so existing large saved offsets keep working and display
their true value.

close #1907
2026-08-16 09:18:49 +02:00
edde746 bb642fce03 fix(plex): send Live TV favorite updates as JSON so they persist again
Adding or removing a Plex Live TV favorite channel never persisted: the PUT
to epg.provider.plex.tv/settings/favoriteChannels answered 400. The dio ->
package:http migration (15b22f75) lost dio's implicit JSON content type, so
the JSON-encoded favorites list went out as text/plain and the Plex cloud
refused to parse the body. Verified live: the identical payload succeeds
with application/json and the mutation persists.

MediaServerHttpClient now defaults content-type to application/json for
structured bodies. Callers and client defaults still win (the headers map
is case-insensitive and already populated), so Jellyfin's pinned default
and the octet-stream artwork upload are unaffected; favorites is the only
Plex request with a JSON body.

close #1878
2026-08-16 09:14:28 +02:00
edde746 8069683bd3 fix(ios): give music playback lock-screen and headphone controls
Music on iOS played through a mixable audio session: mpv's audiounit
output requests mixWithOthers unless audio-exclusive is set, and a
mixable session disqualifies the app from Now Playing. iOS ignored the
published metadata and remote-command targets, so the lock screen showed
no controls, headphone buttons drove the previous media app, and other
apps kept playing alongside plezy.

Set audio-exclusive on the audio-only core at init on iOS — the same
contract the video player already applies at playback start. Its only
effect there is dropping mixWithOthers.

close #1921
2026-08-16 09:00:49 +02:00
edde746 d1d393eec0 fix(plex): stop timeline heartbeats once the server terminates the session
Pausing past the server's paused-session limit (or an admin stop) removed
the session on PMS, but Plezy kept sending paused timeline heartbeats,
re-registering it as a zombie session the server could no longer clear.

Plex signals the termination with terminationCode/terminationText on the
MediaContainer of the next timeline reply. Detect it, close the reporting
session with one final stopped report at the current playhead (which
removes the session row), and suppress paused heartbeats plus the
transcode keepalive until playback actually resumes, which opens a fresh
server session.

close #1916
2026-08-16 08:58:57 +02:00
edde746 972b62f6fa fix(watch-together): tell lobby guests the room's control mode
Guests joining an "Anyone" room saw "Host controls playback" and a
locked room until the host actually started something. Control mode
only travelled inside the host's PlaybackState broadcast, and every
broadcast path requires an active media epoch, so an idle lobby had no
carrier at all: guests sat on the joinAsGuest hostOnly default. The v1
protocol's sessionConfig message covered this; the v3 rewrite lost it.

Carry the mode on the host's join messages instead: the directed join
reply every participant already sends to a new peer, and the host's
reconnect re-announce. The field is optional on the wire ('cm'), so
older clients ignore it and rooms with older hosts degrade to the
previous behavior. Guests apply it only from the relay-derived host
peer ID, never from a join's own spoofable isHost flag.

close #1950
2026-08-16 08:48:58 +02:00
edde746 ea528b5213 fix(macos): use CoreAudio for every audio format
The AVFoundation/CoreAudio split still left PCM on AVFoundation and maintained two macOS timing paths. Select CoreAudio as the sole macOS audio output so PCM and compressed streams share the HAL-backed implementation. This intentionally drops macOS AVFoundation spatialization; iOS and tvOS remain unchanged.
2026-08-15 20:09:35 +02:00
edde746 5a0b595466 fix(android): play MKV files with late track metadata
MKV files whose Tracks element follows media clusters could direct-play with audio but no video. Upgrade Media3 to 1.11.0 and cover the extractor regression.

close #1947
2026-08-15 19:08:00 +02:00
edde746 35b3e97730 fix(macos): route compressed audio through CoreAudio
AC3/EAC3 playback could stutter after AVFoundation began handling compressed streams. Decline compressed formats in macOS AVFoundation so mpv falls through to CoreAudio, while retaining AVFoundation for PCM and the tvOS Dolby path.

close #1940
2026-08-15 17:52:51 +02:00
edde746 2f0a6a6bf5 fix(android): preserve PGS subtitle display-plane aspect
PGS cues use their own composition plane, but ExoPlayer sized bitmap subtitles from the cropped video aspect, stretching and displacing them. Infer the plane aspect from Media3 cue geometry and fit it inside the visible video bounds.

close #1945
2026-08-15 15:05:14 +02:00
edde746 d623c2164f fix(player): exit on phone back even with the chrome up (#1938)
4443b761 staged the system-back path (strip/fullscreen/hide/exit), so on
Android a back with the controls visible hid them instead of closing the
player. The PlayerNavigationCoordinator now takes an exitPlayerBeforeChrome
policy; the player enables it on mobile, restoring immediate exit on Back
while TV/desktop keep the staged chrome handling.
2026-08-15 14:02:07 +02:00
Aldo BarrerasandGitHub 8383c7b73b chore: bump go server version, run formatter & regenerate podfile lock file checksum (#1944)
* Bump go server and run formatter.

* Regenerate Podfile lock file checksum.
2026-08-15 13:44:56 +02:00
edde746 be863a0c1c fix(linux): remove the Flutter-texture fallback permanently
The display-agnostic texture renderer restored by 9cdfe759 is deleted
again, this time for good: it is a second, SDR-only rendering stack
(isolated EGL context on Flutter's display plus EGL-image handoff) kept
alive solely to host sessions that cannot bring up the Wayland plane -
X11/XWayland or a failed plane bootstrap - and it was the source of the
native lifecycle and EGL state-churn fixes of the 9f2e0507 era. Linux
video now requires a Wayland compositor; a session that cannot host the
plane fails initialization with VIDEO_PLANE_UNSUPPORTED instead of
silently rendering through the second stack.

Reverts the restore commit's machinery: mpv_texture.cc/.h and
mpv_gpu_bootstrap.cc/.h deleted, the plugin's texture-registrar,
bootstrap, and waitForVideoReady paths removed, MpvPlayer's texture-mode
render-context API dropped, and the Dart-side renderMode setting, its
settings tile, translation keys, and the Player textureId member
withdrawn. The #1874 HDR diagnostic work is unaffected.
2026-08-15 01:20:44 +02:00
1197 changed files with 116517 additions and 25812 deletions
+2 -2
View File
@@ -3,5 +3,5 @@
!.maestro/jellyfin-demo/
!.maestro/jellyfin-demo/**
!scripts/
!scripts/maestro_fixtures.py
!scripts/maestro_real_jellyfin.py
!scripts/maestro/maestro_fixtures.py
!scripts/maestro/maestro_real_jellyfin.py
+2 -1
View File
@@ -77,11 +77,12 @@ body:
id: media-server
attributes:
label: Media Server
description: Are you using Jellyfin or Plex?
description: Are you using Jellyfin, Plex or Emby?
multiple: true
options:
- Jellyfin
- Plex
- Emby
validations:
required: true
@@ -71,6 +71,7 @@ body:
options:
- Jellyfin
- Plex
- Emby
validations:
required: true
+3 -3
View File
@@ -5,7 +5,7 @@ description: >-
subosito/flutter-action cannot resolve the release for arm64 (no arm64 entry
in the stable manifest) and `channel: master` would clone master HEAD, whose
engine is not the patched revision install-patched-engine.ps1 asserts
(4c525dac). This file is the only place that pin lives: the tag is fetched so
(5d531788). This file is the only place that pin lives: the tag is fetched so
the SDK reports its own version, then verified against the immutable commit
and against the version Flutter itself reports, so a moved tag fails the job
instead of quietly changing SDKs.
@@ -16,8 +16,8 @@ runs:
- name: Clone Flutter from its immutable commit
shell: pwsh
run: |
$version = "3.44.0"
$expectedCommit = "559ffa3f75e7402d65a8def9c28389a9b2e6fe42"
$version = "3.47.1"
$expectedCommit = "6655482ec06e547f90abf8ae7590466f4415978d"
$root = "$env:RUNNER_TEMP\flutter"
git init $root
git -C $root remote add origin https://github.com/flutter/flutter.git
+49 -21
View File
@@ -1,8 +1,13 @@
name: Build
run-name: ${{ inputs.release_tag != '' && format('Release {0}', inputs.release_tag) || format('Build {0}', github.sha) }}
on:
workflow_dispatch:
inputs:
release_tag:
description: Tag for a draft release; omit to build Actions artifacts only
default: ''
type: string
build_android:
description: Build Android
default: true
@@ -26,7 +31,7 @@ on:
env:
# Only place this workflow names the SDK; .github/actions/setup-flutter-git pins the same release.
FLUTTER_VERSION: "3.44.0"
FLUTTER_VERSION: "3.47.1"
# Shared by every release build command; SENTRY_DIST stays per-platform.
RELEASE_DART_DEFINES: --dart-define=ENABLE_UPDATE_CHECK=true ${{ github.repository == 'edde746/plezy' && '--dart-define=ENABLE_SENTRY=true' || '' }} --dart-define=GIT_COMMIT=${{ github.sha }} --dart-define=SENTRY_ENVIRONMENT=github --dart-define=ENABLE_DONATIONS=true
TRUSTED_BUILD_CACHE_VERSION: trusted-build-v1
@@ -409,9 +414,7 @@ jobs:
- arch: arm64
runner: windows-11-arm
flutter_setup: git
native_cache_path: |
build/windows/arm64/_deps
build/windows/arm64/mpv-dev-arm64
native_cache_path: build/windows/arm64/_deps
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
@@ -422,12 +425,7 @@ jobs:
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
with:
path: ${{ matrix.native_cache_path }}
key: ${{ env.TRUSTED_BUILD_CACHE_VERSION }}-windows-native-${{ matrix.arch }}-${{ hashFiles('windows/CMakeLists.txt') }}
- name: Install 7-Zip
if: matrix.arch == 'arm64' && steps.windows-native-cache.outputs.cache-hit != 'true'
shell: pwsh
run: choco install 7zip -y
key: ${{ env.TRUSTED_BUILD_CACHE_VERSION }}-windows-native-${{ matrix.arch }}-${{ hashFiles('windows/CMakeLists.txt', 'mpv-build.lock.json') }}
- name: Setup Flutter
if: matrix.flutter_setup == 'action'
@@ -580,10 +578,10 @@ jobs:
- name: Read version from pubspec
id: version
shell: pwsh
shell: bash
run: |
$v = (Select-String -Path pubspec.yaml -Pattern '^version:\s*(\S+)').Matches[0].Groups[1].Value -replace '\+.*'
echo "version=$v" >> $env:GITHUB_OUTPUT
VERSION=$(python3 scripts/pubspec_version.py pubspec.yaml)
echo "version=${VERSION%%+*}" >> "$GITHUB_OUTPUT"
- name: Build installer and portables
run: .\windows\build-installer.ps1 -X64BuildDir "build-x64" -Arm64BuildDir "build-arm64" -Version "${{ steps.version.outputs.version }}"
@@ -720,17 +718,26 @@ jobs:
exit 1
- name: Cache libmpv build
- name: Cache libmpv prefix
id: libmpv-cache
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
with:
path: libmpv-prefix
key: ${{ env.TRUSTED_BUILD_CACHE_VERSION }}-libmpv-${{ runner.arch }}-${{ hashFiles('linux/packaging/build-libmpv.sh', 'linux/packaging/native-inputs.json') }}
key: ${{ env.TRUSTED_BUILD_CACHE_VERSION }}-libmpv-${{ runner.arch }}-${{ hashFiles('mpv-build.lock.json') }}
- name: Build libmpv
# The prebuilt prefix from our unified mpv-build repo: the script reads
# the asset and expected SHA-256 from the lock and verifies the bytes
# before a single one is extracted. The tarball is a self-relocating
# prefix tree (lib/ or lib/<triplet>/ with the libmpv.so* chain,
# lib/libshaderc_shared.so*, include/, and pkgconfig/ dirs with
# ${pcfiledir}-relative roots), so the downstream PKG_CONFIG_PATH,
# bundle-copy, and find steps are unchanged.
- name: Fetch libmpv
if: steps.libmpv-cache.outputs.cache-hit != 'true'
shell: bash
run: bash linux/packaging/build-libmpv.sh
run: |
command -v zstd >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y --no-install-recommends zstd; }
python3 scripts/fetch_linux_libmpv.py --dest libmpv-prefix
- name: Install fpm
shell: bash
@@ -860,25 +867,43 @@ jobs:
create-release:
needs: [validate-trusted-ref, build-android, build-ios, build-macos, build-windows, package-windows, build-linux]
if: ${{ always() && needs.validate-trusted-ref.result == 'success' && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && inputs.build_android && inputs.build_ios && inputs.build_macos && inputs.build_windows && inputs.build_linux }}
if: ${{ always() && needs.validate-trusted-ref.result == 'success' && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && inputs.build_android && inputs.build_ios && inputs.build_macos && inputs.build_windows && inputs.build_linux && inputs.release_tag != '' }}
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
sparse-checkout: pubspec.yaml
sparse-checkout: |
pubspec.yaml
scripts/pubspec_version.py
sparse-checkout-cone-mode: false
persist-credentials: false
- name: Read version from pubspec.yaml
id: version
run: |
VERSION=$(grep '^version:' pubspec.yaml | sed 's/version: //' | sed 's/+.*//')
BUILD_NUMBER=$(grep '^version:' pubspec.yaml | sed 's/.*+//')
VERSION=$(python3 scripts/pubspec_version.py pubspec.yaml)
BUILD_NUMBER=${VERSION#*+}
VERSION=${VERSION%%+*}
echo "version=$VERSION" >> $GITHUB_OUTPUT
echo "build_number=$BUILD_NUMBER" >> $GITHUB_OUTPUT
- name: Validate release tag
if: ${{ inputs.release_tag != '' }}
env:
RELEASE_TAG: ${{ inputs.release_tag }}
VERSION: ${{ steps.version.outputs.version }}
run: |
if [[ ! "$RELEASE_TAG" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "Release tag must use semantic versioning: $RELEASE_TAG" >&2
exit 1
fi
if [[ "$RELEASE_TAG" != "$VERSION" ]]; then
echo "Release tag $RELEASE_TAG does not match pubspec version $VERSION." >&2
exit 1
fi
- name: Download Android artifacts
if: ${{ inputs.build_android }}
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
@@ -1043,5 +1068,8 @@ jobs:
files: ${{ steps.release-files.outputs.files }}
draft: true
prerelease: false
name: ${{ inputs.release_tag }}
tag_name: ${{ inputs.release_tag }}
target_commitish: ${{ github.sha }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+29 -25
View File
@@ -20,7 +20,7 @@ on:
env:
# Only place this workflow names the SDK; .github/actions/setup-flutter-git pins the same release.
FLUTTER_VERSION: "3.44.0"
FLUTTER_VERSION: "3.47.1"
jobs:
analyze:
@@ -62,7 +62,7 @@ jobs:
run: scripts/codegen.sh --check
- name: Verify translation hygiene
run: python3 scripts/clean_translations.py --check --strict
run: python3 scripts/checks/clean_translations.py --check --strict
- name: Verify workflow and script guards
run: bash scripts/ci_guard_checks.sh
@@ -75,10 +75,10 @@ jobs:
xargs -0 -r dart format --output=none --set-exit-if-changed
- name: Verify icon consistency
run: dart run scripts/check_icon_consistency.dart
run: dart run scripts/checks/check_icon_consistency.dart
- name: Analyze code
run: dart run scripts/check_analyzer.dart
run: dart run scripts/checks/check_analyzer.dart
- name: Check for unused code
run: |
@@ -252,9 +252,6 @@ jobs:
- name: Verify native formatting
run: scripts/format_native.sh --check
- name: Verify Linux native acquisition and build plan
run: bash linux/packaging/build-libmpv_test.sh
linux-native-test:
name: Linux native reliability (${{ matrix.sanitizer }})
runs-on: ubuntu-latest
@@ -317,7 +314,8 @@ jobs:
mpv_property_result_contract_test \
hdr_metadata_test \
plane_geometry_test \
video_params_test
video_params_test \
plane_render_executor_test
- name: Run Linux native reliability tests
run: |
@@ -403,7 +401,9 @@ jobs:
- name: Verify tvOS project wiring
if: matrix.platform == 'tvOS'
run: ruby tvos/scripts/test_wire_mpv.rb
run: |
ruby tvos/scripts/test_wire_mpv.rb
ruby tvos/scripts/test_wire_top_shelf.rb
- name: Select Apple test destination
env:
@@ -644,10 +644,10 @@ jobs:
cache: true
pub-cache: false
# The packaging deps, minus libmpv: this job builds it from source below,
# because the distro's is a different version with different windowing
# backends, and a package smoke-built against it cannot show that
# build-libmpv.sh still works or that the bundle it produces is coherent.
# The packaging deps, minus libmpv: that arrives prebuilt from mpv-build
# below. The dev packages still matter — they install the runtime
# libraries the pinned libmpv links (ass, pulse, pipewire, ...), which
# bundle-libs.sh resolves off the host into the bundle.
- name: Install packaging dependencies
run: |
sudo apt-get update
@@ -661,25 +661,29 @@ jobs:
liblua5.2-dev rpm libarchive-tools imagemagick ruby-dev build-essential
sudo gem install fpm --version 1.17.0 --no-document
# Keyed the same way build.yml keys it, so editing the script or its pinned
# inputs is what invalidates the cache - and this branch's whole point is
# that those edits get exercised somewhere.
- name: Cache libmpv build
# Keyed the same way build.yml keys it: the lock names the asset and its
# checksum, so editing the lock is what invalidates the cache.
- name: Cache libmpv prefix
id: libmpv-cache
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
with:
path: libmpv-prefix
key: ci-libmpv-${{ runner.arch }}-${{ hashFiles('linux/packaging/build-libmpv.sh', 'linux/packaging/native-inputs.json') }}
key: ci-libmpv-${{ runner.arch }}-${{ hashFiles('mpv-build.lock.json') }}
- name: Build libmpv
# Same contract as build.yml: the script reads mpv-build.lock.json,
# downloads the linux asset for this arch, verifies its SHA-256, and
# extracts the prefix tree.
- name: Fetch libmpv
if: steps.libmpv-cache.outputs.cache-hit != 'true'
run: bash linux/packaging/build-libmpv.sh
run: |
command -v zstd >/dev/null 2>&1 || { sudo apt-get update && sudo apt-get install -y --no-install-recommends zstd; }
python3 scripts/fetch_linux_libmpv.py --dest libmpv-prefix
# The windowing backends the runner depends on, read off the library the
# script just produced. The plane hands mpv MPV_RENDER_PARAM_WL_DISPLAY, so
# a libmpv without Wayland cannot find the VAAPI device and quietly decodes
# in software; X11 and VDPAU are gone with the texture path.
- name: Check the built libmpv's backends
# The windowing backends the runner depends on, read off the pinned
# library just extracted. The plane hands mpv MPV_RENDER_PARAM_WL_DISPLAY,
# so a libmpv without Wayland cannot find the VAAPI device and quietly
# decodes in software; X11 and VDPAU are gone with the texture path.
- name: Check the pinned libmpv's backends
run: |
LIB=$(find libmpv-prefix -name 'libmpv.so.2' | head -1)
echo "== $LIB =="
+1 -1
View File
@@ -10,7 +10,7 @@ RUN apt-get update \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /opt/plezy-demo
COPY scripts/maestro_fixtures.py scripts/maestro_real_jellyfin.py scripts/prepare_maestro_media.py ./
COPY scripts/maestro/maestro_fixtures.py scripts/maestro/maestro_real_jellyfin.py scripts/maestro/prepare_maestro_media.py ./
COPY .maestro/jellyfin-demo/seed.sh ./seed.sh
ARG PLEZY_DEMO_MEDIA_BASE_URL=https://demo-files.plezy.app/media-samples/
+11 -7
View File
@@ -16,6 +16,10 @@
- Run `scripts/run_tests.sh` to run the test suite (same as `flutter test`, but scaled to your core count)
- Test your changes thoroughly
### AI-assisted contributions
AI-assisted pull requests must state in the PR description which model(s) were used (e.g. Claude Sonnet 4.5, GPT-5, Gemini 3 Pro).
### Code Quality Checks
The project includes automated CI checks that run on all pull requests:
@@ -51,22 +55,22 @@ Prerequisites: Java 17, Flutter and Android SDK/platform tools, a running Androi
Run the suites from the repository root (`py -3` can replace `python3` on Windows):
```bash
python3 scripts/run_maestro.py basic # Basic user flows
python3 scripts/run_maestro.py catalog # Catalog and music flows
python3 scripts/run_maestro.py media # Codec playback and track selection
python3 scripts/maestro/run_maestro.py basic # Basic user flows
python3 scripts/maestro/run_maestro.py catalog # Catalog and music flows
python3 scripts/maestro/run_maestro.py media # Codec playback and track selection
```
Run one flow with `--flow`:
```bash
python3 scripts/run_maestro.py basic --flow .maestro/flows/04_search.yaml
python3 scripts/maestro/run_maestro.py basic --flow .maestro/flows/04_search.yaml
```
Use `--skip-build` to reuse the debug APK and `--skip-jellyfin-build` to reuse the Jellyfin image. Set
`--device <adb-serial>` when multiple devices are connected; physical devices also require `--adb-reverse`.
Top-level flows live in `.maestro/flows/`, shared setup in `.maestro/subflows/`, and focused regressions in
`.maestro/regression_flows/`. Automatic groups are declared in `scripts/run_maestro_ci.py::GROUPS`. Every top-level
`.maestro/regression_flows/`. Automatic groups are declared in `scripts/maestro/run_maestro_ci.py::GROUPS`. Every top-level
regression flow must be registered either there or in `DESTRUCTIVE_MANUAL_TARGETS`; reusable subflows are not
independent tests. A manual-only classification must state why the flow cannot run automatically.
@@ -75,7 +79,7 @@ manual target rather than an automatic group. Run them only against the pre-seed
emulator, using the required opt-in:
```bash
python3 scripts/run_maestro_ci.py profile-regressions --disposable-emulator
python3 scripts/maestro/run_maestro_ci.py profile-regressions --disposable-emulator
```
The target refuses to start without `--disposable-emulator`. Each profile flow writes to its own Jellyfin log and
@@ -102,7 +106,7 @@ Update a production image only through a reviewed change:
4. Before changing the Bugs digest, exercise it with non-production configuration and a disposable volume. Review
migrations, take a restorable `bugs_data` backup, then validate a cloned volume. A forward-only migration rolls back
with the prior digest and pre-change backup, not by changing the image reference alone.
5. Run `python3 scripts/check_container_image_pins.py`, `python3 scripts/test_check_container_image_pins.py`, and
5. Run `python3 scripts/checks/check_container_image_pins.py`, `python3 scripts/checks/test_check_container_image_pins.py`, and
`(cd server && go test ./...)`. Inspect the rendered Compose configuration and rebuilt images locally without
exposing configuration values. Do not publish or deploy from a review checkout, and never fall back to `latest` when
a digest is unavailable.
+6 -6
View File
@@ -1,6 +1,6 @@
cask "plezy" do
version "2.13.0"
sha256 "045f632883b3418a509c95170fc7767b619280873a66c8d96aa71e01cd35408d"
version "2.19.1"
sha256 "7d3ffd0efccf4db5faf063e8ecc03e897ee30d08e9fa3b007d127c63cbf187e2"
url "https://github.com/edde746/plezy/releases/download/#{version}/plezy-macos.dmg"
name "Plezy"
@@ -16,10 +16,10 @@ cask "plezy" do
app "Plezy.app"
postflight do
system_command "/usr/bin/xattr",
args: ["-cr", "#{appdir}/Plezy.app"],
sudo: false
postflight_steps do
run "/usr/bin/xattr",
args: ["-cr", "{{appdir}}/Plezy.app"],
sudo: false
end
uninstall quit: "com.edde746.plezy"
+48 -18
View File
@@ -30,22 +30,47 @@ A modern client for Plex, Jellyfin, and Emby on desktop, mobile, and TV. Built w
| Linux x64 | [.deb](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-x64.deb) · [.rpm](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-x64.rpm) · [.pkg.tar.zst](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-x64.pkg.tar.zst) · [portable tar.gz](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-x64.tar.gz) |
| Linux arm64 | [.deb](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-arm64.deb) · [.rpm](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-arm64.rpm) · [.pkg.tar.zst](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-arm64.pkg.tar.zst) · [portable tar.gz](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-arm64.tar.gz) |
Package managers:
<details>
<summary>Install with a package manager</summary>
- [Nix](https://search.nixos.org/packages?channel=unstable&query=plezy) - Community package by [@mio-19](https://github.com/mio-19) and [@MiniHarinn](https://github.com/MiniHarinn)
- **Homebrew** (macOS):
```bash
brew tap edde746/plezy https://github.com/edde746/plezy
brew install --cask plezy
```
- [Pacman](https://archlinux.org/packages/extra/x86_64/plezy/) (Arch Linux) - Official package:
```bash
sudo pacman -S plezy
```
- **WinGet** (Windows):
```bash
winget install edde746.Plezy
```
### macOS — Homebrew
```bash
brew tap edde746/plezy https://github.com/edde746/plezy
brew install --cask plezy
```
### Windows — WinGet
```bash
winget install edde746.Plezy
```
### Arch Linux — Pacman
[Distribution package](https://archlinux.org/packages/extra/x86_64/plezy/).
```bash
sudo pacman -S plezy
```
### Fedora / Red Hat — DNF
[Installation instructions](https://github.com/aldobarr/plezy-rpm) · Community repository by [@aldobarr](https://github.com/aldobarr).
### Nix
[Community package](https://search.nixos.org/packages?channel=unstable&query=plezy) maintained by [@mio-19](https://github.com/mio-19) and [@MiniHarinn](https://github.com/MiniHarinn).
### aerynOS — Moss
[Distribution package](https://github.com/aerynOS/recipes/tree/main/p/plezy).
```bash
sudo moss it plezy
```
</details>
## Features
@@ -110,6 +135,11 @@ Package managers:
### <img src="assets/readme_icons/watch-together.svg" height="20" alt="" align="center" /> Watch Together
- Synchronized playback with friends
- Real-time play / pause / seek sync
- Host handoff when the relay and every connected peer support safe transfers
- Automatic reconnect authenticates retained room membership; it never silently joins a reused room code.
Self-hosted relays must support `authenticatedResume` for recovery. Deploy the updated relay before updating clients.
Older relays still accept explicit create/join, but failed recovery requires joining or creating a room again.
### <img src="assets/readme_icons/integrations.svg" height="20" alt="" align="center" /> Integrations
- Discord Rich Presence[^desktop]
@@ -148,7 +178,7 @@ Package managers:
## Building from Source
### Prerequisites
- Flutter SDK 3.44.0+
- Flutter SDK 3.47.0+
- A Plex account, or a Jellyfin or Emby server with user credentials
### Setup
@@ -190,7 +220,7 @@ scripts/setup_hooks.sh
End-to-end tests (Android emulator plus a Dockerized Jellyfin fixture):
```bash
python3 scripts/run_maestro.py basic
python3 scripts/maestro/run_maestro.py basic
```
## Contributing
@@ -205,4 +235,4 @@ Plezy is licensed under [GPL-3.0](LICENSE).
- Built with [Flutter](https://flutter.dev)
- Supports [Plex Media Server](https://www.plex.tv), [Jellyfin](https://jellyfin.org), and [Emby](https://emby.media)
- Playback powered by [mpv](https://mpv.io), [MPVKit](https://github.com/mpvkit/MPVKit), Android [ExoPlayer](https://developer.android.com/media/media3/exoplayer), [libass-android](https://github.com/peerless2012/libass-android), and [libmpv-android](https://github.com/jarnedemeulemeester/libmpv-android)
- Playback powered by [mpv](https://mpv.io) via our [mpv-build](https://github.com/edde746/mpv-build) pipeline (started as a fork of [MPVKit](https://github.com/mpvkit/MPVKit); the Android Kotlin/JNI glue descends from [libmpv-android](https://github.com/jarnedemeulemeester/libmpv-android)), Android [ExoPlayer](https://developer.android.com/media/media3/exoplayer), and [libass-android](https://github.com/peerless2012/libass-android)
+7
View File
@@ -4,6 +4,13 @@ analyzer:
exclude:
- "**/*.g.dart"
- "**/*.freezed.dart"
- build/**
- android/**
- ios/**
- web/**
- windows/**
- macos/**
- linux/**
linter:
rules:
+32 -81
View File
@@ -58,82 +58,31 @@ plugins {
id("dev.flutter.flutter-gradle-plugin")
}
val mpvVersion = "v1.0.7"
val mpvSha256 = "d55d440e587b2a9ffb91874d93069460a987be05fe72af8394849983f0df2d7a"
val mpvDir = layout.buildDirectory.dir("libmpv").get().asFile
val mpvAar = "libmpv-release.aar"
val mpvUrl = "https://github.com/edde746/libmpv-android/releases/download/$mpvVersion/$mpvAar"
// The in-project :libmpv module owns the mpv-build pin (repo-root
// mpv-build.lock.json assets + checksums, plus the plezy.localMpvDir/
// PLEZY_LOCAL_MPV_DIR escape hatch) and extracts the per-ABI tarballs'
// prebuilt native libraries. This file reads two of its output trees
// back: FFmpeg .so files for the Media3 adapter link step, and the libc++
// runtime packaged at PROJECT scope below.
val libmpvBuildDir = project(":libmpv").layout.buildDirectory.dir("libmpv").get().asFile
val libmpvNativeJniDir = File(libmpvBuildDir, "native/jni")
val libmpvLibcxxJniDir = File(libmpvBuildDir, "libcxx/jni")
val media3Version = "1.10.1"
val media3Version = "1.11.0"
val mpvFfmpegVersion = "8.0.1"
val mpvFfmpegSourceSha256 = "05ee0b03119b45c0bdb4df654b96802e909e0a752f72e4fe3794f487229e5a41"
val mpvFfmpegSourceUrl = "https://ffmpeg.org/releases/ffmpeg-$mpvFfmpegVersion.tar.xz"
val mpvFfmpegDevelopmentDir = File(mpvDir, "ffmpeg-development")
val downloadLibmpv = tasks.register("downloadLibmpv") {
val aar = File(mpvDir, mpvAar)
val manifest = File(mpvDir, ".manifest")
inputs.property("version", mpvVersion)
inputs.property("sourceUrl", mpvUrl)
inputs.property("sha256", mpvSha256)
outputs.files(aar, manifest)
doLast {
mpvDir.parentFile.mkdirs()
val staging = File(mpvDir.parentFile, "${mpvDir.name}.staging-${UUID.randomUUID()}")
try {
staging.mkdirs()
val stagedAar = File(staging, mpvAar)
try {
providers.exec {
commandLine("curl", "-sfL", mpvUrl, "-o", stagedAar.absolutePath)
}.result.get().assertNormalExitValue()
} catch (error: Exception) {
throw GradleException("Failed to download $mpvAar $mpvVersion", error)
}
verifySha256(stagedAar, mpvSha256, "$mpvAar $mpvVersion")
File(staging, ".manifest").writeText("version=$mpvVersion\nsha256=$mpvSha256\n")
promoteDirectory(staging, mpvDir)
} finally {
staging.deleteRecursively()
}
}
}
// Extract libc++_shared.so from the libmpv AAR so the app source set can package
// it with top merge priority (see packaging { jniLibs } and sourceSets below).
val extractMpvLibcxx = tasks.register("extractMpvLibcxx") {
dependsOn(downloadLibmpv)
val aar = File(mpvDir, mpvAar)
val outDir = File(mpvDir, "libcxx")
inputs.file(aar)
outputs.dir(outDir)
doLast {
outDir.deleteRecursively() // drop stale ABIs from a previous AAR version
outDir.mkdirs()
providers.exec {
commandLine(
"unzip",
"-q",
"-o",
aar.absolutePath,
"jni/*/libc++_shared.so",
"-d",
outDir.absolutePath
)
}.result.get().assertNormalExitValue()
}
}
val mpvFfmpegDevelopmentDir = layout.buildDirectory.dir("libmpv-ffmpeg-development").get().asFile
// Build the Media3 JNI adapter against the same shared FFmpeg libraries that
// libmpv packages. Headers are pinned to libmpv's FFmpeg version and remain
// build-only; the APK contains one FFmpeg implementation for both players.
val prepareMpvFfmpegDevelopment = tasks.register("prepareMpvFfmpegDevelopment") {
dependsOn(downloadLibmpv)
val aar = File(mpvDir, mpvAar)
dependsOn(":libmpv:extractLibmpvNative")
val manifest = File(mpvFfmpegDevelopmentDir, ".manifest")
val abis = listOf("arm64-v8a", "armeabi-v7a", "x86", "x86_64")
val libraries = listOf("avcodec", "avutil", "swresample")
inputs.file(aar)
inputs.dir(libmpvNativeJniDir)
inputs.property("ffmpegVersion", mpvFfmpegVersion)
inputs.property("sourceUrl", mpvFfmpegSourceUrl)
inputs.property("sourceSha256", mpvFfmpegSourceSha256)
@@ -203,15 +152,12 @@ val prepareMpvFfmpegDevelopment = tasks.register("prepareMpvFfmpegDevelopment")
)
project.copy {
from(zipTree(aar)) {
from(libmpvNativeJniDir) {
include(
"jni/*/libavcodec.so",
"jni/*/libavutil.so",
"jni/*/libswresample.so"
"*/libavcodec.so",
"*/libavutil.so",
"*/libswresample.so"
)
eachFile {
path = path.removePrefix("jni/")
}
}
includeEmptyDirs = false
into(nativeDir)
@@ -222,11 +168,11 @@ val prepareMpvFfmpegDevelopment = tasks.register("prepareMpvFfmpegDevelopment")
}.filterNot(File::isFile)
if (missing.isNotEmpty()) {
throw GradleException(
"libmpv $mpvVersion is missing FFmpeg libraries: ${missing.joinToString { it.relativeTo(staging).path }}"
"the :libmpv prebuilt tree is missing FFmpeg libraries: ${missing.joinToString { it.relativeTo(staging).path }}"
)
}
File(staging, ".manifest").writeText(
"mpv=$mpvVersion\nffmpeg=$mpvFfmpegVersion\nsourceSha256=$mpvFfmpegSourceSha256\n"
"ffmpeg=$mpvFfmpegVersion\nsourceSha256=$mpvFfmpegSourceSha256\n"
)
sourceArchive.delete()
extractedSource.deleteRecursively()
@@ -336,7 +282,7 @@ android {
defaultConfig {
applicationId = "com.edde746.plezy"
minSdk = 25 // Fire OS 6.x (API 25); overrides libmpv-android's minSdk=26
minSdk = 25 // Fire OS 6.x (API 25); :libmpv shares the same floor
targetSdk = flutter.targetSdkVersion
versionCode = flutter.versionCode
versionName = flutter.versionName
@@ -435,8 +381,9 @@ android {
packaging {
jniLibs {
// pickFirst only suppresses the duplicate libc++ merge error; the
// sourceSets rule below makes libmpv's newer runtime win for
// std::from_chars<float>, while older native consumers remain ABI-compatible.
// sourceSets rule below makes the runtime :libmpv extracts from the
// mpv-build tarballs win for std::from_chars<float>, while older
// native consumers remain ABI-compatible.
pickFirsts.add("lib/*/libc++_shared.so")
}
}
@@ -444,8 +391,10 @@ android {
sourceSets {
getByName("main") {
// PROJECT-scope jniLibs merge ahead of subprojects/AARs, so dependency
// order cannot accidentally select the older libc++ copy.
jniLibs.srcDir(File(mpvDir, "libcxx/jni"))
// order cannot accidentally select an older libc++ copy. The directory
// is :libmpv's extractLibmpvNative output (the tarballs' 16 KB-capable
// libc++), wired below via the JniLibFolders dependency.
jniLibs.srcDir(libmpvLibcxxJniDir)
}
}
@@ -501,16 +450,18 @@ tasks.matching { it.name.contains("CMake") || it.name.contains("externalNative")
}
tasks.matching { it.name.startsWith("pre") && it.name.endsWith("Build") }.configureEach {
dependsOn(downloadLibmpv, extractMpvLibcxx, prepareMpvFfmpegDevelopment)
dependsOn(prepareMpvFfmpegDevelopment)
}
// Gradle snapshots jniLibs source dirs before task execution; this keeps the
// extracted libmpv libc++ directory present during input discovery.
tasks.matching { it.name.startsWith("merge") && it.name.endsWith("JniLibFolders") }.configureEach {
dependsOn(extractMpvLibcxx)
dependsOn(":libmpv:extractLibmpvNative")
}
dependencies {
implementation(files(File(mpvDir, mpvAar)))
// mpv Kotlin API + JNI glue live in-project; the prebuilt libmpv/FFmpeg .so
// set rides along from the module's extracted mpv-build tarballs.
implementation(project(":libmpv"))
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.11.0")
// Android TV Watch Next integration
+17
View File
@@ -18,3 +18,20 @@
# growOutputBuffer's JNI descriptor names this type, so it may not be renamed either.
-keep class androidx.media3.decoder.SimpleDecoderOutputBuffer { *; }
# MatroskaExtractor.init is final and its ExtractorOutput / subtitle scratch buffer live
# in private fields, so the extractor wrappers reach both by name: AssMatroskaExtractor
# (android/libass/.../media/extractor/AssMatroskaExtractor.kt) resolves extractorOutput
# and subtitleSample with getDeclaredField to redirect ASS subtitle samples, and
# MatroskaLatmSupport (android/app/.../exoplayer/MatroskaLatmSupport.kt) resolves
# extractorOutput the same way to wrap LATM tracks.
#
# R8 renaming either field makes getDeclaredField throw; AssMatroskaExtractor resolves
# them in its companion object, so the throw surfaces as ExceptionInInitializerError
# while constructing the extractor every MKV direct-play, release builds only. Only
# the *names* need pinning: MatroskaExtractor uses both fields itself, so they survive
# shrinking through the compile-time subclass references.
-keepclassmembernames class androidx.media3.extractor.mkv.MatroskaExtractor {
private androidx.media3.extractor.ExtractorOutput extractorOutput;
private androidx.media3.common.util.ParsableByteArray subtitleSample;
}
@@ -0,0 +1,171 @@
package com.edde746.plezy.exoplayer
import android.net.Uri
import android.os.Handler
import android.os.HandlerThread
import android.util.Log
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.datasource.DefaultDataSource
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.source.ProgressiveMediaSource
import androidx.media3.extractor.Extractor
import androidx.media3.extractor.ExtractorsFactory
import androidx.media3.extractor.mkv.MatroskaExtractor
import androidx.media3.extractor.text.DefaultSubtitleParserFactory
import androidx.test.platform.app.InstrumentationRegistry
import com.edde746.plezy.libass.media.AssHandler
import com.edde746.plezy.libass.media.parser.AssSubtitleParserFactory
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* On-device coverage for MKV files whose SeekHead references Tracks after the Clusters (#1969).
*
* media3 1.11.0 builds the Matroska seek map at the end of the Cues element, which for these files
* is before the Tracks element parsed, so the map permanently reports unseekable and ExoPlayer
* coerces every seek to t=0 (ProgressiveMediaPeriod; tracking issue androidx/media #3377). The
* first test is a canary asserting the upstream defect against a stock MatroskaExtractor — when it
* fails after a media3 upgrade, the TrackAwareSeekMap repair in [CuelessSeekExtractorWrapper] can
* be retired. The second test drives the production wrapper stack and requires the seek to
* actually land.
*/
class MatroskaLateTracksSeekDeviceTest {
private companion object {
const val TAG = "MkvLateTracksSeek"
const val SEEK_TARGET_MS = 500L
const val SETTLE_MS = 2_000L
}
private class Session(
val handler: Handler,
val thread: HandlerThread,
val player: AtomicReference<ExoPlayer?>,
val fixture: File
)
@Test
fun stockMatroskaExtractorSnapsSeeksToStart() {
val result = runSeekScenario("stock") { MatroskaExtractor(DefaultSubtitleParserFactory()) }
assertFalse(
"upstream media3 now reports tracks-after-clusters MKVs seekable — " +
"the TrackAwareSeekMap repair in CuelessSeekExtractorWrapper can be retired",
result.seekable
)
assertTrue(
"unseekable media must snap the seek to the start, position=${result.positionAfterSeekMs}ms",
result.positionAfterSeekMs < SEEK_TARGET_MS / 2
)
}
@Test
fun wrappedExtractorKeepsSeekPosition() {
val result = runSeekScenario("wrapped") {
val assHandler = AssHandler()
CuelessSeekExtractorWrapper(ZlibMatroskaExtractor(AssSubtitleParserFactory(assHandler), assHandler))
}
assertTrue("wrapped extractor must report the item seekable", result.seekable)
assertTrue(
"seek to ${SEEK_TARGET_MS}ms must hold, position=${result.positionAfterSeekMs}ms",
result.positionAfterSeekMs >= SEEK_TARGET_MS / 2
)
}
private class ScenarioResult(val seekable: Boolean, val positionAfterSeekMs: Long)
private fun runSeekScenario(label: String, extractorFactory: () -> Extractor): ScenarioResult {
val session = openPaused(label, extractorFactory)
try {
val seekable = onPlayerThread(session) { it.isCurrentMediaItemSeekable }
session.handler.post { session.player.get()?.seekTo(SEEK_TARGET_MS) }
// The masked position is the seek target; the snap surfaces once the period resolves the
// seek, so give the load a moment before sampling the settled position.
Thread.sleep(SETTLE_MS)
val positionAfterSeekMs = onPlayerThread(session) { it.currentPosition }
Log.i(TAG, "==== $label: seekable=$seekable position=${positionAfterSeekMs}ms ====")
return ScenarioResult(seekable, positionAfterSeekMs)
} finally {
teardown(session)
}
}
private fun openPaused(label: String, extractorFactory: () -> Extractor): Session {
val instrumentation = InstrumentationRegistry.getInstrumentation()
val context = instrumentation.targetContext
val fixture = copyFixture(context)
val thread = HandlerThread("mkv-late-tracks-$label").apply { start() }
val handler = Handler(thread.looper)
val player = AtomicReference<ExoPlayer?>(null)
val ready = CountDownLatch(1)
val failed = AtomicBoolean(false)
handler.post {
val exo = ExoPlayer.Builder(context).build()
player.set(exo)
exo.addListener(
object : Player.Listener {
override fun onPlaybackStateChanged(playbackState: Int) {
if (playbackState == Player.STATE_READY) ready.countDown()
}
override fun onPlayerError(error: androidx.media3.common.PlaybackException) {
Log.e(TAG, "$label player error", error)
failed.set(true)
ready.countDown()
}
}
)
val source = ProgressiveMediaSource.Factory(
DefaultDataSource.Factory(context),
ExtractorsFactory { arrayOf(extractorFactory()) }
).createMediaSource(MediaItem.fromUri(Uri.fromFile(fixture)))
exo.setMediaSource(source)
exo.playWhenReady = false
exo.prepare()
}
val session = Session(handler, thread, player, fixture)
if (!ready.await(30, TimeUnit.SECONDS) || failed.get()) {
teardown(session)
error("$label playback never became ready")
}
return session
}
private fun <T> onPlayerThread(session: Session, read: (ExoPlayer) -> T): T {
val value = AtomicReference<T>()
val done = CountDownLatch(1)
session.handler.post {
session.player.get()?.let { value.set(read(it)) }
done.countDown()
}
assertTrue("player thread stalled", done.await(5, TimeUnit.SECONDS))
return checkNotNull(value.get())
}
private fun teardown(session: Session) {
val done = CountDownLatch(1)
session.handler.post {
session.player.get()?.release()
done.countDown()
}
done.await(10, TimeUnit.SECONDS)
session.thread.quitSafely()
session.thread.join(5_000)
session.fixture.delete()
}
private fun copyFixture(context: android.content.Context): File {
val output = File.createTempFile("mkv-late-tracks-", ".mkv", context.cacheDir)
InstrumentationRegistry.getInstrumentation().context.assets
.open("ffmpeg/matroska_tracks_at_end.mkv")
.use { input -> output.outputStream().use { input.copyTo(it) } }
return output
}
}
@@ -107,7 +107,7 @@ class TrueHdSpeedTransitionTest {
// AudioTrackConfig is built from OutputConfig, which stays PCM16 by design; the real
// AudioTrack format is swapped in the builder modifier. The observable carrier signature is
// therefore the 192kHz carrier rate with no decoder instantiated.
if (carrierEncoding != TrueHdMatPacker.CARRIER_SAMPLE_RATE || decoderBefore != null) {
if (carrierEncoding != IecCarrier.SAMPLE_RATE || decoderBefore != null) {
Log.i(TAG, "==== SKIPPED: device does not take the carrier (rate=$carrierEncoding) ====")
teardown(handler, player, thread, fixture)
return
@@ -137,12 +137,12 @@ class TrueHdSpeedTransitionTest {
assertEquals(
"returning to 1x must put TrueHD back on the carrier",
TrueHdMatPacker.CARRIER_SAMPLE_RATE,
IecCarrier.SAMPLE_RATE,
rateRestored
)
assertNotEquals(
"TrueHD must leave the IEC 61937 carrier when speed leaves 1x",
TrueHdMatPacker.CARRIER_SAMPLE_RATE,
IecCarrier.SAMPLE_RATE,
encodingAfter
)
assertTrue("a decoder must take over the TrueHD track", decoderAfter != null)
@@ -203,7 +203,7 @@ class TrueHdSpeedTransitionTest {
@Test
fun aRateFamilyMismatchFallsBackToTheDecoderInsteadOfGoingSilent() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
if (!supportsTrueHdMatCarrier()) {
if (!supportsIecCarrier(context)) {
Log.i(TAG, "==== MISMATCH SKIPPED: device has no carrier route ====")
return
}
@@ -297,13 +297,13 @@ class TrueHdSpeedTransitionTest {
// AudioTrack is ever opened and the rate sequence alone cannot tell the two apart.
assertTrue(
"the carrier must have been entered and then left at runtime, saw: $diagnostics",
diagnostics.any { it.contains("MAT/IEC 61937 carrier") } &&
diagnostics.any { it.contains("via IEC 61937 carrier") } &&
diagnostics.any { it.contains("44.1kHz-family rate its container did not") }
)
assertTrue("a decoder must take the stream over instead of the carrier", decoder != null)
assertNotEquals(
"the stream must not still be riding the carrier",
TrueHdMatPacker.CARRIER_SAMPLE_RATE,
IecCarrier.SAMPLE_RATE,
rate
)
assertTrue("playback must keep advancing after the fallback", positionSecond > positionFirst)
@@ -0,0 +1,84 @@
package com.edde746.plezy.mpv
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.edde746.plezy.shared.PlayerDelegate
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
/**
* Exercises MPV's JNI reachability against the production-shrunk app with
* `-Pplezy.testBuildType=minified`. Native initialization resolves all nine static
* callback descriptors, so a stale or missing keep fails before initialization completes.
*
* Only calls the core APIs used by production. Referencing MpvPlayer's callbacks
* directly here would let the harness mask missing retention in the app APK.
*/
@RunWith(AndroidJUnit4::class)
class MpvPlayerReachabilityTest {
@Test
fun productionCoreInitializesDeliversNativeLogAndDisposes() {
val instrumentation = InstrumentationRegistry.getInstrumentation()
val core = AtomicReference<MpvPlayerCore>()
val initialized = CountDownLatch(1)
val initializationSucceeded = AtomicBoolean()
val commandCompleted = CountDownLatch(1)
val commandSucceeded = AtomicBoolean()
val nativeLogReceived = CountDownLatch(1)
instrumentation.runOnMainSync {
// Pass every constructor argument: production uses this constructor, not
// the default-argument bridge that R8 may legitimately remove.
core.set(MpvPlayerCore(instrumentation.targetContext, true, true, 1f, "v"))
core.get().delegate = object : PlayerDelegate {
override fun onPropertyChange(name: String, value: Any?) = Unit
override fun onEvent(name: String, data: Map<String, Any>?) {
if (name == "log-message" && data?.get("level") == "info" && data["text"] == LOG_MARKER) {
nativeLogReceived.countDown()
}
}
}
}
try {
instrumentation.runOnMainSync {
core.get().initialize {
initializationSucceeded.set(it)
initialized.countDown()
}
}
assertCompletes(initialized, "initialization")
assertTrue("Native MPV initialization failed", initializationSucceeded.get())
// initialize completes after the production flow collectors subscribe.
// This marker must cross the real native event thread and reach the delegate.
instrumentation.runOnMainSync {
core.get().command(arrayOf("print-text", LOG_MARKER)) {
commandSucceeded.set(it)
commandCompleted.countDown()
}
}
assertCompletes(commandCompleted, "print-text")
assertTrue("Native MPV print-text failed", commandSucceeded.get())
assertCompletes(nativeLogReceived, "native log callback")
} finally {
val disposed = CountDownLatch(1)
instrumentation.runOnMainSync { core.get().dispose(disposed::countDown) }
assertCompletes(disposed, "native teardown")
}
}
private fun assertCompletes(latch: CountDownLatch, operation: String) {
assertTrue("Timed out during $operation", latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS))
}
private companion object {
const val TIMEOUT_SECONDS = 15L
const val LOG_MARKER = "plezy-mpv-r8-native-log"
}
}
@@ -0,0 +1,354 @@
package com.edde746.plezy.mpv
import android.app.Instrumentation
import android.content.Intent
import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import android.view.ViewGroup
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.edde746.plezy.shared.PlayerDelegate
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class MpvLifecycleDeviceTest {
@Test
fun repeatedMediaCodecPlaybackCompletesTerminalTeardown() = runPlaybackTest(recreateSurfaces = false)
@Test
fun pausedMediaCodecPlaybackSurvivesRepeatedSurfaceRecreation() = runPlaybackTest(recreateSurfaces = true)
@Test
fun pausedGpuPlaybackSurvivesRepeatedSurfaceRecreation() = runPlaybackTest(recreateSurfaces = true, hardwareDecoding = false)
@Test
fun placeholderConsumesFramesWithoutBlockingProducer() {
val placeholder = runBlocking { MpvPlaceholderSurface.create() }
val completed = CountDownLatch(1)
val failure = AtomicReference<Throwable?>()
val producer = Thread {
try {
// More than a BufferQueue can retain without an active consumer.
repeat(16) {
val canvas = placeholder.surface.lockCanvas(null)
canvas.drawColor(Color.BLACK)
placeholder.surface.unlockCanvasAndPost(canvas)
}
} catch (error: Throwable) {
failure.set(error)
} finally {
completed.countDown()
}
}.apply { isDaemon = true }
try {
producer.start()
assertCompletes(completed, "placeholder buffer consumption", 0)
failure.get()?.let { throw AssertionError("Placeholder producer failed", it) }
} finally {
placeholder.close()
producer.join(2_000)
assertTrue("Placeholder producer survived cleanup", !producer.isAlive)
}
}
private fun runPlaybackTest(recreateSurfaces: Boolean, hardwareDecoding: Boolean = true) {
val instrumentation = InstrumentationRegistry.getInstrumentation()
val fixtureBytes = instrumentation.context.assets.open("ffmpeg/mediacodec_teardown.mp4").use { it.readBytes() }
val fixture = copyFixture(fixtureBytes, instrumentation.targetContext.cacheDir)
try {
val activity = instrumentation.startActivitySync(
Intent(instrumentation.targetContext, MpvLifecycleTestActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
) as MpvLifecycleTestActivity
try {
instrumentation.waitForIdleSync()
repeat(CYCLE_COUNT) { cycle ->
runPlaybackCycle(instrumentation, activity, fixture, cycle, recreateSurfaces, hardwareDecoding)
}
} finally {
instrumentation.runOnMainSync(activity::finish)
instrumentation.waitForIdleSync()
}
} finally {
fixture.delete()
}
}
private fun runPlaybackCycle(
instrumentation: Instrumentation,
activity: MpvLifecycleTestActivity,
fixture: File,
cycle: Int,
recreateSurfaces: Boolean,
hardwareDecoding: Boolean
) {
val initialized = CountDownLatch(1)
val initializationResult = AtomicReference<Boolean>()
val events = RecordingDelegate()
val core = AtomicReference<MpvPlayerCore>()
instrumentation.runOnMainSync {
core.set(
MpvPlayerCore(activity, hardwareDecoding = hardwareDecoding).also { playerCore ->
playerCore.delegate = events
playerCore.initialize { success ->
initializationResult.set(success)
initialized.countDown()
}
}
)
}
try {
assertCompletes(initialized, "MPV initialization", cycle)
assertTrue("MPV initialization failed in cycle $cycle", initializationResult.get())
setProperty(instrumentation, core.get(), "hwdec", if (hardwareDecoding) "mediacodec" else "no", cycle)
setProperty(instrumentation, core.get(), "aid", "no", cycle)
if (recreateSurfaces) setProperty(instrumentation, core.get(), "loop-file", "inf", cycle)
val commandCompleted = CountDownLatch(1)
val commandResult = AtomicReference<Boolean>()
instrumentation.runOnMainSync {
core.get().command(arrayOf("loadfile", fixture.absolutePath, "replace")) { success ->
commandResult.set(success)
commandCompleted.countDown()
}
}
assertCompletes(commandCompleted, "loadfile command", cycle)
assertTrue("loadfile command failed in cycle $cycle", commandResult.get())
assertCompletes(events.fileLoaded, "file-loaded event", cycle)
assertCompletes(events.playbackRestart, "playback-restart event", cycle)
assertVideoOutput(core.get(), cycle, hardwareDecoding)
if (recreateSurfaces) exerciseSurfaceRecreation(instrumentation, activity, core.get(), cycle, hardwareDecoding)
} finally {
disposeCore(instrumentation, activity, core.get(), cycle)
}
}
private fun disposeCore(
instrumentation: Instrumentation,
activity: MpvLifecycleTestActivity,
core: MpvPlayerCore,
cycle: Int
) {
val disposed = CountDownLatch(1)
val nextMainTurn = CountDownLatch(1)
val disposeElapsedMs = AtomicReference<Long>()
val synchronousDisposeElapsedMs = AtomicReference<Long>()
val disposeStartedAt = SystemClock.elapsedRealtime()
instrumentation.runOnMainSync {
val synchronousDisposeStartedAt = SystemClock.elapsedRealtime()
core.dispose {
disposeElapsedMs.set(SystemClock.elapsedRealtime() - disposeStartedAt)
disposed.countDown()
}
Handler(Looper.getMainLooper()).post(nextMainTurn::countDown)
synchronousDisposeElapsedMs.set(SystemClock.elapsedRealtime() - synchronousDisposeStartedAt)
}
try {
assertTrue(
"dispose() blocked the main thread for ${synchronousDisposeElapsedMs.get()}ms in cycle $cycle",
synchronousDisposeElapsedMs.get() <= MAX_SYNCHRONOUS_DISPOSE_MS
)
assertCompletes(nextMainTurn, "main-looper turn after dispose", cycle, MAIN_LOOP_TIMEOUT_SECONDS)
} finally {
assertCompletes(disposed, "terminal teardown", cycle, DISPOSE_TIMEOUT_SECONDS)
}
assertTrue(
"Terminal teardown took ${disposeElapsedMs.get()}ms in cycle $cycle",
disposeElapsedMs.get() <= MAX_DISPOSE_LATENCY_MS
)
instrumentation.runOnMainSync {
val content = activity.findViewById<ViewGroup>(android.R.id.content)
assertEquals("Player surface container leaked in cycle $cycle", 1, content.childCount)
}
}
private fun exerciseSurfaceRecreation(
instrumentation: Instrumentation,
activity: MpvLifecycleTestActivity,
core: MpvPlayerCore,
cycle: Int,
hardwareDecoding: Boolean
) {
val surfaces = mutableListOf<SurfaceView>()
instrumentation.runOnMainSync {
val content = activity.findViewById<ViewGroup>(android.R.id.content)
val container = content.getChildAt(0) as ViewGroup
// The host's first plane only punches out letterboxing; the remaining
// SurfaceViews are the actual video and OSD planes.
for (index in 1 until container.childCount) {
(container.getChildAt(index) as? SurfaceView)?.let(surfaces::add)
}
}
assertEquals("Expected video and optional OSD surfaces", if (hardwareDecoding) 2 else 1, surfaces.size)
// Separate visibility changes and callback latches guarantee both real
// destruction/creation orders, including video returning before the OSD.
val orders = if (hardwareDecoding) listOf(surfaces, surfaces.reversed()) else listOf(surfaces)
for (order in orders) {
setProperty(instrumentation, core, "pause", "yes", cycle)
awaitProperty(core, "pause", "public pause", cycle) { it == "yes" }
for (surface in order) {
changeSurfaceVisibility(instrumentation, surface, visible = false, cycle = cycle)
assertEquals("Surface loss cleared public pause in cycle $cycle", "yes", core.getProperty("pause"))
}
for (surface in order) {
changeSurfaceVisibility(instrumentation, surface, visible = true, cycle = cycle)
assertEquals("Surface restoration cleared public pause in cycle $cycle", "yes", core.getProperty("pause"))
}
val pausedPosition = awaitProperty(core, "time-pos", "paused playback position", cycle) {
it?.toDoubleOrNull() != null
}.toDouble()
setProperty(instrumentation, core, "pause", "no", cycle)
awaitProperty(core, "pause", "public resume", cycle) { it == "no" }
var progressStart = pausedPosition
awaitProperty(core, "time-pos", "playback progress after surface restoration", cycle) { value ->
val position = value?.toDoubleOrNull()
if (position == null) {
false
} else {
// The fixture is two seconds long and loops. Start measuring again
// across a loop boundary rather than mistaking a wrap for a stall.
if (position < progressStart) progressStart = position
position >= progressStart + 0.1
}
}
assertVideoOutput(core, cycle, hardwareDecoding)
}
}
private fun changeSurfaceVisibility(
instrumentation: Instrumentation,
surface: SurfaceView,
visible: Boolean,
cycle: Int
) {
val changed = CountDownLatch(1)
val callback = object : SurfaceHolder.Callback {
override fun surfaceCreated(holder: SurfaceHolder) {
if (visible) changed.countDown()
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) = Unit
override fun surfaceDestroyed(holder: SurfaceHolder) {
if (!visible) changed.countDown()
}
}
try {
instrumentation.runOnMainSync {
surface.holder.addCallback(callback)
surface.visibility = if (visible) View.VISIBLE else View.INVISIBLE
}
assertCompletes(changed, if (visible) "real surface creation" else "real surface destruction", cycle)
instrumentation.runOnMainSync {
assertEquals("Unexpected surface validity in cycle $cycle", visible, surface.holder.surface.isValid)
}
} finally {
instrumentation.runOnMainSync { surface.holder.removeCallback(callback) }
}
}
private fun awaitProperty(
core: MpvPlayerCore,
name: String,
operation: String,
cycle: Int,
matches: (String?) -> Boolean
): String {
val deadline = SystemClock.elapsedRealtime() + TimeUnit.SECONDS.toMillis(OPERATION_TIMEOUT_SECONDS)
var value: String?
do {
value = core.getProperty(name)
if (matches(value)) return requireNotNull(value)
SystemClock.sleep(20)
} while (SystemClock.elapsedRealtime() < deadline)
throw AssertionError("$operation timed out in cycle $cycle; $name=$value")
}
private fun assertVideoOutput(core: MpvPlayerCore, cycle: Int, hardwareDecoding: Boolean) {
if (hardwareDecoding) {
assertEquals("mediacodec", core.getProperty("current-vo"))
assertTrue(
"Expected MediaCodec hardware decoding in cycle $cycle",
core.getProperty("hwdec-current")?.startsWith("mediacodec") == true
)
} else {
assertEquals("gpu", core.getProperty("current-vo"))
assertEquals("no", core.getProperty("hwdec-current"))
}
}
private fun setProperty(
instrumentation: Instrumentation,
core: MpvPlayerCore,
name: String,
value: String,
cycle: Int
) {
val completed = CountDownLatch(1)
val result = AtomicReference<Result<Unit>>()
instrumentation.runOnMainSync {
core.setProperty(name, value) { outcome ->
result.set(outcome)
completed.countDown()
}
}
assertCompletes(completed, "$name property write", cycle)
assertTrue("$name property write failed in cycle $cycle", result.get().isSuccess)
}
private fun assertCompletes(
latch: CountDownLatch,
operation: String,
cycle: Int,
timeoutSeconds: Long = OPERATION_TIMEOUT_SECONDS
) {
assertTrue(
"$operation timed out in cycle $cycle after ${timeoutSeconds}s",
latch.await(timeoutSeconds, TimeUnit.SECONDS)
)
}
private fun copyFixture(bytes: ByteArray, cacheDir: File): File = File.createTempFile("mpv-lifecycle-", ".mp4", cacheDir).apply { writeBytes(bytes) }
private class RecordingDelegate : PlayerDelegate {
val fileLoaded = CountDownLatch(1)
val playbackRestart = CountDownLatch(1)
override fun onPropertyChange(name: String, value: Any?) = Unit
override fun onEvent(name: String, data: Map<String, Any>?) {
when (name) {
"file-loaded" -> fileLoaded.countDown()
"playback-restart" -> playbackRestart.countDown()
}
}
}
private companion object {
const val CYCLE_COUNT = 8
const val OPERATION_TIMEOUT_SECONDS = 10L
const val DISPOSE_TIMEOUT_SECONDS = 15L
const val MAIN_LOOP_TIMEOUT_SECONDS = 1L
const val MAX_SYNCHRONOUS_DISPOSE_MS = 500L
const val MAX_DISPOSE_LATENCY_MS = 2_000L
}
}
@@ -0,0 +1,146 @@
package com.edde746.plezy.mpv
import android.app.Instrumentation
import android.os.SystemClock
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.edde746.plezy.shared.PlayerDelegate
import java.io.File
import java.util.UUID
import java.util.concurrent.CountDownLatch
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class MpvLogLevelDeviceTest {
@Test
fun normalLoggingPreservesErrorsAndCanToggleVerboseOffAgain() = withCore { instrumentation, core, logs ->
assertLogPhase(instrumentation, core, logs, "normal", expectInfo = false)
setLogLevel(instrumentation, core, "v")
assertLogPhase(instrumentation, core, logs, "verbose", expectInfo = true)
setLogLevel(instrumentation, core, "warn")
assertLogPhase(instrumentation, core, logs, "normal-again", expectInfo = false)
}
@Test
fun verboseLoggingCanBeSelectedBeforeNativeInitialization() = withCore(initialLogLevel = "v") { instrumentation, core, logs ->
assertLogPhase(instrumentation, core, logs, "initial-verbose", expectInfo = true)
}
@Test
fun rejectedInitialLogLevelDoesNotBlockTheNextPlayer() {
withCore(initialLogLevel = "not-a-level", initializationSucceeds = false) { _, _, _ -> }
withCore { instrumentation, core, logs ->
assertLogPhase(instrumentation, core, logs, "after-rejected-init", expectInfo = false)
}
}
private fun withCore(
initialLogLevel: String = "warn",
initializationSucceeds: Boolean = true,
block: (Instrumentation, MpvPlayerCore, LinkedBlockingQueue<Pair<String, String>>) -> Unit
) {
val instrumentation = InstrumentationRegistry.getInstrumentation()
val logs = LinkedBlockingQueue<Pair<String, String>>()
val initialized = CountDownLatch(1)
val success = AtomicReference<Boolean>()
val core = AtomicReference<MpvPlayerCore>()
instrumentation.runOnMainSync {
core.set(MpvPlayerCore(instrumentation.targetContext, audioOnly = true, initialLogLevel = initialLogLevel))
core.get().delegate = object : PlayerDelegate {
override fun onPropertyChange(name: String, value: Any?) = Unit
override fun onEvent(name: String, data: Map<String, Any>?) {
if (name == "log-message") {
logs.add((data?.get("level") as? String ?: "") to (data?.get("text") as? String ?: ""))
}
}
}
core.get().initialize {
success.set(it)
initialized.countDown()
}
}
try {
assertCompletes(initialized, "initialization")
assertEquals("Native MPV initialization result", initializationSucceeds, success.get())
block(instrumentation, core.get(), logs)
} finally {
val disposed = CountDownLatch(1)
instrumentation.runOnMainSync { core.get().dispose(disposed::countDown) }
assertCompletes(disposed, "teardown")
}
}
private fun setLogLevel(instrumentation: Instrumentation, core: MpvPlayerCore, level: String) {
val completed = CountDownLatch(1)
val result = AtomicReference<Result<Unit>>()
instrumentation.runOnMainSync {
core.setLogLevel(level) {
result.set(it)
completed.countDown()
}
}
assertCompletes(completed, "setLogLevel($level)")
result.get().getOrThrow()
}
private fun command(instrumentation: Instrumentation, core: MpvPlayerCore, vararg args: String) {
val completed = CountDownLatch(1)
val success = AtomicReference<Boolean>()
instrumentation.runOnMainSync {
core.command(arrayOf(*args)) {
success.set(it)
completed.countDown()
}
}
assertCompletes(completed, args.first())
assertTrue("MPV command failed: ${args.first()}", success.get())
}
private fun assertLogPhase(
instrumentation: Instrumentation,
core: MpvPlayerCore,
logs: LinkedBlockingQueue<Pair<String, String>>,
phase: String,
expectInfo: Boolean
) {
val token = "mpv-log-$phase-${UUID.randomUUID()}"
val infoMarker = "$token-info"
val errorMarker = "$token-missing"
val missingFile = File(instrumentation.targetContext.cacheDir, errorMarker)
command(instrumentation, core, "print-text", infoMarker)
command(instrumentation, core, "loadfile", missingFile.absolutePath, "replace")
// The failed open is an error-level barrier in the same ordered log stream.
// Seeing it proves the preceding informational message was either delivered
// or filtered; no sleep is needed to assert that a quiet log stayed quiet.
val deadline = SystemClock.elapsedRealtime() + TimeUnit.SECONDS.toMillis(TIMEOUT_SECONDS)
var sawInfo = false
while (true) {
val remaining = deadline - SystemClock.elapsedRealtime()
assertTrue("Missing native error log in $phase", remaining > 0)
val log = logs.poll(remaining, TimeUnit.MILLISECONDS)
assertTrue("Missing native error log in $phase", log != null)
if (log!!.second.contains(infoMarker)) {
assertEquals("info", log.first)
sawInfo = true
}
if (log.first == "error" && log.second.contains(errorMarker)) break
}
assertEquals("Informational log visibility in $phase", expectInfo, sawInfo)
}
private fun assertCompletes(latch: CountDownLatch, operation: String) {
assertTrue("Timed out during $operation", latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS))
}
private companion object {
const val TIMEOUT_SECONDS = 15L
}
}
@@ -4,4 +4,10 @@
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
<application>
<activity
android:name=".mpv.MpvLifecycleTestActivity"
android:exported="false"
android:theme="@style/NormalTheme" />
</application>
</manifest>
@@ -0,0 +1,18 @@
package com.edde746.plezy.mpv
import android.app.Activity
import android.os.Bundle
import android.view.WindowManager
import android.widget.FrameLayout
class MpvLifecycleTestActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
window.addFlags(
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD or
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
)
super.onCreate(savedInstanceState)
setContentView(FrameLayout(this))
}
}
-3
View File
@@ -6,9 +6,6 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:installLocation="auto">
<!-- Allow minSdk=25 despite libmpv-android declaring minSdk=26 -->
<uses-sdk tools:overrideLibrary="dev.jdtech.mpv" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
@@ -28,6 +28,12 @@ internal class ExternalPlayerChannel(private val activity: Activity) {
private const val API_VLC_RESULT_POSITION = "extra_position"
private const val API_VLC_RESULT_DURATION = "extra_duration"
// Honored by VLC and the native Zidoo player (com.android.gallery3d /
// com.zidoo.player). Without it, a launch with no resume point lets the
// player consult its own bookmark store, which on Zidoo collides across
// Plex items because every part URL ends in the same `file.<ext>` (#2223).
private const val API_VLC_FROM_START = "from_start"
private const val API_VIMU_TITLE = "forcename"
private const val API_VIMU_SEEK_POSITION = "startfrom"
private const val API_VIMU_RESUME = "forceresume"
@@ -150,7 +156,7 @@ internal class ExternalPlayerChannel(private val activity: Activity) {
}
}
private data class Source(val uri: Uri, val grantRead: Boolean, val fileName: String?)
internal data class Source(val uri: Uri, val grantRead: Boolean, val fileName: String?)
private fun resolveSource(filePath: String): Source {
if (filePath.startsWith("http://") || filePath.startsWith("https://")) {
@@ -168,7 +174,7 @@ internal class ExternalPlayerChannel(private val activity: Activity) {
return Source(uri, grantRead = true, fileName = file.name)
}
private fun buildIntent(
internal fun buildIntent(
source: Source,
packageName: String?,
startPositionMs: Long,
@@ -181,6 +187,9 @@ internal class ExternalPlayerChannel(private val activity: Activity) {
if (startPosition > 0) {
putExtra(API_MX_RESULT_POSITION, startPosition)
putExtra(API_VIMU_SEEK_POSITION, startPosition)
putExtra(API_VLC_FROM_START, false)
} else {
putExtra(API_VLC_FROM_START, true)
}
putExtra(API_MX_RETURN_RESULT, true)
putExtra(API_MX_SECURE_URI, true)
@@ -31,7 +31,9 @@ import com.edde746.plezy.car.CarRestrictionsMonitor
import com.edde746.plezy.exoplayer.ExoPlayerPlugin
import com.edde746.plezy.mpv.MpvAudioPlayerPlugin
import com.edde746.plezy.mpv.MpvPlayerPlugin
import com.edde746.plezy.shared.AssistiveTechnologyMonitor
import com.edde746.plezy.shared.DeviceQuirks
import com.edde746.plezy.shared.MediaCodecQuery
import com.edde746.plezy.shared.ThemeHelper
import com.edde746.plezy.watchnext.WatchNextPlugin
import io.flutter.embedding.android.FlutterActivity
@@ -95,9 +97,12 @@ class MainActivity : FlutterActivity() {
private val TEXT_INPUT_CHANNEL = "com.plezy/text_input"
private val APP_EXIT_CHANNEL = "com.plezy/app_exit"
private val CAR_RESTRICTIONS_CHANNEL = "com.plezy/car_restrictions"
private val ASSISTIVE_TECHNOLOGY_CHANNEL = "com.plezy/assistive_technology"
private var watchNextPlugin: WatchNextPlugin? = null
private var carRestrictions: CarRestrictionsMonitor? = null
private var carRestrictionsChannel: MethodChannel? = null
private var assistiveTechnology: AssistiveTechnologyMonitor? = null
private var assistiveTechnologyChannel: MethodChannel? = null
private var nativeTextInputFocused = false
private val imeRecoveryHandler = Handler(Looper.getMainLooper())
private var imeShowAttempts = 0
@@ -592,6 +597,9 @@ class MainActivity : FlutterActivity() {
carRestrictions?.release()
carRestrictions = null
carRestrictionsChannel = null
assistiveTechnology?.release()
assistiveTechnology = null
assistiveTechnologyChannel = null
activityStarted = false
flutterSurfaceReconnectPending = false
flutterTextureView = null
@@ -735,6 +743,7 @@ class MainActivity : FlutterActivity() {
"getTvDetection" -> result.success(getAndroidTvDetection())
"getDeviceName" -> result.success(getDeviceName())
"getPerformanceSignals" -> result.success(getPerformanceSignals())
"getVideoDecodeCapabilities" -> result.success(MediaCodecQuery.hardwareVideoDecodeSupport())
"getBackgroundWorkSignals" -> result.success(
BackgroundWorkClassifier.toMap(BackgroundWorkDiagnostics.read(this))
)
@@ -779,6 +788,19 @@ class MainActivity : FlutterActivity() {
}
}
val assistiveChannel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, ASSISTIVE_TECHNOLOGY_CHANNEL)
assistiveTechnologyChannel = assistiveChannel
val assistiveMonitor = assistiveTechnology ?: AssistiveTechnologyMonitor(applicationContext).also {
assistiveTechnology = it
}
assistiveMonitor.start { runOnUiThread { assistiveTechnologyChannel?.invokeMethod("onChanged", null) } }
assistiveChannel.setMethodCallHandler { call, result ->
when (call.method) {
"getSignals" -> result.success(assistiveMonitor.signals())
else -> result.notImplemented()
}
}
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, DEVICE_ADJUSTMENT_CHANNEL).setMethodCallHandler { call, result ->
handleDeviceAdjustmentCall(call.method, call.arguments, result)
}
@@ -882,7 +904,8 @@ class MainActivity : FlutterActivity() {
} catch (e: IllegalStateException) {
result.success(mapOf("success" to false, "errorCode" to "not_supported"))
} catch (e: Exception) {
result.success(mapOf("success" to false, "errorCode" to "unknown", "errorMessage" to (e.message ?: "Unknown error")))
Log.w(TAG, "Failed to enter PiP", e)
result.success(mapOf("success" to false, "errorCode" to "unknown", "errorMessage" to e.message))
}
}
"setAutoPipReady" -> {
@@ -1,6 +1,7 @@
package com.edde746.plezy.exoplayer
import android.content.Context
import android.media.AudioDeviceInfo
import android.media.AudioFormat
import android.media.AudioManager
import android.media.AudioTrack
@@ -30,6 +31,38 @@ internal fun isPassthroughAudioMimeType(mimeType: String): Boolean = when (mimeT
internal fun shouldBlockDirectOutputForPassthrough(mimeType: String, audioPassthroughEnabled: Boolean): Boolean = !audioPassthroughEnabled && isPassthroughAudioMimeType(mimeType)
/**
* The DTS-family mimes the bundled FFmpeg decoder claims (`FfmpegLibrary` maps both to `dca`).
*
* DTS Express (`audio/vnd.dts.hd;profile=lbr`) and DTS:X (`audio/vnd.dts.uhd`) are deliberately
* excluded: FFmpeg does not claim them, so hiding their platform decoders would leave those
* streams with no decoder at all.
*/
internal fun isFfmpegDtsMimeType(mimeType: String): Boolean = mimeType == MimeTypes.AUDIO_DTS || mimeType == MimeTypes.AUDIO_DTS_HD
/**
* Whether a DTS stream should decode in the app's FFmpeg decoder instead of a platform
* MediaCodec decoder.
*
* Platform DTS decoders cannot be trusted with decode. On Amlogic-based Google TV boxes (the
* Onn family) DTS decode is license-gated in firmware, so `c2.amlogic.audio.decoder.dtshd`
* initialises, drains and advances the playback position while rendering silence — and collapses
* 5.1 to stereo where it does produce sound (#1995). FFmpeg decodes the whole `dca` family to
* full multichannel PCM everywhere, which is what mpv and Kodi ship on the same hardware.
*
* Scoped to streams that are actually going to decode: [directOutputBlocked] (passthrough off,
* downmix, normalization, the AudioTrack-failure blocklist) or a route that cannot bitstream DTS
* in any shape ([routeCanBitstreamDts] false — the Android TV default leaves passthrough on, so
* the setting alone cannot identify the decode path). Bitstream-capable routes are left exactly
* alone: media3 selects direct output before it ever consults the decoder list, and leaving the
* platform decoder visible there keeps the hardware-decoder tunneling gate unchanged.
*/
internal fun shouldForceFfmpegDtsDecode(
mimeType: String,
directOutputBlocked: () -> Boolean,
routeCanBitstreamDts: () -> Boolean
): Boolean = isFfmpegDtsMimeType(mimeType) && (directOutputBlocked() || !routeCanBitstreamDts())
/**
* Linear PCM output encodings, i.e. the sink decoded the bitstream instead of
* passing it through. Mirrors the platform's `AudioFormat.ENCODING_PCM_*` set.
@@ -43,56 +76,187 @@ internal fun isPcmEncoding(encoding: Int): Boolean = when (encoding) {
else -> false
}
/**
* mpv `audio-spdif` codec names and the exact platform encoding a route must
* advertise to carry that bitstream.
*/
private val MPV_SPDIF_CODECS: List<Pair<String, Int>> = listOf(
"ac3" to C.ENCODING_AC3,
"eac3" to C.ENCODING_E_AC3,
"dts" to C.ENCODING_DTS,
"dts-hd" to C.ENCODING_DTS_HD,
"truehd" to C.ENCODING_DOLBY_TRUEHD
/** The IEC 61937 track shape a codec's spdif burst rides. */
internal enum class MpvIecShape { STEREO_48K, STEREO_192K, SURROUND_192K }
private class MpvSpdifCodec(
val name: String,
val encoding: Int,
val shape: MpvIecShape,
/** Whether the fork's audiotrack AO opens this codec as a raw bitstream track first. */
val raw: Boolean = false
)
/**
* Builds an `audio-spdif` value naming only the codecs [supportsEncoding] advertises.
* mpv `audio-spdif` codec names, the platform encoding a route must advertise to carry that
* bitstream, and the track shape the fork's `ao_audiotrack` opens for it.
*
* Since the raw-passthrough patch (0102), the AO feeds AC3, E-AC3 and the DTS core to a raw
* `ENCODING_AC3`/`E_AC3`/`DTS` track at 48kHz/stereo — the transport ExoPlayer and Kodi use —
* and only falls back to the IEC 61937 carrier when the route rejects the raw encoding
* outright. Raw tracks keep the platform's Dolby/DTS transcoder in the path; a pre-packed IEC
* track bypasses it and drains into silence on routes whose sink cannot decode the codec
* itself (#2177's Shield in front of a Dolby-Digital-only Sonos). TrueHD (MAT) and DTS-HD MA
* stay on the 8-channel 192kHz IEC carrier the multichannel patch (0101) added: their raw
* forms are not recoverable from the burst stream.
*
* `dts-hd` supersedes plain `dts`: that literal is what selects the lossless `spdif_dts_hd`
* decoder, and it enables spdif for the whole `dts` codec while doing so, with the core burst
* still chosen per file for tracks that are not HD (`ad_spdif.c:240-249`, `:400-418`). HRA rides
* a 2ch/192kHz burst under the same name, so gating it on the 8-channel carrier is the
* conservative choice.
*/
private val MPV_SPDIF_CODECS: List<MpvSpdifCodec> = listOf(
MpvSpdifCodec("ac3", C.ENCODING_AC3, MpvIecShape.STEREO_48K, raw = true),
MpvSpdifCodec("eac3", C.ENCODING_E_AC3, MpvIecShape.STEREO_192K, raw = true),
MpvSpdifCodec("truehd", C.ENCODING_DOLBY_TRUEHD, MpvIecShape.SURROUND_192K),
MpvSpdifCodec("dts", C.ENCODING_DTS, MpvIecShape.STEREO_48K, raw = true),
MpvSpdifCodec("dts-hd", C.ENCODING_DTS_HD, MpvIecShape.SURROUND_192K)
)
/**
* Builds an `audio-spdif` value naming only the codecs the route can carry: [supportsEncoding]
* advertises the codec's encoding *and* a transport the AO's ladder can open exists —
* [supportsRawTrack] for the raw bitstream track it tries first, or [supportsShape] for the
* IEC 61937 burst it falls back to. Plain `dts` is dropped whenever `dts-hd` qualifies, which
* already covers the core burst.
*
* mpv force-passes through every codec named here and has no decode fallback, so an
* unsupported name leaves the file rendering video against a dead audio output (#1703).
*
* The gate is the exact encoding rather than media3's passthrough probe on purpose.
* That probe answers DTS-HD by downgrading to the DTS core (and E-AC3 JOC to E-AC3)
* for receivers that decode only the base layer, and it also rejects channel counts
* above the route's PCM maximum, which does not apply to an IEC 61937 carrier. mpv
* additionally treats `dts,dts-hd` as `dts-hd` alone, so accepting the downgrade would
* name DTS-HD MA to a core-only receiver and lose DTS as well.
* The gate is the exact encoding rather than media3's passthrough probe on purpose. That
* probe answers by downgrading (DTS-HD to the DTS core, E-AC3 JOC to E-AC3) and rejects
* channel counts above the route's PCM maximum, neither of which describes what a
* passthrough track carries.
*/
internal fun mpvSpdifCodecs(supportsEncoding: (Int) -> Boolean): String = MPV_SPDIF_CODECS
.filter { (_, encoding) -> supportsEncoding(encoding) }
.joinToString(",") { (codec, _) -> codec }
internal fun mpvSpdifCodecs(
supportsEncoding: (Int) -> Boolean,
supportsShape: (MpvIecShape) -> Boolean,
supportsRawTrack: (Int) -> Boolean = { false }
): String {
val carried = MPV_SPDIF_CODECS.filter {
supportsEncoding(it.encoding) &&
((it.raw && supportsRawTrack(it.encoding)) || supportsShape(it.shape))
}
val dtsHd = carried.any { it.name == "dts-hd" }
return (if (dtsHd) carried.filterNot { it.name == "dts" } else carried).joinToString(",") { it.name }
}
/** [mpvSpdifCodecs] resolved against the audio route [context] is currently routed to. */
/**
* [mpvSpdifCodecs] resolved against the audio route [context] is currently routed to.
*
* Two conditions per codec, both required:
* - The route must accept a track shape the AO's ladder actually opens. For AC3, E-AC3 and the
* DTS core that is the raw bitstream track probed by [supportsMpvRawTrack], with the IEC
* stereo shapes ([supportsMpvIecShape], [supportsMpvHighRateIecShape]) as the AO's fallback
* transport; TrueHD and DTS-HD MA need the 192kHz/7.1 carrier ([supportsIecCarrier]).
* Advertising the raw encoding only says the receiver decodes it, not that the HAL takes the
* track: #1991's Shield strands playback on every mpv IEC attempt while bitstreaming AC3 raw.
* The probes are independent, so none of them may veto the whole list: a route that takes the
* 192kHz carrier but no raw track still bitstreams TrueHD and DTS-HD MA.
* - The receiver must decode the codec itself — the raw encoding on the current
* [AudioCapabilities] — because passthrough is transport, not transcoding. (On a raw track
* the platform may additionally transcode, which is exactly why the AO prefers it.)
*/
// Deprecated only in favour of an overload that also takes spatializer channel masks, which
// do not affect bitstream routing. Same probe ExoPlayerCore's TrueHD decision uses.
@Suppress("DEPRECATION")
@OptIn(UnstableApi::class)
internal fun supportedMpvSpdifCodecs(context: Context): String {
val audioAttributes = AudioAttributes.Builder()
.setContentType(C.AUDIO_CONTENT_TYPE_MOVIE)
.setUsage(C.USAGE_MEDIA)
.build()
val audioAttributes = movieMedia3AudioAttributes()
val capabilities = try {
AudioCapabilities.getCapabilities(context, audioAttributes, null)
} catch (error: Exception) {
Log.w(TAG, "Audio route capabilities unavailable; mpv will decode instead of bitstreaming", error)
return ""
}
return mpvSpdifCodecs(capabilities::supportsEncoding)
// Every probe costs real route calls and may be shared by more than one codec, so probe once.
val shapeProbed = HashMap<MpvIecShape, Boolean>(3)
val rawProbed = HashMap<Int, Boolean>(3)
val codecs = mpvSpdifCodecs(
capabilities::supportsEncoding,
{ shape -> shapeProbed.getOrPut(shape) { routeTakesIecShape(context, shape) } },
{ encoding -> rawProbed.getOrPut(encoding) { supportsMpvRawTrack(context, encoding) } }
)
if (codecs.isEmpty()) {
Log.i(TAG, "Route takes no passthrough track mpv can fill; mpv will decode instead of bitstreaming")
} else {
Log.i(TAG, "mpv will bitstream: $codecs")
}
return codecs
}
private fun routeTakesIecShape(context: Context, shape: MpvIecShape): Boolean = when (shape) {
MpvIecShape.STEREO_48K -> supportsMpvIecShape(context)
MpvIecShape.STEREO_192K -> supportsMpvHighRateIecShape(context)
MpvIecShape.SURROUND_192K -> supportsIecCarrier(context)
}
/** The track shape mpv's audiotrack AO opens for an AC3 or DTS-core burst: stereo at the mixer rate. */
private const val MPV_IEC_SAMPLE_RATE = 48_000
private const val MPV_IEC_CHANNEL_COUNT = 2
private const val MPV_IEC_HIGH_SAMPLE_RATE = 192_000
internal fun supportsMpvIecShape(context: Context): Boolean = iecRouteSupported(
sdkInt = Build.VERSION.SDK_INT,
canSizeBuffer = { canSizeIecBuffer(MPV_IEC_SAMPLE_RATE, AudioFormat.CHANNEL_OUT_STEREO) },
// The SDK_INT guards repeat iecRouteSupported's tiering only because lint's NewApi
// check cannot see through the injected lambdas.
bitstreamSupported = {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
iecBitstreamSupported(iecProbeFormat(MPV_IEC_SAMPLE_RATE, AudioFormat.CHANNEL_OUT_STEREO))
},
directPlaybackSupported = {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q &&
iecDirectPlaybackSupported(iecProbeFormat(MPV_IEC_SAMPLE_RATE, AudioFormat.CHANNEL_OUT_STEREO))
},
hdmiRouteAdvertised = { hdmiAdvertisesIecRoute(context, MPV_IEC_SAMPLE_RATE, MPV_IEC_CHANNEL_COUNT) }
)
/**
* Whether this route can carry TrueHD as MAT inside IEC 61937 (#1804).
* Whether the route takes a raw bitstream `AudioTrack` for [encoding] at the shape the fork's
* `ao_audiotrack` opens first: the codec frame rate with a stereo mask (Kodi's raw shape; the
* HAL reads the real channel layout from the bitstream). Same probe tiering as the IEC shapes,
* except below API 29, where no runtime oracle exists for raw tracks and media3 gates its raw
* path on the advertised encoding alone — which [supportedMpvSpdifCodecs] already requires via
* [AudioCapabilities]. #1991's API 28 Shield bitstreams AC3 exactly this way.
*/
internal fun supportsMpvRawTrack(context: Context, encoding: Int): Boolean = iecRouteSupported(
sdkInt = Build.VERSION.SDK_INT,
canSizeBuffer = { canSizeDirectBuffer(MPV_IEC_SAMPLE_RATE, AudioFormat.CHANNEL_OUT_STEREO, encoding) },
// The SDK_INT guards repeat iecRouteSupported's tiering only because lint's NewApi
// check cannot see through the injected lambdas.
bitstreamSupported = {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
iecBitstreamSupported(directProbeFormat(encoding, MPV_IEC_SAMPLE_RATE, AudioFormat.CHANNEL_OUT_STEREO))
},
directPlaybackSupported = {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q &&
iecDirectPlaybackSupported(directProbeFormat(encoding, MPV_IEC_SAMPLE_RATE, AudioFormat.CHANNEL_OUT_STEREO))
},
hdmiRouteAdvertised = { true }
)
/** E-AC3's geometry: the stereo shape at the 192kHz burst rate, same route tiering as the others. */
internal fun supportsMpvHighRateIecShape(context: Context): Boolean = iecRouteSupported(
sdkInt = Build.VERSION.SDK_INT,
canSizeBuffer = { canSizeIecBuffer(MPV_IEC_HIGH_SAMPLE_RATE, AudioFormat.CHANNEL_OUT_STEREO) },
// The SDK_INT guards repeat iecRouteSupported's tiering only because lint's NewApi
// check cannot see through the injected lambdas.
bitstreamSupported = {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
iecBitstreamSupported(iecProbeFormat(MPV_IEC_HIGH_SAMPLE_RATE, AudioFormat.CHANNEL_OUT_STEREO))
},
directPlaybackSupported = {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q &&
iecDirectPlaybackSupported(iecProbeFormat(MPV_IEC_HIGH_SAMPLE_RATE, AudioFormat.CHANNEL_OUT_STEREO))
},
hdmiRouteAdvertised = { hdmiAdvertisesIecRoute(context, MPV_IEC_HIGH_SAMPLE_RATE, MPV_IEC_CHANNEL_COUNT) }
)
/**
* Whether this route can carry a packed bitstream inside IEC 61937 at 192kHz/7.1 — TrueHD as MAT
* (#1804) and DTS-HD MA as DTS type IV (#1988) both ride this exact tuple.
*
* This is Kodi's test, and deliberately not media3's. Kodi asks the AudioTrack layer whether it can
* size a buffer for one exact tuple — `getMinBufferSize(rate, mask, encoding) > 0` — and gates the
@@ -100,8 +264,8 @@ internal fun supportedMpvSpdifCodecs(context: Context): String {
* layer about the encoding, which on the boxes measured for this issue answers "TrueHD is
* offload-capable" and says nothing about whether a raw TrueHD track will ever drain.
*
* Both are consulted: `getMinBufferSize` proves a track can be built, and a direct-playback oracle
* proves the route will actually bitstream it rather than silently decode or wedge. Sizing alone is
* Both are consulted: `getMinBufferSize` proves a track can be built, and a route oracle proves
* the route will actually bitstream it rather than silently decode or wedge. Sizing alone is
* not sufficient — on a Shield it answers yes for this tuple and the AudioTrack then fails to
* initialise.
*
@@ -112,76 +276,133 @@ internal fun supportedMpvSpdifCodecs(context: Context): String {
* for it means the route carries the frames. Fire OS 8 (API 30) devices bitstream TrueHD this way
* and lost passthrough entirely under an API 33 gate (#1863). A route that still lies here fails
* AudioTrack initialisation, which the audio recovery path answers by force-decoding.
* - Below API 29 there is no oracle at all, so the carrier is not offered and TrueHD decodes as
* before.
* - API 2428: no runtime oracle exists, so the HDMI `AudioDeviceInfo` must explicitly advertise
* IEC 61937 at 192kHz/8ch. Shield Experience 8.x is API 28, and the previous flat `false` on
* this tier force-decoded TrueHD on routes that genuinely carry it (#1991). A route that
* advertises and still refuses the track fails AudioTrack initialisation into the same
* recovery path as the tier above.
*/
internal fun supportsTrueHdMatCarrier(): Boolean = trueHdMatCarrierSupported(
internal fun supportsIecCarrier(context: Context): Boolean = iecRouteSupported(
sdkInt = Build.VERSION.SDK_INT,
canSizeCarrierBuffer = {
try {
AudioTrack.getMinBufferSize(
TrueHdMatPacker.CARRIER_SAMPLE_RATE,
AudioFormat.CHANNEL_OUT_7POINT1_SURROUND,
AudioFormat.ENCODING_IEC61937
) > 0
} catch (error: Exception) {
false
}
},
// The SDK_INT guards repeat trueHdMatCarrierSupported's tiering only because lint's NewApi
canSizeBuffer = { canSizeIecBuffer(IecCarrier.SAMPLE_RATE, AudioFormat.CHANNEL_OUT_7POINT1_SURROUND) },
// The SDK_INT guards repeat iecRouteSupported's tiering only because lint's NewApi
// check cannot see through the injected lambdas.
bitstreamSupported = {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && iecCarrierBitstreamSupported()
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
iecBitstreamSupported(iecProbeFormat(IecCarrier.SAMPLE_RATE, AudioFormat.CHANNEL_OUT_7POINT1_SURROUND))
},
directPlaybackSupported = {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && iecCarrierDirectPlaybackSupported()
}
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q &&
iecDirectPlaybackSupported(iecProbeFormat(IecCarrier.SAMPLE_RATE, AudioFormat.CHANNEL_OUT_7POINT1_SURROUND))
},
hdmiRouteAdvertised = { hdmiAdvertisesIecRoute(context, IecCarrier.SAMPLE_RATE, IecCarrier.CHANNEL_COUNT) }
)
/**
* [supportsTrueHdMatCarrier] with the platform probes injected. Probes are only consulted on the
* API tiers where they exist: [bitstreamSupported] (`getDirectPlaybackSupport`) on 33+ and
* [directPlaybackSupported] (`AudioTrack.isDirectPlaybackSupported`) on 2932.
* Whether the route carries the IEC 61937 tuple *and* advertises DTS-HD. TrueHD rides the same
* tuple, so carrying it says nothing about whether the receiver decodes DTS-HD.
*/
internal fun trueHdMatCarrierSupported(
internal fun dtsHdCarrierUsable(
supportsEncoding: (Int) -> Boolean,
supportsCarrier: () -> Boolean
): Boolean = supportsEncoding(C.ENCODING_DTS_HD) && supportsCarrier()
/** [dtsHdCarrierUsable] resolved against the audio route [context] is currently routed to. */
internal fun supportsDtsHdIecCarrier(context: Context): Boolean = dtsHdCarrierUsable(
// Encoding first: it skips the carrier tiering's several route calls.
supportsEncoding = { encoding -> routeSupportsEncoding(context, encoding) },
supportsCarrier = { supportsIecCarrier(context) }
)
@Suppress("DEPRECATION")
@OptIn(UnstableApi::class)
private fun routeSupportsEncoding(context: Context, encoding: Int): Boolean = try {
AudioCapabilities.getCapabilities(context, movieMedia3AudioAttributes(), null).supportsEncoding(encoding)
} catch (error: Exception) {
Log.w(TAG, "Audio route capabilities unavailable; DTS-HD will not bitstream", error)
false
}
/**
* [supportsIecCarrier]/[supportsMpvIecShape] with the platform probes injected. Probes are only
* consulted on the API tiers where they exist: [bitstreamSupported] (`getDirectPlaybackSupport`)
* on 33+, [directPlaybackSupported] (`AudioTrack.isDirectPlaybackSupported`) on 2932, and
* [hdmiRouteAdvertised] (explicit HDMI `AudioDeviceInfo` advertisement) on 2428 (#1991).
*/
internal fun iecRouteSupported(
sdkInt: Int,
canSizeCarrierBuffer: () -> Boolean,
canSizeBuffer: () -> Boolean,
bitstreamSupported: () -> Boolean,
directPlaybackSupported: () -> Boolean
directPlaybackSupported: () -> Boolean,
hdmiRouteAdvertised: () -> Boolean
): Boolean = when {
sdkInt < Build.VERSION_CODES.Q -> false
!canSizeCarrierBuffer() -> false
// ENCODING_IEC61937 itself only exists from API 24.
sdkInt < Build.VERSION_CODES.N -> false
!canSizeBuffer() -> false
sdkInt >= Build.VERSION_CODES.TIRAMISU -> bitstreamSupported()
else -> directPlaybackSupported()
sdkInt >= Build.VERSION_CODES.Q -> directPlaybackSupported()
else -> hdmiRouteAdvertised()
}
private fun canSizeIecBuffer(sampleRate: Int, channelMask: Int): Boolean = canSizeDirectBuffer(sampleRate, channelMask, AudioFormat.ENCODING_IEC61937)
private fun canSizeDirectBuffer(sampleRate: Int, channelMask: Int, encoding: Int): Boolean = try {
AudioTrack.getMinBufferSize(sampleRate, channelMask, encoding) > 0
} catch (error: Exception) {
false
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
private fun iecCarrierBitstreamSupported(): Boolean = try {
val support = AudioManager.getDirectPlaybackSupport(iecCarrierProbeFormat(), movieAudioAttributes())
private fun iecBitstreamSupported(format: AudioFormat): Boolean = try {
val support = AudioManager.getDirectPlaybackSupport(format, movieAudioAttributes())
(support and AudioManager.DIRECT_PLAYBACK_BITSTREAM_SUPPORTED) != 0
} catch (error: Exception) {
Log.w(TAG, "IEC 61937 carrier probe failed; not offering the TrueHD carrier", error)
Log.w(TAG, "IEC 61937 route probe failed; not offering bitstream output", error)
false
}
@RequiresApi(Build.VERSION_CODES.Q)
@Suppress("DEPRECATION") // Deprecated in favour of the API 33 probe the tier above uses.
private fun iecCarrierDirectPlaybackSupported(): Boolean = try {
AudioTrack.isDirectPlaybackSupported(iecCarrierProbeFormat(), movieAudioAttributes())
private fun iecDirectPlaybackSupported(format: AudioFormat): Boolean = try {
AudioTrack.isDirectPlaybackSupported(format, movieAudioAttributes())
} catch (error: Exception) {
Log.w(TAG, "IEC 61937 carrier probe failed; not offering the TrueHD carrier", error)
Log.w(TAG, "IEC 61937 route probe failed; not offering bitstream output", error)
false
}
/** The exact tuple the carrier's `AudioTrack` is built with; see [PlezyRenderersFactory]. */
private fun iecCarrierProbeFormat(): AudioFormat = AudioFormat.Builder()
.setEncoding(AudioFormat.ENCODING_IEC61937)
.setChannelMask(AudioFormat.CHANNEL_OUT_7POINT1_SURROUND)
.setSampleRate(TrueHdMatPacker.CARRIER_SAMPLE_RATE)
/**
* Whether an HDMI output *explicitly* advertises IEC 61937 at [sampleRate]/[channelCount] —
* the only oracle below API 29 (#1991).
*
* Empty `AudioDeviceInfo` capability arrays mean "unspecified" and deliberately fail this
* check: an unvouched IEC track that initialises on a route that then renders it as PCM plays
* the carrier as full-scale noise, which the AudioTrack-init recovery path cannot catch.
*/
private fun hdmiAdvertisesIecRoute(context: Context, sampleRate: Int, channelCount: Int): Boolean = try {
val manager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
manager.getDevices(AudioManager.GET_DEVICES_OUTPUTS).any { device ->
(device.type == AudioDeviceInfo.TYPE_HDMI || device.type == AudioDeviceInfo.TYPE_HDMI_ARC) &&
device.encodings.contains(AudioFormat.ENCODING_IEC61937) &&
device.sampleRates.contains(sampleRate) &&
device.channelCounts.contains(channelCount)
}
} catch (error: Exception) {
Log.w(TAG, "HDMI route inspection failed; not offering IEC 61937 output", error)
false
}
/** The exact tuple an IEC output's `AudioTrack` is built with; see [PlezyRenderersFactory]. */
private fun iecProbeFormat(sampleRate: Int, channelMask: Int): AudioFormat = directProbeFormat(AudioFormat.ENCODING_IEC61937, sampleRate, channelMask)
private fun directProbeFormat(encoding: Int, sampleRate: Int, channelMask: Int): AudioFormat = AudioFormat.Builder()
.setEncoding(encoding)
.setChannelMask(channelMask)
.setSampleRate(sampleRate)
.build()
private fun movieAudioAttributes(): android.media.AudioAttributes = AudioAttributes.Builder()
private fun movieMedia3AudioAttributes(): AudioAttributes = AudioAttributes.Builder()
.setContentType(C.AUDIO_CONTENT_TYPE_MOVIE)
.setUsage(C.USAGE_MEDIA)
.build()
.getPlatformAudioAttributes()
private fun movieAudioAttributes(): android.media.AudioAttributes = movieMedia3AudioAttributes().getPlatformAudioAttributes()
@@ -8,14 +8,21 @@ import androidx.media3.extractor.ExtractorOutput
import androidx.media3.extractor.PositionHolder
import androidx.media3.extractor.SeekMap
import androidx.media3.extractor.SeekPoint
import androidx.media3.extractor.TrackAwareSeekMap
import androidx.media3.extractor.TrackOutput
import java.util.concurrent.CopyOnWriteArrayList
/**
* Extractor wrapper that enables approximate seeking for MKV files without Cues.
* Extractor wrapper that repairs seeking for MKV files media3 reports as unseekable.
*
* When the underlying extractor reports an [SeekMap.Unseekable] seek map (i.e. the MKV
* has no Cues element), this wrapper replaces it with a proportional byte-position
* estimate and scans for the nearest Cluster boundary after seeking.
* Two repairs, in priority order:
* - [SeekMap.Unseekable] with a known duration (no Cues element at all): replaced with a
* proportional byte-position estimate, resynced to the nearest Cluster boundary after seeking.
* - A [TrackAwareSeekMap] whose [SeekMap.isSeekable] is false (media3 1.11.0 builds the Matroska
* seek map while parsing Cues, which for files whose Tracks element follows the Clusters is
* before any track is known — the primary seek track stays unset even though the Cues parsed):
* wrapped so seeks resolve through the per-track cue lookups using the track IDs observed on
* this output.
*/
@androidx.media3.common.util.UnstableApi
class CuelessSeekExtractorWrapper(
@@ -38,6 +45,9 @@ class CuelessSeekExtractorWrapper(
private var isApproximateSeeking = false
private var pendingSeekTimeUs: Long = C.TIME_UNSET
/** Track IDs and types observed on the output, consulted by [TrackCueSeekMap]. */
private val registeredTracks = CopyOnWriteArrayList<Pair<Int, Int>>()
override fun sniff(input: ExtractorInput): Boolean = delegate.sniff(input)
override fun init(output: ExtractorOutput) {
@@ -125,7 +135,13 @@ class CuelessSeekExtractorWrapper(
private val delegate: ExtractorOutput
) : ExtractorOutput {
override fun track(id: Int, type: Int): TrackOutput = delegate.track(id, type)
override fun track(id: Int, type: Int): TrackOutput {
if (registeredTracks.none { it.first == id }) {
registeredTracks.add(id to type)
}
return delegate.track(id, type)
}
override fun endTracks() = delegate.endTracks()
override fun seekMap(seekMap: SeekMap) {
@@ -137,6 +153,11 @@ class CuelessSeekExtractorWrapper(
delegate.seekMap(ApproximateSeekMap(durationUs))
return
}
} else if (!seekMap.isSeekable && seekMap is TrackAwareSeekMap) {
Log.i(TAG, "Wrapping unseekable TrackAwareSeekMap with per-track cue seeking")
isApproximateSeeking = false
delegate.seekMap(TrackCueSeekMap(seekMap))
return
}
// File has real Cues or unknown duration — pass through
isApproximateSeeking = false
@@ -166,4 +187,40 @@ class CuelessSeekExtractorWrapper(
return SeekMap.SeekPoints(SeekPoint(clampedTimeUs, position))
}
}
/**
* Routes seeks through [TrackAwareSeekMap]'s per-track cue lookups when the delegate reports
* unseekable overall. The per-track queries read the live cue data (populated once the Cues
* element parsed), so they resolve correctly even when the map was constructed before the
* Tracks element — the media3 1.11.0 tracks-after-clusters case (androidx/media #3377).
*/
private inner class TrackCueSeekMap(
private val delegate: TrackAwareSeekMap
) : SeekMap {
override fun isSeekable(): Boolean = delegate.isSeekable || seekableTrackId() != null
override fun getDurationUs(): Long = delegate.durationUs
override fun getSeekPoints(timeUs: Long): SeekMap.SeekPoints {
if (delegate.isSeekable) return delegate.getSeekPoints(timeUs)
val trackId = seekableTrackId() ?: return delegate.getSeekPoints(timeUs)
return delegate.getSeekPoints(timeUs, trackId)
}
/** Mirrors media3's primary-track priority: video first, then audio, then anything with cues. */
private fun seekableTrackId(): Int? {
var audio: Int? = null
var fallback: Int? = null
for ((id, type) in registeredTracks) {
if (!delegate.isSeekable(id)) continue
when (type) {
C.TRACK_TYPE_VIDEO -> return id
C.TRACK_TYPE_AUDIO -> if (audio == null) audio = id
else -> if (fallback == null) fallback = id
}
}
return audio ?: fallback
}
}
}
@@ -124,6 +124,17 @@ object DoviBridge {
.also { Log.i(TAG, "Device advertises DV Profile 8 (DvheSt): $it") }
}
/**
* Whether this device can natively render single-layer Dolby Vision
* Profile 5 (IPT-PQ-c2): it needs both a decoder advertising DvheStn and a
* Dolby Vision display pipeline. P5 has no compatible base layer, so a
* device that fails either check decodes it as plain HEVC with garbage
* colors; callers route those sessions to software decode + gpu-next,
* where libplacebo applies the RPU reshaping instead.
*/
fun canPlayDolbyVisionP5(context: Context): Boolean = deviceAdvertisesDvProfile(MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheStn) &&
displaySupportsDolbyVision(context)
fun displaySupportsDolbyVision(context: Context): Boolean {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
Log.i(TAG, "Display Dolby Vision support: false (HDR capabilities require API 24, device API=${Build.VERSION.SDK_INT})")
@@ -145,6 +156,17 @@ object DoviBridge {
return supported
}
/** Whether the active display advertises any HDR output type. */
fun displaySupportsHdr(context: Context): Boolean {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) return false
val display = getCurrentDisplay(context) ?: return false
val hdrTypes = runCatching { getDisplayHdrTypes(display) }.getOrElse { error ->
Log.w(TAG, "Display HDR support: failed to query HDR types", error)
return false
}
return hdrTypes.isNotEmpty()
}
fun describeDisplayHdrCapabilities(context: Context): String {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) return "HDR capabilities unavailable (API=${Build.VERSION.SDK_INT})"
val display = getCurrentDisplay(context) ?: return "HDR capabilities unavailable (no active display)"
@@ -0,0 +1,308 @@
package com.edde746.plezy.exoplayer
import java.nio.ByteBuffer
/**
* Packs DTS-HD (Master Audio) access units into IEC 61937 "DTS type IV" bursts (#1988).
*
* Some HDMI routes advertise `ENCODING_DTS_HD` but cannot actually carry Master Audio: Amazon
* specifies the Fire TV Stick 4K Max as "DTS-HD passthrough, basic profile", and Android has one
* ambiguous encoding constant for both profiles until API 34. Handing media3's raw path full MA
* frames there initialises an AudioTrack that drains normally and renders silence. The same
* devices do bitstream the 192kHz/7.1 `ENCODING_IEC61937` carrier — the split Kodi models with
* its "AudioTrack (IEC)" sink, and the one TrueHD already rides here (#1804, #1863) — so DTS-HD
* is packed onto that carrier instead.
*
* The algorithm is a port of FFmpeg's `spdif_header_dts`/`spdif_header_dts4`
* (libavformat/spdifenc.c, n8.1) at `dtshd_rate=768000`, the rate that fills the 8-channel/192kHz
* carrier; Kodi's `CAEBitstreamPacker::PackDTSHD` produces the same bytes.
*
* Output is one complete IEC 61937 burst per access unit:
*
* - 8-byte preamble, little endian: `Pa=0xF872 Pb=0x4E1F Pc=0x11|subtype<<8 Pd=aligned bytes`
* - 10-byte DTS-HD start code, 16-bit big-endian payload size, then the access unit, all 16-bit
* byte-swapped
* - zero padding to the burst repetition period the core frame duration maps to
* (512 samples at 48kHz — the shape of essentially all Master Audio — is 32768 bytes)
*
* Unlike MAT's fixed frames, a Master Audio peak can genuinely exceed the carrier. FFmpeg answers
* by stripping such units to the always-fitting core substream and holding that for
* `dtshd_fallback_time` (60s) so receivers do not flap between core and MA decoding; that
* behavior is ported as-is and pinned by the golden fixture.
*
* Not thread safe; the sink drives it from the playback thread only.
*/
internal class DtsHdIecPacker : IecCarrierPacker {
internal companion object {
private const val BURST_HEADER_SIZE = 8
private const val SYNCWORD1 = 0xF872
private const val SYNCWORD2 = 0x4E1F
private const val IEC61937_DTSHD = 0x11
/** Core and extension-substream sync words, big-endian raw framing. */
private const val SYNC_CORE = 0x7FFE8001
private const val SYNC_EXSS = 0x64582025
/**
* Little-endian and 14-bit core framings, from S/PDIF and DTS-in-WAV captures. They have no
* period mapping here (FFmpeg's HD path refuses them too), so they latch the stream
* unsupported and it decodes.
*/
private const val SYNC_CORE_LE = 0xFE7F0180.toInt()
private const val SYNC_CORE_14B_BE = 0x1FFFE800
private const val SYNC_CORE_14B_LE = 0xFF1F00E8.toInt()
/**
* The carrier's IEC 60958 frame rate as FFmpeg's two-channel model counts it: the burst
* repetition period is `period = 768000 * coreSamples / coreRate` IEC 60958 frames of 4 bytes,
* which is the same byte rate as [IecCarrier]'s 8 channels at 192kHz.
*/
private const val CARRIER_IEC958_RATE = 768_000
/** Core SFREQ index to Hz (`ff_dca_sample_rates`); zero marks invalid indices. */
private val CORE_SAMPLE_RATES = intArrayOf(
0, 8000, 16000, 32000, 0, 0, 11025, 22050, 44100, 0, 0, 12000, 24000, 48000, 96000, 192000
)
/** Precedes every burst payload; `spdifenc.c`'s `dtshd_start_code`. */
private val START_CODE = byteArrayOf(0x01, 0, 0, 0, 0, 0, 0, 0, 0xFE.toByte(), 0xFE.toByte())
/** Seconds of core-only output after an overflow; FFmpeg's `dtshd_fallback_time` default. */
private const val HD_STRIP_SECONDS = 60
/** Minimum bytes needed to read a core header through its SFREQ field. */
private const val MIN_CORE_HEADER_LENGTH = 9
/** IEC 61937-11 subtype for a burst repetition period in IEC 60958 frames, or -1. */
private fun subtypeForPeriod(period: Long): Int = when (period) {
512L -> 0
1024L -> 1
2048L -> 2
4096L -> 3
8192L -> 4
16384L -> 5
else -> -1
}
private fun readSyncWord(data: ByteArray, offset: Int): Int = ((data[offset].toInt() and 0xFF) shl 24) or
((data[offset + 1].toInt() and 0xFF) shl 16) or
((data[offset + 2].toInt() and 0xFF) shl 8) or
(data[offset + 3].toInt() and 0xFF)
/** Reads [count] (≤ 24) bits big-endian starting at absolute bit [bitPosition]. */
private fun readBits(data: ByteArray, bitPosition: Int, count: Int): Int {
var result = 0
var position = bitPosition
var remaining = count
while (remaining > 0) {
val byte = data[position ushr 3].toInt() and 0xFF
val bitsLeftInByte = 8 - (position and 7)
val take = minOf(bitsLeftInByte, remaining)
result = (result shl take) or ((byte shr (bitsLeftInByte - take)) and ((1 shl take) - 1))
position += take
remaining -= take
}
return result
}
/** `NBLKS + 1`: PCM blocks of 32 samples in the core frame at [offset]. */
private fun coreBlocks(data: ByteArray, offset: Int): Int {
val word = ((data[offset + 4].toInt() and 0xFF) shl 8) or (data[offset + 5].toInt() and 0xFF)
return ((word shr 2) and 0x7F) + 1
}
/** `FSIZE + 1`: the core frame's byte length. */
private fun coreFrameSize(data: ByteArray, offset: Int): Int {
val bits = ((data[offset + 5].toInt() and 0xFF) shl 16) or
((data[offset + 6].toInt() and 0xFF) shl 8) or
(data[offset + 7].toInt() and 0xFF)
return ((bits shr 4) and 0x3FFF) + 1
}
/** The core `SFREQ` field mapped to Hz; 0 for reserved indices. */
private fun coreSampleRate(data: ByteArray, offset: Int): Int = CORE_SAMPLE_RATES[((data[offset + 8].toInt() and 0xFF) shr 2) and 0x0F]
/**
* Total byte length of the extension substream at [offset] (`nuBits4ExSSFsize + 1`), or 0
* when the header does not fit in [limit].
*
* Header layout after the 32-bit sync: UserDefinedBits(8), nExtSSIndex(2),
* bHeaderSizeType(1), then a header-size field of 8 or 12 bits and this size field of 16 or
* 20 bits — at most 75 bits, so 10 bytes cover every shape.
*/
private fun extensionSubstreamSize(data: ByteArray, offset: Int, limit: Int): Int {
if (offset + 10 > limit) return 0
val base = offset shl 3
val wide = readBits(data, base + 42, 1) == 1
val sizeFieldPosition = base + 43 + if (wide) 12 else 8
return readBits(data, sizeFieldPosition, if (wide) 20 else 16) + 1
}
}
/** Burst geometry learned from the stream's core framing; zero until the first unit packs. */
private var burstBytes = 0
private var burstBacking = Array(2) { ByteArray(0) }
private var burstBuffers = Array(2) { ByteBuffer.wrap(burstBacking[it]) }
private var burstIndex = 0
/** Bytes each reusable buffer was dirtied to, so padding only clears what a prior burst wrote. */
private val dirtyEnd = intArrayOf(0, 0)
/** Assembles start code + size + access unit before the byte swap; sized with the bursts. */
private var payloadScratch = ByteArray(0)
/** Access units still to strip to their core after an overflow. */
private var hdStripRemaining = 0
/**
* Latched when a burst had to be stripped to the core substream, so the sink can log the
* downgrade once. Cleared by [reset].
*/
var strippedToCore = false
private set
override var unsupportedStream = false
private set
override fun reset() {
// Buffers and the learned burst geometry survive; only per-stream state drops. The flag is
// re-learned from the next unit; leaving it latched would silence every later stream.
hdStripRemaining = 0
strippedToCore = false
unsupportedStream = false
}
override fun accessUnitLength(data: ByteArray, offset: Int, limit: Int): Int {
if (offset + 4 > limit) return 0
when (readSyncWord(data, offset)) {
SYNC_CORE -> Unit
SYNC_EXSS -> {
// A stray HD frame without its core, seen at stream starts. Its size is walkable, so it
// is consumed as a unit and dropped by packAccessUnit; FFmpeg discards these too.
val size = extensionSubstreamSize(data, offset, limit)
return if (size < 4 || offset + size > limit) 0 else size
}
SYNC_CORE_LE, SYNC_CORE_14B_BE, SYNC_CORE_14B_LE -> {
unsupportedStream = true
return 0
}
else -> return 0
}
if (offset + MIN_CORE_HEADER_LENGTH > limit) return 0
val coreSize = coreFrameSize(data, offset)
var end = offset + coreSize
if (coreSize < MIN_CORE_HEADER_LENGTH || end > limit) return 0
// Master Audio glues one or more extension substreams to the core; they belong to this unit.
while (end + 4 <= limit && readSyncWord(data, end) == SYNC_EXSS) {
val size = extensionSubstreamSize(data, end, limit)
if (size < 4 || end + size > limit) return 0
end += size
}
return end - offset
}
override fun packAccessUnit(data: ByteArray, offset: Int, length: Int): ByteBuffer? {
if (length < MIN_CORE_HEADER_LENGTH) return null
when (readSyncWord(data, offset)) {
SYNC_CORE -> Unit
// The stray leading HD frame accessUnitLength admitted; there is no core to derive a
// period from, so it is dropped rather than carried.
SYNC_EXSS -> return null
else -> return null
}
val blocks = coreBlocks(data, offset)
val coreSize = coreFrameSize(data, offset)
val sampleRate = coreSampleRate(data, offset)
if (sampleRate == 0) {
unsupportedStream = true
return null
}
val coreSamples = blocks shl 5
val periodProduct = CARRIER_IEC958_RATE.toLong() * coreSamples
val period = periodProduct / sampleRate
val newSubtype = if (periodProduct % sampleRate != 0L) -1 else subtypeForPeriod(period)
if (newSubtype < 0) {
// 44.1kHz-family cores and exotic frame lengths map to no IEC 61937-11 repetition period at
// this carrier rate; FFmpeg refuses them the same way, so the stream decodes instead.
unsupportedStream = true
return null
}
setBurstGeometry((period * 4).toInt())
// FFmpeg's overflow answer: a Master Audio peak the carrier cannot hold strips this and the
// next ~60 seconds of units to the always-fitting core substream, so the receiver does not
// flap between core and MA decoding.
if (START_CODE.size + 2 + length > burstBytes - BURST_HEADER_SIZE) {
hdStripRemaining = sampleRate * HD_STRIP_SECONDS / coreSamples
}
var payloadSize = length
if (hdStripRemaining > 0 && coreSize <= length) {
payloadSize = coreSize
hdStripRemaining--
strippedToCore = true
}
val payloadBytes = START_CODE.size + 2 + payloadSize
if (payloadBytes > burstBytes - BURST_HEADER_SIZE) {
// Even the bare core overflows this period (only possible for very short core frames);
// nothing can be carried.
unsupportedStream = true
return null
}
START_CODE.copyInto(payloadScratch, 0)
payloadScratch[START_CODE.size] = (payloadSize ushr 8).toByte()
payloadScratch[START_CODE.size + 1] = (payloadSize and 0xFF).toByte()
data.copyInto(payloadScratch, START_CODE.size + 2, offset, offset + payloadSize)
// A final lone byte goes out MSB-aligned; its swap partner must be zero, not stale scratch.
if (payloadBytes and 1 == 1) payloadScratch[payloadBytes] = 0
burstIndex = burstIndex xor 1
val backing = burstBacking[burstIndex]
putLittleEndianShort(backing, 0, SYNCWORD1)
putLittleEndianShort(backing, 2, SYNCWORD2)
putLittleEndianShort(backing, 4, IEC61937_DTSHD or (newSubtype shl 8))
// Aligned so (Pd & 0xF) == 0x8, which some receivers reportedly require; FFmpeg and Kodi
// both apply the same quirk.
putLittleEndianShort(backing, 6, ((payloadBytes + 0x17) and 0x0F.inv()) - BURST_HEADER_SIZE)
// The carrier is a 16-bit sample stream, so the payload goes out byte-swapped per word.
var source = 0
var destination = BURST_HEADER_SIZE
val swappedPayload = payloadBytes + (payloadBytes and 1)
while (source < swappedPayload) {
backing[destination] = payloadScratch[source + 1]
backing[destination + 1] = payloadScratch[source]
source += 2
destination += 2
}
if (destination < dirtyEnd[burstIndex]) {
java.util.Arrays.fill(backing, destination, dirtyEnd[burstIndex], 0)
}
dirtyEnd[burstIndex] = destination
val burst = burstBuffers[burstIndex]
burst.limit(burstBytes)
burst.position(0)
return burst
}
private fun setBurstGeometry(newBurstBytes: Int) {
if (newBurstBytes == burstBytes) return
burstBytes = newBurstBytes
burstBacking = Array(2) { ByteArray(newBurstBytes) }
burstBuffers = Array(2) { ByteBuffer.wrap(burstBacking[it]).order(java.nio.ByteOrder.LITTLE_ENDIAN) }
dirtyEnd[0] = 0
dirtyEnd[1] = 0
payloadScratch = ByteArray(newBurstBytes)
}
private fun putLittleEndianShort(target: ByteArray, offset: Int, value: Int) {
target[offset] = (value and 0xFF).toByte()
target[offset + 1] = ((value shr 8) and 0xFF).toByte()
}
}
@@ -218,6 +218,9 @@ class ExoPlayerCore(private val activity: Activity) :
private var subtitleAnchorToScreen: Boolean = false
private var lastSubtitleCues: List<Cue> = emptyList()
// Retain the inferred composition-plane aspect across empty cue groups.
private var bitmapSubtitlePlaneAspect: Float? = null
// Tracks whether a text track was selected on the previous onTracksChanged so we
// can detect the transition to "no subtitle" and clear the painted overlays (#1387).
private var hadSelectedTextTrack: Boolean = false
@@ -226,6 +229,12 @@ class ExoPlayerCore(private val activity: Activity) :
private var trackSelector: DefaultTrackSelector? = null
private var tunnelingUserEnabled: Boolean = true
private var tunnelingDisabledForAudioCodec: Boolean = false
// Tunnelled playback is driven by the audio codec's clock, so without a
// hardware audio decoder media3 never tunnels regardless of the flag —
// used to skip selector churn for no-op flips (see
// updateCurrentTunnelingState). True until an evaluation says otherwise.
private var selectedAudioHasHwDecoder: Boolean = true
private var tunnelingDisabledForVideoCodec: Boolean = false
private var tunnelingDisabledForDecodedPcm: Boolean = false
private var tunnelingDisabledForAudioRecovery: Boolean = false
@@ -311,6 +320,7 @@ class ExoPlayerCore(private val activity: Activity) :
private var lastAudioRecoveryReason: String? = null
private var lastAudioSinkError: String? = null
private var loggedEwasteEac3Workaround: Boolean = false
private val loggedDtsAppDecoderMimes = mutableSetOf<String>()
private var lastTrueHdDirectOutputLogKey: String? = null
private var loggedDecodedPcmTunnelingGuard: Boolean = false
private var hasRenderedVideoFrameForMedia: Boolean = false
@@ -561,8 +571,6 @@ class ExoPlayerCore(private val activity: Activity) :
}
fun initialize(
bufferSizeBytes: Int? = null,
bufferSizeAuto: Boolean = false,
tunnelingEnabled: Boolean = true,
audioPassthroughEnabled: Boolean = false,
// Read-ahead depth, as the wire name Dart sends. Kept a String because `LoadControlPolicy`
@@ -727,10 +735,12 @@ class ExoPlayerCore(private val activity: Activity) :
val handler = AssHandler()
assHandler = handler
val assParserFactory = AssSubtitleParserFactory(handler)
// PGS goes through PgsCompositionParser; media3's parser drops all but one
// composition object and blanks palette-only fade updates (#1953).
val subtitleParserFactory = PgsSubtitleParserFactory(AssSubtitleParserFactory(handler))
// Wrap extractors: replace MatroskaExtractor with ASS+DV variant,
// wrap MP4 extractors with DV converter when enabled.
// Wrap extractors: replace MatroskaExtractor with the ASS+zlib+LATM
// variant, wrap MP4 extractors with the DV converter when enabled.
// Reads this.dvMode each time (not captured) so DV7→8.1 retry can
// change mode and reload without reinitializing the player.
val wrappedExtractorsFactory = androidx.media3.extractor.ExtractorsFactory {
@@ -739,7 +749,7 @@ class ExoPlayerCore(private val activity: Activity) :
extractorsFactory.createExtractors().map { extractor ->
when {
extractor is MatroskaExtractor -> {
val assExtractor = ZlibMatroskaExtractor(assParserFactory, handler)
val assExtractor = ZlibMatroskaExtractor(subtitleParserFactory, handler)
val inner = if (doviEnabled) {
DoviExtractorWrapper(assExtractor, currentDvMode) { level, prefix, message ->
emitLog(level, prefix, message)
@@ -765,7 +775,7 @@ class ExoPlayerCore(private val activity: Activity) :
}
val mediaSourceFactory = DefaultMediaSourceFactory(dataSourceFactory!!, wrappedExtractorsFactory)
.setSubtitleParserFactory(assParserFactory)
.setSubtitleParserFactory(subtitleParserFactory)
playbackMediaSourceFactory = mediaSourceFactory
// Wrap text renderers with subtitle delay support
@@ -775,21 +785,15 @@ class ExoPlayerCore(private val activity: Activity) :
.toTypedArray()
}
// Buffer budget. `bufferSizeBytes` carries the user's explicit Buffer Size choice; on
// Auto it still arrives (Dart derives it for mpv's demuxer, which shares the property)
// but `bufferSizeAuto` says to ignore it here, because mpv's demuxer and ExoPlayer's
// sample allocator have different shapes and different failure modes.
// Buffer budget. Derived natively from device memory (LoadControlPolicy);
// mpv's demuxer sizes itself the same way in MpvPlayerCore.
val activityManager = activity.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val memoryInfo = ActivityManager.MemoryInfo()
activityManager.getMemoryInfo(memoryInfo)
val availableMB = (memoryInfo.availMem / (1024 * 1024)).toInt()
val largeHeapMB = activityManager.largeMemoryClass
val targetBufferBytes = if (!bufferSizeAuto && bufferSizeBytes != null && bufferSizeBytes > 0) {
bufferSizeBytes
} else {
LoadControlPolicy.autoTargetBufferBytes(largeHeapMB, availableMB)
}
val targetBufferBytes = LoadControlPolicy.autoTargetBufferBytes(largeHeapMB, availableMB)
val resolvedTier = LoadControlPolicy.BufferTier.fromWire(bufferTier)
val bufferDurations = LoadControlPolicy.bufferDurations(resolvedTier, availableMB)
@@ -812,8 +816,8 @@ class ExoPlayerCore(private val activity: Activity) :
emitLog(
"info",
"init",
"Buffer: ${targetBufferBytes / 1024 / 1024}MB limit (${if (bufferSizeAuto) "auto" else "manual"}, " +
"heap=${largeHeapMB}MB, available=${availableMB}MB), " +
"Buffer: ${targetBufferBytes / 1024 / 1024}MB limit " +
"(heap=${largeHeapMB}MB, available=${availableMB}MB), " +
"buffer=${bufferDurations.minBufferMs / 1000}-${bufferDurations.maxBufferMs / 1000}s " +
"(${resolvedTier.name.lowercase()}), " +
"tunneling=$tunnelingUserEnabled, dataSource=$dataSourceLabel"
@@ -1110,11 +1114,31 @@ class ExoPlayerCore(private val activity: Activity) :
private fun renderSubtitleCues(cues: List<Cue>) {
val textCues = cues.filter { it.bitmap == null }
val bitmapCues = cues.filter { it.bitmap != null }
updateBitmapSubtitlePlaneAspect(bitmapCues)
val outgoing = SubtitleCueLayout.layout(textCues, subtitlePositionPercent, subtitleFontSize)
subtitleView?.setCues(outgoing)
bitmapSubtitleView?.setCues(bitmapCues)
}
private fun updateBitmapSubtitlePlaneAspect(bitmapCues: List<Cue>) {
val inferredAspect = bitmapCues.firstNotNullOfOrNull { cue ->
val bitmap = cue.bitmap ?: return@firstNotNullOfOrNull null
SubtitleViewLayout.bitmapPlaneAspect(
bitmap.width,
bitmap.height,
cue.size,
cue.bitmapHeight
)
} ?: return
val previousAspect = bitmapSubtitlePlaneAspect
if (previousAspect != null && kotlin.math.abs(inferredAspect / previousAspect - 1f) <= 0.001f) return
bitmapSubtitlePlaneAspect = inferredAspect
lastVideoSize?.let {
updateSubtitleViewSize(it.width, it.height, it.pixelWidthHeightRatio)
}
}
private fun handleIsPlayingChanged(isPlaying: Boolean) {
Log.d(TAG, "onIsPlayingChanged: $isPlaying")
// A pause/resume can occur entirely between watchdog polls while the
@@ -1230,12 +1254,13 @@ class ExoPlayerCore(private val activity: Activity) :
}
}
// Disabling the text track produces no trailing empty CueGroup, and no new
// video frame re-renders the libass overlay while paused, so the last SRT/VTT
// cue stays painted on the SubtitleViews and the last ASS frame stays on the
// overlay. AssHandler (registered before this listener) has already nulled the
// libass track by now, so re-rendering the last position clears it. Gate on the
// transition to avoid redundant clears on every track change. (#1387)
// Disabling the text track produces no trailing empty CueGroup, so the last
// SRT/VTT cue stays painted on the SubtitleViews. AssHandler (registered
// before this listener) has already nulled the libass track by now, so the
// invalidate pushes one request through the atlas pipeline, which swaps an
// explicit blank frame for a trackless render — required while paused, where
// no video frame triggers one. Gate on the transition to avoid redundant
// clears on every track change. (#1387, #1884)
val hasSelectedText = hasSelectedTextTrack(tracks)
if (!hasSelectedText && hadSelectedTextTrack) {
lastSubtitleCues = emptyList()
@@ -1767,8 +1792,7 @@ class ExoPlayerCore(private val activity: Activity) :
videoWidth,
videoHeight,
pixelRatio,
resizeMode,
videoZoomScale
bitmapSubtitlePlaneAspect
)
activity.runOnUiThread {
@@ -2293,7 +2317,20 @@ class ExoPlayerCore(private val activity: Activity) :
}
return true
}
return false
// DTS that is going to decode must not decode in a platform codec: on license-gated
// Amlogic boxes (the Onn family) the platform decoder drains normally while rendering
// silence (#1995). Bitstream-capable routes are untouched — media3 selects direct output
// before consulting the decoder list, and the visible platform decoder keeps the
// tunneling gate as it was.
val forceDts = shouldForceFfmpegDtsDecode(
mimeType,
directOutputBlocked = { shouldBlockDirectAudioOutput(dtsProbeFormat(mimeType), "decoder selection") },
routeCanBitstreamDts = { routeCanBitstreamDts(mimeType) }
)
if (forceDts && loggedDtsAppDecoderMimes.add(mimeType)) {
emitLog("info", "decoder", "Using app decoder for $mimeType; the stream will decode and platform DTS decoders render silence on license-gated devices")
}
return forceDts
}
private fun evaluateTrueHdDirectOutput(format: Format?): TrueHdDirectOutputDecision {
@@ -2402,6 +2439,33 @@ class ExoPlayerCore(private val activity: Activity) :
.build()
}
/**
* Whether the current route can bitstream [mimeType] at all: media3's raw direct path
* ([AudioCapabilities]) or, for DTS-HD, the IEC 61937 carrier ([IecCarrierSink]). When this
* is false the stream decodes regardless of the passthrough setting.
*/
private fun routeCanBitstreamDts(mimeType: String): Boolean {
if (mimeType == MimeTypes.AUDIO_DTS_HD && supportsDtsHdIecCarrier(activity)) return true
val audioAttributes = buildMovieAudioAttributes()
return try {
AudioCapabilities
.getCapabilities(activity, audioAttributes, null)
.isPassthroughPlaybackSupported(dtsProbeFormat(mimeType), audioAttributes)
} catch (e: Exception) {
// An unanswerable probe biases toward FFmpeg decode. A wrong "can't bitstream" is benign
// (bypass still wins before decoder selection); a wrong "can" leaves the silent platform
// decode path reachable.
false
}
}
/** DTS selection probe at the family's common shape; decoder selection only knows the mime. */
private fun dtsProbeFormat(mimeType: String): Format = Format.Builder()
.setSampleMimeType(mimeType)
.setChannelCount(6)
.setSampleRate(48_000)
.build()
@RequiresApi(Build.VERSION_CODES.Q)
@Suppress("DEPRECATION")
private fun isDirectPlaybackSupportedApi29(
@@ -2633,6 +2697,18 @@ class ExoPlayerCore(private val activity: Activity) :
private fun updateCurrentTunnelingState(reason: String, shouldTunnel: Boolean): Boolean {
if (shouldTunnel == currentTunneledPlayback) return false
// A switch to "off" that the selected audio decoder could never have
// honored anyway is transparent to media3: tunnelled playback needs a
// tunneling-capable audio codec (it owns the AV-sync clock), so a
// software decoder already ignored the flag. Writing the selector
// parameter regardless forces a renderer rebuild that can tear down a
// live codec mid-queueInputBuffer — observed as
// "queueInputBuffer ... Released state" right after tracks arrive from
// the ffmpeg demuxer. Record the state without the churn.
if (!shouldTunnel && !selectedAudioHasHwDecoder) {
currentTunneledPlayback = false
return false
}
currentTunneledPlayback = shouldTunnel
val speed = exoPlayer?.playbackParameters?.speed ?: 1f
val audioDelayActive = (renderersFactory?.audioDelayUs?.get() ?: 0L) != 0L
@@ -2660,6 +2736,7 @@ class ExoPlayerCore(private val activity: Activity) :
}
val newDisabled = !hasHardwareAudioDecoder(mimeType)
selectedAudioHasHwDecoder = !newDisabled
if (newDisabled != tunnelingDisabledForAudioCodec) {
tunnelingDisabledForAudioCodec = newDisabled
emitLog("info", "tunneling", "Audio codec ${format.codecs} ($mimeType): tunneling ${if (newDisabled) "DISABLED (no hw decoder)" else "enabled"}")
@@ -3381,6 +3458,7 @@ class ExoPlayerCore(private val activity: Activity) :
externalSubtitleUris.clear()
externalSubtitleContainerUris.clear()
lastSubtitleCues = emptyList()
bitmapSubtitlePlaneAspect = null
hadSelectedTextTrack = false
audioTrackGroupMap.clear()
subtitleTrackGroupMap.clear()
@@ -4044,6 +4122,7 @@ class ExoPlayerCore(private val activity: Activity) :
extraDelayMs: Long,
videoWidth: Int,
videoHeight: Int,
matchResolution: Boolean,
onComplete: (switched: Boolean) -> Unit
) {
val mgr = frameRateManager
@@ -4051,11 +4130,17 @@ class ExoPlayerCore(private val activity: Activity) :
onComplete(false)
return
}
mgr.setVideoFrameRate(fps, videoDurationMs, extraDelayMs, videoWidth, videoHeight, onComplete)
mgr.setVideoFrameRate(fps, videoDurationMs, extraDelayMs, videoWidth, videoHeight, matchResolution, onComplete)
}
override fun clearVideoFrameRate() {
frameRateManager?.clearVideoFrameRate()
// HDR content on an HDR display means the decoder's dataspace put the
// display into HDR signaling; defer the rate restore past the HDR exit
// (see FrameRateManager.clearVideoFrameRate).
val transfer = currentVideoFormat?.colorInfo?.colorTransfer
val hdrActive = (transfer == C.COLOR_TRANSFER_ST2084 || transfer == C.COLOR_TRANSFER_HLG) &&
DoviBridge.displaySupportsHdr(activity)
frameRateManager?.clearVideoFrameRate(hdrActive = hdrActive)
}
private fun computeFrameRate(timestamps: LongArray): Float {
@@ -4146,7 +4231,7 @@ class ExoPlayerCore(private val activity: Activity) :
"audioMimeType" to audioFormat?.sampleMimeType,
"audioSampleRate" to audioFormat?.sampleRate,
"audioChannels" to audioFormat?.channelCount,
"audioBitrate" to audioFormat?.bitrate,
"audioBitrate" to audioFormat?.bitrate?.takeIf { it > 0 },
"audioDecoderName" to audioDecoderInitName,
"audioOutputEncoding" to audioTrackConfig?.encoding,
"audioOutputChannels" to audioTrackConfig?.channelConfig?.let { Integer.bitCount(it) },
@@ -1,8 +1,6 @@
package com.edde746.plezy.exoplayer
import android.app.Activity
import android.app.ActivityManager
import android.content.Context
import android.util.Log
import com.edde746.plezy.libass.media.AssHandler
import com.edde746.plezy.mpv.MpvPlayerCore
@@ -40,6 +38,11 @@ class ExoPlayerPlugin :
private val mainHandler get() = channels.mainHandler
private fun runOnMain(block: () -> Unit) = channels.runOnMain(block)
private var playerCore: ExoPlayerCore? = null
// The Dart instanceId that created the current core. A `dispose` carrying a
// different token lost the ownership race to a successor and must not tear
// down that successor's session; it is acknowledged without touching it.
private var coreInstanceId: Long? = null
private var mpvCore: MpvPlayerCore? = null // MPV fallback player
private var usingMpvFallback: Boolean = false
private var fallbackInProgress: Boolean = false
@@ -108,8 +111,6 @@ class ExoPlayerPlugin :
private val observedProperties = LinkedHashMap<String, ObservedProperty>()
private var configuredBufferSizeBytes: Int? = null
private var sessionGeneration = 0
private var mediaGeneration = 0
private var fallbackMediaGeneration: Int? = null
@@ -119,7 +120,8 @@ class ExoPlayerPlugin :
private var mpvForwardGeneration: Int? = null
private var mpvSignalGate: MpvSignalGate? = null
private var mpvCoreNeedsReplacement = false
internal var createMpvCore: (Activity) -> MpvPlayerCore = { MpvPlayerCore(it) }
internal var createMpvCore: (Activity) -> MpvPlayerCore =
{ MpvPlayerCore(it, hardwareDecoding = fallbackHardwareDecoding()) }
internal var initializeMpvCore: (MpvPlayerCore, (Boolean) -> Unit) -> Unit = { core, onInitialized ->
core.initialize(onInitialized)
}
@@ -139,6 +141,12 @@ class ExoPlayerPlugin :
// every codec in audio-spdif with no decode fallback, so the fallback core's value is
// derived from the audio route at the moment mpv actually starts (#1703).
private var audioPassthroughRequested = false
// `dv-conversion-mode` is not an mpv property and never reaches
// pendingMpvProperties: Dart routes it through setDvConversionMode (see
// PlayerAndroid.setProperty), so the fallback core has to be seeded from the
// last configured value or it loses the fork's P7/P5 handling entirely.
private var dvConversionMode = "auto"
private var currentExternalSubtitles: List<Map<String, Any?>>? = null
// FlutterPlugin
@@ -158,6 +166,7 @@ class ExoPlayerPlugin :
val exoCore = playerCore
val fallbackCore = mpvCore
playerCore = null
coreInstanceId = null
mpvCore = null
usingMpvFallback = false
fallbackInProgress = false
@@ -174,6 +183,7 @@ class ExoPlayerPlugin :
currentExternalSubtitles = null
pendingMpvProperties.clear()
audioPassthroughRequested = false
dvConversionMode = "auto"
if (clearActivity) {
activity = null
activityBinding = null
@@ -224,7 +234,7 @@ class ExoPlayerPlugin :
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
when (call.method) {
"initialize" -> handleInitialize(call, result)
"dispose" -> handleDispose(result)
"dispose" -> handleDispose(call, result)
"open" -> handleOpen(call, result)
"play" -> handlePlay(result)
"pause" -> handlePause(result)
@@ -250,10 +260,6 @@ class ExoPlayerPlugin :
)
"getStats" -> handleGetStats(result)
"getPlayerType" -> result.success(if (usingMpvFallback) "mpv" else "exoplayer")
"getHeapSize" -> {
val am = activity?.getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager
result.success(am?.largeMemoryClass ?: 0)
}
"setSubtitleStyle" -> handleSetSubtitleStyle(call, result)
"setBoxFitMode" -> handleSetBoxFitMode(call, result)
"setVideoZoom" -> handleSetVideoZoom(call, result)
@@ -291,20 +297,14 @@ class ExoPlayerPlugin :
return
}
val bufferSizeBytes = call.argument<Int>("bufferSizeBytes")
// Auto sizing is decided natively (LoadControlPolicy). `bufferSizeBytes` still arrives
// on Auto because Dart derives one for mpv's demuxer, which shares the property, and
// the fallback replay below needs it.
val bufferSizeAuto = call.argument<Boolean>("bufferSizeAuto") ?: false
val tunnelingEnabled = call.argument<Boolean>("tunnelingEnabled") ?: true
val dvConversionMode = call.argument<String>("dvConversionMode") ?: "auto"
val tunnelingEnabled = call.argument<Boolean>("tunnelingEnabled") ?: false
dvConversionMode = call.argument<String>("dvConversionMode") ?: "auto"
val audioPassthroughEnabled = call.argument<Boolean>("audioPassthroughEnabled") ?: false
val assVideoLatencyFrames = call.argument<Int>("assVideoLatencyFrames") ?: 0
val subtitleRenderScale = call.argument<Double>("subtitleRenderScale")?.toFloat() ?: 1.0f
// ExoPlayer-only: mpv's read-ahead is owned by the mpv.conf editor, so there is no
// fallback replay for this one. Resolved in the core; unrecognised means Auto (#1816).
val bufferTier = call.argument<String>("bufferTier") ?: "auto"
configuredBufferSizeBytes = bufferSizeBytes
// Seed the request here rather than waiting for Dart's separate setAudioPassthrough
// call, so a fallback raised before that arrives still derives audio-spdif correctly.
audioPassthroughRequested = audioPassthroughEnabled
@@ -343,9 +343,8 @@ class ExoPlayerPlugin :
this.debugLoggingEnabled = this@ExoPlayerPlugin.debugLoggingEnabled
}
playerCore = core
coreInstanceId = call.argument<Number>("instanceId")?.toLong()
val success = core.initialize(
bufferSizeBytes = bufferSizeBytes,
bufferSizeAuto = bufferSizeAuto,
tunnelingEnabled = tunnelingEnabled,
audioPassthroughEnabled = audioPassthroughEnabled,
bufferTier = bufferTier
@@ -373,8 +372,15 @@ class ExoPlayerPlugin :
}
}
private fun handleDispose(result: MethodChannel.Result) {
private fun handleDispose(call: MethodCall, result: MethodChannel.Result) {
val token = call.argument<Number>("instanceId")?.toLong()
runOnMain {
val owner = coreInstanceId
if ((playerCore != null || mpvCore != null) && token != null && owner != null && token != owner) {
Log.d(TAG, "Ignoring stale dispose (token=$token, core owner=$owner)")
result.success(null)
return@runOnMain
}
teardownSession(clearActivity = false)
Log.d(TAG, "Disposed")
result.success(null)
@@ -1015,14 +1021,19 @@ class ExoPlayerPlugin :
val extraDelayMs = call.argument<Number>("extraDelayMs")?.toLong() ?: 0L
val videoWidth = call.argument<Number>("videoWidth")?.toInt() ?: 0
val videoHeight = call.argument<Number>("videoHeight")?.toInt() ?: 0
val matchResolution = call.argument<Boolean>("matchResolution") ?: false
Log.d(TAG, "setVideoFrameRate: fps=$fps, duration=$duration, extraDelayMs=$extraDelayMs, video=${videoWidth}x$videoHeight")
Log.d(
TAG,
"setVideoFrameRate: fps=$fps, duration=$duration, extraDelayMs=$extraDelayMs, " +
"video=${videoWidth}x$videoHeight, matchResolution=$matchResolution"
)
val core = activeSurfaceCore
if (core == null) {
result.success(false)
return
}
core.setVideoFrameRate(fps, duration, extraDelayMs, videoWidth, videoHeight) { switched ->
core.setVideoFrameRate(fps, duration, extraDelayMs, videoWidth, videoHeight, matchResolution) { switched ->
result.success(switched)
}
}
@@ -1123,12 +1134,24 @@ class ExoPlayerPlugin :
return
}
if (usingMpvFallback) {
result.success(false)
// The fallback core owns the property now; dropping the write would
// strand it on the mode ExoPlayer started with.
val core = mpvCore
if (core == null) {
result.success(false)
return
}
dvConversionMode = mode
core.setProperty("dv-conversion-mode", mode) { outcome ->
completeMpvPropertyResult(result, outcome, successValue = true)
}
return
}
activity?.runOnUiThread {
val handled = playerCore?.setDebugDvConversionMode(mode) == true
if (handled) {
// Keep the fallback seed on the value ExoPlayer is actually running.
dvConversionMode = mode
result.success(true)
} else {
result.error("INVALID_ARGS", "Invalid DV conversion mode: $mode", null)
@@ -1301,6 +1324,16 @@ class ExoPlayerPlugin :
}
}
/**
* Decode intent for a fallback mpv core, read from the `hwdec` value Dart
* already wrote for this session. It picks the core's initial vo chain
* ([MpvPlayerCore.initialVideoOutput]), so a software-decoding session must
* not inherit the hardware default: only gpu-next applies Dolby Vision RPU
* reshaping, and a session that asked for software decode is usually the
* one that needs it.
*/
private fun fallbackHardwareDecoding(): Boolean = pendingMpvProperties["hwdec"]?.let { it != "no" } ?: true
/**
* Configure a freshly initialized MPV fallback core: replay the properties
* and observers Dart registered against the ExoPlayer session, then resume
@@ -1310,15 +1343,13 @@ class ExoPlayerPlugin :
private fun prepareMpvFallback(core: MpvPlayerCore) {
val pendingProps = pendingMpvProperties.filterKeys { it != "audio-spdif" }.toList()
val observedProps = observedProperties.toList()
val bufferSize = configuredBufferSizeBytes
core.setProperty("hwdec", "mediacodec,mediacodec-copy")
core.setProperty("vo", "gpu")
// hwdec is not seeded here — Dart's write in pendingMpvProperties is the
// single source of the fallback core's chain.
core.setProperty("ao", "audiotrack")
if (bufferSize != null && bufferSize > 0) {
core.setProperty("demuxer-max-bytes", bufferSize.toString())
}
// Dart routes dv-conversion-mode through setDvConversionMode, so unlike
// hwdec it never reaches pendingMpvProperties.
core.setProperty("dv-conversion-mode", dvConversionMode)
for ((propName, propValue) in pendingProps) {
core.setProperty(propName, propValue) { outcome ->
@@ -0,0 +1,50 @@
package com.edde746.plezy.exoplayer
import java.nio.ByteBuffer
/**
* The IEC 61937 carrier tuple every packed bitstream rides: 192kHz, 7.1, PCM-16 shaped.
*
* This is the high-bitrate HDMI shape Kodi uses for both TrueHD/MAT and DTS-HD Master Audio, and
* the one [supportsIecCarrier] probes. The 44.1kHz family would need a 176.4kHz sibling, which is
* deliberately not built; streams from that family decode instead.
*/
internal object IecCarrier {
const val SAMPLE_RATE = 192_000
const val CHANNEL_COUNT = 8
const val BYTES_PER_FRAME = CHANNEL_COUNT * 2
}
/**
* Splits one codec's bitstream into access units and packs them into IEC 61937 bursts for
* [IecCarrierSink].
*
* Implementations are not thread safe; the sink drives them from the playback thread only.
*/
internal interface IecCarrierPacker {
/**
* Length in bytes of the access unit starting at [offset], or 0 when no unit boundary is
* recognised there. May latch [unsupportedStream] when the boundary is recognisable but names a
* framing this carrier cannot ride.
*/
fun accessUnitLength(data: ByteArray, offset: Int, limit: Int): Int
/**
* Packs one access unit, returning a completed burst or null when this unit did not finish one.
*
* Returned buffers are owned by the packer and reused, alternating between two so a burst handed
* downstream stays valid while the next one fills. Callers must submit or copy it before the
* second following call.
*/
fun packAccessUnit(data: ByteArray, offset: Int, length: Int): ByteBuffer?
/**
* True when the bitstream announced a shape this carrier cannot ride. The packer emits nothing
* in that state; the sink latches the stream onto the decoder instead.
*/
val unsupportedStream: Boolean
/** Drops all carrier state. Called on flush/seek: bursts must not straddle a discontinuity. */
fun reset()
}
@@ -16,13 +16,16 @@ import java.nio.ByteBuffer
import java.util.concurrent.atomic.AtomicInteger
/**
* Routes Dolby TrueHD through a MAT/IEC 61937 carrier, and everything else through the normal sink
* (#1804).
* Routes Dolby TrueHD (#1804) and DTS-HD Master Audio (#1988) through an IEC 61937 carrier, and
* everything else through the normal sink.
*
* Android will not bitstream raw TrueHD on the TV routes measured for this issue: the platform
* reports `ENCODING_DOLBY_TRUEHD` as offload-only while reporting `ENCODING_IEC61937` at 192kHz/7.1
* as bitstream-capable. Kodi models the same split and packs the carrier itself; media3 only ever
* hands Android raw TrueHD, at the stream rate. This sink adds the missing path.
* Android will not bitstream raw TrueHD on the TV routes measured for #1804: the platform reports
* `ENCODING_DOLBY_TRUEHD` as offload-only while reporting `ENCODING_IEC61937` at 192kHz/7.1 as
* bitstream-capable. Raw `ENCODING_DTS_HD` is worse on Fire OS: the route advertises it, the
* AudioTrack initialises and drains, and the receiver hears silence, because the encoding only
* means "basic profile" there (#1988). Kodi models the same split and packs the carrier itself;
* media3 only ever hands Android the raw encodings, at the stream rate. This sink adds the
* missing path, with one [IecCarrierPacker] per codec.
*
* **Why two delegates rather than one sink with the processors held inactive.** The carrier is a
* bit-exact byte stream that happens to be shaped like PCM. Any sample mutation downmix, Sonic,
@@ -39,49 +42,52 @@ import java.util.concurrent.atomic.AtomicInteger
* delegates so either can be activated later; per-stream calls go to the active one alone.
*/
@OptIn(UnstableApi::class)
internal class TrueHdCarrierSink(
internal class IecCarrierSink(
private val defaultSink: AudioSink,
private val carrierSink: AudioSink,
/** Whether the current route can bitstream the carrier tuple. Evaluated per format. */
private val carrierRouteAvailable: () -> Boolean,
/**
* Whether the current route can bitstream this format on the carrier. Per format: the tuple is
* shared, but a route carrying it does not necessarily advertise every codec riding it.
*/
private val carrierRouteAvailable: (Format) -> Boolean,
/** Whether policy currently forbids bitstreaming at all (downmix, normalization, user setting). */
private val directOutputBlocked: (Format) -> Boolean,
private val log: ((String, String, String) -> Unit)? = null
) : AudioSink {
private companion object {
/** One MAT frame is exactly one carrier period: 3840 frames at 192kHz. */
const val CARRIER_BURST_DURATION_US =
TrueHdMatPacker.MAT_PKT_OFFSET.toLong() / TrueHdMatPacker.CARRIER_BYTES_PER_FRAME *
1_000_000L / TrueHdMatPacker.CARRIER_SAMPLE_RATE
}
private val matPacker = TrueHdMatPacker()
private val dtsHdPacker = DtsHdIecPacker()
private val packer = TrueHdMatPacker()
/** The packer for the configured stream; chosen by mime type in [configure]. */
private var activePacker: IecCarrierPacker = matPacker
private var active: AudioSink = defaultSink
private var carrierActive = false
private var loggedCoreStrip = false
/** A burst the delegate refused; it must be placed before any further input is consumed. */
private var pendingBurst: ByteBuffer? = null
private var pendingBurstTimeUs: Long = 0
/**
* Anchor for carrier timestamps, and how many bursts have been emitted since it.
* Anchor for carrier timestamps, and how many carrier frames have been emitted since it.
*
* Each MAT frame is exactly one carrier period of audio, so timestamps are derived from the
* cadence rather than from whichever access unit happened to close the frame. Handing the sink
* the closing unit's own presentation time drifts against the time it derives from written
* frames, which it reports as a discontinuity on nearly every frame.
* Every burst is a whole number of carrier frames, so timestamps are derived from the cadence
* rather than from whichever access unit happened to close the burst. Handing the sink the
* closing unit's own presentation time drifts against the time it derives from written frames,
* which it reports as a discontinuity on nearly every burst. Counting frames rather than bursts
* keeps the arithmetic exact for burst durations that are not whole microseconds (a DTS-HD
* burst is 10666.67us).
*/
private var carrierAnchorUs: Long = C.TIME_UNSET
private var burstsSinceAnchor: Long = 0
private var carrierFramesSinceAnchor: Long = 0
private var playbackParameters: PlaybackParameters = PlaybackParameters.DEFAULT
private var sinkListener: AudioSink.Listener? = null
/**
* Latched when a stream's bitstream contradicts the rate its container announced, which selection
* was made from.
* Latched when a stream's bitstream contradicts the shape its container announced, which
* selection was made from.
*
* Deliberately outlives [flush] and [reset]: media3 resets every renderer disabled by a new
* selection before enabling the replacement (ExoPlayerImplInternal.enableRenderers), and both
@@ -106,7 +112,6 @@ internal class TrueHdCarrierSink(
@Volatile
private var mismatchGeneration = -1
/**
* True when this format should ride the carrier.
*
@@ -115,16 +120,16 @@ internal class TrueHdCarrierSink(
* [directOutputBlocked] already reports.
*
* The rate family is decided from the format rather than from the packer, which only learns it
* from a major sync once buffers are already flowing far too late for a selection that happens
* before configure.
* from the bitstream once buffers are already flowing far too late for a selection that
* happens before configure.
*/
private fun shouldUseCarrier(format: Format): Boolean {
if (format.sampleMimeType != MimeTypes.AUDIO_TRUEHD) return false
if (!isTrueHd(format) && !isDtsHd(format)) return false
if (mismatchGeneration == mediaGeneration.get()) return false
if (!isCarrierRateFamily(format.sampleRate)) return false
if (playbackParameters.speed != 1f) return false
if (directOutputBlocked(format)) return false
return carrierRouteAvailable()
return carrierRouteAvailable(format)
}
/**
@@ -137,15 +142,15 @@ internal class TrueHdCarrierSink(
private fun carrierFormat(): Format = Format.Builder()
.setSampleMimeType(MimeTypes.AUDIO_RAW)
.setPcmEncoding(C.ENCODING_PCM_16BIT)
.setChannelCount(TrueHdMatPacker.CARRIER_CHANNEL_COUNT)
.setSampleRate(TrueHdMatPacker.CARRIER_SAMPLE_RATE)
.setChannelCount(IecCarrier.CHANNEL_COUNT)
.setSampleRate(IecCarrier.SAMPLE_RATE)
.build()
/**
* TrueHD is deliberately binary: the carrier, or decoded PCM. Never media3's own raw TrueHD path.
*
* That path builds an `ENCODING_DOLBY_TRUEHD` track at the *stream* rate, which is the
* configuration this issue is about one box takes a single write and never advances its
* configuration #1804 is about one box takes a single write and never advances its
* playback head, another freezes for ten seconds, and the third declines it and decodes anyway.
* Even Kodi's raw fallback is a different thing: it only offers raw TrueHD after verifying it at
* 192kHz, which media3 never requests. So when the carrier is unavailable no IEC route, a speed
@@ -154,44 +159,68 @@ internal class TrueHdCarrierSink(
*/
private fun isTrueHd(format: Format): Boolean = format.sampleMimeType == MimeTypes.AUDIO_TRUEHD
/**
* DTS-HD is binary only while the carrier route exists: the carrier, or decoded PCM. Falling
* through to media3's raw `ENCODING_DTS_HD` path on such a route would land on exactly the
* silent configuration #1988 is about the route that advertises the carrier and raw DTS-HD at
* once is the one whose raw path renders silence. Without a carrier route the raw path is the
* pre-carrier behavior and is left alone: those routes never had the carrier to lose, and some
* of them bitstream raw DTS-HD genuinely.
*
* DTS Express deliberately stays off the carrier: its mime carries a `;profile=lbr` suffix, so
* the equality below excludes it and it keeps decoding as before.
*/
private fun isDtsHd(format: Format): Boolean = format.sampleMimeType == MimeTypes.AUDIO_DTS_HD
override fun supportsFormat(format: Format): Boolean = when {
shouldUseCarrier(format) -> true
isTrueHd(format) -> false
isDtsHd(format) && carrierRouteAvailable(format) -> false
else -> defaultSink.supportsFormat(format)
}
override fun getFormatSupport(format: Format): Int = when {
shouldUseCarrier(format) -> AudioSink.SINK_FORMAT_SUPPORTED_DIRECTLY
isTrueHd(format) -> AudioSink.SINK_FORMAT_UNSUPPORTED
isDtsHd(format) && carrierRouteAvailable(format) -> AudioSink.SINK_FORMAT_UNSUPPORTED
else -> defaultSink.getFormatSupport(format)
}
override fun configure(inputFormat: Format, specifiedBufferSize: Int, outputChannels: IntArray?) {
override fun configure(audioSinkConfig: AudioSink.AudioSinkConfig) {
val inputFormat = audioSinkConfig.format
val useCarrier = shouldUseCarrier(inputFormat)
if (useCarrier != carrierActive) {
log?.invoke(
"info",
"audio",
if (useCarrier) {
"TrueHD via MAT/IEC 61937 carrier at ${TrueHdMatPacker.CARRIER_SAMPLE_RATE}Hz/" +
"${TrueHdMatPacker.CARRIER_CHANNEL_COUNT}ch"
"${carrierCodecName(inputFormat)} via IEC 61937 carrier at ${IecCarrier.SAMPLE_RATE}Hz/" +
"${IecCarrier.CHANNEL_COUNT}ch"
} else {
"Leaving the MAT carrier; audio returns to the normal sink"
"Leaving the IEC 61937 carrier; audio returns to the normal sink"
}
)
}
carrierActive = useCarrier
configuredGeneration = mediaGeneration.get()
activePacker = if (isDtsHd(inputFormat)) dtsHdPacker else matPacker
active = if (useCarrier) carrierSink else defaultSink
loggedCoreStrip = false
discardCarrierState()
if (useCarrier) {
carrierSink.configure(carrierFormat(), specifiedBufferSize, null)
val carrierConfig = AudioSink.AudioSinkConfig.Builder(carrierFormat())
.setPreferredBufferSizeOverride(audioSinkConfig.preferredBufferSizeOverride)
.setTimeline(audioSinkConfig.timeline)
.setMediaPeriodId(audioSinkConfig.mediaPeriodId)
.build()
carrierSink.configure(carrierConfig)
} else {
defaultSink.configure(inputFormat, specifiedBufferSize, outputChannels)
defaultSink.configure(audioSinkConfig)
}
}
private fun carrierCodecName(format: Format): String = if (isDtsHd(format)) "DTS-HD" else "TrueHD (MAT)"
override fun handleBuffer(buffer: ByteBuffer, presentationTimeUs: Long, encodedAccessUnitCount: Int): Boolean {
if (!carrierActive) return defaultSink.handleBuffer(buffer, presentationTimeUs, encodedAccessUnitCount)
@@ -213,37 +242,30 @@ internal class TrueHdCarrierSink(
var offset = 0
while (offset < remaining.size) {
val length = TrueHdMatPacker.accessUnitLength(remaining, offset, remaining.size)
val length = activePacker.accessUnitLength(remaining, offset, remaining.size)
if (activePacker.unsupportedStream) return latchMismatch()
if (length == 0) {
// Not a unit boundary we recognise. Consuming the tail keeps the stream moving; trying to
// resynchronise mid-carrier would splice a frame.
buffer.position(buffer.limit())
return true
}
val burst = packer.packAccessUnit(remaining, offset, length)
if (packer.unsupportedRateFamily) {
// Selection is made from Format.sampleRate, so the bitstream disagrees with its container.
// The packer emits nothing in that state; consuming here would turn the stream into
// silence. Leave this unit in the buffer, latch the carrier off, and ask for reselection so
// the decoder takes over and receives it.
if (mismatchGeneration != configuredGeneration) {
mismatchGeneration = configuredGeneration
log?.invoke(
"warn",
"audio",
"TrueHD bitstream announced a 44.1kHz-family rate its container did not; " +
"leaving the carrier so it decodes"
)
sinkListener?.onAudioCapabilitiesChanged()
}
return false
}
val burst = activePacker.packAccessUnit(remaining, offset, length)
if (activePacker.unsupportedStream) return latchMismatch()
offset += length
buffer.position(buffer.position() + length)
if (burst == null) continue
if (activePacker === dtsHdPacker && dtsHdPacker.strippedToCore && !loggedCoreStrip) {
loggedCoreStrip = true
log?.invoke(
"warn",
"audio",
"DTS-HD MA bitrate exceeds the IEC 61937 carrier; sending the DTS core substream for ~60s"
)
}
val burstTimeUs = carrierAnchorUs + burstsSinceAnchor * CARRIER_BURST_DURATION_US
burstsSinceAnchor++
val burstTimeUs = carrierAnchorUs + carrierFramesSinceAnchor * 1_000_000L / IecCarrier.SAMPLE_RATE
carrierFramesSinceAnchor += burst.remaining().toLong() / IecCarrier.BYTES_PER_FRAME
if (!carrierSink.handleBuffer(burst, burstTimeUs, 1)) {
pendingBurst = burst
pendingBurstTimeUs = burstTimeUs
@@ -253,10 +275,35 @@ internal class TrueHdCarrierSink(
return true
}
/**
* The bitstream announced a shape the carrier cannot ride, which selection could not see in the
* container's Format. The packer emits nothing in that state; consuming here would turn the
* stream into silence. Leave the unit in the buffer, latch the carrier off, and ask for
* reselection so the decoder takes over and receives it.
*/
private fun latchMismatch(): Boolean {
if (mismatchGeneration != configuredGeneration) {
mismatchGeneration = configuredGeneration
log?.invoke(
"warn",
"audio",
if (activePacker === dtsHdPacker) {
"DTS-HD bitstream cannot ride the 192kHz carrier (44.1kHz-family core or non-standard framing); " +
"leaving the carrier so it decodes"
} else {
"TrueHD bitstream announced a 44.1kHz-family rate its container did not; " +
"leaving the carrier so it decodes"
}
)
sinkListener?.onAudioCapabilitiesChanged()
}
return false
}
override fun getCurrentPositionUs(sourceEnded: Boolean): Long = active.getCurrentPositionUs(sourceEnded)
override fun playToEndOfStream() {
// A partially filled MAT frame cannot be emitted; up to 20ms is dropped at the end of a stream.
// A partially filled burst cannot be emitted; up to one burst is dropped at the end of a stream.
active.playToEndOfStream()
}
@@ -281,11 +328,12 @@ internal class TrueHdCarrierSink(
override fun getAudioTrackBufferSizeUs(): Long = active.getAudioTrackBufferSizeUs()
private fun discardCarrierState() {
packer.reset()
matPacker.reset()
dtsHdPacker.reset()
pendingBurst = null
// Re-anchor on the next burst: after a seek the carrier restarts from a new media time.
carrierAnchorUs = C.TIME_UNSET
burstsSinceAnchor = 0
carrierFramesSinceAnchor = 0
}
// --- Persistent state: mirrored, so either delegate can be activated later ---
@@ -317,23 +365,23 @@ internal class TrueHdCarrierSink(
if (isUnitSpeed) playbackParameters else PlaybackParameters.DEFAULT
)
// Crossing 1x changes whether TrueHD may ride the carrier, but nothing re-asks on its own:
// the renderer only consults the sink when capabilities are invalidated. Rebuilding the track
// selector parameters is not enough either — DefaultTrackSelector skips invalidation when the
// rebuilt parameters compare equal. This is the path media3 itself uses for a route change,
// and it reaches onRendererCapabilitiesChanged, so the format is re-evaluated and TrueHD moves
// between the carrier and the decoder.
// Crossing 1x changes whether a bitstream may ride the carrier, but nothing re-asks on its
// own: the renderer only consults the sink when capabilities are invalidated. Rebuilding the
// track selector parameters is not enough either — DefaultTrackSelector skips invalidation
// when the rebuilt parameters compare equal. This is the path media3 itself uses for a route
// change, and it reaches onRendererCapabilitiesChanged, so the format is re-evaluated and the
// stream moves between the carrier and the decoder.
if (wasUnitSpeed != isUnitSpeed && (carrierActive || isUnitSpeed)) {
log?.invoke(
"info",
"audio",
"Playback speed ${if (isUnitSpeed) "returned to" else "left"} 1.0x; re-evaluating the TrueHD carrier"
"Playback speed ${if (isUnitSpeed) "returned to" else "left"} 1.0x; re-evaluating the bitstream carrier"
)
sinkListener?.onAudioCapabilitiesChanged()
}
}
/** Whether TrueHD is currently riding the carrier. Read by the core when speed changes. */
/** Whether the configured stream is currently riding the carrier. */
val isCarrierActive: Boolean
get() = carrierActive
@@ -341,7 +389,7 @@ internal class TrueHdCarrierSink(
* While the carrier is live the delegate is deliberately pinned to 1x, but the player polls this
* through the media clock and adopts whatever it reads. Reporting the delegate's value would push
* the pinned 1x back and silently undo the user's speed change, so the requested parameters are
* reported instead; the reselection triggered above then moves TrueHD onto the decoder, which
* reported instead; the reselection triggered above then moves the stream onto the decoder, which
* really can apply them.
*/
override fun getPlaybackParameters(): PlaybackParameters = if (carrierActive) playbackParameters else active.getPlaybackParameters()
@@ -403,7 +451,7 @@ internal class TrueHdCarrierSink(
/**
* Called by the owner immediately before a new media item is set, which is the only point where
* "this stream lied about its rate" stops being true and the carrier can be offered again.
* "this stream lied about its shape" stops being true and the carrier can be offered again.
*/
fun beginMediaItem() {
mediaGeneration.incrementAndGet()
@@ -0,0 +1,310 @@
package com.edde746.plezy.exoplayer
import android.graphics.Bitmap
import androidx.media3.common.C
import androidx.media3.common.Format
import androidx.media3.common.MimeTypes
import androidx.media3.common.text.Cue
import androidx.media3.common.util.Consumer
import androidx.media3.common.util.ParsableByteArray
import androidx.media3.common.util.UnstableApi
import androidx.media3.common.util.Util
import androidx.media3.extractor.text.CuesWithTiming
import androidx.media3.extractor.text.SubtitleParser
import java.util.zip.Inflater
import kotlin.math.min
import kotlin.math.roundToInt
/**
* Delegates to [delegate] for every subtitle format except PGS, which is handled by
* [PgsCompositionParser] because media3's PgsParser drops all but one composition object (#1953).
*/
@UnstableApi
class PgsSubtitleParserFactory(private val delegate: SubtitleParser.Factory) : SubtitleParser.Factory {
override fun supportsFormat(format: Format): Boolean = delegate.supportsFormat(format)
override fun getCueReplacementBehavior(format: Format): Int = delegate.getCueReplacementBehavior(format)
override fun create(format: Format): SubtitleParser = if (format.sampleMimeType == MimeTypes.APPLICATION_PGS) PgsCompositionParser() else delegate.create(format)
}
/**
* PGS subtitle parser that renders every composition object in a display set.
*
* media3's PgsParser keeps one bitmap buffer and only the first composition object's
* coordinates, so a display set with two simultaneous images (dialogue plus a sign or
* song caption) draws the last object at the first object's position and loses the rest.
* It is also stateless across display sets, so Normal-state sets that only update the
* palette (fades) or reuse cached objects blank the screen.
*
* This parser follows FFmpeg's pgssubdec model, which Kodi/mpv/VLC share: objects and
* palettes are cached per epoch keyed by id, any non-Normal composition state releases
* the caches, palette sections update entries in place, and the display-end section
* composes one cue per object reference in the presentation. Colors use limited-range
* BT.709 for HD planes and BT.601 otherwise, matching FFmpeg output.
*/
@UnstableApi
class PgsCompositionParser : SubtitleParser {
companion object {
private const val SECTION_TYPE_PALETTE = 0x14
private const val SECTION_TYPE_OBJECT = 0x15
private const val SECTION_TYPE_PRESENTATION = 0x16
private const val SECTION_TYPE_END = 0x80
// Blu-ray spec limits, as enforced by FFmpeg's pgssubdec.
private const val MAX_OBJECT_REFS = 2
private const val MAX_EPOCH_OBJECTS = 64
private const val MAX_EPOCH_PALETTES = 8
// Bounds object dimensions when a damaged stream declares them before any
// presentation section has established the composition plane.
private const val MAX_PLANE_DIMENSION = 4096
}
private class PgsObject {
var width = 0
var height = 0
var rle = ByteArray(0)
var received = 0
val complete: Boolean
get() = rle.isNotEmpty() && received == rle.size
}
private class ObjectRef(val objectId: Int, val x: Int, val y: Int)
private val buffer = ParsableByteArray()
private val inflatedBuffer = ParsableByteArray()
private var inflater: Inflater? = null
// Epoch state: objects and palettes persist across display sets until a
// non-Normal composition state starts a new epoch or [reset] follows a seek.
private val objects = HashMap<Int, PgsObject>()
private val palettes = HashMap<Int, IntArray>()
// Latest presentation composition.
private var planeWidth = 0
private var planeHeight = 0
private var paletteId = 0
private var objectRefs = emptyList<ObjectRef>()
override fun getCueReplacementBehavior(): Int = Format.CUE_REPLACEMENT_BEHAVIOR_REPLACE
override fun reset() {
objects.clear()
palettes.clear()
objectRefs = emptyList()
planeWidth = 0
planeHeight = 0
paletteId = 0
}
override fun parse(
data: ByteArray,
offset: Int,
length: Int,
outputOptions: SubtitleParser.OutputOptions,
output: Consumer<CuesWithTiming>
) {
buffer.reset(data, offset + length)
buffer.setPosition(offset)
val inflater = this.inflater ?: Inflater().also { this.inflater = it }
if (Util.maybeInflate(buffer, inflatedBuffer, inflater)) {
buffer.reset(inflatedBuffer.data, inflatedBuffer.limit())
}
val cues = ArrayList<Cue>()
while (buffer.bytesLeft() >= 3) {
readNextSection(cues)
}
output.accept(
CuesWithTiming(
cues,
C.TIME_UNSET, // startTimeUs
C.TIME_UNSET // durationUs
)
)
}
private fun readNextSection(cues: MutableList<Cue>) {
val sectionType = buffer.readUnsignedByte()
val sectionLength = buffer.readUnsignedShort()
val nextSectionPosition = buffer.position + sectionLength
if (nextSectionPosition > buffer.limit()) {
buffer.setPosition(buffer.limit())
return
}
when (sectionType) {
SECTION_TYPE_PALETTE -> parsePalette(sectionLength)
SECTION_TYPE_OBJECT -> parseObject(sectionLength)
SECTION_TYPE_PRESENTATION -> parsePresentation(sectionLength)
SECTION_TYPE_END -> composeCues(cues)
// Window sections (0x17) carry no information the composition needs.
}
buffer.setPosition(nextSectionPosition)
}
private fun parsePresentation(sectionLength: Int) {
if (sectionLength < 11) return
planeWidth = buffer.readUnsignedShort()
planeHeight = buffer.readUnsignedShort()
buffer.skipBytes(3) // Frame rate (1), composition number (2).
val compositionState = buffer.readUnsignedByte()
if (compositionState and 0xC0 != 0) {
// Epoch start/acquisition point display sets carry complete data; previous
// epoch objects and palettes are released.
objects.clear()
palettes.clear()
}
buffer.skipBytes(1) // Palette update flag.
paletteId = buffer.readUnsignedByte()
val objectCount = buffer.readUnsignedByte()
var remaining = sectionLength - 11
val refs = ArrayList<ObjectRef>(min(objectCount, MAX_OBJECT_REFS))
for (i in 0 until min(objectCount, MAX_OBJECT_REFS)) {
if (remaining < 8) break
val objectId = buffer.readUnsignedShort()
buffer.skipBytes(1) // Window id.
val flags = buffer.readUnsignedByte()
val x = buffer.readUnsignedShort()
val y = buffer.readUnsignedShort()
remaining -= 8
if (flags and 0x80 != 0) {
// Cropped object: skip the crop rectangle. Like FFmpeg, the crop itself
// is not applied, but the following reference must parse correctly.
if (remaining < 8) break
buffer.skipBytes(8)
remaining -= 8
}
refs.add(ObjectRef(objectId, x, y))
}
objectRefs = refs
}
private fun parsePalette(sectionLength: Int) {
if (sectionLength % 5 != 2) return
val id = buffer.readUnsignedByte()
buffer.skipBytes(1) // Palette version.
if (palettes.size >= MAX_EPOCH_PALETTES && id !in palettes) return
// Entries update in place: fade ramps resend only the entries that changed.
val palette = palettes.getOrPut(id) { IntArray(256) }
val bt709 = planeHeight <= 0 || planeHeight > 576
repeat(sectionLength / 5) {
val index = buffer.readUnsignedByte()
val y = buffer.readUnsignedByte()
val cr = buffer.readUnsignedByte()
val cb = buffer.readUnsignedByte()
val alpha = buffer.readUnsignedByte()
palette[index] = argbColor(y, cb, cr, alpha, bt709)
}
}
private fun parseObject(sectionLength: Int) {
if (sectionLength < 4) return
val id = buffer.readUnsignedShort()
if (objects.size >= MAX_EPOCH_OBJECTS && id !in objects) return
buffer.skipBytes(1) // Object version.
val isFirstFragment = buffer.readUnsignedByte() and 0x80 != 0
var remaining = sectionLength - 4
val obj = objects.getOrPut(id) { PgsObject() }
if (isFirstFragment) {
if (remaining < 7) return
val rleLength = buffer.readUnsignedInt24() - 4 // Length includes the width/height fields.
val width = buffer.readUnsignedShort()
val height = buffer.readUnsignedShort()
remaining -= 7
val maxWidth = if (planeWidth > 0) planeWidth else MAX_PLANE_DIMENSION
val maxHeight = if (planeHeight > 0) planeHeight else MAX_PLANE_DIMENSION
if (rleLength <= 0 || width !in 1..maxWidth || height !in 1..maxHeight) {
obj.rle = ByteArray(0)
obj.received = 0
return
}
obj.width = width
obj.height = height
obj.rle = ByteArray(rleLength)
obj.received = 0
}
val bytesToRead = min(remaining, obj.rle.size - obj.received)
if (bytesToRead > 0) {
buffer.readBytes(obj.rle, obj.received, bytesToRead)
obj.received += bytesToRead
}
}
private fun composeCues(cues: MutableList<Cue>) {
if (planeWidth <= 0 || planeHeight <= 0) return
val palette = palettes[paletteId] ?: return
for (ref in objectRefs) {
// Skip references to missing or incomplete objects (damaged stream, or a
// post-seek Normal set whose epoch data was never observed).
val obj = objects[ref.objectId] ?: continue
if (!obj.complete) continue
cues.add(
Cue.Builder()
.setBitmap(decodeBitmap(obj, palette))
.setPosition(ref.x.toFloat() / planeWidth)
.setPositionAnchor(Cue.ANCHOR_TYPE_START)
.setLine(ref.y.toFloat() / planeHeight, Cue.LINE_TYPE_FRACTION)
.setLineAnchor(Cue.ANCHOR_TYPE_START)
.setSize(obj.width.toFloat() / planeWidth)
.setBitmapHeight(obj.height.toFloat() / planeHeight)
.build()
)
}
}
private fun decodeBitmap(obj: PgsObject, palette: IntArray): Bitmap {
val pixels = IntArray(obj.width * obj.height)
val rle = obj.rle
var input = 0
var output = 0
while (input < rle.size && output < pixels.size) {
val first = rle[input++].toInt() and 0xFF
if (first != 0) {
pixels[output++] = palette[first]
continue
}
if (input >= rle.size) break
val flags = rle[input++].toInt() and 0xFF
if (flags == 0) continue // End-of-line marker.
var run = flags and 0x3F
if (flags and 0x40 != 0) {
if (input >= rle.size) break
run = run shl 8 or (rle[input++].toInt() and 0xFF)
}
val color = if (flags and 0x80 != 0) {
if (input >= rle.size) break
palette[rle[input++].toInt() and 0xFF]
} else {
palette[0]
}
val end = min(output + run, pixels.size)
pixels.fill(color, output, end)
output = end
}
return Bitmap.createBitmap(pixels, obj.width, obj.height, Bitmap.Config.ARGB_8888)
}
private fun argbColor(y: Int, cb: Int, cr: Int, alpha: Int, bt709: Boolean): Int {
val yc = (y - 16) * (255f / 219f)
val cbc = (cb - 128) * (255f / 224f)
val crc = (cr - 128) * (255f / 224f)
val r: Float
val g: Float
val b: Float
if (bt709) {
r = yc + 1.5747f * crc
g = yc - 0.1873f * cbc - 0.4682f * crc
b = yc + 1.8556f * cbc
} else {
r = yc + 1.402f * crc
g = yc - 0.34414f * cbc - 0.71414f * crc
b = yc + 1.772f * cbc
}
return (alpha shl 24) or
(r.roundToInt().coerceIn(0, 255) shl 16) or
(g.roundToInt().coerceIn(0, 255) shl 8) or
b.roundToInt().coerceIn(0, 255)
}
}
@@ -151,14 +151,14 @@ class PlezyRenderersFactory(context: Context) : DefaultRenderersFactory(context)
)
}
private var trueHdCarrierSink: TrueHdCarrierSink? = null
private var iecCarrierSink: IecCarrierSink? = null
/**
* Clears per-stream carrier state that must survive renderer resets but not a new media item.
* Call before setting a new source; see [TrueHdCarrierSink.beginMediaItem].
* Call before setting a new source; see [IecCarrierSink.beginMediaItem].
*/
fun beginMediaItem() {
trueHdCarrierSink?.beginMediaItem()
iecCarrierSink?.beginMediaItem()
}
override fun buildAudioSink(
@@ -166,16 +166,15 @@ class PlezyRenderersFactory(context: Context) : DefaultRenderersFactory(context)
enableFloatOutput: Boolean,
enableAudioOutputPlaybackParams: Boolean
): AudioSink {
AudioTrackAudioOutputProvider.failOnSpuriousAudioTimestamp = false
// Media3 1.11's replacement is fixed at 500ms; preserve the dynamic 5001000ms PCM policy.
@Suppress("DEPRECATION")
val bufferSizeProvider = DefaultAudioTrackBufferSizeProvider.Builder()
.setMinPcmBufferDurationUs(500_000)
.setMaxPcmBufferDurationUs(1_000_000)
.setPcmBufferMultiplicationFactor(4)
// media3 defaults passthrough to 250ms, which the AC3 factor doubles to 500ms — 40000
// bytes at 640 kbps. Some HDMI routes reject a buffer that short outright and the only
// retry media3 1.10.1 has is to keep halving it (#1790). Ask for a second up front;
// upstream adopted the same 1s floor as its last-resort retry in #3207.
// Media3 defaults passthrough to 250ms, which the AC3 factor doubles to 500ms. Some
// HDMI routes reject a buffer that short (#1790). Ask for a second up front; Media3 1.11
// now uses the same one-second floor for its last-resort retry (#3207).
.setPassthroughBufferDurationUs(500_000)
.build()
@@ -205,17 +204,20 @@ class PlezyRenderersFactory(context: Context) : DefaultRenderersFactory(context)
audioDiagnosticsLogger
)
return TrueHdCarrierSink(
return IecCarrierSink(
defaultSink = processedSink,
carrierSink = buildCarrierSink(context, bufferSizeProvider),
carrierRouteAvailable = { supportsTrueHdMatCarrier() },
carrierRouteAvailable = { format -> carrierRouteAvailableFor(context, format) },
directOutputBlocked = { format -> shouldBlockDirectAudioOutput?.invoke(format) == true },
log = audioDiagnosticsLogger
).also { trueHdCarrierSink = it }
).also { iecCarrierSink = it }
}
/** TrueHD needs only the carrier tuple (#1804); DTS-HD also needs the route to advertise it. */
private fun carrierRouteAvailableFor(context: Context, format: Format): Boolean = if (format.sampleMimeType == MimeTypes.AUDIO_DTS_HD) supportsDtsHdIecCarrier(context) else supportsIecCarrier(context)
/**
* The delegate that carries packed TrueHD (#1804).
* The delegate that carries packed TrueHD and DTS-HD (#1804, #1988).
*
* Deliberately separate from the processed sink, and deliberately barren: an empty
* [DefaultAudioSink.AudioProcessorChain] means no downmix, no Sonic, no silence skipping and no
@@ -42,16 +42,35 @@ internal object SubtitleViewLayout {
videoWidth: Int,
videoHeight: Int,
pixelRatio: Float,
resizeMode: Int,
zoomScale: Float
planeAspect: Float?
): SubtitleViewDimensions? {
val videoAspect = videoAspect(videoWidth, videoHeight, pixelRatio) ?: return null
if (containerWidth <= 0 || containerHeight <= 0) return null
val videoAspect = videoAspect(videoWidth, videoHeight, pixelRatio) ?: return null
val visibleVideoBounds = fit(containerWidth, containerHeight, videoAspect)
val layoutAspect = planeAspect?.takeIf { it.isFinite() && it > 0f }
?: return visibleVideoBounds
// PGS/VOB cues are authored in video coordinates, but users expect them to
// remain readable and fully visible when the video is cropped or zoomed.
// Fit to the visible container instead of following the cropped video rect.
return fit(containerWidth, containerHeight, videoAspect)
// Media3 expresses bitmap cue positions and dimensions relative to the
// subtitle composition plane, which can differ from a cropped video's
// dimensions. Fit that plane inside the visible video bounds so cues keep
// their authored geometry without entering the letterbox bars.
return fit(visibleVideoBounds.width, visibleVideoBounds.height, layoutAspect)
}
fun bitmapPlaneAspect(
bitmapWidth: Int,
bitmapHeight: Int,
cueWidthFraction: Float,
cueHeightFraction: Float
): Float? {
if (bitmapWidth <= 0 || bitmapHeight <= 0) return null
if (!cueWidthFraction.isFinite() || cueWidthFraction <= 0f) return null
if (!cueHeightFraction.isFinite() || cueHeightFraction <= 0f) return null
// cueWidth = bitmapWidth / planeWidth and cueHeight = bitmapHeight / planeHeight.
val aspect = bitmapWidth.toDouble() * cueHeightFraction.toDouble() /
(bitmapHeight.toDouble() * cueWidthFraction.toDouble())
return aspect.toFloat().takeIf { it.isFinite() && it > 0f }
}
private fun videoAspect(videoWidth: Int, videoHeight: Int, pixelRatio: Float): Float? {
@@ -24,7 +24,7 @@ import java.nio.ByteBuffer
*
* Not thread safe; the sink drives it from the playback thread only.
*/
internal class TrueHdMatPacker {
internal class TrueHdMatPacker : IecCarrierPacker {
internal companion object {
/** Payload bytes in one MAT frame. */
@@ -33,11 +33,6 @@ internal class TrueHdMatPacker {
/** Bytes from the start of one burst to the next, including preamble and trailing gap. */
const val MAT_PKT_OFFSET = 61440
/** Carrier the packed stream must be played at. */
const val CARRIER_SAMPLE_RATE = 192_000
const val CARRIER_CHANNEL_COUNT = 8
const val CARRIER_BYTES_PER_FRAME = CARRIER_CHANNEL_COUNT * 2
private const val BURST_HEADER_SIZE = 8
private const val SYNCWORD1 = 0xF872
private const val SYNCWORD2 = 0x4E1F
@@ -99,7 +94,7 @@ internal class TrueHdMatPacker {
private var samplesPerFrame = 0
/** Drops all carrier state. Call on flush/seek: MAT frames must not straddle a discontinuity. */
fun reset() {
override fun reset() {
matBufferIndex = 0
matBufferFilled = 0
previousTiming = 0
@@ -107,7 +102,7 @@ internal class TrueHdMatPacker {
samplesPerFrame = 0
// The family is re-learned from the next major sync. Leaving it latched here would make every
// later stream on this packer emit nothing.
unsupportedRateFamily = false
unsupportedStream = false
java.util.Arrays.fill(matBuffers[0], 0)
java.util.Arrays.fill(matBuffers[1], 0)
}
@@ -119,9 +114,11 @@ internal class TrueHdMatPacker {
* whole path is built around. Rather than carry a second carrier configuration for a combination
* that is essentially absent from real media, the sink reads this and falls back to decoding.
*/
var unsupportedRateFamily: Boolean = false
override var unsupportedStream: Boolean = false
private set
override fun accessUnitLength(data: ByteArray, offset: Int, limit: Int): Int = Companion.accessUnitLength(data, offset, limit)
/**
* Packs one access unit, returning a completed burst when this unit finished a MAT frame.
*
@@ -137,7 +134,7 @@ internal class TrueHdMatPacker {
* At most one burst can complete per access unit: padding is bounded below half a MAT frame and
* an access unit is far smaller, so a single unit cannot span two frame boundaries.
*/
fun packAccessUnit(data: ByteArray, offset: Int, length: Int): ByteBuffer? {
override fun packAccessUnit(data: ByteArray, offset: Int, length: Int): ByteBuffer? {
if (length < MIN_ACCESS_UNIT_LENGTH) return null
if (hasMajorSync(data, offset, offset + length)) {
@@ -148,11 +145,11 @@ internal class TrueHdMatPacker {
else -> return null
}
// Bit 3 selects the 44.1kHz family, which rides a 176.4kHz carrier we do not build.
unsupportedRateFamily = (rateBits and 8) != 0
if (unsupportedRateFamily) return null
unsupportedStream = (rateBits and 8) != 0
if (unsupportedStream) return null
samplesPerFrame = 40 shl (rateBits and 3)
}
if (unsupportedRateFamily || samplesPerFrame == 0) return null
if (unsupportedStream || samplesPerFrame == 0) return null
val inputTiming = ((data[offset + 2].toInt() and 0xFF) shl 8) or (data[offset + 3].toInt() and 0xFF)
var paddingRemaining = 0
@@ -1,6 +1,9 @@
package com.edde746.plezy.exoplayer
import android.util.Log
import androidx.media3.common.C
import androidx.media3.common.DataReader
import androidx.media3.extractor.DefaultExtractorInput
import androidx.media3.extractor.ExtractorInput
import androidx.media3.extractor.ExtractorOutput
import androidx.media3.extractor.SeekMap
@@ -8,6 +11,9 @@ import androidx.media3.extractor.TrackOutput
import androidx.media3.extractor.text.SubtitleParser
import com.edde746.plezy.libass.media.AssHandler
import com.edde746.plezy.libass.media.extractor.AssMatroskaExtractor
import java.io.EOFException
import java.util.zip.DataFormatException
import java.util.zip.Inflater
/**
* Extends AssMatroskaExtractor to add support for MKV quirks media3 rejects:
@@ -16,8 +22,19 @@ import com.edde746.plezy.libass.media.extractor.AssMatroskaExtractor
* stripping). This subclass intercepts the compression algorithm during track
* header parsing:
* - Tells the parent it's header stripping (algo 3) to avoid the ParserException
* - Wraps TrackOutputs with ZlibInflatingTrackOutput to decompress per-sample data
* - Skips ContentCompSettings for zlib tracks (not applicable)
* - For text subtitle tracks, inflates the block payload *before* the parent
* parses it (see below). For every other zlib track, wraps TrackOutputs with
* ZlibInflatingTrackOutput to decompress per-sample data.
*
* Text subtitle tracks (SRT/ASS/SSA/VTT) cannot be inflated at the TrackOutput
* level: MatroskaExtractor rewrites their samples in-place before any TrackOutput
* runs it prepends a plaintext timecode prefix ("Dialogue: 0:00:00:00,…,") to
* the still-compressed payload and truncates the sample at the first NUL byte,
* which deflate streams routinely contain (#2023). AssTrackOutput additionally
* feeds that same internal buffer straight to libass. So for zlib text tracks the
* frame payload is inflated at the block level, before the parent's sample
* assembly, and the TrackOutput wrapper is left inactive.
*
* LOAS/LATM AAC as A_MS/ACM media3 sets audio/x-unknown for non-PCM ACM
* tracks (silent playback). Detected tracks are wrapped with LatmTrackOutput,
@@ -36,15 +53,43 @@ class ZlibMatroskaExtractor(
private const val ID_TRACK_ENTRY = 0xAE
private const val ID_CONTENT_COMPRESSION_ALGORITHM = 0x4254
private const val ID_CONTENT_COMPRESSION_SETTINGS = 0x4255
private const val ID_CONTENT_COMPRESSION = 0x5034
private const val ID_SIMPLE_BLOCK = 0xA3
private const val ID_BLOCK = 0xA1
/**
* Codec IDs whose samples MatroskaExtractor rewrites in-place (timecode prefix
* plus NUL truncation) before any TrackOutput runs the authority is the
* prefix list in MatroskaExtractor.writeSampleData.
*/
private val TEXT_SUBTITLE_CODEC_IDS = setOf("S_TEXT/UTF8", "S_TEXT/ASS", "S_TEXT/SSA", "S_TEXT/WEBVTT")
/** Subtitle blocks are tiny; anything above this passes through untouched. */
private const val MAX_TEXT_BLOCK_BYTES = 16 * 1024 * 1024
}
private var zlibOutput: ZlibExtractorOutputWrapper? = null
private var latmOutput: LatmExtractorOutputWrapper? = null
private var currentTrackUsesZlib = false
/** Track numbers whose blocks are inflated before the parent parses them. */
private val zlibTextTrackNumbers = mutableSetOf<Int>()
private val blockInflater = Inflater()
private var blockBuf = ByteArray(0)
private val peekBuf = ByteArray(8)
override fun startMasterElement(id: Int, contentPosition: Long, contentSize: Long) {
super.startMasterElement(id, contentPosition, contentSize)
// ContentCompAlgo DEFAULTS to 0 (zlib), so mkvmerge omits the element for
// zlib tracks entirely — the mere presence of ContentCompression means zlib
// until an explicit ContentCompAlgo says otherwise. media3 ignores an empty
// ContentCompression and would silently emit compressed samples.
if (id == ID_CONTENT_COMPRESSION) {
currentTrackUsesZlib = true
Log.i(TAG, "Track has ContentCompression, assuming ContentCompAlgo 0 (zlib) until told otherwise")
}
// After super installs AssSubtitleExtractorOutput, wrap it with our zlib +
// LATM layers (zlib outermost so inflation runs before LATM parsing).
if (id == ID_SEGMENT && zlibOutput == null) {
@@ -59,12 +104,17 @@ class ZlibMatroskaExtractor(
}
override fun integerElement(id: Int, value: Long) {
if (id == ID_CONTENT_COMPRESSION_ALGORITHM && value == 0L) {
currentTrackUsesZlib = true
Log.i(TAG, "Track uses ContentCompAlgo 0 (zlib), will inflate samples")
// Tell parent it's header stripping (algo 3) to avoid ParserException
super.integerElement(id, 3)
return
if (id == ID_CONTENT_COMPRESSION_ALGORITHM) {
if (value == 0L) {
currentTrackUsesZlib = true
Log.i(TAG, "Track uses explicit ContentCompAlgo 0 (zlib), will inflate samples")
// Tell parent it's header stripping (algo 3) to avoid ParserException
super.integerElement(id, 3)
return
}
// Explicit non-zlib algorithm: header stripping (3) is handled by the
// parent; anything else makes the parent throw, matching stock behavior.
currentTrackUsesZlib = false
}
super.integerElement(id, value)
}
@@ -76,27 +126,47 @@ class ZlibMatroskaExtractor(
input.skipFully(contentSize)
return
}
if ((id == ID_SIMPLE_BLOCK || id == ID_BLOCK) &&
zlibTextTrackNumbers.isNotEmpty() &&
contentSize in MIN_BLOCK_BYTES..MAX_TEXT_BLOCK_BYTES &&
peekBlockTrackNumber(input) in zlibTextTrackNumbers
) {
inflateTextBlock(id, contentSize, input)
return
}
super.binaryElement(id, contentSize, input)
}
override fun endMasterElement(id: Int) {
var zlibTextTrackNumber: Int? = null
if (id == ID_TRACK_ENTRY) {
// Must mark before super — the track output is created inside super's
// endMasterElement, and the x-unknown format must never reach the queue.
// Must inspect before super — the track output is created inside super's
// endMasterElement, and the current track is cleared afterwards.
val track = getCurrentTrack(id)
if (isLoasAcmTrack(track.codecId, track.codecPrivate)) {
Log.i(TAG, "Track ${track.number} is LOAS/LATM AAC, unwrapping to raw AAC")
latmOutput?.markNextTrackLatm()
}
if (currentTrackUsesZlib && track.codecId in TEXT_SUBTITLE_CODEC_IDS) {
zlibTextTrackNumber = track.number
}
}
val wasZlib = currentTrackUsesZlib
super.endMasterElement(id)
if (id == ID_TRACK_ENTRY && wasZlib) {
zlibOutput?.activateLast()
currentTrackUsesZlib = false
Log.i(TAG, "Activated zlib inflation for track")
if (zlibTextTrackNumber != null) {
// Text subtitle samples are rewritten inside the parent before any
// TrackOutput runs, so the TrackOutput wrapper stays inactive and the
// block payload is inflated in binaryElement instead.
zlibTextTrackNumbers.add(zlibTextTrackNumber)
Log.i(TAG, "Track $zlibTextTrackNumber is a zlib text subtitle track, inflating at block level")
} else {
zlibOutput?.activateLast()
Log.i(TAG, "Activated zlib inflation for track")
}
}
}
@@ -106,6 +176,64 @@ class ZlibMatroskaExtractor(
super.seek(position, timeUs)
}
/**
* Peeks the EBML varint at the block start the block's track number without
* consuming input. Returns null for malformed varints or truncated input; the
* parent then produces the canonical failure for the untouched stream.
*/
private fun peekBlockTrackNumber(input: ExtractorInput): Int? {
try {
input.peekFully(peekBuf, 0, 1)
val first = peekBuf[0].toInt() and 0xFF
if (first == 0) return null
val length = Integer.numberOfLeadingZeros(first) - 23
var value = (first and (0xFF ushr length)).toLong()
if (length > 1) {
input.peekFully(peekBuf, 1, length - 1)
for (i in 1 until length) {
value = (value shl 8) or (peekBuf[i].toLong() and 0xFF)
}
}
return if (value <= Int.MAX_VALUE) value.toInt() else null
} catch (_: EOFException) {
return null
} finally {
input.resetPeekPosition()
}
}
/**
* Buffers one text-subtitle block, inflates its frame payload, and hands the
* parent a block whose payload is plaintext. A block that cannot be rewritten
* (laced, corrupt, or over-bound) passes through byte-identical.
*/
private fun inflateTextBlock(id: Int, contentSize: Int, input: ExtractorInput) {
val basePosition = input.position
if (blockBuf.size < contentSize) blockBuf = ByteArray(maxOf(contentSize, blockBuf.size * 2))
input.readFully(blockBuf, 0, contentSize)
val rewritten = rewriteZlibTextBlock(blockBuf, contentSize, blockInflater)
if (rewritten == null) {
Log.w(TAG, "Passing zlib text block through uninflated (laced, corrupt, or over-bound)")
super.binaryElement(id, contentSize, bufferedInput(blockBuf, contentSize, basePosition))
} else {
super.binaryElement(id, rewritten.size, bufferedInput(rewritten, rewritten.size, basePosition))
}
}
private fun bufferedInput(data: ByteArray, limit: Int, position: Long): ExtractorInput = DefaultExtractorInput(ByteRangeDataReader(data, limit), position, position + limit)
private class ByteRangeDataReader(private val data: ByteArray, private val limit: Int) : DataReader {
private var position = 0
override fun read(buffer: ByteArray, offset: Int, length: Int): Int {
if (position == limit) return C.RESULT_END_OF_INPUT
val count = minOf(length, limit - position)
System.arraycopy(data, position, buffer, offset, count)
position += count
return count
}
}
/**
* ExtractorOutput wrapper that wraps all TrackOutputs with ZlibInflatingTrackOutput.
* Tracks are created inactive; activateLast() enables inflation for the most recently
@@ -138,3 +266,50 @@ class ZlibMatroskaExtractor(
override fun seekMap(seekMap: SeekMap) = delegate.seekMap(seekMap)
}
}
/** Smallest well-formed unlaced block: 1-byte varint + 2-byte timecode + flags + 1 payload byte. */
internal const val MIN_BLOCK_BYTES = 5
/**
* Rewrites one unlaced Matroska block whose frame payload is zlib-compressed:
* returns the unchanged block header followed by the inflated payload, or null
* when the block must pass through unchanged lacing (never produced for text
* subtitle tracks), a truncated or corrupt deflate stream, or an inflated size
* beyond the bounds shared with [ZlibInflatingTrackOutput]'s hardening.
*/
internal fun rewriteZlibTextBlock(data: ByteArray, limit: Int, inflater: Inflater): ByteArray? {
if (limit < MIN_BLOCK_BYTES) return null
val first = data[0].toInt() and 0xFF
if (first == 0) return null // track-number varint longer than 8 bytes
val varintLength = Integer.numberOfLeadingZeros(first) - 23
val headerLength = varintLength + 3 // varint + 2-byte timecode + flags
if (limit <= headerLength) return null
if (data[headerLength - 1].toInt() and 0x06 != 0) return null // laced
val payloadLength = limit - headerLength
val ratioBound = maxOf(1024L * 1024, payloadLength.toLong() * 1024)
val maxInflatedBytes = 16 * 1024 * 1024
inflater.reset()
inflater.setInput(data, headerLength, payloadLength)
var buf = ByteArray(maxOf(4096, payloadLength * 4))
var written = 0
try {
while (true) {
if (written == buf.size) {
if (buf.size >= maxInflatedBytes) return null
buf = buf.copyOf(minOf(maxInflatedBytes, buf.size * 2))
}
val count = inflater.inflate(buf, written, buf.size - written)
written += count
if (written > ratioBound) return null
if (inflater.finished()) break
if (count == 0) return null // truncated stream or preset-dictionary request
}
} catch (_: DataFormatException) {
return null
}
return ByteArray(headerLength + written).also {
System.arraycopy(data, 0, it, 0, headerLength)
System.arraycopy(buf, 0, it, headerLength, written)
}
}
@@ -0,0 +1,28 @@
package com.edde746.plezy.mpv
/**
* Demuxer cache budget derived from the device heap class.
*
* mpv has no device-memory awareness: `demuxer-max-bytes` defaults to a fixed
* 150 MiB forward (+50 MiB back) on every device and the demuxer fills
* whatever it is allowed, which crowds a 1 GB TV box until Android's
* low-memory killer takes the whole app. Tiered off
* [android.app.ActivityManager.getLargeMemoryClass], the same signal
* `stream_buffer_sizing.dart` and ExoPlayer's `LoadControlPolicy` use.
*
* Applied as pre-init *options* in [MpvPlayerCore], so a `demuxer-max-bytes`
* line in the user's mpv.conf still wins.
*/
data class DemuxerBudget(val aheadBytes: Long, val backBytes: Long) {
companion object {
private const val MIB = 1024L * 1024L
/** Null for an unknown class (<= 0): callers keep mpv's own defaults. */
fun forHeapClassMB(largeMemoryClassMB: Int): DemuxerBudget? = when {
largeMemoryClassMB <= 0 -> null
largeMemoryClassMB <= 256 -> DemuxerBudget(aheadBytes = 32 * MIB, backBytes = 16 * MIB)
largeMemoryClassMB <= 512 -> DemuxerBudget(aheadBytes = 64 * MIB, backBytes = 32 * MIB)
else -> DemuxerBudget(aheadBytes = 100 * MIB, backBytes = 48 * MIB)
}
}
}
@@ -0,0 +1,74 @@
package com.edde746.plezy.mpv
import android.opengl.EGL14
/**
* Which mpv `egl-output-format` this device can pair with a BT.2020 PQ window
* surface, or null when HDR GL output is unavailable. 10-bit fixed point is
* preferred; fp16 is the fallback because some drivers (Tegra among them)
* expose the PQ colorspace but no 1010102 window config.
*
* Both halves are required by the mpv side: the fork's android GL context asks
* for `EGL_EXT_gl_colorspace_bt2020_pq` on the window surface, and the app
* pairs it with an `egl-output-format` that makes mpv's EGL config selection
* fail outright when no matching config exists - so this probe must be
* consulted before those options are ever set.
*/
internal object EglHdrCaps {
private const val EGL_COLOR_COMPONENT_TYPE_EXT = 0x3339
private const val EGL_COLOR_COMPONENT_TYPE_FLOAT_EXT = 0x333B
private object Unprobed
@Volatile private var cached: Any? = Unprobed
fun pqOutputFormat(): String? {
val value = cached
if (value !== Unprobed) return value as String?
return probe().also { cached = it }
}
private fun probe(): String? {
val display = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY)
if (display == EGL14.EGL_NO_DISPLAY) return null
val version = IntArray(2)
// Deliberately no eglTerminate: the default display is process-global and
// Flutter's renderer shares it; terminating would invalidate its state.
if (!EGL14.eglInitialize(display, version, 0, version, 1)) return null
val extensions = EGL14.eglQueryString(display, EGL14.EGL_EXTENSIONS) ?: return null
if (!extensions.contains("EGL_EXT_gl_colorspace_bt2020_pq")) return null
if (hasWindowConfig(display, intArrayOf(EGL14.EGL_RED_SIZE, 10, EGL14.EGL_GREEN_SIZE, 10, EGL14.EGL_BLUE_SIZE, 10, EGL14.EGL_ALPHA_SIZE, 2))) {
return "rgb10_a2"
}
if (extensions.contains("EGL_EXT_pixel_format_float") &&
hasWindowConfig(
display,
intArrayOf(
EGL14.EGL_RED_SIZE,
16,
EGL14.EGL_GREEN_SIZE,
16,
EGL14.EGL_BLUE_SIZE,
16,
EGL_COLOR_COMPONENT_TYPE_EXT,
EGL_COLOR_COMPONENT_TYPE_FLOAT_EXT
)
)
) {
return "rgba16f"
}
return null
}
private fun hasWindowConfig(display: android.opengl.EGLDisplay, extra: IntArray): Boolean {
val attribs = intArrayOf(
EGL14.EGL_SURFACE_TYPE,
EGL14.EGL_WINDOW_BIT,
EGL14.EGL_RENDERABLE_TYPE,
EGL14.EGL_OPENGL_ES2_BIT
) + extra + intArrayOf(EGL14.EGL_NONE)
val numConfigs = IntArray(1)
if (!EGL14.eglChooseConfig(display, attribs, 0, null, 0, 0, numConfigs, 0)) return false
return numConfigs[0] > 0
}
}
@@ -0,0 +1,138 @@
package com.edde746.plezy.mpv
/**
* Pure policy for when an mpv session must leave the video plane
* (vo=mediacodec) for a GL video output, and which one. Kept free of player
* and platform state so the routing matrix is unit-testable.
*/
internal object GpuVoPolicy {
/**
* Single-layer Dolby Vision Profile 5 (IPT-PQ-c2) has no compatible base
* layer: on a device without native DV support it decodes as plain HEVC
* with garbage colors, and the video plane applies no reshaping. gpu-next
* (libplacebo) under software decode is the only Android path that
* composites the RPU metadata (#1902). [dvProfile] comes from mpv's
* track-list the bitstream's DOVI configuration record never from
* server metadata, which mis-tags DV routinely. Only `auto` routes; the
* other modes are explicit user choices.
*/
fun needsDvReshaping(dvProfile: Long?, conversionMode: String, canPlayP5Natively: Boolean): Boolean = dvProfile == 5L && conversionMode == "auto" && !canPlayP5Natively
/**
* Whether an HDR signal has nowhere to tone-map: the video plane hands
* PQ/HLG straight to a display pipeline that advertises no HDR output, so
* it renders washed out (#2121). The GL vo tone-maps in the render chain.
*/
fun needsHdrToneMapping(gamma: String?, displaySupportsHdr: Boolean): Boolean = (gamma == "pq" || gamma == "hlg") && !displaySupportsHdr
/**
* Whether the decoder is handing mpv software frames, from `hwdec-current`.
*
* The plane refuses every format but MediaCodec buffers, so a per-file
* decode fallback (AV1 on Tegra, Hi10 without a profile match) has to move
* to a GL vo. Routing on this gets there before mpv fails the chain and
* [REASON_CHAIN_FAILURE] has to catch it.
*/
fun needsSoftwareRender(hwdecCurrent: String?): Boolean = !hwdecCurrent.isNullOrBlank() && hwdecCurrent != "mediacodec"
/**
* Select native software decoding before opening a decoder when hardware
* cannot serve the stream. H.264 High 10 needs an advertised profile
* (#2065); AV1 needs an actual hardware decoder (#2272), not a software
* MediaCodec component whose surface/copy paths can fail on VO changes.
* [codec] and [codecProfile] come from mpv's pending video track.
*/
fun needsSoftwareDecode(
codec: String?,
codecProfile: String?,
hardwareHigh10: Boolean,
hardwareAv1: Boolean
): Boolean = when (codec) {
"h264" -> !hardwareHigh10 && codecProfile?.startsWith("High 10") == true
"av1" -> !hardwareAv1
else -> false
}
/**
* The video track the per-file policies ([needsDvReshaping],
* [needsSoftwareDecode]) decide for, or null when no video track will be
* selected. They run inside on_preloaded, where the track list is complete
* but nothing is selected yet, so "the selected track" does not exist:
* `vid` still reads the option value, and mpv's own selection
* (default/forced flags, --vlang, attached pictures skipped) only runs
* after the hook. [vid] is the `vid` property: `no` and an explicit id are
* authoritative on their own; `auto` defers to [pendingVid], the fork's
* `pending-vid` property, which runs that selection ahead of time. A null
* [pendingVid] means the libmpv has no such property, and the first track
* in [videoTrackIds] (track-list order) is the best guess left wrong for
* files whose first video track is not the one mpv picks.
*/
fun pendingVideoTrackId(vid: String?, pendingVid: String?, videoTrackIds: List<Long>): Long? {
val requested = when {
vid == null || vid == "auto" -> pendingVid ?: return videoTrackIds.firstOrNull()
else -> vid
}
val id = requested.toLongOrNull() ?: return null
return id.takeIf { it in videoTrackIds }
}
/**
* Whether a GL vo session should drop to the cheap render tier: bilinear
* scalers and no dither. Keyed on `GL_EXT_texture_norm16` being absent,
* which on Android singles out the low-end Mali/Adreno TV class whose
* texture units cannot afford a second full-resolution pass at 1080p
* (measured on an S905X4/Mali-G31: mpv's default lanczos chroma pass alone
* runs the frame over budget, bilinear brings it back under; every
* norm16-capable GPU tested renders the whole default ladder in a few
* milliseconds). The video plane never scales in GL, so hardware sessions
* on it are untouched.
*/
fun needsCheapRenderTier(glVoActive: Boolean, textureNorm16: Boolean): Boolean = glVoActive && !textureNorm16
/** mpv option -> value for the cheap render tier, applied only where the
* option still carries its mpv default (a user's mpv.conf line wins). */
val CHEAP_RENDER_OPTIONS: Map<String, String> = linkedMapOf(
"scale" to "bilinear",
"cscale" to "bilinear",
"dscale" to "bilinear",
"dither" to "no"
)
/** The values mpv 0.41 reports for [CHEAP_RENDER_OPTIONS] when nothing
* set them; anything else is a user choice and stays. `cscale` inherits
* `scale` by default, which the property reads back as an empty string
* (measured on 0.41) or `inherit`. */
val MPV_DEFAULT_RENDER_OPTIONS: Map<String, Set<String>> = mapOf(
"scale" to setOf("lanczos"),
"cscale" to setOf("", "inherit"),
"dscale" to setOf("hermite"),
"dither" to setOf("fruit")
)
/** Whether [value] is what mpv reports for [option] by default. */
fun isDefaultRenderOption(option: String, value: String?): Boolean = value != null && MPV_DEFAULT_RENDER_OPTIONS[option]?.contains(value) == true
/**
* The vo a session with these active requirements should run, or null for
* the video plane.
*
* dv-reshape is the only reason that needs gpu-next, since libplacebo is
* what composites the RPU. Everything else takes gpu, the battle-tested
* GLES renderer on the Android device zoo. (The magenta field gpu-next
* used to render for 10-bit software frames on Tegra was its AV1 film
* grain shader overrunning the driver's uniform register budget; grain is
* decoder-applied now, but gpu-next buys this path nothing over gpu.)
*/
fun targetFor(reasons: Set<String>): String? = when {
reasons.isEmpty() -> null
REASON_DV_RESHAPE in reasons -> "gpu-next"
else -> "gpu"
}
const val REASON_DV_RESHAPE = "dv-reshape"
const val REASON_SHADERS = "shaders"
const val REASON_CHAIN_FAILURE = "chain-failure"
const val REASON_HDR_SDR = "hdr-sdr"
const val REASON_SW_DECODE = "sw-decode"
const val REASON_CODEC_SW_DECODE = "codec-sw-decode"
}
@@ -1,14 +1,24 @@
package com.edde746.plezy.mpv
import dev.jdtech.mpv.EndFileReason
import dev.jdtech.mpv.LogLevel
import dev.jdtech.mpv.LogMessage
import dev.jdtech.mpv.MpvEvent
import com.edde746.plezy.libmpv.EndFileReason
import com.edde746.plezy.libmpv.LogLevel
import com.edde746.plezy.libmpv.LogMessage
import com.edde746.plezy.libmpv.MpvError
import com.edde746.plezy.libmpv.MpvEvent
/** Adds the native diagnostic that libmpv-android exposes separately via logFlow. */
internal class MpvEndFileDiagnostics {
private var errorMessage: String? = null
companion object {
/**
* The audio device stopped taking audio (or never could) and mpv gave up
* on it. Keep in sync with PlayerError.audioOutputFailed in Dart: a device
* fault, so no stream retry or backend switch can recover it.
*/
const val CAUSE_AUDIO_OUTPUT_FAILED = "audio-output-failed"
}
fun onStartFile() {
errorMessage = null
}
@@ -20,16 +30,16 @@ internal class MpvEndFileDiagnostics {
}
fun onEndFile(event: MpvEvent.EndFile): Map<String, Any>? {
val reason = event.reason
if (reason == null) {
errorMessage = null
return null
}
val data = mutableMapOf<String, Any>("reason" to reason.id)
if (reason == EndFileReason.Error) {
errorMessage?.let { data["message"] = it }
val data = mutableMapOf<String, Any>()
event.sourceId?.let { data["sourceId"] = it }
event.reason?.let { reason ->
data["reason"] = reason.id
if (reason == EndFileReason.Error) {
errorMessage?.let { data["message"] = it }
if (event.error == MpvError.AoInitFailed) data["cause"] = CAUSE_AUDIO_OUTPUT_FAILED
}
}
errorMessage = null
return data
return data.takeIf { it.isNotEmpty() }
}
}
@@ -0,0 +1,54 @@
package com.edde746.plezy.mpv
import android.os.Handler
import android.os.HandlerThread
import android.view.Surface
import androidx.media3.common.util.EGLSurfaceTexture
import kotlinx.coroutines.android.asCoroutineDispatcher
import kotlinx.coroutines.withContext
/**
* An offscreen consumer, not an undrained ImageReader queue. MediaCodec and GPU
* output can both keep posting buffers while the real SurfaceViews are absent.
* Media3's common EGL utility consumes each frame on its own GL thread, including
* while the main thread is waiting for MPV to acknowledge a surface handoff.
*/
internal class MpvPlaceholderSurface private constructor(
val surface: Surface,
private val handler: Handler,
private val texture: EGLSurfaceTexture
) : AutoCloseable {
companion object {
/** The caller must retain or close the result even if initialization is canceled. */
suspend fun create(): MpvPlaceholderSurface {
val thread = HandlerThread("MpvPlaceholder").apply { start() }
val handler = Handler(thread.looper)
val texture = EGLSurfaceTexture(handler)
return withContext(handler.asCoroutineDispatcher("MpvPlaceholder")) {
try {
texture.init(EGLSurfaceTexture.SECURE_MODE_NONE)
MpvPlaceholderSurface(Surface(texture.surfaceTexture), handler, texture)
} catch (error: Throwable) {
try {
texture.release()
} finally {
thread.quitSafely()
}
throw error
}
}
}
}
/** Call only after native consumers have retired; destruction stays on the GL thread. */
override fun close() {
handler.post {
try {
surface.release()
texture.release()
} finally {
handler.looper.quitSafely()
}
}
}
}
File diff suppressed because it is too large Load Diff
@@ -1,10 +1,12 @@
package com.edde746.plezy.mpv
import android.app.Activity
import android.app.ActivityManager
import android.content.Context
import android.net.Uri
import android.os.ParcelFileDescriptor
import android.util.Log
import com.edde746.plezy.exoplayer.supportedMpvSpdifCodecs
import com.edde746.plezy.shared.PlayerChannelBinding
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
@@ -13,6 +15,7 @@ import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import java.util.concurrent.CancellationException
import java.util.concurrent.atomic.AtomicBoolean
internal fun completeMpvPropertyResult(
result: MethodChannel.Result,
@@ -61,6 +64,17 @@ open class MpvPlayerPlugin(
private val nameToId = mutableMapOf<String, Int>()
private var sessionGeneration = 0
// The Dart instanceId that created the current core. A `dispose` carrying a
// different token lost the ownership race to a successor and must not tear
// down that successor's core; it is acknowledged without touching anything.
private var coreInstanceId: Long? = null
// How long a Dart `dispose` waits for native teardown before being
// acknowledged. Native lifecycle operations remain serialized on background
// workers after the watchdog fires, so a successor cannot overlap a stuck
// decoder, exhaust codec instances, or block Android's main thread.
private val disposeWatchdogMs = 6_000L
/** Same semantics as Activity.runOnUiThread, without needing an Activity. */
private fun runOnMain(block: () -> Unit) = channels.runOnMain(block)
@@ -74,7 +88,6 @@ open class MpvPlayerPlugin(
private var initAttemptCounter = 0
private var activeInitAttempt: Int? = null
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
applicationContext = binding.applicationContext
channels.attach(binding)
@@ -95,6 +108,7 @@ open class MpvPlayerPlugin(
++sessionGeneration
val core = playerCore
playerCore = null
coreInstanceId = null
cancelPendingInits()
return core
}
@@ -103,7 +117,6 @@ open class MpvPlayerPlugin(
takeCoreForTeardown()?.dispose()
}
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
activity = binding.activity
activityBinding = binding
@@ -139,7 +152,6 @@ open class MpvPlayerPlugin(
Log.d(tag, "Detached from activity for config changes")
}
override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
channels.listen(events)
}
@@ -148,11 +160,10 @@ open class MpvPlayerPlugin(
channels.cancel()
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
when (call.method) {
"initialize" -> handleInitialize(result)
"dispose" -> handleDispose(result)
"initialize" -> handleInitialize(call, result)
"dispose" -> handleDispose(call, result)
"setProperty" -> handleSetProperty(call, result)
"getProperty" -> handleGetProperty(call, result)
"getStats" -> handleGetStats(result)
@@ -163,16 +174,43 @@ open class MpvPlayerPlugin(
"setVideoFrameRate" -> handleSetVideoFrameRate(call, result)
"clearVideoFrameRate" -> handleClearVideoFrameRate(result)
"requestAudioFocus" -> handleRequestAudioFocus(result)
"getAudioSpdifCodecs" -> handleGetAudioSpdifCodecs(result)
"abandonAudioFocus" -> handleAbandonAudioFocus(result)
"openContentFd" -> handleOpenContentFd(call, result)
"closeContentFd" -> handleCloseContentFd(call, result)
"getHeapSize" -> {
// Device heap class for Dart-side memory tiering (stream ring cache).
// Lives on the always-registered mpv channel so it survives backends.
val context: Context? = activity ?: applicationContext
val am = context?.getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager
result.success(am?.largeMemoryClass ?: 0)
}
"isInitialized" -> result.success(playerCore?.isInitialized ?: false)
"setLogLevel" -> handleSetLogLevel(call, result)
else -> result.notImplemented()
}
}
private fun handleInitialize(result: MethodChannel.Result) {
/**
* Derives the `audio-spdif` value for the current audio route. mpv force-passthroughs
* every codec named there with no decode fallback, so with no context to inspect the
* route the conservative answer is the empty list decode everything (#1703, #1991).
*/
private fun handleGetAudioSpdifCodecs(result: MethodChannel.Result) {
val context: Context? = activity ?: applicationContext
result.success(context?.let(::supportedMpvSpdifCodecs) ?: "")
}
private fun handleInitialize(call: MethodCall, result: MethodChannel.Result) {
// Whether the session will hardware-decode; decides the initial vo chain
// (MpvPlayerCore.initialVideoOutput). Absent on the audio-only core and
// from older callers; hardware decode is the setting's default.
val hardwareDecoding = call.argument<Boolean>("hardwareDecoding") ?: true
// Subtitle "Render Resolution" for the vo=mediacodec OSD plane (Full / ¾ / ½ /
// ⅓ / ¼ of the surface); the same fraction the ExoPlayer overlay applies.
// Absent from older callers and the audio-only core; full is the default.
val subtitleRenderScale = call.argument<Double>("subtitleRenderScale")?.toFloat() ?: 1f
val logLevel = call.argument<String>("logLevel") ?: "warn"
// Video cores need the Activity (surface/view hierarchy); the audio-only
// core is built on the application context so it can outlive it.
val coreContext: Context? = if (audioOnly) applicationContext else activity
@@ -231,10 +269,11 @@ open class MpvPlayerPlugin(
}
gen = ++sessionGeneration
core = MpvPlayerCore(coreContext, audioOnly).apply {
core = MpvPlayerCore(coreContext, audioOnly, hardwareDecoding, subtitleRenderScale, logLevel).apply {
delegate = this@MpvPlayerPlugin
}
playerCore = core
coreInstanceId = call.argument<Number>("instanceId")?.toLong()
} catch (e: Exception) {
Log.e(tag, "Failed to initialize: ${e.message}", e)
completePendingInits(attempt, success = false, errorMessage = e.message)
@@ -246,7 +285,10 @@ open class MpvPlayerPlugin(
playerCore !== core ||
!isCurrentInitAttempt(attempt)
if (stale || !success) {
if (playerCore === core) playerCore = null
if (playerCore === core) {
playerCore = null
coreInstanceId = null
}
core.dispose()
if (stale) {
Log.d(tag, "Stale init callback (gen=$gen, current=$sessionGeneration)")
@@ -303,13 +345,37 @@ open class MpvPlayerPlugin(
}
}
private fun handleDispose(result: MethodChannel.Result) {
private fun handleDispose(call: MethodCall, result: MethodChannel.Result) {
val token = call.argument<Number>("instanceId")?.toLong()
runOnMain {
val core = takeCoreForTeardown()
core?.dispose {
Log.d(tag, "Disposed")
val owner = coreInstanceId
if (playerCore != null && token != null && owner != null && token != owner) {
// This dispose lost the ownership race: a successor already created
// the current core. Acknowledge without touching it.
Log.d(tag, "Ignoring stale dispose (token=$token, core owner=$owner)")
result.success(null)
} ?: result.success(null)
return@runOnMain
}
val core = takeCoreForTeardown()
if (core == null) {
result.success(null)
return@runOnMain
}
// A hung native teardown must not wedge the Dart-side release chain.
// Native create/destroy remains serialized on background workers behind
// that teardown, so a successor cannot accumulate another MediaCodec
// instance while the old one still owns its resources.
val completed = AtomicBoolean(false)
fun completeOnce(reason: String) {
if (completed.compareAndSet(false, true)) {
Log.d(tag, reason)
result.success(null)
}
}
channels.mainHandler.postDelayed({
completeOnce("Dispose watchdog fired after ${disposeWatchdogMs}ms; teardown continues in background")
}, disposeWatchdogMs)
core.dispose { completeOnce("Disposed") }
}
}
@@ -408,25 +474,42 @@ open class MpvPlayerPlugin(
result.error("NOT_INITIALIZED", "Player not initialized", null)
return
}
core.command(args.toTypedArray()) { success ->
if (success) {
result.success(null)
} else {
result.error("COMMAND_FAILED", "mpv command failed", args)
}
// `loadfile` answers with the playlist entry it created so Dart can tie
// the load to that source's start-file/playback-restart/end-file events;
// every other command answers null.
core.commandForSource(args.toTypedArray()) { outcome ->
outcome.fold(
onSuccess = { playlistEntryId ->
result.success(playlistEntryId?.let { mapOf("playlistEntryId" to it) })
},
onFailure = { error ->
result.error("COMMAND_FAILED", error.message ?: "mpv command failed", args)
}
)
}
}
private fun handleSetLogLevel(call: MethodCall, result: MethodChannel.Result) {
if (call.argument<String>("level") == null) {
result.error("INVALID_ARGS", "Missing 'level'", null)
val level = call.argument<Any>("level") as? String
if (level == null) {
result.error("INVALID_ARGS", "Missing or invalid 'level'", null)
return
}
result.error(
"UNSUPPORTED",
"Runtime mpv log level changes are not supported on Android",
null
)
val core = playerCore
if (core?.isInitialized != true) {
completeMpvPropertyNotInitialized(result)
return
}
core.setLogLevel(level) { outcome ->
when (val failure = outcome.exceptionOrNull()) {
null -> result.success(null)
is CancellationException -> completeMpvPropertyNotInitialized(result)
else -> {
Log.w(tag, "MPV rejected log level change", failure)
result.error("SET_LOG_LEVEL_FAILED", "MPV log level change was rejected", null)
}
}
}
}
private fun handleSetVisible(call: MethodCall, result: MethodChannel.Result) {
@@ -452,14 +535,19 @@ open class MpvPlayerPlugin(
val extraDelayMs = call.argument<Number>("extraDelayMs")?.toLong() ?: 0L
val videoWidth = call.argument<Number>("videoWidth")?.toInt() ?: 0
val videoHeight = call.argument<Number>("videoHeight")?.toInt() ?: 0
val matchResolution = call.argument<Boolean>("matchResolution") ?: false
Log.d(tag, "setVideoFrameRate: fps=$fps, duration=$duration, extraDelayMs=$extraDelayMs, video=${videoWidth}x$videoHeight")
Log.d(
tag,
"setVideoFrameRate: fps=$fps, duration=$duration, extraDelayMs=$extraDelayMs, " +
"video=${videoWidth}x$videoHeight, matchResolution=$matchResolution"
)
val core = playerCore
if (core == null) {
result.success(false)
return
}
core.setVideoFrameRate(fps, duration, extraDelayMs, videoWidth, videoHeight) { switched ->
core.setVideoFrameRate(fps, duration, extraDelayMs, videoWidth, videoHeight, matchResolution) { switched ->
result.success(switched)
}
}
@@ -542,8 +630,12 @@ open class MpvPlayerPlugin(
// PlayerDelegate
override fun onPropertyChange(name: String, value: Any?) {
onPropertyChange(name, value, null)
}
override fun onPropertyChange(name: String, value: Any?, sourceId: Long?) {
val propId = nameToId[name] ?: return
channels.emitProperty(propId, value)
channels.emitProperty(propId, value, sourceId)
}
override fun onEvent(name: String, data: Map<String, Any>?) {
@@ -0,0 +1,41 @@
package com.edde746.plezy.mpv
import kotlin.math.roundToInt
/**
* Pure geometry for the `vo=mediacodec` subtitle/OSD plane.
*
* mpv rasterizes subtitles at whatever size the OSD Surface reports, so the
* "Render Resolution" setting is applied by giving the OSD SurfaceView a
* fixed buffer size below its view size; SurfaceFlinger scales the plane back
* up. Every stage of the OSD pass (libass rasterization, the software
* composite, the Surface copy) is proportional to that pixel count, which is
* what makes the setting a throughput knob on render-bound TV hardware. The
* ExoPlayer path applies the same fraction to its libass overlay.
*/
internal object OsdPlanePolicy {
data class Size(val width: Int, val height: Int)
/**
* Fixed buffer size for an OSD plane whose view measures [viewWidth] x
* [viewHeight], or null when the plane should track the view (full
* resolution, or a view that has not been laid out yet).
*
* Dimensions are rounded to even values: the 4:2:0-derived alignment
* assumptions in the compositor stack are cheap to honor here and an odd
* OSD width buys nothing.
*/
fun fixedSizeFor(viewWidth: Int, viewHeight: Int, renderScale: Float): Size? {
if (viewWidth <= 0 || viewHeight <= 0) return null
if (!(renderScale > 0f) || renderScale >= 1f) return null
return Size(
width = scaledEven(viewWidth, renderScale),
height = scaledEven(viewHeight, renderScale)
)
}
private fun scaledEven(value: Int, scale: Float): Int {
val scaled = (value * scale).roundToInt().coerceAtLeast(2)
return scaled and 1.inv()
}
}
@@ -0,0 +1,53 @@
package com.edde746.plezy.mpv
import kotlin.math.max
import kotlin.math.min
import kotlin.math.pow
/**
* Pure geometry for the video plane's surface rectangle.
*
* The fork `vo=mediacodec` scales decoded buffers to the whole Surface and
* implements none of mpv's src/dst rect math, so aspect, cover and zoom are
* view geometry: the video surface is sized to the rectangle the image should
* occupy and the container clips whatever falls outside it. That mirrors the
* ExoPlayer path, which scales its own surface and keeps the subtitle overlay
* on the full-size container.
*/
internal object VideoRectPolicy {
/**
* `video-zoom` is reachable from the user's mpv.conf, where an absurd value
* is a compositor allocation rather than just arithmetic. Bounds it well
* outside the range the player's own zoom control offers.
*/
private const val MAX_ZOOM_LOG2 = 2f
data class Size(val width: Int, val height: Int)
/**
* Size for the video surface, or null when a dimension is not known yet.
*
* [panscan] is mpv's 0..1 property: 0 fits the image inside the container
* (letterbox), 1 fills it (crop), values between interpolate the scale.
* [videoZoomLog2] is mpv's `video-zoom`, a log2 factor, applied on top.
*/
fun sizeFor(
containerWidth: Int,
containerHeight: Int,
videoWidth: Int,
videoHeight: Int,
panscan: Float = 0f,
videoZoomLog2: Float = 0f
): Size? {
if (containerWidth <= 0 || containerHeight <= 0 || videoWidth <= 0 || videoHeight <= 0) return null
val fit = min(containerWidth.toFloat() / videoWidth, containerHeight.toFloat() / videoHeight)
val cover = max(containerWidth.toFloat() / videoWidth, containerHeight.toFloat() / videoHeight)
val pan = panscan.coerceIn(0f, 1f)
val zoom = 2.0f.pow(videoZoomLog2.coerceIn(-MAX_ZOOM_LOG2, MAX_ZOOM_LOG2))
val scale = (fit + (cover - fit) * pan) * zoom
return Size(
width = (videoWidth * scale).toInt().coerceAtLeast(1),
height = (videoHeight * scale).toInt().coerceAtLeast(1)
)
}
}
@@ -0,0 +1,86 @@
package com.edde746.plezy.shared
import android.accessibilityservice.AccessibilityServiceInfo
import android.content.Context
import android.os.Build
import android.view.accessibility.AccessibilityManager
/**
* Reports whether an enabled accessibility service can consume the app's semantics tree.
*
* Flutter compiles a semantics tree for every frame while [AccessibilityManager.isEnabled], which
* Android sets for any bound service. On TV that is routinely a utility that never reads app
* content (a launcher's foreground-app hook, a key remapper), so Dart gates the tree on this
* verdict. The verdict errs towards keeping the tree:
*
* - touch exploration is a screen reader, full stop;
* - an empty enabled list while accessibility is on means a [android.app.UiAutomation] client
* (instrumentation, Maestro), which is not listed but reads the tree;
* - on API 33+ a service flagged `isAccessibilityTool`, or one giving spoken, braille, audible or
* visual feedback, consumes; a non-tool with only generic/haptic feedback does not;
* - below 33 only a haptic-only service is treated as not consuming, since `feedbackGeneric` is
* what Switch Access-style tools declare.
*/
class AssistiveTechnologyMonitor(context: Context) {
private val manager = context.getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager
private var onChanged: (() -> Unit)? = null
private val stateListener = AccessibilityManager.AccessibilityStateChangeListener { onChanged?.invoke() }
private val touchExplorationListener =
AccessibilityManager.TouchExplorationStateChangeListener { onChanged?.invoke() }
private var servicesListener: AccessibilityManager.AccessibilityServicesStateChangeListener? = null
fun start(onChanged: () -> Unit) {
if (this.onChanged != null) return
this.onChanged = onChanged
manager.addAccessibilityStateChangeListener(stateListener)
manager.addTouchExplorationStateChangeListener(touchExplorationListener)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
val listener = AccessibilityManager.AccessibilityServicesStateChangeListener { onChanged() }
servicesListener = listener
manager.addAccessibilityServicesStateChangeListener(listener)
}
}
fun release() {
if (onChanged == null) return
onChanged = null
manager.removeAccessibilityStateChangeListener(stateListener)
manager.removeTouchExplorationStateChangeListener(touchExplorationListener)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
servicesListener?.let { manager.removeAccessibilityServicesStateChangeListener(it) }
servicesListener = null
}
}
fun signals(): Map<String, Any> {
val services = manager.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_ALL_MASK)
return mapOf(
"accessibilityEnabled" to manager.isEnabled,
"touchExplorationEnabled" to manager.isTouchExplorationEnabled,
"enabledServiceCount" to services.size,
"consumesSemantics" to consumesSemantics(services)
)
}
private fun consumesSemantics(services: List<AccessibilityServiceInfo>): Boolean {
if (manager.isTouchExplorationEnabled) return true
if (services.isEmpty()) return true
return services.any { info -> consumesSemantics(info) }
}
private fun consumesSemantics(info: AccessibilityServiceInfo): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (info.isAccessibilityTool) return true
return info.feedbackType and READER_FEEDBACK != 0
}
return info.feedbackType and AccessibilityServiceInfo.FEEDBACK_HAPTIC.inv() != 0
}
private companion object {
const val READER_FEEDBACK =
AccessibilityServiceInfo.FEEDBACK_SPOKEN or
AccessibilityServiceInfo.FEEDBACK_BRAILLE or
AccessibilityServiceInfo.FEEDBACK_AUDIBLE or
AccessibilityServiceInfo.FEEDBACK_VISUAL
}
}
@@ -0,0 +1,145 @@
package com.edde746.plezy.shared
import kotlin.math.abs
import kotlin.math.roundToInt
/**
* Pure display-mode selection policy for content-adaptive display switching.
* Extracted from [FrameRateManager] so the policy is unit-testable on the
* JVM, where android.view.Display.Mode cannot be instantiated.
*/
object DisplayModeSelector {
const val RATE_TOLERANCE = 0.1f
/** JVM-testable mirror of android.view.Display.Mode. */
data class ModeInfo(val modeId: Int, val width: Int, val height: Int, val refreshRate: Float) {
val area: Long get() = width.toLong() * height
}
data class RefreshRateMatch(val reason: String, val priority: Int, val error: Float)
data class Selection(val mode: ModeInfo, val reason: String)
private data class Candidate(val mode: ModeInfo, val match: RefreshRateMatch)
/** How well [refreshRate] presents [fps] content: exact, an integer multiple, or not at all. */
fun matchRefreshRate(refreshRate: Float, fps: Float): RefreshRateMatch? {
if (refreshRate <= 0f || fps <= 0f) return null
val exactError = abs(refreshRate - fps)
if (exactError < RATE_TOLERANCE) {
return RefreshRateMatch(reason = "exact", priority = 0, error = exactError)
}
val multiple = (refreshRate / fps).roundToInt()
if (multiple > 1) {
val multipleError = abs(refreshRate - (fps * multiple))
if (multipleError < RATE_TOLERANCE) {
return RefreshRateMatch(reason = "${multiple}x", priority = 1, error = multipleError)
}
}
return null
}
/**
* Pick the display mode for the video, or null when no switch target exists.
* The caller compares the result against the current mode to decide whether
* an actual switch is needed.
*
* With [matchResolution] and known video dimensions, resolution wins over
* cadence: the target is the smallest mode that still contains the video
* (never downscaling it), rate-matched within that resolution when [fps] is
* known. Otherwise the cadence-only policy applies and requires [fps] > 0.
*/
fun findBestMode(
fps: Float,
currentMode: ModeInfo,
supportedModes: List<ModeInfo>,
videoWidth: Int,
videoHeight: Int,
matchResolution: Boolean
): Selection? {
if (matchResolution && videoWidth > 0 && videoHeight > 0) {
resolutionMatch(fps, currentMode, supportedModes, videoWidth, videoHeight)?.let { return it }
// No mode can contain the video (source larger than the panel):
// fall back to the cadence-only policy below.
}
return cadenceMatch(fps, currentMode, supportedModes, videoWidth, videoHeight)
}
private fun resolutionMatch(
fps: Float,
currentMode: ModeInfo,
supportedModes: List<ModeInfo>,
videoWidth: Int,
videoHeight: Int
): Selection? {
val candidates = supportedModes.filter { it.width >= videoWidth && it.height >= videoHeight }
if (candidates.isEmpty()) return null
// Native target: the smallest resolution that still contains the video,
// so the display (not the device) performs the upscale.
val targetArea = candidates.minOf { it.area }
val bucket = candidates.filter { it.area == targetArea }
// Rate-match within the target resolution when requested. Resolution
// wins over cadence: a missing rate match here deliberately does not
// widen back out to other resolutions.
if (fps > 0f) {
bucket
.mapNotNull { mode -> matchRefreshRate(mode.refreshRate, fps)?.let { Candidate(mode, it) } }
.minWithOrNull(
compareBy<Candidate> { it.match.priority }
.thenBy { it.match.error }
.thenBy { abs(it.mode.refreshRate - currentMode.refreshRate) }
)
?.let { return Selection(it.mode, "resolution + ${it.match.reason} rate, error=${it.match.error}") }
}
// Resolution-only request, or no cadence match at the target resolution:
// stay as close to the current refresh rate as possible so the switch
// renegotiates only what it has to.
val fallback = bucket.minWithOrNull(
compareBy<ModeInfo> { abs(it.refreshRate - currentMode.refreshRate) }.thenByDescending { it.refreshRate }
)
return fallback?.let { Selection(it, "resolution only") }
}
private fun cadenceMatch(
fps: Float,
currentMode: ModeInfo,
supportedModes: List<ModeInfo>,
videoWidth: Int,
videoHeight: Int
): Selection? {
// Tier 1 — a matching-refresh mode at the CURRENT resolution: a refresh-only
// switch, the least disruptive (no resolution/HDMI renegotiation).
supportedModes.asSequence()
.filter { it.width == currentMode.width && it.height == currentMode.height }
.mapNotNull { mode -> matchRefreshRate(mode.refreshRate, fps)?.let { Candidate(mode, it) } }
.minWithOrNull(
compareBy<Candidate> { it.match.priority }
.thenBy { it.match.error }
.thenBy { abs(it.mode.refreshRate - currentMode.refreshRate) }
)
?.let { return Selection(it.mode, "${it.match.reason}, error=${it.match.error}") }
// Tier 2 — no same-resolution match (e.g. a 4K panel with no 4K@24 mode, but a
// 1080p@23.976 mode for 1080p content). Allow a resolution change, but never one
// that downscales the video below its native size (trading detail for cadence).
// Requires known video dimensions; without them keep Tier-1-only behaviour.
if (videoWidth <= 0 || videoHeight <= 0) return null
return supportedModes.asSequence()
.filter { it.width >= videoWidth && it.height >= videoHeight }
.mapNotNull { mode -> matchRefreshRate(mode.refreshRate, fps)?.let { Candidate(mode, it) } }
.minWithOrNull(
// Prefer the resolution closest to the panel's current one (least change,
// keeps panel-native res when a high-res match exists), then refresh match.
compareBy<Candidate> { abs(it.mode.area - currentMode.area) }
.thenBy { it.match.priority }
.thenBy { it.match.error }
)
?.let { Selection(it.mode, "${it.match.reason}, error=${it.match.error}") }
}
}
@@ -9,8 +9,6 @@ import android.util.Log
import android.view.Display
import android.view.WindowManager
import androidx.annotation.RequiresApi
import kotlin.math.abs
import kotlin.math.roundToInt
class FrameRateManager(
private val activity: Activity,
@@ -21,38 +19,45 @@ class FrameRateManager(
private const val TAG = "FrameRateManager"
private const val DISPLAY_SETTLE_MS = 2000L
private const val WATCHDOG_MARGIN_MS = 3000L
private const val RATE_TOLERANCE = 0.1f
// How long to let the HDR-exit commit land before restoring the refresh
// rate. Restoring while the display is still signaling HDR folds the
// HDR-exit and the mode change into one HDMI renegotiation, which some
// sink chains take 8-30 s to complete (#2172); sequenced, the HDR
// infoframe clear is free and the SDR mode switch takes ~1 s. The
// player's surface teardown commits the HDR exit within ~50 ms of
// dispose, so 400 ms covers it with margin even on a busy main thread.
private const val HDR_EXIT_SETTLE_MS = 400L
}
private data class RefreshRateMatch(
val reason: String,
val priority: Int,
val error: Float
)
@RequiresApi(Build.VERSION_CODES.M)
private data class DisplayModeCandidate(
val mode: Display.Mode,
val match: RefreshRateMatch
)
private var currentVideoFps: Float = 0f
private var currentVideoWidth: Int = 0
private var currentVideoHeight: Int = 0
private var currentMatchResolution: Boolean = false
private var displayListener: DisplayManager.DisplayListener? = null
private var pendingSettleRunnable: Runnable? = null
private var watchdogRunnable: Runnable? = null
private var pendingCompletion: ((switched: Boolean) -> Unit)? = null
// Owns the deferred HDR-exit restore. Deliberately NOT the shared player
// [handler]: core dispose clears that one wholesale, and the restore must
// survive player disposal or the display stays at the content rate.
private val restoreHandler = Handler(android.os.Looper.getMainLooper())
private var pendingRestoreRunnable: Runnable? = null
private fun getDisplayManager(): DisplayManager = activity.getSystemService(Context.DISPLAY_SERVICE) as DisplayManager
// Request a display frame-rate switch. Invokes [onComplete] once, either:
// - immediately with `switched=false` when no switch is needed (invalid fps,
// no matching mode, or already matching); or
// Request a display mode switch for the video's frame rate and/or, with
// [matchResolution], its native resolution. Invokes [onComplete] once, either:
// - immediately with `switched=false` when no switch is needed (no usable
// fps/resolution target, no matching mode, or already matching); or
// - after the real DisplayListener event + [DISPLAY_SETTLE_MS] + the caller's
// [extraDelayMs], with `switched=true`; or
// - via a watchdog if the real event never arrives, so the caller doesn't hang.
//
// fps <= 0 with [matchResolution] requests a resolution-only switch that
// keeps the refresh rate as close to the current one as possible.
//
// The caller is responsible for pausing playback before calling and resuming
// it after [onComplete] fires.
fun setVideoFrameRate(
@@ -61,20 +66,27 @@ class FrameRateManager(
extraDelayMs: Long,
videoWidth: Int = 0,
videoHeight: Int = 0,
matchResolution: Boolean = false,
onComplete: (switched: Boolean) -> Unit
) {
// A new session's switch must not be clobbered by a still-pending
// deferred restore from the previous session's teardown.
cancelPendingRestore()
currentVideoFps = fps
currentVideoWidth = videoWidth
currentVideoHeight = videoHeight
if (fps <= 0f) {
Log.d(TAG, "setVideoFrameRate: Invalid fps ($fps), skipping")
currentMatchResolution = matchResolution
val hasResolutionTarget = matchResolution && videoWidth > 0 && videoHeight > 0
if (fps <= 0f && !hasResolutionTarget) {
Log.d(TAG, "setVideoFrameRate: no usable target (fps=$fps, video=${videoWidth}x$videoHeight), skipping")
onComplete(false)
return
}
log(
"request fps=$fps, duration=${videoDurationMs}ms, extraDelayMs=$extraDelayMs, " +
"video=${videoWidth}x$videoHeight, API=${Build.VERSION.SDK_INT}, currentMode=${currentModeDescription()}"
"video=${videoWidth}x$videoHeight, matchResolution=$matchResolution, " +
"API=${Build.VERSION.SDK_INT}, currentMode=${currentModeDescription()}"
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
@@ -84,21 +96,47 @@ class FrameRateManager(
}
}
fun clearVideoFrameRate() {
Log.d(TAG, "clearVideoFrameRate")
// [hdrActive]: the session was outputting HDR. The restore is then deferred
// by [HDR_EXIT_SETTLE_MS] so the caller's surface teardown can commit the
// HDR exit first — see [HDR_EXIT_SETTLE_MS] for why stacking them is slow.
fun clearVideoFrameRate(hdrActive: Boolean = false) {
Log.d(TAG, "clearVideoFrameRate(hdrActive=$hdrActive)")
currentVideoFps = 0f
// Resolve any pending setVideoFrameRate future as "not switched" so
// the Dart caller's await doesn't hang on player dispose.
firePendingCompletion("clear", switched = false)
// Restore default display mode on API M (preferredDisplayModeId persists)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
activity.window?.attributes?.let { attrs ->
attrs.preferredDisplayModeId = 0
activity.window?.attributes = attrs
cancelPendingRestore()
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return
// Nothing to restore when no preferred mode was ever applied.
if ((activity.window?.attributes?.preferredDisplayModeId ?: 0) == 0) return
if (hdrActive) {
val restore = Runnable {
pendingRestoreRunnable = null
// Log.d, not [log]: this fires after core dispose, when the
// Flutter-channel logger is already gone.
Log.d(TAG, "restoring default display mode after HDR exit")
restorePreferredDisplayMode()
}
pendingRestoreRunnable = restore
restoreHandler.postDelayed(restore, HDR_EXIT_SETTLE_MS)
} else {
restorePreferredDisplayMode()
}
}
private fun restorePreferredDisplayMode() {
// preferredDisplayModeId persists on the window; restore the default.
activity.window?.attributes?.let { attrs ->
attrs.preferredDisplayModeId = 0
activity.window?.attributes = attrs
}
}
private fun cancelPendingRestore() {
pendingRestoreRunnable?.let { restoreHandler.removeCallbacks(it) }
pendingRestoreRunnable = null
}
// Release pending callbacks/listener without restoring the display mode.
// Used by player-core dispose paths so a backend handoff (e.g. ExoPlayer→MPV
// audio fallback) doesn't clobber the just-applied refresh-rate switch —
@@ -129,7 +167,12 @@ class FrameRateManager(
cb(switched)
}
private fun registerDisplayListener(fps: Float, extraDelayMs: Long, onComplete: (switched: Boolean) -> Unit) {
private fun registerDisplayListener(
fps: Float,
targetModeId: Int,
extraDelayMs: Long,
onComplete: (switched: Boolean) -> Unit
) {
// Resolve any previous pending op before starting a new one.
firePendingCompletion("superseded", switched = false)
pendingCompletion = onComplete
@@ -144,7 +187,9 @@ class FrameRateManager(
getDisplayManager().unregisterDisplayListener(this)
displayListener = null
val settle = Runnable { firePendingCompletion("display settled", switched = currentRateMatch(fps) != null) }
val settle = Runnable {
firePendingCompletion("display settled", switched = currentMatchesRequest(fps, targetModeId))
}
pendingSettleRunnable = settle
handler.postDelayed(settle, DISPLAY_SETTLE_MS + extraDelayMs)
}
@@ -154,37 +199,20 @@ class FrameRateManager(
// Watchdog: if the TV never signals a display change (silently ignoring
// the mode request), still complete after a bounded wait so the caller
// doesn't hang.
val watchdog = Runnable { firePendingCompletion("watchdog", switched = currentRateMatch(fps) != null) }
val watchdog = Runnable { firePendingCompletion("watchdog", switched = currentMatchesRequest(fps, targetModeId)) }
watchdogRunnable = watchdog
handler.postDelayed(watchdog, DISPLAY_SETTLE_MS + extraDelayMs + WATCHDOG_MARGIN_MS)
}
private fun matchRefreshRate(refreshRate: Float, fps: Float): RefreshRateMatch? {
if (refreshRate <= 0f || fps <= 0f) return null
val exactError = abs(refreshRate - fps)
if (exactError < RATE_TOLERANCE) {
return RefreshRateMatch(reason = "exact", priority = 0, error = exactError)
}
val multiple = (refreshRate / fps).roundToInt()
if (multiple > 1) {
val multipleError = abs(refreshRate - (fps * multiple))
if (multipleError < RATE_TOLERANCE) {
return RefreshRateMatch(reason = "${multiple}x", priority = 1, error = multipleError)
}
}
return null
}
private fun currentRateMatch(fps: Float): RefreshRateMatch? {
val current = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
currentDisplayMode()?.refreshRate
} else {
null
} ?: return null
return matchRefreshRate(current, fps)
// Whether the display landed on the requested mode: the exact target, or —
// for a rate request — any mode whose refresh presents [fps] (a TV may pick
// a different-but-equivalent mode). A resolution-only request (fps <= 0)
// only counts the exact target.
private fun currentMatchesRequest(fps: Float, targetModeId: Int): Boolean {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return false
val current = currentDisplayMode() ?: return false
if (current.modeId == targetModeId) return true
return DisplayModeSelector.matchRefreshRate(current.refreshRate, fps) != null
}
private fun currentModeDescription(): String = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
@@ -214,46 +242,11 @@ class FrameRateManager(
private fun describeSupportedModes(modes: Array<Display.Mode>): String = modes.joinToString(prefix = "[", postfix = "]") { describeMode(it) }
@RequiresApi(Build.VERSION_CODES.M)
private fun findBestModeMatch(
fps: Float,
currentMode: Display.Mode,
supportedModes: Array<Display.Mode>,
videoWidth: Int,
videoHeight: Int
): DisplayModeCandidate? {
// Tier 1 — a matching-refresh mode at the CURRENT resolution: a refresh-only
// switch, the least disruptive (no resolution/HDMI renegotiation).
supportedModes.asSequence()
.filter { it.physicalHeight == currentMode.physicalHeight && it.physicalWidth == currentMode.physicalWidth }
.mapNotNull { mode -> matchRefreshRate(mode.refreshRate, fps)?.let { DisplayModeCandidate(mode, it) } }
.minWithOrNull(
compareBy<DisplayModeCandidate> { it.match.priority }
.thenBy { it.match.error }
.thenBy { abs(it.mode.refreshRate - currentMode.refreshRate) }
)
?.let { return it }
// Tier 2 — no same-resolution match (e.g. a 4K panel with no 4K@24 mode, but a
// 1080p@23.976 mode for 1080p content). Allow a resolution change, but never one
// that downscales the video below its native size (trading detail for cadence).
// Requires known video dimensions; without them keep Tier-1-only behaviour.
if (videoWidth <= 0 || videoHeight <= 0) return null
val currentArea = currentMode.physicalWidth.toLong() * currentMode.physicalHeight
return supportedModes.asSequence()
.filter { it.physicalWidth >= videoWidth && it.physicalHeight >= videoHeight }
.mapNotNull { mode -> matchRefreshRate(mode.refreshRate, fps)?.let { DisplayModeCandidate(mode, it) } }
.minWithOrNull(
// Prefer the resolution closest to the panel's current one (least change,
// keeps panel-native res when a high-res match exists), then refresh match.
compareBy<DisplayModeCandidate> { abs(it.mode.physicalWidth.toLong() * it.mode.physicalHeight - currentArea) }
.thenBy { it.match.priority }
.thenBy { it.match.error }
)
}
private fun Display.Mode.toModeInfo(): DisplayModeSelector.ModeInfo = DisplayModeSelector.ModeInfo(modeId, physicalWidth, physicalHeight, refreshRate)
@RequiresApi(Build.VERSION_CODES.M)
private fun setDisplayMode(fps: Float, extraDelayMs: Long, onComplete: (switched: Boolean) -> Unit) {
log("setDisplayMode fps=$fps")
log("setDisplayMode fps=$fps, matchResolution=$currentMatchResolution")
val display = currentDisplay()
if (display == null) {
log("display unavailable")
@@ -270,34 +263,43 @@ class FrameRateManager(
val currentMode = display.mode
log("supported modes=${describeSupportedModes(supportedModes)}")
val modeMatch = findBestModeMatch(fps, currentMode, supportedModes, currentVideoWidth, currentVideoHeight)
if (modeMatch == null) {
val selection = DisplayModeSelector.findBestMode(
fps,
currentMode.toModeInfo(),
supportedModes.map { it.toModeInfo() },
currentVideoWidth,
currentVideoHeight,
currentMatchResolution
)
if (selection == null) {
log(
"no matching display mode for ${fps}fps at ${currentMode.physicalWidth}x${currentMode.physicalHeight} " +
"(video=${currentVideoWidth}x$currentVideoHeight)"
"(video=${currentVideoWidth}x$currentVideoHeight, matchResolution=$currentMatchResolution)"
)
onComplete(false)
return
}
val modeToUse = modeMatch.mode
val modeToUse = supportedModes.firstOrNull { it.modeId == selection.mode.modeId }
if (modeToUse == null) {
log("selected mode #${selection.mode.modeId} disappeared from supported modes")
onComplete(false)
return
}
if (modeToUse.modeId == currentMode.modeId) {
log("current mode already matches ${fps}fps (${modeMatch.match.reason}), no switch needed")
log("current mode already matches ${fps}fps (${selection.reason}), no switch needed")
onComplete(false)
return
}
log(
"switching to ${describeMode(modeToUse)} for ${fps}fps " +
"(${modeMatch.match.reason}, error=${modeMatch.match.error})"
)
log("switching to ${describeMode(modeToUse)} for ${fps}fps (${selection.reason})")
val window = activity.window
if (window == null) {
log("window unavailable")
onComplete(false)
return
}
registerDisplayListener(fps, extraDelayMs, onComplete)
registerDisplayListener(fps, modeToUse.modeId, extraDelayMs, onComplete)
window.attributes = window.attributes.apply { preferredDisplayModeId = modeToUse.modeId }
}
}
@@ -0,0 +1,104 @@
package com.edde746.plezy.shared
import android.opengl.EGL14
import android.opengl.EGLConfig
import android.opengl.EGLContext
import android.opengl.EGLDisplay
import android.opengl.EGLSurface
import android.opengl.GLES20
import android.util.Log
/**
* GLES capabilities that decide render policy before mpv creates its own
* context. Probed once per process on a throwaway pbuffer context; the
* answers are hardware/driver properties and do not change at runtime.
*/
internal object GlCapabilities {
private const val TAG = "GlCapabilities"
private const val EGL_OPENGL_ES3_BIT_KHR = 0x0040
@Volatile private var textureNorm16: Boolean? = null
/**
* Whether the GLES driver exposes `GL_EXT_texture_norm16`. Without it mpv
* cannot upload >8-bit planes as filterable textures, and the GPUs that
* lack it are the ones that cannot afford mpv's default scalers either
* (see [com.edde746.plezy.mpv.GpuVoPolicy.needsCheapRenderTier]).
*
* A probe failure reports `true`: the default render path is the safe
* answer for an unknown GPU, not the cheap tier.
*/
fun hasTextureNorm16(): Boolean {
textureNorm16?.let { return it }
synchronized(this) {
textureNorm16?.let { return it }
val probed = probe { extensions -> extensions.contains("GL_EXT_texture_norm16") } ?: true
textureNorm16 = probed
return probed
}
}
/** Test seam: pretend the probe answered [value]. */
internal fun overrideTextureNorm16ForTesting(value: Boolean?) {
textureNorm16 = value
}
/**
* Runs [read] against the extension string of a fresh ES3 pbuffer context
* and tears everything down again. Returns null when EGL refuses any step;
* callers pick the safe default. Must not run on a thread that already
* has an EGL context current the temporary context replaces it.
*/
private fun probe(read: (String) -> Boolean): Boolean? {
var display: EGLDisplay = EGL14.EGL_NO_DISPLAY
var context: EGLContext = EGL14.EGL_NO_CONTEXT
var surface: EGLSurface = EGL14.EGL_NO_SURFACE
try {
display = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY)
if (display == EGL14.EGL_NO_DISPLAY) return null
val version = IntArray(2)
if (!EGL14.eglInitialize(display, version, 0, version, 1)) return null
val configAttributes = intArrayOf(
EGL14.EGL_SURFACE_TYPE, EGL14.EGL_PBUFFER_BIT,
EGL14.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT_KHR,
EGL14.EGL_RED_SIZE, 8,
EGL14.EGL_GREEN_SIZE, 8,
EGL14.EGL_BLUE_SIZE, 8,
EGL14.EGL_NONE
)
val configs = arrayOfNulls<EGLConfig>(1)
val count = IntArray(1)
if (!EGL14.eglChooseConfig(display, configAttributes, 0, configs, 0, 1, count, 0) || count[0] < 1) return null
val config = configs[0] ?: return null
surface = EGL14.eglCreatePbufferSurface(
display,
config,
intArrayOf(EGL14.EGL_WIDTH, 1, EGL14.EGL_HEIGHT, 1, EGL14.EGL_NONE),
0
)
if (surface == EGL14.EGL_NO_SURFACE) return null
context = EGL14.eglCreateContext(
display,
config,
EGL14.EGL_NO_CONTEXT,
intArrayOf(EGL14.EGL_CONTEXT_CLIENT_VERSION, 3, EGL14.EGL_NONE),
0
)
if (context == EGL14.EGL_NO_CONTEXT) return null
if (!EGL14.eglMakeCurrent(display, surface, surface, context)) return null
val extensions = GLES20.glGetString(GLES20.GL_EXTENSIONS) ?: return null
return read(extensions)
} catch (e: RuntimeException) {
Log.w(TAG, "GLES capability probe failed", e)
return null
} finally {
if (display != EGL14.EGL_NO_DISPLAY) {
EGL14.eglMakeCurrent(display, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_CONTEXT)
if (context != EGL14.EGL_NO_CONTEXT) EGL14.eglDestroyContext(display, context)
if (surface != EGL14.EGL_NO_SURFACE) EGL14.eglDestroySurface(display, surface)
// No eglTerminate: the default display is shared with the Flutter
// engine and mpv; eglInitialize on an initialized display is a no-op.
}
}
}
}
@@ -7,6 +7,61 @@ import java.util.Locale
/** Canonical decoder lookup and hardware classification for native playback. */
internal object MediaCodecQuery {
/**
* Codecs whose advertised support is decided by hardware: both have a
* software decoder behind them, but a software HEVC or AV1 decode on
* phone/TV-class hardware drops frames.
*/
private val HARDWARE_GATED_VIDEO_MIME_TYPES = mapOf(
"hevc" to "video/hevc",
"av1" to "video/av01"
)
/** Codec name -> whether this device has a hardware decoder for it. */
fun hardwareVideoDecodeSupport(
hardwareMimeTypes: Set<String> = hardwareDecoderMimeTypes()
): Map<String, Boolean> = HARDWARE_GATED_VIDEO_MIME_TYPES.mapValues { (_, mimeType) -> mimeType in hardwareMimeTypes }
/**
* Every MIME type served by a hardware decoder, lowercased. One walk answers
* for all codecs, unlike [findHardwareDecoder], which rescans per lookup.
*/
private fun hardwareDecoderMimeTypes(): Set<String> {
val mimeTypes = HashSet<String>()
for (info in MediaCodecList(MediaCodecList.REGULAR_CODECS).codecInfos) {
if (info.isEncoder || !isHardwareAccelerated(info)) continue
for (type in info.supportedTypes) mimeTypes.add(type.lowercase(Locale.ROOT))
}
return mimeTypes
}
/**
* Whether a hardware `video/avc` decoder advertises H.264 High 10 (Hi10P).
* Decoders that do not advertise it either refuse the stream (this is what
* the mpv/FFmpeg MediaCodec path sees) or, on some SoCs, accept it and
* render garbage; neither is a reason to let the hardware path try first
* (#2065). Answered once per process: the codec list is static.
*/
fun hardwareAvcHigh10Support(): Boolean = hardwareAvcHigh10.value
private val hardwareAvcHigh10: Lazy<Boolean> = lazy {
findHardwareDecoder("video/avc") { info, type ->
val profiles = try {
info.getCapabilitiesForType(type).profileLevels
} catch (e: IllegalArgumentException) {
return@findHardwareDecoder false
}
profiles.any { it.profile == MediaCodecInfo.CodecProfileLevel.AVCProfileHigh10 }
} != null
}
/** Software MediaCodec AV1 components are not a hardware decode path (#2272). */
fun hardwareAv1Support(): Boolean = hardwareAv1.value
private val hardwareAv1: Lazy<Boolean> = lazy {
findHardwareDecoder("video/av01") != null
}
fun findHardwareDecoder(
mimeType: String,
codecKind: Int = MediaCodecList.REGULAR_CODECS,
@@ -62,6 +62,10 @@ internal class PlayerChannelBinding(
runOnMain { eventSink?.success(listOf(id, value)) }
}
fun emitProperty(id: Int, value: Any?, sourceId: Long?) {
runOnMain { eventSink?.success(listOf(id, value, sourceId)) }
}
fun emitEvent(name: String, data: Map<String, Any>? = null) {
val event = mutableMapOf<String, Any>(
"type" to "event",
@@ -2,5 +2,9 @@ package com.edde746.plezy.shared
interface PlayerDelegate {
fun onPropertyChange(name: String, value: Any?)
fun onPropertyChange(name: String, value: Any?, sourceId: Long?) {
onPropertyChange(name, value)
}
fun onEvent(name: String, data: Map<String, Any>?)
}
@@ -2,10 +2,12 @@ package com.edde746.plezy.shared
import android.app.Activity
import android.graphics.Color
import android.graphics.PixelFormat
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.ViewGroup
import android.widget.FrameLayout
import com.edde746.plezy.mpv.OsdPlanePolicy
/** Shared Android view scaffold beneath the ExoPlayer and mpv cores. */
internal object PlayerSurfaceHost {
@@ -14,8 +16,37 @@ internal object PlayerSurfaceHost {
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
// Fallback fill for the frames before the punch surface below is placed.
setBackgroundColor(Color.BLACK)
this.clipChildren = clipChildren
addView(createLetterboxPunchSurface(activity))
}
/**
* Fullscreen, buffer-less SurfaceView kept beneath the video surface.
*
* Its only job is taking the letterbox area off the app-window (graphics)
* plane: like any below-window SurfaceView it punches the parent canvas and
* registers its rect as a window transparent region, so the pixels around
* the video rect scan out as the SurfaceFlinger backdrop instead of
* window-plane black. Several TV compositors (Fire TV Stick 4K Max, some
* Sony/Philips models) raise SDR graphics-plane black while the display is
* in HDR/Dolby Vision mode, which shows as gray letterbox bars on OLED
* panels (issue #2163; same mechanism as ExoPlayer #8803 and Kodi #25300).
*
* No buffer is ever posted to it: SurfaceFlinger skips buffer-less layers,
* and drawing black into it would put the bars back onto an SDR layer
* exactly the plane being avoided. Views drawn on the parent canvas after
* the punch (Media3 subtitle cues) still re-claim their own bounds.
*/
private fun createLetterboxPunchSurface(activity: Activity): SurfaceView = SurfaceView(activity).apply {
layoutParams = FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT
)
setZOrderOnTop(false)
setZOrderMediaOverlay(false)
FlutterOverlayHelper.applyCompositionOrder(this, -2)
}
fun createVideoSurface(activity: Activity, callback: SurfaceHolder.Callback): SurfaceView = SurfaceView(activity).apply {
@@ -29,6 +60,35 @@ internal object PlayerSurfaceHost {
FlutterOverlayHelper.applyCompositionOrder(this, -2)
}
/**
* Transparent plane directly above the video surface for the mpv
* `vo=mediacodec` subtitle/OSD output. Media-overlay z-order keeps it above
* the video SurfaceView but still beneath the Flutter window content.
*
* [renderScale] < 1 gives the plane a fixed buffer size below its view size
* (see [OsdPlanePolicy]); mpv then rasterizes at that size and the
* compositor scales the plane to the view. Re-applied on every layout so a
* container resize keeps the ratio.
*/
fun createOsdSurface(activity: Activity, callback: SurfaceHolder.Callback, renderScale: Float = 1f): SurfaceView = SurfaceView(activity).apply {
layoutParams = FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT
)
holder.addCallback(callback)
holder.setFormat(PixelFormat.TRANSLUCENT)
setZOrderOnTop(false)
setZOrderMediaOverlay(true)
FlutterOverlayHelper.applyCompositionOrder(this, -1)
if (renderScale < 1f) {
addOnLayoutChangeListener { view, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
if (right - left == oldRight - oldLeft && bottom - top == oldBottom - oldTop) return@addOnLayoutChangeListener
val size = OsdPlanePolicy.fixedSizeFor(right - left, bottom - top, renderScale) ?: return@addOnLayoutChangeListener
(view as SurfaceView).holder.setFixedSize(size.width, size.height)
}
}
}
fun attachToContent(activity: Activity, container: FrameLayout): ViewGroup {
val contentView = activity.findViewById<ViewGroup>(android.R.id.content)
contentView.addView(container, 0)
@@ -22,6 +22,7 @@ interface SurfacePlayerCore {
extraDelayMs: Long,
videoWidth: Int,
videoHeight: Int,
matchResolution: Boolean,
onComplete: (switched: Boolean) -> Unit
)
}
+14
View File
@@ -13,3 +13,17 @@ add_executable(ffmpeg_audio_buffer_test ffmpeg_audio_buffer_test.cpp)
target_compile_features(ffmpeg_audio_buffer_test PRIVATE cxx_std_17)
add_test(NAME ffmpeg_audio_buffer_test COMMAND ffmpeg_audio_buffer_test)
add_executable(mpv_utf8_convert_test mpv_utf8_convert_test.cpp)
target_compile_features(mpv_utf8_convert_test PRIVATE cxx_std_17)
add_test(NAME mpv_utf8_convert_test COMMAND mpv_utf8_convert_test)
find_package(Threads REQUIRED)
add_executable(mpv_lifecycle_test mpv_lifecycle_test.cpp)
target_compile_features(mpv_lifecycle_test PRIVATE cxx_std_17)
target_include_directories(mpv_lifecycle_test PRIVATE fakes ../../../../libmpv/src/main/cpp/include)
target_link_libraries(mpv_lifecycle_test PRIVATE Threads::Threads)
add_test(NAME mpv_lifecycle_test COMMAND mpv_lifecycle_test)
set_tests_properties(mpv_lifecycle_test PROPERTIES TIMEOUT 30)
@@ -2,6 +2,7 @@
#define ANDROID_LOG_INFO 4
#define ANDROID_LOG_WARN 5
#define ANDROID_LOG_ERROR 6
#ifdef __cplusplus
extern "C" {
+47
View File
@@ -1,5 +1,6 @@
#pragma once
#include <cstdarg>
#include <cstdint>
#include <cstring>
#include <string>
@@ -14,6 +15,10 @@ using jboolean = uint8_t;
using jbyte = int8_t;
using jint = int32_t;
using jsize = jint;
using jlong = int64_t;
using jdouble = double;
using jobject = void*;
using jmethodID = void*;
struct _jclass {};
using jclass = _jclass*;
@@ -28,11 +33,53 @@ struct _jstring {
};
using jstring = _jstring*;
struct _jobjectArray {
std::vector<jobject> objects;
};
using jobjectArray = _jobjectArray*;
class JavaVM {
public:
void (*on_detach)() = nullptr;
jint DetachCurrentThread() {
if (on_detach) on_detach();
return 0;
}
};
class JNIEnv {
public:
bool exception_pending = false;
bool fail_next_write = false;
JavaVM* vm = nullptr;
jobject (*on_new_global_ref)(jobject) = nullptr;
void (*on_delete_global_ref)(jobject) = nullptr;
void (*on_static_void_method)(jmethodID, va_list) = nullptr;
jint GetJavaVM(JavaVM** result) {
*result = vm;
return 0;
}
jobject NewGlobalRef(jobject object) { return on_new_global_ref ? on_new_global_ref(object) : object; }
void DeleteGlobalRef(jobject object) {
if (on_delete_global_ref) on_delete_global_ref(object);
}
void DeleteLocalRef(jobject) {}
void CallStaticVoidMethod(jclass, jmethodID method, ...) {
va_list args;
va_start(args, method);
if (on_static_void_method) on_static_void_method(method, args);
va_end(args);
}
jsize GetArrayLength(jobjectArray array) { return static_cast<jsize>(array->objects.size()); }
jobject GetObjectArrayElement(jobjectArray array, jsize index) { return array->objects.at(index); }
jsize GetArrayLength(jbyteArray array) { return static_cast<jsize>(array->bytes.size()); }
void GetByteArrayRegion(jbyteArray array, jsize offset, jsize length, jbyte* destination) {
@@ -0,0 +1,700 @@
#include <pthread.h>
#include <cerrno>
#include <chrono>
#include <condition_variable>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <map>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
static int tracked_mutex_lock(pthread_mutex_t* mutex);
static int tracked_write_lock(pthread_rwlock_t* lock);
static int controlled_thread_create(pthread_t* thread, const pthread_attr_t* attr, void* (*entry)(void*), void* arg);
// Compile the real JNI entries, admission guards, event loop and surface
// cleanup. Only external dependencies are controlled; no copy of the lock
// algorithm or direct assignment to production lifecycle globals is used.
#define UTIL_EXTERN
#define pthread_mutex_lock tracked_mutex_lock
#define pthread_rwlock_wrlock tracked_write_lock
#define pthread_create controlled_thread_create
// Android's two-argument thread naming API is not available on macOS.
#define pthread_setname_np(thread, name) ((void)0)
#include "../../../../libmpv/src/main/cpp/main.cpp"
#undef pthread_setname_np
#undef pthread_create
#undef pthread_rwlock_wrlock
#undef pthread_mutex_lock
#include "../../../../libmpv/src/main/cpp/event.cpp"
#define pthread_mutex_lock tracked_mutex_lock
#include "../../../../libmpv/src/main/cpp/render.cpp"
#undef pthread_mutex_lock
struct mpv_handle {
bool initialized = false;
bool terminated = false;
bool event_started = false;
bool event_exited = false;
bool woken = false;
bool hook_pending = false;
bool reject_hook_during_destroy = false;
bool callback_entered = false;
bool callback_returned = false;
bool command_active = false;
bool termination_entered = false;
int initialize_result = 0;
int hook_continuations = 0;
int commands = 0;
jlong callback_session = 0;
jobject video = nullptr;
jobject osd = nullptr;
jobject osd_option = nullptr;
int rebuilds = 0;
mpv_event_hook hook{"on_preloaded", 17};
mpv_event event{};
};
namespace {
std::mutex gate;
std::condition_variable changed;
JavaVM vm;
JNIEnv jni;
int app_context;
mpv_handle* active_handle = nullptr;
// Retain fake allocations after termination so any erroneous late MPV access
// fails explicitly rather than depending on allocator reuse or undefined UAF.
std::vector<std::unique_ptr<mpv_handle>> handles;
std::vector<std::unique_ptr<_jstring>> callback_strings;
// Each NewGlobalRef is a distinct handle, even for the same Java Surface.
std::vector<std::unique_ptr<jobject>> reference_handles;
std::map<jobject, jobject> global_refs;
int fail_ref_after = 0;
std::vector<std::string> option_failures;
bool consume_osd_before_failure = false;
bool hold_wid = false;
bool wid_entered = false;
bool allow_wid = false;
bool surface_waiting = false;
mpv_handle* held_termination = nullptr;
bool allow_termination = false;
bool allow_command = false;
bool successor_waiting = false;
bool reader_draining = false;
bool fail_thread_create = false;
thread_local mpv_handle* event_handle = nullptr;
enum class Operation { ordinary, successor, replacing_reader, surface_handoff };
thread_local Operation operation = Operation::ordinary;
void require(bool condition, const char* message) {
if (condition) return;
std::fprintf(stderr, "%s\n", message);
std::abort();
}
template <typename Predicate>
void await(std::unique_lock<std::mutex>& lock, Predicate predicate, const char* message) {
require(changed.wait_for(lock, std::chrono::seconds(5), predicate), message);
}
void require_live(mpv_handle* handle) {
require(handle && handle == active_handle && !handle->terminated, "MPV accessed outside its native lifetime");
}
void require_surfaces(mpv_handle* handle) {
for (jobject ref : {handle->video, handle->osd, handle->osd_option}) {
if (ref) require(global_refs.count(ref) == 1, "Surface option/consumer retained a deleted JNI reference");
}
}
jobject new_global_ref(jobject object) {
std::lock_guard<std::mutex> lock(gate);
if (!object) return nullptr;
if (fail_ref_after > 0 && --fail_ref_after == 0) return nullptr;
reference_handles.push_back(std::make_unique<jobject>(object));
jobject ref = reference_handles.back().get();
global_refs.emplace(ref, object);
return ref;
}
void delete_global_ref(jobject object) {
if (!object) return;
std::lock_guard<std::mutex> lock(gate);
require(global_refs.count(object) == 1, "JNI global reference released more than once");
if (active_handle &&
(active_handle->video == object || active_handle->osd == object || active_handle->osd_option == object)) {
require(active_handle->terminated, "Surface released while still referenced by MPV");
}
global_refs.erase(object);
}
int live_surface_refs() {
int count = 0;
for (const auto& entry : global_refs) {
if (entry.second != &app_context) ++count;
}
return count;
}
void require_pair(mpv_handle* handle, jobject video, jobject osd) {
require_surfaces(handle);
require(global_refs.at(handle->video) == video, "VO retained the wrong video Surface");
require((handle->osd ? global_refs.at(handle->osd) : nullptr) == osd, "VO retained the wrong OSD Surface");
require(handle->osd_option == handle->osd, "OSD option and active consumer disagree");
}
void detach_event_thread() {
std::lock_guard<std::mutex> lock(gate);
require_live(event_handle);
event_handle->event_exited = true;
changed.notify_all();
}
void on_static_void_method(jmethodID method, va_list args) {
require(method == mpv_MpvPlayer_onHook, "unexpected callback in lifecycle scenario");
const jlong session = va_arg(args, jlong);
const jstring name = va_arg(args, jstring);
const jlong hook = va_arg(args, jlong);
require(name->value == "on_preloaded", "wrong hook callback delivered");
{
std::unique_lock<std::mutex> lock(gate);
require_live(event_handle);
event_handle->callback_session = session;
event_handle->callback_entered = true;
changed.notify_all();
if (event_handle->reject_hook_during_destroy) {
// The callback is already inside Java when teardown starts. Kotlin's
// rejected-channel path continues synchronously on this event thread.
await(lock, [] { return event_handle->woken; }, "destroy never woke the overlapping hook callback");
}
}
jni_func_name(nativeHookContinue)(&jni, nullptr, session, hook);
{
std::lock_guard<std::mutex> lock(gate);
event_handle->callback_returned = true;
changed.notify_all();
}
}
jlong create_player() {
const jlong session = jni_func_name(nativeCreate)(&jni, nullptr, &app_context);
require(session > 0, "nativeCreate failed");
return session;
}
jlong command(jlong session, const char* name = "play") {
_jstring argument{name};
_jobjectArray arguments{{&argument}};
return jni_func_name(nativeCommand)(&jni, nullptr, session, &arguments);
}
void initialize_player(jlong session) {
require(jni_func_name(nativeInit)(&jni, nullptr, session) == 0, "nativeInit failed");
}
void destroy_player(jlong session) { jni_func_name(nativeDestroy)(&jni, nullptr, session); }
jint attach_surfaces(jlong session, jobject video, jobject osd) {
return jni_func_name(nativeAttachSurfaces)(&jni, nullptr, session, video, osd);
}
void reset_dependencies() {
std::lock_guard<std::mutex> lock(gate);
require(active_handle == nullptr, "previous test left a live MPV instance");
require(live_surface_refs() == 0, "terminal Surface cleanup leaked a global reference");
handles.clear();
callback_strings.clear();
global_refs.clear();
reference_handles.clear();
fail_ref_after = 0;
option_failures.clear();
consume_osd_before_failure = false;
hold_wid = false;
wid_entered = false;
allow_wid = false;
surface_waiting = false;
held_termination = nullptr;
allow_termination = false;
allow_command = false;
successor_waiting = false;
reader_draining = false;
fail_thread_create = false;
jni.exception_pending = false;
}
void rejected_hook_and_successor_retirement() {
reset_dependencies();
const jlong old_session = create_player();
mpv_handle* old = active_handle;
int video, osd;
require(attach_surfaces(old_session, &video, &osd) == 0, "initial surface handoff failed");
{
std::lock_guard<std::mutex> lock(gate);
old->hook_pending = true;
old->reject_hook_during_destroy = true;
held_termination = old;
}
initialize_player(old_session);
{
std::unique_lock<std::mutex> lock(gate);
await(lock, [&] { return old->callback_entered; }, "event loop did not deliver the hook");
}
std::thread retiring([&] { destroy_player(old_session); });
{
std::unique_lock<std::mutex> lock(gate);
await(lock, [&] { return old->termination_entered; }, "retirement deadlocked with the synchronous hook callback");
require(old->callback_returned && old->event_exited, "termination preceded event-thread completion");
require(old->callback_session == old_session, "retiring callback lost its bound session");
require(old->hook_continuations == 0, "revoked hook reached the retiring MPV handle");
require_surfaces(old);
}
jlong successor_session = 0;
std::thread creating([&] {
operation = Operation::successor;
successor_session = create_player();
});
{
std::unique_lock<std::mutex> lock(gate);
await(lock, [] { return successor_waiting; }, "successor did not wait for terminal retirement");
}
// S must be available while termination holds L. These calls must reject
// without touching the retiring core, surfaces, or a future successor.
require(command(old_session) == MPV_ERROR_UNINITIALIZED, "revoked command was admitted during termination");
jni_func_name(nativeHookContinue)(&jni, nullptr, old_session, old->hook.id);
require(
attach_surfaces(old_session, nullptr, nullptr) == MPV_ERROR_UNINITIALIZED,
"revoked surface handoff was admitted during termination");
{
std::lock_guard<std::mutex> lock(gate);
require_surfaces(old);
allow_termination = true;
changed.notify_all();
}
retiring.join();
creating.join();
require(successor_session > old_session, "successor did not receive a new session");
mpv_handle* successor = active_handle;
{
std::lock_guard<std::mutex> lock(gate);
successor->hook_pending = true;
}
require(attach_surfaces(successor_session, &video, &osd) == 0, "successor surface handoff failed");
initialize_player(successor_session);
{
std::unique_lock<std::mutex> lock(gate);
await(lock, [&] { return successor->callback_returned; }, "successor event loop did not serve its own hook");
require(successor->callback_session == successor_session, "successor inherited the old event binding");
require(successor->hook_continuations == 1, "live hook was not continued exactly once");
}
destroy_player(old_session);
require(
jni_func_name(nativeInit)(&jni, nullptr, old_session) == MPV_ERROR_UNINITIALIZED, "stale init reached successor");
require(command(old_session) == MPV_ERROR_UNINITIALIZED, "stale command reached successor");
jni_func_name(nativeHookContinue)(&jni, nullptr, old_session, old->hook.id);
require(
attach_surfaces(old_session, nullptr, nullptr) == MPV_ERROR_UNINITIALIZED,
"stale surface handoff reached successor");
require(command(successor_session) == 0, "stale teardown retired the successor");
{
std::lock_guard<std::mutex> lock(gate);
require_surfaces(successor);
require(successor->hook_continuations == 1, "old hook id was forwarded to successor");
}
destroy_player(successor_session);
}
void admitted_command_survives_replacement() {
reset_dependencies();
const jlong old_session = create_player();
mpv_handle* old = active_handle;
initialize_player(old_session);
jlong result = MPV_ERROR_GENERIC;
std::thread reader([&] { result = command(old_session, "hold"); });
{
std::unique_lock<std::mutex> lock(gate);
await(lock, [&] { return old->command_active; }, "command was not admitted");
}
jlong successor_session = 0;
std::thread replacing([&] {
operation = Operation::replacing_reader;
successor_session = create_player();
});
{
std::unique_lock<std::mutex> lock(gate);
await(lock, [] { return reader_draining; }, "replacement did not drain the admitted command");
require(!old->termination_entered && !old->woken, "retirement overtook an admitted command");
allow_command = true;
changed.notify_all();
}
reader.join();
replacing.join();
require(result == 0 && old->commands == 1, "admitted command lost its handle before returning");
require(command(old_session) == MPV_ERROR_UNINITIALIZED, "late old-session command was admitted");
destroy_player(old_session);
initialize_player(successor_session);
require(command(successor_session) == 0, "replacement was affected by stale owner traffic");
destroy_player(successor_session);
}
void partial_initialization_can_retire() {
enum class Failure { configuration, initialization, thread_start };
for (Failure failure : {Failure::configuration, Failure::initialization, Failure::thread_start}) {
reset_dependencies();
const jlong session = create_player();
mpv_handle* failed = active_handle;
if (failure == Failure::configuration) {
_jstring invalid{"not-a-level"};
require(
jni_func_name(nativeSetLogLevel)(&jni, nullptr, session, &invalid) < 0, "invalid configuration succeeded");
} else {
failed->initialize_result = failure == Failure::initialization ? MPV_ERROR_GENERIC : 0;
fail_thread_create = failure == Failure::thread_start;
require(jni_func_name(nativeInit)(&jni, nullptr, session) < 0, "injected initialization failure was lost");
if (failure == Failure::thread_start)
require(jni.ExceptionCheck(), "thread-start failure lost its JNI exception");
}
destroy_player(session);
require(
failed->terminated && !failed->event_started && !failed->woken, "partial init used an unstarted event thread");
require(command(session) == MPV_ERROR_UNINITIALIZED, "failed session retained public admission");
jni.exception_pending = false;
const jlong successor = create_player();
initialize_player(successor);
require(command(successor) == 0, "partial init prevented the next player from working");
destroy_player(successor);
}
}
void paired_surface_replacements() {
reset_dependencies();
const jlong session = create_player();
initialize_player(session);
mpv_handle* handle = active_handle;
int video_a, video_b, osd_a, osd_b;
require(attach_surfaces(session, &video_a, &osd_a) == 0, "initial paired handoff failed");
require_pair(handle, &video_a, &osd_a);
require(attach_surfaces(session, &video_b, &osd_b) == 0, "paired replacement failed");
require_pair(handle, &video_b, &osd_b);
for (jobject next_osd : {static_cast<jobject>(&osd_a), static_cast<jobject>(nullptr), static_cast<jobject>(&osd_b)}) {
const int rebuilds = handle->rebuilds;
require(attach_surfaces(session, &video_b, next_osd) == 0, "OSD-only replacement failed");
require_pair(handle, &video_b, next_osd);
require(handle->rebuilds == rebuilds + 1, "OSD-only change did not rebuild the VO");
require(live_surface_refs() == (next_osd ? 2 : 1), "replacement leaked overwritten Surface references");
}
destroy_player(session);
}
void surface_handoff_failures() {
reset_dependencies();
const jlong session = create_player();
initialize_player(session);
mpv_handle* handle = active_handle;
int video_a, video_b, osd_a, osd_b;
require(attach_surfaces(session, &video_a, &osd_a) == 0, "initial paired handoff failed");
require(
attach_surfaces(session, nullptr, &osd_b) == MPV_ERROR_INVALID_PARAMETER,
"live session admitted a null video Surface");
for (int allocation : {1, 2}) {
fail_ref_after = allocation;
require(
attach_surfaces(session, &video_b, &osd_b) == MPV_ERROR_NOMEM, "global-reference allocation failure was lost");
require_pair(handle, &video_a, &osd_a);
require(live_surface_refs() == 2, "allocation failure leaked a staged Surface");
}
option_failures = {"vo-mediacodec-osd-surface"};
require(attach_surfaces(session, &video_b, &osd_b) == MPV_ERROR_GENERIC, "OSD option failure was lost");
require_pair(handle, &video_a, &osd_a);
require(live_surface_refs() == 2, "rejected OSD option leaked staged references");
option_failures = {"wid"};
require(attach_surfaces(session, &video_b, &osd_b) == MPV_ERROR_GENERIC, "wid option failure was lost");
require_pair(handle, &video_a, &osd_a);
require(attach_surfaces(session, &video_b, &osd_b) == 0, "handoff did not recover from wid failure");
require_pair(handle, &video_b, &osd_b);
require(live_surface_refs() == 2, "successful replacement retained failed handoff references");
// A VO may start between the option writes. Rollback changes only the OSD
// option, so the staged reference must survive even when rollback succeeds.
consume_osd_before_failure = true;
for (bool fail_rollback : {false, true}) {
option_failures = {"wid"};
if (fail_rollback) option_failures.push_back("vo-mediacodec-osd-surface");
require(attach_surfaces(session, &video_a, &osd_a) == MPV_ERROR_GENERIC, "failed handoff reported success");
require(option_failures.empty(), "OSD option rollback was not attempted");
require_surfaces(handle);
}
require(attach_surfaces(session, &video_a, nullptr) == 0, "handoff did not recover from rollback failure");
require_pair(handle, &video_a, nullptr);
require(live_surface_refs() == 1, "successful null-OSD replacement leaked failed handoff references");
option_failures = {"wid", "vo-mediacodec-osd-surface"};
require(attach_surfaces(session, &video_b, &osd_b) < 0, "terminal failed handoff reported success");
destroy_player(session);
require(live_surface_refs() == 0, "termination leaked pending failed-handoff references");
}
void overlapping_handoffs_and_teardown() {
reset_dependencies();
const jlong session = create_player();
initialize_player(session);
mpv_handle* handle = active_handle;
int video_a, video_b, video_c, osd_a, osd_b, osd_c;
require(attach_surfaces(session, &video_a, &osd_a) == 0, "initial paired handoff failed");
hold_wid = true;
jint first_result = MPV_ERROR_GENERIC, second_result = MPV_ERROR_GENERIC;
std::thread first([&] { first_result = attach_surfaces(session, &video_b, &osd_b); });
{
std::unique_lock<std::mutex> lock(gate);
await(lock, [] { return wid_entered; }, "first handoff did not enter synchronous VO rebuild");
require_surfaces(handle);
require(live_surface_refs() == 4, "old Surface references did not survive the wid rebuild");
}
std::thread second([&] {
operation = Operation::surface_handoff;
second_result = attach_surfaces(session, &video_c, &osd_c);
});
{
std::unique_lock<std::mutex> lock(gate);
await(lock, [] { return surface_waiting; }, "overlapping handoff bypassed surface serialization");
require(live_surface_refs() == 4, "waiting handoff mutated active Surface references");
}
std::thread retiring([&] {
operation = Operation::replacing_reader;
destroy_player(session);
});
{
std::unique_lock<std::mutex> lock(gate);
await(lock, [] { return reader_draining; }, "teardown did not drain admitted surface handoffs");
require(!handle->termination_entered, "teardown overtook an admitted surface handoff");
allow_wid = true;
changed.notify_all();
}
first.join();
second.join();
retiring.join();
require(first_result == 0 && second_result == 0, "admitted handoff lost its session during teardown");
require(handle->rebuilds == 3, "overlapping handoffs lost a complete VO rebuild");
require(live_surface_refs() == 0, "overlapping replacement/teardown leaked Surface references");
}
} // namespace
// Observe real contention to arrange overlap without sleeps or a guessed
// scheduling delay. The production guards still acquire the real pthread
// locks; the notification only lets the test release its external MPV gates.
static int tracked_mutex_lock(pthread_mutex_t* mutex) {
if (operation != Operation::successor && operation != Operation::surface_handoff) return pthread_mutex_lock(mutex);
const int result = pthread_mutex_trylock(mutex);
if (result != EBUSY) return result;
{
std::lock_guard<std::mutex> lock(gate);
if (operation == Operation::successor) successor_waiting = true;
if (operation == Operation::surface_handoff) surface_waiting = true;
changed.notify_all();
}
return pthread_mutex_lock(mutex);
}
static int tracked_write_lock(pthread_rwlock_t* lock) {
if (operation != Operation::replacing_reader) return pthread_rwlock_wrlock(lock);
const int result = pthread_rwlock_trywrlock(lock);
if (result != EBUSY) return result;
{
std::lock_guard<std::mutex> guard(gate);
reader_draining = true;
changed.notify_all();
}
return pthread_rwlock_wrlock(lock);
}
static int controlled_thread_create(pthread_t* thread, const pthread_attr_t* attr, void* (*entry)(void*), void* arg) {
std::lock_guard<std::mutex> lock(gate);
if (fail_thread_create) {
fail_thread_create = false;
return EAGAIN;
}
const int result = pthread_create(thread, attr, entry, arg);
if (result == 0) active_handle->event_started = true;
return result;
}
extern "C" mpv_handle* mpv_create() {
std::lock_guard<std::mutex> lock(gate);
require(active_handle == nullptr, "successor MPV creation overlapped predecessor termination");
require(live_surface_refs() == 0, "successor creation preceded retiring Surface cleanup");
handles.push_back(std::make_unique<mpv_handle>());
active_handle = handles.back().get();
return active_handle;
}
extern "C" int mpv_initialize(mpv_handle* handle) {
std::lock_guard<std::mutex> lock(gate);
require_live(handle);
if (handle->initialize_result < 0) return handle->initialize_result;
handle->initialized = true;
return 0;
}
extern "C" void mpv_wakeup(mpv_handle* handle) {
std::lock_guard<std::mutex> lock(gate);
require_live(handle);
require(!handle->command_active, "wake overtook an admitted command");
require(handle->event_started, "wake targeted an unstarted event thread");
handle->woken = true;
changed.notify_all();
}
extern "C" void mpv_terminate_destroy(mpv_handle* handle) {
std::unique_lock<std::mutex> lock(gate);
require_live(handle);
require(!handle->command_active, "termination overtook an admitted command");
require(!handle->event_started || handle->event_exited, "termination overtook the bound event thread");
require_surfaces(handle);
handle->termination_entered = true;
changed.notify_all();
if (handle == held_termination)
await(lock, [] { return allow_termination; }, "test did not release native termination");
require_surfaces(handle);
handle->terminated = true;
active_handle = nullptr;
}
extern "C" mpv_event* mpv_wait_event(mpv_handle* handle, double) {
std::unique_lock<std::mutex> lock(gate);
event_handle = handle;
require_live(handle);
await(lock, [&] { return handle->hook_pending || handle->woken; }, "event loop was not woken for teardown");
handle->event = {};
if (handle->hook_pending) {
handle->hook_pending = false;
handle->event.event_id = MPV_EVENT_HOOK;
handle->event.data = &handle->hook;
}
return &handle->event;
}
extern "C" int mpv_hook_add(mpv_handle* handle, uint64_t, const char*, int) {
std::lock_guard<std::mutex> lock(gate);
require_live(handle);
return 0;
}
extern "C" int mpv_hook_continue(mpv_handle* handle, uint64_t id) {
std::lock_guard<std::mutex> lock(gate);
require_live(handle);
require(id == handle->hook.id && handle->hook_continuations == 0, "hook continued twice or on the wrong handle");
++handle->hook_continuations;
return 0;
}
extern "C" int mpv_command_ret(mpv_handle* handle, const char** args, mpv_node* result) {
std::unique_lock<std::mutex> lock(gate);
require_live(handle);
require(handle->initialized, "command reached an uninitialized core");
handle->command_active = true;
changed.notify_all();
if (std::strcmp(args[0], "hold") == 0)
await(lock, [] { return allow_command; }, "test did not release admitted command");
require_live(handle);
handle->command_active = false;
++handle->commands;
*result = {};
return 0;
}
extern "C" int mpv_request_log_messages(mpv_handle* handle, const char* level) {
std::lock_guard<std::mutex> lock(gate);
require_live(handle);
return std::strcmp(level, "not-a-level") == 0 ? MPV_ERROR_INVALID_PARAMETER : 0;
}
extern "C" int mpv_set_option(mpv_handle* handle, const char* name, mpv_format format, void* data) {
std::unique_lock<std::mutex> lock(gate);
require_live(handle);
require_surfaces(handle);
require(format == MPV_FORMAT_INT64, "unexpected Surface option format");
jobject object = reinterpret_cast<jobject>(static_cast<intptr_t>(*static_cast<int64_t*>(data)));
require(!object || global_refs.count(object) == 1, "option received an invalid JNI reference");
const bool is_wid = std::strcmp(name, "wid") == 0;
if (is_wid && hold_wid) {
wid_entered = true;
changed.notify_all();
await(lock, [] { return allow_wid; }, "test did not release the synchronous wid rebuild");
require_surfaces(handle);
}
if (!option_failures.empty() && option_failures.front() == name) {
option_failures.erase(option_failures.begin());
if (is_wid && consume_osd_before_failure) handle->osd = handle->osd_option;
return MPV_ERROR_GENERIC;
}
if (is_wid) {
// mpv ignores equal option values; changing wid synchronously retires the
// consumers and rebuilds using the OSD option, not the former OSD plane.
if (handle->video != object) {
handle->video = object;
handle->osd = handle->osd_option;
++handle->rebuilds;
}
} else {
require(std::strcmp(name, "vo-mediacodec-osd-surface") == 0, "unexpected Surface option");
handle->osd_option = object;
}
return 0;
}
extern "C" int mpv_get_property(mpv_handle*, const char*, mpv_format, void*) {
require(false, "unexpected property read in lifecycle scenario");
return MPV_ERROR_GENERIC;
}
extern "C" const char* mpv_error_string(int) { return "controlled MPV failure"; }
extern "C" void mpv_free_node_contents(mpv_node*) {}
extern "C" int av_jni_set_java_vm(void*, void*) { return 0; }
extern "C" int av_jni_set_android_app_ctx(void*, void*) { return 0; }
extern "C" int __android_log_print(int, const char*, const char*, ...) { return 0; }
bool acquire_jni_env(JavaVM* supplied_vm, JNIEnv** env) {
require(supplied_vm == &vm, "event thread acquired the wrong Java VM");
*env = &jni;
return true;
}
void init_methods_cache(JNIEnv*) {
std::lock_guard<std::mutex> lock(gate);
require(active_handle == nullptr, "JNI environment rewritten before predecessor retirement");
mpv_MpvPlayer_onHook = reinterpret_cast<jmethodID>(1);
}
jstring new_java_string(JNIEnv*, const char* value) {
std::lock_guard<std::mutex> lock(gate);
callback_strings.push_back(std::make_unique<_jstring>(_jstring{value ? value : ""}));
return callback_strings.back().get();
}
std::string java_string_to_utf8(JNIEnv*, jstring value) { return value ? value->value : ""; }
void die(const char*) { jni.exception_pending = true; }
int main() {
jni.vm = &vm;
jni.on_new_global_ref = new_global_ref;
jni.on_delete_global_ref = delete_global_ref;
jni.on_static_void_method = on_static_void_method;
vm.on_detach = detach_event_thread;
rejected_hook_and_successor_retirement();
admitted_command_survives_replacement();
partial_initialization_can_retire();
paired_surface_replacements();
surface_handoff_failures();
overlapping_handoffs_and_teardown();
reset_dependencies();
std::puts("MPV lifecycle: session isolation, paired handoffs, rollback ownership and overlapping teardown passed");
return 0;
}
@@ -0,0 +1,59 @@
#include <cstdio>
#include <string>
#include "../../../../libmpv/src/main/cpp/utf8_convert.h"
namespace {
using plezy::utf8::FromUtf16;
using plezy::utf8::ToUtf16;
bool check(bool condition, const char* message) {
if (!condition) std::fprintf(stderr, "%s\n", message);
return condition;
}
bool roundTripsAsciiBmpAndSupplementary() {
// "a" U+00E9 U+4E2D U+1F3AC (clapper board) — 1/2/3/4-byte sequences.
const std::string utf8 = "a\xC3\xA9\xE4\xB8\xAD\xF0\x9F\x8E\xAC";
const std::u16string utf16 = ToUtf16(utf8.c_str());
return check(utf16 == u"a\u00E9\u4E2D\U0001F3AC", "UTF-8 -> UTF-16 mismatch") &&
check(FromUtf16(utf16.data(), utf16.size()) == utf8, "UTF-16 -> UTF-8 mismatch");
}
bool doesNotEmitModifiedUtf8() {
// JNI's modified UTF-8 would encode U+1F3AC as a 6-byte CESU-8 surrogate
// pair; mpv/open() need the real 4-byte form.
const std::u16string clapper = u"\U0001F3AC";
return check(FromUtf16(clapper.data(), clapper.size()) == "\xF0\x9F\x8E\xAC", "supplementary char not 4 bytes") &&
check(
ToUtf16("\xED\xA0\xBC\xED\xBE\xAC") == u"\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD",
"CESU-8 surrogate bytes accepted as UTF-8");
}
bool replacesMalformedBytesOneAtATime() {
return check(ToUtf16("ok\xFF\xFEz") == u"ok\uFFFD\uFFFDz", "stray bytes not replaced individually") &&
check(ToUtf16("\xC0\x80") == u"\uFFFD\uFFFD", "overlong NUL accepted") &&
check(ToUtf16("\xE2\x82") == u"\uFFFD\uFFFD", "truncated sequence not replaced") &&
check(ToUtf16("\xF4\x90\x80\x80") == u"\uFFFD\uFFFD\uFFFD\uFFFD", "code point above U+10FFFF accepted") &&
check(ToUtf16("\xE0\x80\xAF") == u"\uFFFD\uFFFD\uFFFD", "overlong 3-byte form accepted");
}
bool replacesLoneSurrogates() {
const std::u16string lone = u"x\xD83Cy\xDFACz";
return check(FromUtf16(lone.data(), lone.size()) == "x\xEF\xBF\xBDy\xEF\xBF\xBDz", "lone surrogates not replaced");
}
bool handlesNullAndEmpty() {
return check(ToUtf16(nullptr).empty(), "NULL input not empty") &&
check(ToUtf16("").empty(), "empty input not empty") &&
check(FromUtf16(nullptr, 0).empty(), "NULL UTF-16 not empty");
}
} // namespace
int main() {
const bool ok = roundTripsAsciiBmpAndSupplementary() && doesNotEmitModifiedUtf8() &&
replacesMalformedBytesOneAtATime() && replacesLoneSurrogates() && handlesNullAndEmpty();
return ok ? 0 : 1;
}
@@ -2,8 +2,10 @@ package com.edde746.plezy
import android.app.Activity
import android.content.Intent
import android.net.Uri
import io.flutter.plugin.common.MethodChannel
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
@@ -30,6 +32,40 @@ class ExternalPlayerChannelTest {
assertEquals(false, result["playbackError"])
}
@Test
fun freshLaunchTellsPlayerToStartFromBeginning() {
val activity = Robolectric.buildActivity(Activity::class.java).get()
val channel = ExternalPlayerChannel(activity)
val source = ExternalPlayerChannel.Source(
Uri.parse("http://plex:32400/library/parts/9808/1775431760/file.mkv?X-Plex-Token=tok"),
grantRead = false,
fileName = "file.mkv"
)
val intent = channel.buildIntent(source, packageName = null, startPositionMs = 0L, title = "Episode")
assertTrue(intent.getBooleanExtra("from_start", false))
assertFalse(intent.hasExtra("position"))
assertFalse(intent.hasExtra("startfrom"))
}
@Test
fun resumeLaunchPassesPositionAndDisablesFromStart() {
val activity = Robolectric.buildActivity(Activity::class.java).get()
val channel = ExternalPlayerChannel(activity)
val source = ExternalPlayerChannel.Source(
Uri.parse("http://plex:32400/library/parts/9808/1775431760/file.mkv?X-Plex-Token=tok"),
grantRead = false,
fileName = "file.mkv"
)
val intent = channel.buildIntent(source, packageName = null, startPositionMs = 90_000L, title = null)
assertFalse(intent.getBooleanExtra("from_start", true))
assertEquals(90_000, intent.getIntExtra("position", -1))
assertEquals(90_000, intent.getIntExtra("startfrom", -1))
}
@Test
fun activityDestroyCompletesPendingChannelCall() {
val activity = Robolectric.buildActivity(Activity::class.java).get()
@@ -48,83 +48,219 @@ class AudioOutputPolicyTest {
}
@Test
fun spdifListNamesEveryCodecAnUnrestrictedRouteAdvertises() {
assertEquals("ac3,eac3,dts,dts-hd,truehd", mpvSpdifCodecs { true })
fun dtsDecodeIsForcedToFfmpegWhenDirectOutputIsBlocked() {
// Passthrough disabled (the #1995 report), downmix, normalization, or a failure block:
// the stream decodes, and platform DTS decoders render silence on license-gated devices.
assertTrue(shouldForceFfmpegDtsDecode("audio/vnd.dts", { true }, { true }))
assertTrue(shouldForceFfmpegDtsDecode("audio/vnd.dts.hd", { true }, { true }))
}
@Test
fun spdifListDropsCodecsTheRouteCannotBitstream() {
// Google TV Streamer over HDMI to a Dolby-only sink: AC3/E-AC3 bitstream,
// TrueHD and DTS do not (#1703).
val dolbyOnlyRoute = setOf(C.ENCODING_AC3, C.ENCODING_E_AC3)
assertEquals("ac3,eac3", mpvSpdifCodecs { encoding -> encoding in dolbyOnlyRoute })
fun dtsDecodeIsForcedToFfmpegWhenTheRouteCannotBitstream() {
// Onn 4K Plus over HDMI to a Dolby-only TV: passthrough enabled (the Android TV default)
// still decodes because the route carries no DTS shape (#1995).
assertTrue(shouldForceFfmpegDtsDecode("audio/vnd.dts", { false }, { false }))
assertTrue(shouldForceFfmpegDtsDecode("audio/vnd.dts.hd", { false }, { false }))
}
@Test
fun spdifListOmitsDtsHdOnDtsCoreOnlyRoutes() {
// media3's passthrough probe would answer yes for DTS-HD here by downgrading to the
// DTS core. mpv reads `dts,dts-hd` as `dts-hd` alone and force-passes DTS-HD MA, so
// accepting that downgrade would break DTS too.
val dtsCoreOnlyRoute = setOf(C.ENCODING_DTS)
assertEquals("dts", mpvSpdifCodecs { encoding -> encoding in dtsCoreOnlyRoute })
fun bitstreamCapableDtsRoutesKeepThePlatformDecoderVisible() {
// A bitstreaming session never engages a decoder; leaving the platform decoder visible
// keeps the hardware-decoder tunneling gate exactly as it was.
assertFalse(shouldForceFfmpegDtsDecode("audio/vnd.dts", { false }, { true }))
assertFalse(shouldForceFfmpegDtsDecode("audio/vnd.dts.hd", { false }, { true }))
}
@Test
fun spdifListKeepsDtsHdWhenTheRouteAdvertisesIt() {
val dtsHdRoute = setOf(C.ENCODING_DTS, C.ENCODING_DTS_HD)
assertEquals("dts,dts-hd", mpvSpdifCodecs { encoding -> encoding in dtsHdRoute })
fun dtsVariantsFfmpegCannotClaimAreLeftAlone() {
// DTS Express and DTS:X are not in FfmpegLibrary's mime map; hiding their platform
// decoders would leave those streams with no decoder at all.
assertFalse(shouldForceFfmpegDtsDecode("audio/vnd.dts.hd;profile=lbr", { true }, { false }))
assertFalse(shouldForceFfmpegDtsDecode("audio/vnd.dts.uhd", { true }, { false }))
assertFalse(shouldForceFfmpegDtsDecode(MimeTypes.AUDIO_TRUEHD, { true }, { false }))
}
@Test
fun spdifListIsEmptyForPcmOnlyRoutes() {
assertEquals("", mpvSpdifCodecs { false })
fun dtsHdTakesTheCarrierOnlyWhenTheRouteAdvertisesDtsHd() {
assertTrue(dtsHdCarrierUsable({ it == C.ENCODING_DTS_HD }, { true }))
// Carries the tuple for TrueHD but decodes no DTS-HD: the burst would drain unheard.
assertFalse(dtsHdCarrierUsable({ false }, { true }))
assertFalse(dtsHdCarrierUsable({ true }, { false }))
}
@Test
fun carrierIsNeverOfferedBelowApi29() {
// No direct-playback oracle exists there, and getMinBufferSize alone is known to lie
// (a Shield sizes the tuple, then the AudioTrack fails to initialise).
fun theCarrierProbeIsSkippedWhenDtsHdIsNotAdvertised() {
// The carrier tiering costs several route calls; a route without DTS-HD must not pay them.
assertFalse(dtsHdCarrierUsable({ false }, { throw AssertionError("carrier probed without DTS-HD") }))
}
@Test
fun nonDtsMimesNeverConsultTheDtsProbes() {
// Decoder selection runs this predicate for every mime, video included; the probes make
// binder calls and must stay behind the mime gate.
assertFalse(
trueHdMatCarrierSupported(
sdkInt = 28,
canSizeCarrierBuffer = { true },
bitstreamSupported = { true },
directPlaybackSupported = { true }
shouldForceFfmpegDtsDecode(
MimeTypes.VIDEO_H265,
{ throw AssertionError("directOutputBlocked consulted for a non-DTS mime") },
{ throw AssertionError("routeCanBitstreamDts consulted for a non-DTS mime") }
)
)
}
@Test
fun carrierRequiresASizableBufferOnEveryTier() {
for (sdkInt in intArrayOf(29, 30, 32, 33, 34)) {
fun spdifListNamesEveryCodecARouteWithAllShapesCanCarry() {
// libmpv v1.1.0's audiotrack AO opens each burst at its own rate and channel mask, so a route
// that takes all three shapes and advertises everything bitstreams the lossless codecs too.
// `dts-hd` supersedes plain `dts`: ad_spdif picks the core burst per file for non-HD tracks.
assertEquals("ac3,eac3,truehd,dts-hd", spdifCodecs(allEncodings, allShapes))
}
@Test
fun spdifListOnAStereo48kOnlyRouteNamesTheCoreCodecsOnly() {
// E-AC3 (192kHz), TrueHD MAT and DTS-HD MA (192kHz/8ch) have no track to ride here.
assertEquals("ac3,dts", spdifCodecs(allEncodings, setOf(MpvIecShape.STEREO_48K)))
}
@Test
fun dtsHdFallsBackToThePlainCoreWithoutTheCarrierShape() {
// Advertising ENCODING_DTS_HD says the receiver decodes it, not that the route takes the
// 192kHz/8ch track its burst needs (#1988); naming `dts-hd` anyway strands playback.
assertEquals(
"dts",
spdifCodecs(setOf(C.ENCODING_DTS, C.ENCODING_DTS_HD), setOf(MpvIecShape.STEREO_48K))
)
}
@Test
fun eac3IsNotNamedWithoutThe192kStereoShape() {
assertEquals("", spdifCodecs(setOf(C.ENCODING_E_AC3), setOf(MpvIecShape.STEREO_48K)))
}
@Test
fun trueHdIsNotNamedWithoutTheCarrierShape() {
assertEquals(
"",
spdifCodecs(
setOf(C.ENCODING_DOLBY_TRUEHD),
setOf(MpvIecShape.STEREO_48K, MpvIecShape.STEREO_192K)
)
)
}
@Test
fun plainDtsSurvivesWhenTheRouteDoesNotAdvertiseDtsHd() {
// The core burst is stereo/48k, so it rides a full-shape route unchanged when only the
// lossless encoding is missing.
assertEquals("dts", spdifCodecs(setOf(C.ENCODING_DTS), allShapes))
}
@Test
fun spdifListDropsCodecsTheRouteCannotBitstream() {
// Google TV Streamer over HDMI to a Dolby-only sink: AC3/E-AC3 bitstream, DTS does not (#1703).
val dolbyOnlyRoute = setOf(C.ENCODING_AC3, C.ENCODING_E_AC3)
assertEquals("ac3,eac3", spdifCodecs(dolbyOnlyRoute, allShapes))
}
@Test
fun spdifListIsEmptyForPcmOnlyRoutes() {
assertEquals("", mpvSpdifCodecs({ false }, { false }))
}
@Test
fun spdifListIsEmptyWhenTheRouteTakesNoIecTrackAtAll() {
// Every encoding advertised, but no raw track and no IEC 61937 shape opens: mpv has no
// decode fallback for a named codec, so nothing may be named (#1991).
assertEquals("", spdifCodecs(allEncodings, emptySet()))
}
@Test
fun rawCapableRouteBitstreamsTheCoreCodecsWithoutAnyIecShape() {
// #2177's Shield: every mpv IEC track opens and drains into silence, while raw
// ENCODING_AC3/E_AC3/DTS tracks (the ExoPlayer transport) play. The AO opens raw first,
// so raw support alone must qualify the core codecs.
assertEquals(
"ac3,eac3,dts",
spdifCodecs(allEncodings, emptySet(), raw = setOf(C.ENCODING_AC3, C.ENCODING_E_AC3, C.ENCODING_DTS))
)
}
@Test
fun rawSupportNeverQualifiesTheLosslessCodecs() {
// TrueHD and DTS-HD MA have no raw transport in the AO; they ride the 192kHz/7.1 IEC
// carrier or decode. A route that takes every raw track but no carrier must not name them.
assertEquals("ac3,eac3,dts", spdifCodecs(allEncodings, emptySet(), raw = allEncodings))
}
@Test
fun rawProbeIsOnlyConsultedForRawCandidates() {
// The raw probe costs real route calls; the carrier-only codecs must never trigger it.
val codecs = mpvSpdifCodecs(
{ true },
{ true },
{ encoding ->
if (encoding == C.ENCODING_DOLBY_TRUEHD || encoding == C.ENCODING_DTS_HD) {
throw AssertionError("raw probe consulted for a carrier-only codec")
}
true
}
)
assertEquals("ac3,eac3,truehd,dts-hd", codecs)
}
@Test
fun dtsHdStillSupersedesPlainDtsWhenDtsBitstreamsRaw() {
// dts-hd selects the lossless spdif decoder for the whole dts codec; the raw core track
// must not resurrect the plain name beside it.
assertEquals("ac3,eac3,truehd,dts-hd", spdifCodecs(allEncodings, allShapes, raw = allEncodings))
}
@Test
fun iecRouteIsNeverOfferedBelowApi24() {
// ENCODING_IEC61937 does not exist there.
assertFalse(
iecRouteSupported(
sdkInt = 23,
canSizeBuffer = { true },
bitstreamSupported = { true },
directPlaybackSupported = { true },
hdmiRouteAdvertised = { true }
)
)
}
@Test
fun iecRouteRequiresASizableBufferOnEveryTier() {
for (sdkInt in intArrayOf(25, 28, 29, 30, 32, 33, 34)) {
assertFalse(
"api $sdkInt",
trueHdMatCarrierSupported(
iecRouteSupported(
sdkInt = sdkInt,
canSizeCarrierBuffer = { false },
canSizeBuffer = { false },
bitstreamSupported = { true },
directPlaybackSupported = { true }
directPlaybackSupported = { true },
hdmiRouteAdvertised = { true }
)
)
}
}
@Test
fun carrierOnApi29To32FollowsTheDirectPlaybackProbe() {
// Fire OS 8 (API 30) bitstreams TrueHD over this route; an API 33 gate force-decoded it (#1863).
fun routeOnApi24To28FollowsTheHdmiAdvertisement() {
// No runtime oracle exists below API 29; only an HDMI AudioDeviceInfo that explicitly
// advertises the IEC tuple can vouch for it. Shield Experience 8.x is API 28, and a flat
// `false` on this tier force-decoded TrueHD on routes that genuinely carry it (#1991).
for (supported in booleanArrayOf(true, false)) {
for (sdkInt in intArrayOf(29, 30, 32)) {
for (sdkInt in intArrayOf(25, 28)) {
assertEquals(
"api $sdkInt supported=$supported",
supported,
trueHdMatCarrierSupported(
iecRouteSupported(
sdkInt = sdkInt,
canSizeCarrierBuffer = { true },
canSizeBuffer = { true },
bitstreamSupported = { throw AssertionError("getDirectPlaybackSupport does not exist below API 33") },
directPlaybackSupported = { supported }
directPlaybackSupported = { throw AssertionError("isDirectPlaybackSupported does not exist below API 29") },
hdmiRouteAdvertised = { supported }
)
)
}
@@ -132,20 +268,54 @@ class AudioOutputPolicyTest {
}
@Test
fun carrierOnApi33UsesTheBitstreamProbe() {
fun routeOnApi29To32FollowsTheDirectPlaybackProbe() {
// Fire OS 8 (API 30) bitstreams TrueHD over this route; an API 33 gate force-decoded it (#1863).
for (supported in booleanArrayOf(true, false)) {
for (sdkInt in intArrayOf(29, 30, 32)) {
assertEquals(
"api $sdkInt supported=$supported",
supported,
iecRouteSupported(
sdkInt = sdkInt,
canSizeBuffer = { true },
bitstreamSupported = { throw AssertionError("getDirectPlaybackSupport does not exist below API 33") },
directPlaybackSupported = { supported },
hdmiRouteAdvertised = { throw AssertionError("the HDMI advertisement must not shadow the runtime probe") }
)
)
}
}
}
@Test
fun routeOnApi33UsesTheBitstreamProbe() {
// getDirectPlaybackSupport distinguishes bitstream from offload-only; the coarser API 29
// probe must not shadow it where the platform can answer precisely.
for (supported in booleanArrayOf(true, false)) {
assertEquals(
"supported=$supported",
supported,
trueHdMatCarrierSupported(
iecRouteSupported(
sdkInt = 33,
canSizeCarrierBuffer = { true },
canSizeBuffer = { true },
bitstreamSupported = { supported },
directPlaybackSupported = { throw AssertionError("API 29 probe must not be consulted on API 33+") }
directPlaybackSupported = { throw AssertionError("API 29 probe must not be consulted on API 33+") },
hdmiRouteAdvertised = { throw AssertionError("the HDMI advertisement must not shadow the runtime probe") }
)
)
}
}
/** Every encoding the spdif table can ask for, i.e. a receiver that decodes all of them. */
private val allEncodings = setOf(
C.ENCODING_AC3,
C.ENCODING_E_AC3,
C.ENCODING_DOLBY_TRUEHD,
C.ENCODING_DTS,
C.ENCODING_DTS_HD
)
private val allShapes = MpvIecShape.values().toSet()
private fun spdifCodecs(encodings: Set<Int>, shapes: Set<MpvIecShape>, raw: Set<Int> = emptySet()): String = mpvSpdifCodecs({ it in encodings }, { it in shapes }, { it in raw })
}
@@ -8,12 +8,23 @@ import androidx.media3.common.util.ParsableByteArray
import androidx.media3.extractor.TrackOutput
import java.io.ByteArrayOutputStream
import java.io.EOFException
import org.junit.After
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertThrows
import org.junit.Before
import org.junit.Test
class BufferedTransformingTrackOutputTest {
@Before
fun enableMedia3TestBoundsChecks() {
ParsableByteArray.setShouldEnforceLimitOnLegacyMethods(true)
}
@After
fun resetMedia3TestBoundsChecks() {
ParsableByteArray.setShouldEnforceLimitOnLegacyMethods(null)
}
@Test
fun activeTransformBuffersChunksAndEmitsOneNormalizedSample() {
@@ -28,7 +28,6 @@ class BufferingStallPolicyTest {
loading = loading
)
@Test
fun aLoaderThatStoppedAskingForDataCountsAsEnoughBuffer() {
// The #1790 shape on a high bitrate stream: the byte cap is full at a couple of seconds, the
@@ -50,7 +49,6 @@ class BufferingStallPolicyTest {
assertEquals(Verdict.STALLED, evaluate(bufferedAheadMs = 2_000L, loading = false, loadControlReady = false))
}
@Test
fun aByteCappedBufferBelowTheDurationBarIsStillIndicted() {
// The real failure this watchdog exists for, on a high bitrate stream: media3 released playback
@@ -81,7 +79,6 @@ class BufferingStallPolicyTest {
)
}
@Test
fun aFastForwardNeedsProportionallyMoreMediaBeforeItIsIndicted() {
// Enough media to start at 1x, but the load control measures its bar in playout time, so at 2x
@@ -104,7 +101,6 @@ class BufferingStallPolicyTest {
assertEquals(Verdict.STALLED, evaluate(playbackSpeed = -1f))
}
@Test
fun advancingPositionIsHealthy() {
assertEquals(
@@ -134,7 +130,6 @@ class BufferingStallPolicyTest {
assertEquals(Verdict.STALLED, evaluate(currentPositionMs = position - 5_000))
}
@Test
fun frozenPositionWaitsOutTheTimeout() {
assertEquals(Verdict.WAITING, evaluate(elapsedMs = BufferingStallPolicy.STALL_TIMEOUT_MS - 1))
@@ -146,7 +141,6 @@ class BufferingStallPolicyTest {
assertEquals(Verdict.STALLED, evaluate())
}
@Test
fun emptyBufferIsStarved() {
assertEquals(Verdict.STARVED, evaluate(bufferedAheadMs = 0))
@@ -197,7 +191,6 @@ class BufferingStallPolicyTest {
)
}
@Test
fun starvationAndProgressBothRestartTheStallClock() {
assertTrue(BufferingStallPolicy.resetsStallClock(Verdict.STARVED))
@@ -0,0 +1,270 @@
package com.edde746.plezy.exoplayer
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* Pins the DTS-HD -> IEC 61937 "DTS type IV" carrier against FFmpeg (#1988).
*
* The carrier is fed straight to an `ENCODING_IEC61937` AudioTrack, so a wrong byte is not a subtle
* defect: the receiver either drops sync or renders the carrier as full-scale noise. The only
* defensible bar is byte-for-byte agreement with a reference implementation, so the fixtures are
* FFmpeg's own input and output at the 768kHz HD rate that fills the 192kHz/7.1 carrier.
*
* FFmpeg cannot encode Master Audio, so the access units are synthesized real `dca` core frames,
* each glued to a hand-built extension substream by `dtshd_fixture_generator.py` beside the
* fixtures; the golden is then FFmpeg's own packing:
*
* ```
* ffmpeg -f dts -i dtshd_ma_access_units.bin -c:a copy -f spdif -dtshd_rate 768000 \
* dtshd_ma_iec61937_golden.bin
* ```
*
* One mid-stream unit is oversized on purpose, so the fixtures also pin FFmpeg's overflow answer:
* strip to the core substream and hold that for ~60s.
*/
class DtsHdIecPackerTest {
private fun resource(name: String): ByteArray = checkNotNull(javaClass.classLoader?.getResourceAsStream(name)) { "missing fixture $name" }
.use { it.readBytes() }
private val accessUnits by lazy { resource("dtshd_ma_access_units.bin") }
private val golden by lazy { resource("dtshd_ma_iec61937_golden.bin") }
/** 512 samples at the fixture's 48kHz core rate on the 768kHz carrier model, in bytes. */
private val burstSize = 32768
/** The whole point: our carrier and FFmpeg's are the same bytes. */
@Test
fun packedCarrierMatchesFfmpegByteForByte() {
val packed = packAll(accessUnits)
assertEquals(
"burst count differs from FFmpeg",
golden.size / burstSize,
packed.size / burstSize
)
// Compare per burst so a failure names the burst rather than dumping 480KB.
for (index in 0 until packed.size / burstSize) {
val from = index * burstSize
val to = from + burstSize
assertArrayEquals(
"burst $index differs from FFmpeg",
golden.copyOfRange(from, to),
packed.copyOfRange(from, to)
)
}
}
/** Each burst is a full IEC 61937 frame: preamble, then payload, then zero padding. */
@Test
fun everyBurstCarriesTheDtsHdPreamble() {
val packed = packAll(accessUnits)
for (index in 0 until packed.size / burstSize) {
val at = index * burstSize
assertEquals("burst $index Pa", 0xF872, readLittleEndianShort(packed, at))
assertEquals("burst $index Pb", 0x4E1F, readLittleEndianShort(packed, at + 2))
// Data type 0x11 with subtype 4: an 8192 IEC 60958 frame repetition period.
assertEquals("burst $index Pc (IEC61937_DTSHD)", 0x0411, readLittleEndianShort(packed, at + 4))
val payloadSize = 10 + 2 + burstAccessUnitSize(packed, at)
assertEquals(
"burst $index Pd must carry FFmpeg's (length & 0xf) == 0x8 alignment",
((payloadSize + 0x17) and 0x0F.inv()) - 8,
readLittleEndianShort(packed, at + 6)
)
}
}
/**
* A Master Audio peak the carrier cannot hold is stripped to the always-fitting core substream,
* and stays stripped for ~60s so the receiver does not flap between core and MA decoding. The
* fixture's fifth unit is oversized on purpose; everything after it is core-only.
*/
@Test
fun anOversizedUnitStripsToTheCoreAndHolds() {
val packer = DtsHdIecPacker()
val packed = packAll(accessUnits, packer)
val fullUnit = 3904
val coreOnly = 1884
for (index in 0 until packed.size / burstSize) {
val expected = if (index < 4) fullUnit else coreOnly
assertEquals("burst $index payload size", expected, burstAccessUnitSize(packed, index * burstSize))
}
assertTrue("the strip must be observable for logging", packer.strippedToCore)
assertFalse("stripping is a downgrade, not an unsupported stream", packer.unsupportedStream)
}
/** Core frames and their glued extension substreams split as one access unit each. */
@Test
fun accessUnitsSpanTheCoreAndItsExtensionSubstreams() {
val packer = DtsHdIecPacker()
var units = 0
var offset = 0
while (offset < accessUnits.size) {
val length = packer.accessUnitLength(accessUnits, offset, accessUnits.size)
if (length == 0) break
units++
offset += length
}
assertEquals("every byte of the fixture belongs to a unit", accessUnits.size, offset)
assertEquals(golden.size / burstSize, units)
}
/**
* Streams with core sometimes open with a stray HD frame that has no core (FFmpeg discards
* these). It must be consumed as a unit so the stream keeps moving, but never carried: there is
* no core to derive the burst period from.
*/
@Test
fun aStrayLeadingExtensionSubstreamIsConsumedButNotCarried() {
val packer = DtsHdIecPacker()
val firstUnit = packer.accessUnitLength(accessUnits, 0, accessUnits.size)
val exssSize = 2020
val stray = accessUnits.copyOfRange(firstUnit - exssSize, firstUnit)
val length = packer.accessUnitLength(stray, 0, stray.size)
assertEquals("the stray frame's own size field walks it", exssSize, length)
assertNull("a coreless frame cannot ride the carrier", packer.packAccessUnit(stray, 0, length))
assertFalse("a stray frame is dropped, not latched", packer.unsupportedStream)
}
/** The wide (bHeaderSizeType=1) extension-substream header carries 20-bit size fields. */
@Test
fun wideHeaderExtensionSubstreamSizesAreParsed() {
val packer = DtsHdIecPacker()
val core = accessUnits.copyOfRange(0, 1884)
val exssSize = 4100
val unit = core + wideHeaderExtensionSubstream(exssSize)
assertEquals(1884 + exssSize, packer.accessUnitLength(unit, 0, unit.size))
}
/**
* Little-endian and 14-bit core framings (S/PDIF and DTS-in-WAV captures) have no period mapping
* on this carrier; they must latch the stream unsupported so the sink hands it to the decoder,
* not silently consume it.
*/
@Test
fun nonBigEndianCoreFramingLatchesTheStreamUnsupported() {
for (sync in listOf(
byteArrayOf(0xFE.toByte(), 0x7F, 0x01, 0x80.toByte()),
byteArrayOf(0x1F, 0xFF.toByte(), 0xE8.toByte(), 0x00),
byteArrayOf(0xFF.toByte(), 0x1F, 0x00, 0xE8.toByte())
)) {
val packer = DtsHdIecPacker()
val buffer = sync + ByteArray(64)
assertEquals(0, packer.accessUnitLength(buffer, 0, buffer.size))
assertTrue("sync ${sync.joinToString { "%02x".format(it) }}", packer.unsupportedStream)
}
}
/** A 44.1kHz-family core maps to no IEC 61937-11 repetition period at 192kHz; it must decode. */
@Test
fun aFortyFourFamilyCoreLatchesTheStreamUnsupported() {
val packer = DtsHdIecPacker()
val unit = accessUnits.copyOfRange(0, 1884)
// SFREQ sits in bits [5:2] of byte 8; index 8 is 44100Hz.
unit[8] = ((unit[8].toInt() and 0b11000011) or (8 shl 2)).toByte()
assertNull(packer.packAccessUnit(unit, 0, unit.size))
assertTrue(packer.unsupportedStream)
}
/**
* The flags gate every later call, so leaving them latched across a reset would make a packer
* that once saw a bad stream emit nothing (or log strips) for the rest of its life.
*/
@Test
fun resetClearsTheLatchesAndReproducesTheStream() {
val packer = DtsHdIecPacker()
val leSync = byteArrayOf(0xFE.toByte(), 0x7F, 0x01, 0x80.toByte()) + ByteArray(64)
packer.accessUnitLength(leSync, 0, leSync.size)
assertTrue(packer.unsupportedStream)
packer.reset()
assertFalse("reset must clear the unsupported latch", packer.unsupportedStream)
assertFalse("reset must clear the strip latch", packer.strippedToCore)
assertArrayEquals(
"a clean packer must reproduce the stream after a poisoned one",
golden,
packAll(accessUnits, packer)
)
}
/** The packer must not allocate a burst per unit; buffers alternate and are reused. */
@Test
fun burstBuffersAreReusedRatherThanAllocated() {
val packer = DtsHdIecPacker()
val seen = java.util.IdentityHashMap<java.nio.ByteBuffer, Boolean>()
var bursts = 0
var offset = 0
while (offset < accessUnits.size) {
val length = packer.accessUnitLength(accessUnits, offset, accessUnits.size)
if (length == 0) break
packer.packAccessUnit(accessUnits, offset, length)?.let {
seen[it] = true
bursts++
}
offset += length
}
assertTrue("expected multiple bursts", bursts > 2)
assertEquals("buffers must alternate between exactly two", 2, seen.size)
}
private fun packAll(units: ByteArray, packer: DtsHdIecPacker = DtsHdIecPacker()): ByteArray {
val out = java.io.ByteArrayOutputStream()
var offset = 0
while (offset < units.size) {
val length = packer.accessUnitLength(units, offset, units.size)
if (length == 0) break
packer.packAccessUnit(units, offset, length)?.let { burst ->
val copy = ByteArray(burst.remaining())
burst.duplicate().get(copy)
out.write(copy)
}
offset += length
}
return out.toByteArray()
}
/** The 16-bit big-endian size field after the start code, read from the byte-swapped burst. */
private fun burstAccessUnitSize(packed: ByteArray, burstOffset: Int): Int {
// Payload bytes 10 and 11 land swapped within their 16-bit word: 10 -> +19, 11 -> +18.
val high = packed[burstOffset + 8 + 11].toInt() and 0xFF
val low = packed[burstOffset + 8 + 10].toInt() and 0xFF
return (high shl 8) or low
}
/** An extension substream whose header uses the wide 12/20-bit size fields. */
private fun wideHeaderExtensionSubstream(size: Int): ByteArray {
val frame = ByteArray(size)
frame[0] = 0x64
frame[1] = 0x58
frame[2] = 0x20
frame[3] = 0x25
// After UserDefinedBits(8): nExtSSIndex(2)=0, bHeaderSizeType(1)=1, then 12 header-size bits
// and 20 frame-size bits, all values stored minus one.
var bits = 0L
bits = (bits shl 2) or 0L
bits = (bits shl 1) or 1L
bits = (bits shl 12) or (32L - 1)
bits = (bits shl 20) or (size.toLong() - 1)
// 35 bits, MSB-aligned into bytes 5..9.
val aligned = bits shl (40 - 35)
for (i in 0 until 5) {
frame[5 + i] = ((aligned shr (32 - 8 * i)) and 0xFF).toByte()
}
return frame
}
private fun readLittleEndianShort(data: ByteArray, offset: Int): Int = (data[offset].toInt() and 0xFF) or ((data[offset + 1].toInt() and 0xFF) shl 8)
}
@@ -10,7 +10,6 @@ class DvBitstreamSanitizerTest {
private val sanitizer = DvBitstreamSanitizer()
@Test
fun stripsHdr10PlusPrefixSeiBetweenVclNals() {
val vcl1 = annexBNal(1, byteArrayOf(0x01, 0x02))
@@ -84,7 +83,6 @@ class DvBitstreamSanitizerTest {
assertArrayEquals(original, remainingBytes(buffer))
}
@Test
fun rpuModeStripsRpuAndElButKeepsHdr10PlusSei() {
val vcl = annexBNal(1, byteArrayOf(0x01))
@@ -109,7 +107,6 @@ class DvBitstreamSanitizerTest {
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
}
@Test
fun respectsPositionAndRestoresIt() {
val prefix = byteArrayOf(0xAA.toByte(), 0xBB.toByte())
@@ -242,7 +239,6 @@ class DvBitstreamSanitizerTest {
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
}
/** Builds an HEVC NAL unit: start code + 2-byte NAL header encoding [nalUnitType] + payload. */
private fun annexBNal(nalUnitType: Int, payload: ByteArray, startCodeLen: Int = 4): ByteArray {
val startCode = if (startCodeLen == 3) byteArrayOf(0, 0, 1) else byteArrayOf(0, 0, 0, 1)
@@ -24,7 +24,6 @@ class EndOfStreamPolicyTest {
frameStallMs = frameStallMs
)
@Test
fun stuckPastDurationWithNoPictureIsTheEndOfTheFile() {
// The reported failure: the clock ran a minute past the last frame.
@@ -64,7 +63,6 @@ class EndOfStreamPolicyTest {
assertFalse(isFinishedFile(hasPlaybackOutput = false))
}
@Test
fun fallbackResumesStrictlyInsideTheMedia() {
// The observed hand-off asked MPV to start 59_816ms past the end.
@@ -236,7 +236,8 @@ class ExoPlayerPluginTest {
fun openDuringFallbackDispatchesOnlyTheNewestMediaGeneration() {
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
val exoCore = ExoPlayerCore(activity)
val mpvCore = MpvPlayerCore(activity, true) { _, _ -> Unit }
val loads = ConcurrentLinkedQueue<List<String>>()
val mpvCore = MpvPlayerCore(activity, true, { _, _ -> Unit }, recordingLoads(loads))
val plugin = ExoPlayerPlugin()
val sink = RecordingEventSink()
plugin.onListen(null, sink)
@@ -273,15 +274,30 @@ class ExoPlayerPluginTest {
assertEquals(1, superseded.completionCount)
assertEquals("OPEN_SUPERSEDED", superseded.errorCode)
assertEquals(0, active.completionCount)
assertTrue(loads.isEmpty())
initializeCallback!!(true)
mpvCore.delegate?.onEvent("file-loaded", null)
awaitCompletion(active)
assertEquals(null, active.errorCode)
assertEquals(true, getField(plugin, "usingMpvFallback"))
assertEquals(false, getField(plugin, "fallbackInProgress"))
assertNull(getField(plugin, "pendingOpen"))
// mpv received exactly the newest open, with its play intent; neither the
// failed Exo URI nor the superseded episode was ever loaded.
assertEquals(listOf("https://example.test/episode-3.mkv"), loads.map { it[1] })
assertEquals("pause=no", loads.single()[4].split(",")[1])
assertEquals(listOf("backend-switched", "file-loaded"), sink.eventNames)
// The fallback owns subsequent opens: they reach mpv directly, without
// another backend switch.
val next = RecordingResult()
plugin.onMethodCall(
MethodCall("open", mapOf("uri" to "https://example.test/episode-4.mkv", "autoPlay" to false)),
next
)
awaitCompletion(next)
assertEquals(null, next.errorCode)
assertEquals("https://example.test/episode-4.mkv", loads.last()[1])
assertEquals("pause=yes", loads.last()[4].split(",")[1])
assertEquals(listOf("backend-switched", "file-loaded"), sink.eventNames)
val disposeResult = RecordingResult()
@@ -643,7 +659,9 @@ class ExoPlayerPluginTest {
fun reusedHeldFallbackSynchronouslyBlocksAutoResumeWithoutPausePropertyWrite() {
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
val writes = ConcurrentLinkedQueue<Pair<String, String>>()
val core = MpvPlayerCore(activity, true) { name, value -> writes += name to value }
val loads = ConcurrentLinkedQueue<List<String>>()
val core = MpvPlayerCore(activity, true, { name, value -> writes += name to value }, recordingLoads(loads))
// A reused core that lost its surface mid-playback with a resume still deferred.
core.setPrivateField("desiredPaused", false)
core.setPrivateField("cachedPaused", false)
core.setPrivateField("resumeBlockedByPublicPause", false)
@@ -664,11 +682,10 @@ class ExoPlayerPluginTest {
assertEquals(1, result.completionCount)
assertNull(result.errorCode)
assertEquals(true, core.getPrivateField("desiredPaused"))
assertEquals(true, core.getPrivateField("cachedPaused"))
assertEquals(true, core.getPrivateField("resumeBlockedByPublicPause"))
assertEquals(false, core.getPrivateField("pausedForSurfaceLoss"))
assertEquals(false, core.getPrivateField("deferredResumeRequested"))
// The load itself carries the hold; the stale deferred resume must not
// undo it with a late pause write.
assertEquals("https://example.test/video.mkv", loads.single()[1])
assertEquals("pause=yes", loads.single()[4].split(",")[1])
assertFalse(awaitPauseWriteCount(writes, 1))
core.dispose()
}
@@ -677,10 +694,10 @@ class ExoPlayerPluginTest {
fun reusedAutoplayFallbackClearsIntentBeforeLoadWithoutLatePausePropertyWrite() {
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
val writes = ConcurrentLinkedQueue<Pair<String, String>>()
val core = MpvPlayerCore(activity, true) { name, value -> writes += name to value }
core.setPrivateField("desiredPaused", true)
core.setPrivateField("cachedPaused", true)
core.setPrivateField("resumeBlockedByPublicPause", true)
val loads = ConcurrentLinkedQueue<List<String>>()
val core = MpvPlayerCore(activity, true, { name, value -> writes += name to value }, recordingLoads(loads))
// A reused core whose previous load was explicitly held.
core.setPauseIntentForLoad(true)
val plugin = reusedFallbackPlugin(activity, core)
val result = RecordingResult()
@@ -695,9 +712,10 @@ class ExoPlayerPluginTest {
assertEquals(1, result.completionCount)
assertNull(result.errorCode)
assertEquals(false, core.getPrivateField("desiredPaused"))
assertEquals(false, core.getPrivateField("cachedPaused"))
assertEquals(false, core.getPrivateField("resumeBlockedByPublicPause"))
// The new load carries the play intent; the earlier hold is not replayed
// as a separate pause write before or after it.
assertEquals("https://example.test/video.mkv", loads.single()[1])
assertEquals("pause=no", loads.single()[4].split(",")[1])
assertFalse(awaitPauseWriteCount(writes, 1))
assertEquals(emptyList<Pair<String, String>>(), writes.filter { it.first == "pause" })
core.dispose()
@@ -955,6 +973,14 @@ class ExoPlayerPluginTest {
}
}
/** Accepts every native command, recording each one; a `loadfile` yields playlist entry 1. */
private fun recordingLoads(
loads: ConcurrentLinkedQueue<List<String>>
): suspend (Array<String>) -> Long? = { args ->
loads += args.toList()
if (args.firstOrNull() == "loadfile") 1L else null
}
private fun awaitQueueEntry(
queue: ConcurrentLinkedQueue<Pair<String, String>>,
expected: Pair<String, String>
@@ -8,10 +8,12 @@ import androidx.media3.common.C
import androidx.media3.common.Format
import androidx.media3.common.MimeTypes
import androidx.media3.common.PlaybackParameters
import androidx.media3.common.Timeline
import androidx.media3.common.util.Clock
import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.analytics.PlayerId
import androidx.media3.exoplayer.audio.AudioSink
import androidx.media3.exoplayer.source.MediaSource
import java.io.ByteArrayOutputStream
import java.nio.ByteBuffer
import org.junit.Assert.assertArrayEquals
@@ -22,13 +24,14 @@ import org.junit.Assert.assertTrue
import org.junit.Test
/**
* Routing and back-pressure contract for the TrueHD MAT carrier (#1804).
* Routing and back-pressure contract for the IEC 61937 carrier: TrueHD/MAT (#1804) and DTS-HD
* (#1988).
*
* The carrier is bit-exact, so the two failure modes that matter here are losing bytes and letting
* the wrong sink handle TrueHD.
* the wrong sink handle a carrier codec.
*/
@OptIn(UnstableApi::class)
class TrueHdCarrierSinkTest {
class IecCarrierSinkTest {
private val accessUnits: ByteArray =
checkNotNull(javaClass.classLoader?.getResourceAsStream("truehd_access_units.bin"))
@@ -38,19 +41,36 @@ class TrueHdCarrierSinkTest {
checkNotNull(javaClass.classLoader?.getResourceAsStream("truehd_iec61937_golden.bin"))
.use { it.readBytes() }
private val dtsHdAccessUnits: ByteArray by lazy {
checkNotNull(javaClass.classLoader?.getResourceAsStream("dtshd_ma_access_units.bin"))
.use { it.readBytes() }
}
private val dtsHdGolden: ByteArray by lazy {
checkNotNull(javaClass.classLoader?.getResourceAsStream("dtshd_ma_iec61937_golden.bin"))
.use { it.readBytes() }
}
private fun trueHdFormat(sampleRate: Int = 48_000): Format = Format.Builder()
.setSampleMimeType(MimeTypes.AUDIO_TRUEHD)
.setChannelCount(6)
.setSampleRate(sampleRate)
.build()
private fun dtsHdFormat(sampleRate: Int = 48_000): Format = Format.Builder()
.setSampleMimeType(MimeTypes.AUDIO_DTS_HD)
.setChannelCount(6)
.setSampleRate(sampleRate)
.build()
private fun audioSinkConfig(format: Format = trueHdFormat()) = AudioSink.AudioSinkConfig.Builder(format).build()
private fun sink(
carrier: FakeSink = FakeSink(),
normal: FakeSink = FakeSink(),
routeAvailable: Boolean = true,
blocked: Boolean = false
) = TrueHdCarrierSink(normal, carrier, { routeAvailable }, { blocked })
) = IecCarrierSink(normal, carrier, { routeAvailable }, { blocked })
/**
* TrueHD is the carrier or it is decoded. Falling through to the normal sink would hand media3
@@ -72,6 +92,68 @@ class TrueHdCarrierSinkTest {
assertEquals(AudioSink.SINK_FORMAT_SUPPORTED_DIRECTLY, carrierSink.getFormatSupport(trueHdFormat()))
}
@Test
fun dtsHdWithACarrierRouteIsSupportedDirectly() {
val carrierSink = sink()
assertTrue(carrierSink.supportsFormat(dtsHdFormat()))
assertEquals(AudioSink.SINK_FORMAT_SUPPORTED_DIRECTLY, carrierSink.getFormatSupport(dtsHdFormat()))
}
/**
* The route that advertises the carrier and raw `ENCODING_DTS_HD` at once is the one whose raw
* path renders silence (#1988), so while the carrier route exists DTS-HD is the carrier or it is
* decoded never the normal sink's raw path, even when policy declines the carrier.
*/
@Test
fun dtsHdOnACarrierRouteNeverFallsThroughToTheRawPath() {
val normal = FakeSink().apply { formatSupport = AudioSink.SINK_FORMAT_SUPPORTED_DIRECTLY }
val blockedSink = sink(normal = normal, blocked = true)
assertFalse(blockedSink.supportsFormat(dtsHdFormat()))
assertEquals(AudioSink.SINK_FORMAT_UNSUPPORTED, blockedSink.getFormatSupport(dtsHdFormat()))
}
/**
* Routes without the IEC carrier never had it to lose, and some of them bitstream raw DTS-HD
* genuinely; the pre-carrier behavior is preserved there.
*/
@Test
fun dtsHdWithoutACarrierRouteFallsThroughToTheNormalSink() {
val normal = FakeSink().apply { formatSupport = AudioSink.SINK_FORMAT_SUPPORTED_DIRECTLY }
val carrierSink = sink(normal = normal, routeAvailable = false)
assertTrue(carrierSink.supportsFormat(dtsHdFormat()))
assertEquals(AudioSink.SINK_FORMAT_SUPPORTED_DIRECTLY, carrierSink.getFormatSupport(dtsHdFormat()))
}
/** The tuple is shared, so the gate is per format: TrueHD keeps the carrier while DTS-HD leaves. */
@Test
fun theCarrierGateIsEvaluatedPerFormat() {
val carrier = FakeSink()
val normal = FakeSink()
val carrierSink = IecCarrierSink(normal, carrier, { it.sampleMimeType != MimeTypes.AUDIO_DTS_HD }, { false })
carrierSink.configure(audioSinkConfig(trueHdFormat()))
assertEquals(IecCarrier.SAMPLE_RATE, checkNotNull(carrier.configuredConfig).format.sampleRate)
carrierSink.configure(audioSinkConfig(dtsHdFormat()))
assertEquals(MimeTypes.AUDIO_DTS_HD, checkNotNull(normal.configuredConfig).format.sampleMimeType)
}
/** DTS Express shares the DTS-HD mime prefix but carries `;profile=lbr`; it keeps decoding. */
@Test
fun dtsExpressIsLeftToTheNormalSink() {
val normal = FakeSink().apply { formatSupport = AudioSink.SINK_FORMAT_SUPPORTED_DIRECTLY }
val carrierSink = sink(normal = normal)
val express = Format.Builder()
.setSampleMimeType(MimeTypes.AUDIO_DTS_EXPRESS)
.setSampleRate(48_000)
.build()
assertEquals(AudioSink.SINK_FORMAT_SUPPORTED_DIRECTLY, carrierSink.getFormatSupport(express))
assertTrue(carrierSink.supportsFormat(express))
}
/** Downmix and normalization already force decoding; the carrier must not override that. */
@Test
fun blockedDirectOutputDeclinesTheCarrier() {
@@ -80,8 +162,8 @@ class TrueHdCarrierSinkTest {
}
/**
* 44.1kHz-family TrueHD rides a 176.4kHz carrier this path does not build. It has to be decided
* from the format: the packer only learns the rate from a major sync, long after selection, and
* 44.1kHz-family streams ride a 176.4kHz carrier this path does not build. It has to be decided
* from the format: the packer only learns the rate from the bitstream, long after selection, and
* selecting the carrier for it would produce silence.
*/
@Test
@@ -89,6 +171,8 @@ class TrueHdCarrierSinkTest {
val carrierSink = sink()
assertEquals(AudioSink.SINK_FORMAT_UNSUPPORTED, carrierSink.getFormatSupport(trueHdFormat(sampleRate = 44_100)))
assertEquals(AudioSink.SINK_FORMAT_UNSUPPORTED, carrierSink.getFormatSupport(trueHdFormat(sampleRate = 176_400)))
assertEquals(AudioSink.SINK_FORMAT_UNSUPPORTED, carrierSink.getFormatSupport(dtsHdFormat(sampleRate = 44_100)))
assertEquals(AudioSink.SINK_FORMAT_UNSUPPORTED, carrierSink.getFormatSupport(dtsHdFormat(sampleRate = 88_200)))
}
/** A bitstream cannot be resampled, so any speed other than 1.0x decodes. */
@@ -97,6 +181,7 @@ class TrueHdCarrierSinkTest {
val carrierSink = sink()
carrierSink.setPlaybackParameters(PlaybackParameters(1.5f))
assertEquals(AudioSink.SINK_FORMAT_UNSUPPORTED, carrierSink.getFormatSupport(trueHdFormat()))
assertEquals(AudioSink.SINK_FORMAT_UNSUPPORTED, carrierSink.getFormatSupport(dtsHdFormat()))
}
/**
@@ -110,7 +195,7 @@ class TrueHdCarrierSinkTest {
val carrierSink = sink(carrier = carrier)
val listener = RecordingSinkListener()
carrierSink.setListener(listener)
carrierSink.configure(trueHdFormat(), 0, null)
carrierSink.configure(audioSinkConfig())
assertTrue("carrier should be live before the speed change", carrierSink.isCarrierActive)
carrierSink.setPlaybackParameters(PlaybackParameters(1.5f))
@@ -131,7 +216,7 @@ class TrueHdCarrierSinkTest {
val carrierSink = sink()
val listener = RecordingSinkListener()
carrierSink.setListener(listener)
carrierSink.configure(trueHdFormat(), 0, null)
carrierSink.configure(audioSinkConfig())
carrierSink.setPlaybackParameters(PlaybackParameters(1.5f))
carrierSink.setPlaybackParameters(PlaybackParameters(1f))
@@ -146,14 +231,13 @@ class TrueHdCarrierSinkTest {
val carrierSink = sink()
val listener = RecordingSinkListener()
carrierSink.setListener(listener)
carrierSink.configure(trueHdFormat(), 0, null)
carrierSink.configure(audioSinkConfig())
carrierSink.setPlaybackParameters(PlaybackParameters(1f))
assertEquals(0, listener.capabilityInvalidations)
}
/**
* Selection reads Format.sampleRate; the rate family is only certain once a major sync is parsed.
* When they disagree the packer emits nothing, so consuming the input would turn the stream into
@@ -165,7 +249,7 @@ class TrueHdCarrierSinkTest {
val carrierSink = sink(carrier = carrier)
val listener = RecordingSinkListener()
carrierSink.setListener(listener)
carrierSink.configure(trueHdFormat(), 0, null)
carrierSink.configure(audioSinkConfig())
val buffer = ByteBuffer.wrap(fortyFourFamilyAccessUnits())
val accepted = carrierSink.handleBuffer(buffer, 0L, 1)
@@ -181,6 +265,33 @@ class TrueHdCarrierSinkTest {
assertEquals("nothing may reach the carrier delegate", 0, carrier.written.size())
}
/**
* The DTS-HD equivalent: a bitstream whose framing the carrier cannot ride (an S/PDIF-style
* little-endian capture) must latch onto the decoder, and the offending unit must survive.
*/
@Test
fun aDtsHdFramingMismatchLeavesTheCarrierInsteadOfGoingSilent() {
val carrier = FakeSink()
val carrierSink = sink(carrier = carrier)
val listener = RecordingSinkListener()
carrierSink.setListener(listener)
carrierSink.configure(audioSinkConfig(dtsHdFormat()))
val littleEndianCapture = byteArrayOf(0xFE.toByte(), 0x7F, 0x01, 0x80.toByte()) + ByteArray(64)
val buffer = ByteBuffer.wrap(littleEndianCapture)
val accepted = carrierSink.handleBuffer(buffer, 0L, 1)
assertFalse("a mismatch must apply back pressure, not report success", accepted)
assertEquals("the offending unit must stay in the buffer", 0, buffer.position())
assertEquals("the renderer must be asked to reselect", 1, listener.capabilityInvalidations)
assertEquals(
"DTS-HD must now decode rather than ride the carrier or the raw path",
AudioSink.SINK_FORMAT_UNSUPPORTED,
carrierSink.getFormatSupport(dtsHdFormat())
)
assertEquals("nothing may reach the carrier delegate", 0, carrier.written.size())
}
/**
* media3 resets every renderer disabled by a new selection before enabling the replacement, and
* both audio renderers share this sink. That reset lands mid-handover, so a latch cleared there
@@ -190,7 +301,7 @@ class TrueHdCarrierSinkTest {
fun theMismatchLatchSurvivesTheResetThatAccompaniesTheHandover() {
val carrierSink = sink()
carrierSink.setListener(RecordingSinkListener())
carrierSink.configure(trueHdFormat(), 0, null)
carrierSink.configure(audioSinkConfig())
carrierSink.handleBuffer(ByteBuffer.wrap(fortyFourFamilyAccessUnits()), 0L, 1)
carrierSink.flush()
@@ -208,7 +319,7 @@ class TrueHdCarrierSinkTest {
fun releasingTheSinkClearsTheMismatchLatch() {
val carrierSink = sink()
carrierSink.setListener(RecordingSinkListener())
carrierSink.configure(trueHdFormat(), 0, null)
carrierSink.configure(audioSinkConfig())
carrierSink.handleBuffer(ByteBuffer.wrap(fortyFourFamilyAccessUnits()), 0L, 1)
carrierSink.release()
@@ -238,7 +349,7 @@ class TrueHdCarrierSinkTest {
fun aNewMediaItemClearsTheMismatchLatch() {
val carrierSink = sink()
carrierSink.setListener(RecordingSinkListener())
carrierSink.configure(trueHdFormat(), 0, null)
carrierSink.configure(audioSinkConfig())
carrierSink.handleBuffer(ByteBuffer.wrap(fortyFourFamilyAccessUnits()), 0L, 1)
assertEquals(
AudioSink.SINK_FORMAT_UNSUPPORTED,
@@ -263,7 +374,7 @@ class TrueHdCarrierSinkTest {
fun aLateMismatchFromThePreviousItemDoesNotPoisonTheNewOne() {
val carrierSink = sink()
carrierSink.setListener(RecordingSinkListener())
carrierSink.configure(trueHdFormat(), 0, null)
carrierSink.configure(audioSinkConfig())
// The new item starts before the outgoing stream's last buffer is handled.
carrierSink.beginMediaItem()
@@ -276,7 +387,7 @@ class TrueHdCarrierSinkTest {
)
}
/** Everything that is not TrueHD keeps going to the existing processed sink. */
/** Everything that is not a carrier codec keeps going to the existing processed sink. */
@Test
fun otherFormatsAreLeftToTheNormalSink() {
val normal = FakeSink().apply { formatSupport = AudioSink.SINK_FORMAT_SUPPORTED_DIRECTLY }
@@ -287,7 +398,6 @@ class TrueHdCarrierSinkTest {
assertTrue(carrierSink.supportsFormat(ac3))
}
/**
* The regression this exists for: a delegate that refuses a burst part-way through a sample must
* not cost the access units behind it. media3 re-delivers the same buffer after a false return,
@@ -297,12 +407,12 @@ class TrueHdCarrierSinkTest {
fun aRefusedBurstMidSampleLosesNoAccessUnits() {
val carrier = FakeSink()
val carrierSink = sink(carrier = carrier)
carrierSink.configure(trueHdFormat(), 0, null)
carrierSink.configure(audioSinkConfig())
// Refuse every third burst once, so rejections land inside samples rather than between them.
carrier.refuseEveryNth = 3
val produced = feedWholeStream(carrierSink)
val produced = feedWholeStream(carrierSink, accessUnits)
assertArrayEquals("carrier output must survive back pressure unchanged", golden, produced)
assertTrue("the fake must actually have exercised the refusal path", carrier.refusals > 0)
}
@@ -312,9 +422,55 @@ class TrueHdCarrierSinkTest {
fun theCarrierOutputMatchesTheGoldenStream() {
val carrier = FakeSink()
val carrierSink = sink(carrier = carrier)
carrierSink.configure(trueHdFormat(), 0, null)
carrierSink.configure(audioSinkConfig())
assertArrayEquals(golden, feedWholeStream(carrierSink))
assertArrayEquals(golden, feedWholeStream(carrierSink, accessUnits))
}
/** A DTS-HD stream must select the DTS packer and come out matching FFmpeg's bytes. */
@Test
fun theDtsHdCarrierOutputMatchesTheGoldenStream() {
val carrier = FakeSink()
val carrierSink = sink(carrier = carrier)
carrierSink.configure(audioSinkConfig(dtsHdFormat()))
assertArrayEquals(dtsHdGolden, feedWholeStream(carrierSink, dtsHdAccessUnits))
}
/** Back pressure must not cost DTS-HD units either; bursts and units are one-to-one there. */
@Test
fun aRefusedDtsHdBurstLosesNoAccessUnits() {
val carrier = FakeSink()
val carrierSink = sink(carrier = carrier)
carrierSink.configure(audioSinkConfig(dtsHdFormat()))
carrier.refuseEveryNth = 3
val produced = feedWholeStream(carrierSink, dtsHdAccessUnits)
assertArrayEquals(dtsHdGolden, produced)
assertTrue(carrier.refusals > 0)
}
/**
* Burst timestamps come from the carrier cadence, not the closing access unit. A DTS-HD burst is
* 10666.67us of carrier not a whole number so the cadence must be derived from cumulative
* carrier frames; per-burst rounding would drift ~62ms over a movie.
*/
@Test
fun dtsHdBurstTimestampsFollowTheExactCarrierCadence() {
val carrier = FakeSink()
val carrierSink = sink(carrier = carrier)
carrierSink.configure(audioSinkConfig(dtsHdFormat()))
feedWholeStream(carrierSink, dtsHdAccessUnits)
val framesPerBurst = 32768L / IecCarrier.BYTES_PER_FRAME
carrier.bufferTimesUs.forEachIndexed { index, timeUs ->
assertEquals(
"burst $index timestamp",
index * framesPerBurst * 1_000_000L / IecCarrier.SAMPLE_RATE,
timeUs
)
}
}
/** A refused burst must be re-offered before any further input is taken. */
@@ -322,7 +478,7 @@ class TrueHdCarrierSinkTest {
fun aPendingBurstIsPlacedBeforeMoreInputIsConsumed() {
val carrier = FakeSink()
val carrierSink = sink(carrier = carrier)
carrierSink.configure(trueHdFormat(), 0, null)
carrierSink.configure(audioSinkConfig())
carrier.refuseNext = true
val buffer = ByteBuffer.wrap(accessUnits)
@@ -333,7 +489,6 @@ class TrueHdCarrierSinkTest {
assertTrue(carrierSink.hasPendingData())
}
@Test
fun persistentControlsReachBothDelegates() {
val carrier = FakeSink()
@@ -366,14 +521,37 @@ class TrueHdCarrierSinkTest {
fun theCarrierDelegateIsConfiguredAsAFixedRatePcmCarrier() {
val carrier = FakeSink()
val carrierSink = sink(carrier = carrier)
val inputConfig = AudioSink.AudioSinkConfig.Builder(trueHdFormat())
.setPreferredBufferSizeOverride(4_096)
.setTimeline(Timeline.EMPTY)
.setMediaPeriodId(MediaSource.MediaPeriodId("period"))
.build()
carrierSink.configure(trueHdFormat(), 0, null)
carrierSink.configure(inputConfig)
val configured = checkNotNull(carrier.configuredFormat)
assertEquals(MimeTypes.AUDIO_RAW, configured.sampleMimeType)
assertEquals(C.ENCODING_PCM_16BIT, configured.pcmEncoding)
assertEquals(TrueHdMatPacker.CARRIER_SAMPLE_RATE, configured.sampleRate)
assertEquals(TrueHdMatPacker.CARRIER_CHANNEL_COUNT, configured.channelCount)
val configured = checkNotNull(carrier.configuredConfig)
assertEquals(inputConfig.preferredBufferSizeOverride, configured.preferredBufferSizeOverride)
assertSame(inputConfig.timeline, configured.timeline)
assertEquals(inputConfig.mediaPeriodId, configured.mediaPeriodId)
assertEquals(MimeTypes.AUDIO_RAW, configured.format.sampleMimeType)
assertEquals(C.ENCODING_PCM_16BIT, configured.format.pcmEncoding)
assertEquals(IecCarrier.SAMPLE_RATE, configured.format.sampleRate)
assertEquals(IecCarrier.CHANNEL_COUNT, configured.format.channelCount)
}
/** DTS-HD rides the same PCM-shaped carrier tuple TrueHD does. */
@Test
fun theDtsHdCarrierDelegateIsConfiguredAsAFixedRatePcmCarrier() {
val carrier = FakeSink()
val carrierSink = sink(carrier = carrier)
carrierSink.configure(audioSinkConfig(dtsHdFormat()))
val configured = checkNotNull(carrier.configuredConfig)
assertEquals(MimeTypes.AUDIO_RAW, configured.format.sampleMimeType)
assertEquals(C.ENCODING_PCM_16BIT, configured.format.pcmEncoding)
assertEquals(IecCarrier.SAMPLE_RATE, configured.format.sampleRate)
assertEquals(IecCarrier.CHANNEL_COUNT, configured.format.channelCount)
}
@Test
@@ -382,25 +560,29 @@ class TrueHdCarrierSinkTest {
val normal = FakeSink()
val carrierSink = sink(carrier = carrier, normal = normal)
val ac3 = Format.Builder().setSampleMimeType(MimeTypes.AUDIO_AC3).setSampleRate(48_000).build()
val config = audioSinkConfig(ac3)
carrierSink.configure(ac3, 0, null)
carrierSink.configure(config)
assertSame(ac3, normal.configuredFormat)
assertEquals(null, carrier.configuredFormat)
assertSame(config, normal.configuredConfig)
assertSame(ac3, normal.configuredConfig?.format)
assertEquals(null, carrier.configuredConfig)
}
private fun feedWholeStream(carrierSink: TrueHdCarrierSink): ByteArray {
val buffer = ByteBuffer.wrap(accessUnits)
private fun feedWholeStream(carrierSink: IecCarrierSink, units: ByteArray): ByteArray {
val buffer = ByteBuffer.wrap(units)
var guard = 0
while (buffer.hasRemaining() && guard++ < 10_000) {
// media3 retries handleBuffer until it returns true, even once the buffer is fully consumed;
// a refusal of the stream's final burst leaves it pending with nothing remaining to read.
while ((buffer.hasRemaining() || carrierSink.hasPendingData()) && guard++ < 10_000) {
carrierSink.handleBuffer(buffer, 0L, 1)
}
val carrier = carrierSinkDelegate(carrierSink)
return carrier.written.toByteArray()
}
private fun carrierSinkDelegate(sink: TrueHdCarrierSink): FakeSink {
val field = TrueHdCarrierSink::class.java.getDeclaredField("carrierSink")
private fun carrierSinkDelegate(sink: IecCarrierSink): FakeSink {
val field = IecCarrierSink::class.java.getDeclaredField("carrierSink")
field.isAccessible = true
return field.get(sink) as FakeSink
}
@@ -420,7 +602,8 @@ class TrueHdCarrierSinkTest {
/** Minimal AudioSink that records what it was handed and can apply back pressure. */
private class FakeSink : AudioSink {
val written = ByteArrayOutputStream()
var configuredFormat: Format? = null
val bufferTimesUs = mutableListOf<Long>()
var configuredConfig: AudioSink.AudioSinkConfig? = null
var formatSupport: Int = AudioSink.SINK_FORMAT_UNSUPPORTED
var lastVolume: Float = -1f
var sessionId: Int = -1
@@ -444,12 +627,13 @@ class TrueHdCarrierSinkTest {
val copy = ByteArray(buffer.remaining())
buffer.duplicate().get(copy)
written.write(copy)
bufferTimesUs.add(presentationTimeUs)
buffer.position(buffer.limit())
return true
}
override fun configure(inputFormat: Format, specifiedBufferSize: Int, outputChannels: IntArray?) {
configuredFormat = inputFormat
override fun configure(audioSinkConfig: AudioSink.AudioSinkConfig) {
configuredConfig = audioSinkConfig
}
override fun supportsFormat(format: Format) = formatSupport == AudioSink.SINK_FORMAT_SUPPORTED_DIRECTLY
@@ -9,7 +9,6 @@ private const val MIB = 1024 * 1024
class LoadControlPolicyTest {
@Test
fun neverExceedsMedia3sOwnTargetEvenWithHugeMemory() {
assertEquals(
@@ -63,7 +62,6 @@ class LoadControlPolicyTest {
)
}
@Test
fun readAheadReportsSecondsAtAKnownBitrate() {
// 64MiB of the #1618 stream (103_341 kbps) is ~5.2s — under the 15s minBufferMs, so the
@@ -84,7 +82,6 @@ class LoadControlPolicyTest {
assertNull(LoadControlPolicy.readAheadSeconds(64 * MIB, -1L))
}
/**
* media3 validates the ordering with Guava `Preconditions`, which is a plain throw rather than
* a JVM assert, so a bad pair takes down `DefaultLoadControl.Builder.build()` in release too.
@@ -169,7 +166,6 @@ class LoadControlPolicyTest {
}
}
@Test
fun theWireNamesMatchTheDartNativeValues() {
assertEquals(LoadControlPolicy.BufferTier.LARGE, LoadControlPolicy.BufferTier.fromWire("large"))
@@ -0,0 +1,154 @@
package com.edde746.plezy.exoplayer
import androidx.media3.common.C
import androidx.media3.common.DataReader
import androidx.media3.common.Format
import androidx.media3.common.util.ParsableByteArray
import androidx.media3.extractor.DefaultExtractorInput
import androidx.media3.extractor.Extractor
import androidx.media3.extractor.ExtractorInput
import androidx.media3.extractor.ExtractorOutput
import androidx.media3.extractor.PositionHolder
import androidx.media3.extractor.SeekMap
import androidx.media3.extractor.TrackOutput
import com.edde746.plezy.libass.media.AssHandler
import com.edde746.plezy.libass.media.parser.AssSubtitleParserFactory
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
/** Regression coverage for Matroska files whose SeekHead references Tracks after the Clusters. */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
class MatroskaLateTracksTest {
private class CapturedTrack(val type: Int) : TrackOutput {
val timesUs = mutableListOf<Long>()
var format: Format? = null
val sampleCount: Int
get() = timesUs.size
override fun format(format: Format) {
this.format = format
}
override fun sampleData(input: DataReader, length: Int, allowEndOfInput: Boolean, sampleDataPart: Int): Int = input.read(ByteArray(length), 0, length)
override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) {
data.skipBytes(length)
}
override fun sampleMetadata(timeUs: Long, flags: Int, size: Int, offset: Int, cryptoData: TrackOutput.CryptoData?) {
timesUs.add(timeUs)
}
}
private class CapturingExtractorOutput : ExtractorOutput {
val tracks = mutableMapOf<Int, CapturedTrack>()
val seekMaps = mutableListOf<SeekMap>()
override fun track(id: Int, type: Int): TrackOutput = tracks.getOrPut(id) { CapturedTrack(type) }
override fun endTracks() = Unit
override fun seekMap(seekMap: SeekMap) {
seekMaps.add(seekMap)
}
}
private class ByteArrayDataReader(private val data: ByteArray) : DataReader {
var position = 0L
override fun read(buffer: ByteArray, offset: Int, length: Int): Int {
if (position >= data.size) return C.RESULT_END_OF_INPUT
val bytesRead = minOf(length, data.size - position.toInt())
data.copyInto(buffer, offset, position.toInt(), position.toInt() + bytesRead)
position += bytesRead
return bytesRead
}
}
private fun fixtureData(): ByteArray = checkNotNull(javaClass.getResourceAsStream("/matroska_tracks_at_end.mkv")) {
"fixture matroska_tracks_at_end.mkv missing from test resources"
}.use { it.readBytes() }
private fun readToEnd(extractor: Extractor, reader: ByteArrayDataReader, length: Long) {
var input: ExtractorInput = DefaultExtractorInput(reader, reader.position, length)
val seekPosition = PositionHolder()
repeat(100_000) {
when (extractor.read(input, seekPosition)) {
Extractor.RESULT_END_OF_INPUT -> return
Extractor.RESULT_SEEK -> {
reader.position = seekPosition.position
input = DefaultExtractorInput(reader, seekPosition.position, length)
}
}
}
error("extractor did not reach end of input")
}
@Test
fun extractsSamplesWhenSeekHeadReferencesTracksAfterClusters() {
val assHandler = AssHandler()
val extractor = ZlibMatroskaExtractor(AssSubtitleParserFactory(assHandler), assHandler)
val output = CapturingExtractorOutput()
extractor.init(output)
val data = fixtureData()
readToEnd(extractor, ByteArrayDataReader(data), data.size.toLong())
assertEquals(2, output.tracks.size)
assertEquals(setOf(C.TRACK_TYPE_VIDEO, C.TRACK_TYPE_AUDIO), output.tracks.values.map { it.type }.toSet())
output.tracks.values.forEach { track ->
assertNotNull(track.format)
assertTrue("expected extracted samples for track type ${track.type}", track.sampleCount > 0)
}
}
/**
* media3 1.11.0 builds the Matroska seek map at the end of the Cues element, which for
* tracks-after-clusters files is before the Tracks element parsed the map then permanently
* reports unseekable and resolves every seek to byte 0, snapping playback to the start
* (#1969; upstream androidx/media #3377).
* The production stack must repair it through the per-track cue lookups.
*/
@Test
fun seeksViaCuesWhenSeekMapIsBuiltBeforeTracks() {
val assHandler = AssHandler()
val extractor = CuelessSeekExtractorWrapper(ZlibMatroskaExtractor(AssSubtitleParserFactory(assHandler), assHandler))
val output = CapturingExtractorOutput()
extractor.init(output)
val data = fixtureData()
val reader = ByteArrayDataReader(data)
readToEnd(extractor, reader, data.size.toLong())
assertEquals(1, output.seekMaps.size)
val seekMap = output.seekMaps.single()
assertTrue("tracks-after-clusters file with Cues must be seekable", seekMap.isSeekable)
val points = seekMap.getSeekPoints(500_000L)
// Cue-based resolution snaps to the fixture's only cue point (t=0); a byte-proportional
// estimate would return the requested time instead.
assertEquals(0L, points.first.timeUs)
val position = points.first.position
val clusterId = byteArrayOf(0x1F, 0x43, 0xB6.toByte(), 0x75)
assertTrue(
"seek position $position must point at a Cluster element",
data.copyOfRange(position.toInt(), position.toInt() + 4).contentEquals(clusterId)
)
output.tracks.values.forEach { it.timesUs.clear() }
extractor.seek(position, points.first.timeUs)
reader.position = position
readToEnd(extractor, reader, data.size.toLong())
output.tracks.values.forEach { track ->
assertTrue("expected extracted samples after seek for track type ${track.type}", track.sampleCount > 0)
assertEquals(points.first.timeUs, track.timesUs.first())
}
}
}
@@ -0,0 +1,300 @@
package com.edde746.plezy.exoplayer
import androidx.media3.common.text.Cue
import androidx.media3.extractor.text.CuesWithTiming
import androidx.media3.extractor.text.SubtitleParser
import java.io.ByteArrayOutputStream
import java.util.zip.Deflater
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
/**
* Regression coverage for #1953: display sets with several composition objects must
* produce one cue per object, and Normal-state display sets (palette-only fades,
* cached-object reuse) must keep the composition instead of blanking it.
*/
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
class PgsCompositionParserTest {
private companion object {
const val WHITE = 0xFFFFFFFF.toInt()
const val FADED_WHITE = 0x80FFFFFF.toInt()
const val YELLOW = 0xFFFFF000.toInt()
const val GREEN_BT709 = 0xFF00D800.toInt()
const val GREEN_BT601 = 0xFF00FF01.toInt()
val WHITE_ENTRY = intArrayOf(1, 235, 128, 128, 255)
val YELLOW_ENTRY = intArrayOf(2, 210, 146, 16, 255)
const val STATE_NORMAL = 0x00
const val STATE_EPOCH_START = 0x80
}
private class Buf {
private val out = ByteArrayOutputStream()
fun u8(value: Int) = apply { out.write(value) }
fun u16(value: Int) = apply {
out.write(value ushr 8)
out.write(value)
}
fun u24(value: Int) = apply {
out.write(value ushr 16)
out.write(value ushr 8)
out.write(value)
}
fun raw(bytes: ByteArray) = apply { out.write(bytes) }
fun build(): ByteArray = out.toByteArray()
}
private fun segment(type: Int, payload: ByteArray): ByteArray = Buf().u8(type).u16(payload.size).raw(payload).build()
private fun objectRef(id: Int, x: Int, y: Int, cropped: Boolean = false): ByteArray = Buf()
.u16(id)
.u8(0) // Window id.
.u8(if (cropped) 0x80 else 0)
.u16(x)
.u16(y)
.raw(if (cropped) ByteArray(8) else ByteArray(0)) // Crop rectangle.
.build()
private fun pcs(planeWidth: Int, planeHeight: Int, state: Int, vararg refs: ByteArray): ByteArray {
val payload = Buf()
.u16(planeWidth)
.u16(planeHeight)
.u8(0x10) // Frame rate.
.u16(0) // Composition number.
.u8(state)
.u8(0) // Palette update flag.
.u8(0) // Palette id.
.u8(refs.size)
refs.forEach { payload.raw(it) }
return segment(0x16, payload.build())
}
private fun pds(vararg entries: IntArray): ByteArray {
val payload = Buf().u8(0).u8(0) // Palette id, version.
entries.forEach { e -> payload.u8(e[0]).u8(e[1]).u8(e[2]).u8(e[3]).u8(e[4]) }
return segment(0x14, payload.build())
}
private fun ods(id: Int, width: Int, height: Int, rle: ByteArray): ByteArray = segment(
0x15,
Buf().u16(id).u8(0).u8(0xC0).u24(rle.size + 4).u16(width).u16(height).raw(rle).build()
)
/** RLE for a solid bitmap: one literal palette-index byte per pixel. */
private fun solidRle(width: Int, height: Int, colorIndex: Int): ByteArray = ByteArray(width * height) { colorIndex.toByte() }
private fun end(): ByteArray = segment(0x80, ByteArray(0))
private fun displaySet(vararg segments: ByteArray): ByteArray {
val out = ByteArrayOutputStream()
segments.forEach { out.write(it) }
return out.toByteArray()
}
private fun parseCues(parser: PgsCompositionParser, sample: ByteArray): List<Cue> {
val outputs = mutableListOf<CuesWithTiming>()
parser.parse(sample, SubtitleParser.OutputOptions.allCues()) { outputs.add(it) }
assertEquals(1, outputs.size)
return outputs[0].cues
}
/** Epoch-start display set: white 4x2 object at (100, 900) and yellow 6x3 object at (200, 100). */
private fun twoObjectEpochStart(): ByteArray = displaySet(
pcs(1920, 1080, STATE_EPOCH_START, objectRef(1, 100, 900), objectRef(2, 200, 100)),
pds(WHITE_ENTRY, YELLOW_ENTRY),
ods(1, 4, 2, solidRle(4, 2, 1)),
ods(2, 6, 3, solidRle(6, 3, 2)),
end()
)
@Test
fun twoCompositionObjectsProduceIndependentlyPositionedCues() {
val cues = parseCues(PgsCompositionParser(), twoObjectEpochStart())
assertEquals(2, cues.size)
val (dialogue, sign) = cues
assertEquals(100f / 1920f, dialogue.position, 1e-6f)
assertEquals(900f / 1080f, dialogue.line, 1e-6f)
assertEquals(4f / 1920f, dialogue.size, 1e-6f)
assertEquals(2f / 1080f, dialogue.bitmapHeight, 1e-6f)
assertEquals(WHITE, dialogue.bitmap!!.getPixel(0, 0))
assertEquals(200f / 1920f, sign.position, 1e-6f)
assertEquals(100f / 1080f, sign.line, 1e-6f)
assertEquals(6, sign.bitmap!!.width)
assertEquals(3, sign.bitmap!!.height)
assertEquals(YELLOW, sign.bitmap!!.getPixel(5, 2))
}
@Test
fun paletteOnlyFadeUpdateKeepsBothObjectsAndPreservesUnsentEntries() {
val parser = PgsCompositionParser()
parseCues(parser, twoObjectEpochStart())
// Normal-state fade step: same references, only the white entry's alpha changes.
val cues = parseCues(
parser,
displaySet(
pcs(1920, 1080, STATE_NORMAL, objectRef(1, 100, 900), objectRef(2, 200, 100)),
pds(intArrayOf(1, 235, 128, 128, 128)),
end()
)
)
assertEquals(2, cues.size)
assertEquals(FADED_WHITE, cues[0].bitmap!!.getPixel(0, 0))
// The yellow entry was not resent; an in-place palette update must preserve it.
assertEquals(YELLOW, cues[1].bitmap!!.getPixel(0, 0))
}
@Test
fun zeroObjectDisplaySetClearsTheComposition() {
val parser = PgsCompositionParser()
parseCues(parser, twoObjectEpochStart())
val cues = parseCues(parser, displaySet(pcs(1920, 1080, STATE_NORMAL), end()))
assertTrue(cues.isEmpty())
}
@Test
fun epochStartReleasesCachedObjects() {
val parser = PgsCompositionParser()
parseCues(parser, twoObjectEpochStart())
// New epoch referencing an object it never defines: nothing may leak across.
val cues = parseCues(
parser,
displaySet(pcs(1920, 1080, STATE_EPOCH_START, objectRef(1, 100, 900)), end())
)
assertTrue(cues.isEmpty())
}
@Test
fun resetDropsEpochState() {
val parser = PgsCompositionParser()
parseCues(parser, twoObjectEpochStart())
parser.reset()
val cues = parseCues(
parser,
displaySet(pcs(1920, 1080, STATE_NORMAL, objectRef(1, 100, 900)), end())
)
assertTrue(cues.isEmpty())
}
@Test
fun fragmentedObjectReassembles() {
val rle = solidRle(4, 2, 1)
val first = segment(
0x15,
Buf().u16(1).u8(0).u8(0x80).u24(rle.size + 4).u16(4).u16(2).raw(rle.copyOfRange(0, 3)).build()
)
val continuation = segment(
0x15,
Buf().u16(1).u8(0).u8(0x40).raw(rle.copyOfRange(3, rle.size)).build()
)
val cues = parseCues(
PgsCompositionParser(),
displaySet(pcs(1920, 1080, STATE_EPOCH_START, objectRef(1, 0, 0)), pds(WHITE_ENTRY), first, continuation, end())
)
assertEquals(1, cues.size)
assertEquals(WHITE, cues[0].bitmap!!.getPixel(3, 1))
}
@Test
fun croppedFirstReferenceDoesNotCorruptTheSecond() {
val cues = parseCues(
PgsCompositionParser(),
displaySet(
pcs(1920, 1080, STATE_EPOCH_START, objectRef(1, 100, 900, cropped = true), objectRef(2, 200, 100)),
pds(WHITE_ENTRY, YELLOW_ENTRY),
ods(1, 4, 2, solidRle(4, 2, 1)),
ods(2, 6, 3, solidRle(6, 3, 2)),
end()
)
)
assertEquals(2, cues.size)
assertEquals(200f / 1920f, cues[1].position, 1e-6f)
assertEquals(100f / 1080f, cues[1].line, 1e-6f)
}
@Test
fun runLengthEncodedBitmapsDecode() {
// Short-form color run (16 white pixels), then a long-form run (100 pixels).
val shortRun = byteArrayOf(0x00, 0x90.toByte(), 0x01)
val longRun = byteArrayOf(0x00, 0xC0.toByte(), 0x64, 0x01)
val cues = parseCues(
PgsCompositionParser(),
displaySet(
pcs(1920, 1080, STATE_EPOCH_START, objectRef(1, 0, 0), objectRef(2, 0, 200)),
pds(WHITE_ENTRY),
ods(1, 16, 1, shortRun),
ods(2, 100, 1, longRun),
end()
)
)
assertEquals(2, cues.size)
assertEquals(WHITE, cues[0].bitmap!!.getPixel(15, 0))
assertEquals(WHITE, cues[1].bitmap!!.getPixel(99, 0))
}
@Test
fun zlibCompressedSampleParses() {
val deflater = Deflater()
deflater.setInput(twoObjectEpochStart())
deflater.finish()
val compressed = ByteArray(4096)
val length = deflater.deflate(compressed)
deflater.end()
val cues = parseCues(PgsCompositionParser(), compressed.copyOf(length))
assertEquals(2, cues.size)
}
@Test
fun paletteMatrixFollowsPlaneHeight() {
val greenEntry = intArrayOf(1, 145, 34, 54, 255)
val hdCues = parseCues(
PgsCompositionParser(),
displaySet(
pcs(1920, 1080, STATE_EPOCH_START, objectRef(1, 0, 0)),
pds(greenEntry),
ods(1, 1, 1, solidRle(1, 1, 1)),
end()
)
)
val sdCues = parseCues(
PgsCompositionParser(),
displaySet(
pcs(720, 576, STATE_EPOCH_START, objectRef(1, 0, 0)),
pds(greenEntry),
ods(1, 1, 1, solidRle(1, 1, 1)),
end()
)
)
assertEquals(GREEN_BT709, hdCues[0].bitmap!!.getPixel(0, 0))
assertEquals(GREEN_BT601, sdCues[0].bitmap!!.getPixel(0, 0))
}
}
@@ -52,7 +52,6 @@ class RawPositionAudioOutputTest {
return output to listener
}
/**
* A parked track is never going to release, so its flush has to be answered at once. Deferring
* until the eviction would hold `DefaultAudioSink`'s process-wide pending-release count above
@@ -115,7 +114,6 @@ class RawPositionAudioOutputTest {
assertEquals(1, listener.releasedCount)
}
@Test
fun aParkedOutputIsHandedBackForAnIdenticalConfig() {
val delegate = FakeOutputProvider()
@@ -176,7 +174,6 @@ class RawPositionAudioOutputTest {
assertEquals(1, secondListener.underrunCount)
}
/**
* The replacement is deliberately built while the evicted track is still going away. Refusing
* until it confirms looks safer, but the refusal reaches media3 as an init failure with no
@@ -218,7 +215,6 @@ class RawPositionAudioOutputTest {
assertEquals(1, listener.releasedCount)
}
private class RecordingListener : AudioOutput.Listener {
var releasedCount = 0
var underrunCount = 0
@@ -7,7 +7,6 @@ import org.junit.Test
class ResumeStallPolicyTest {
@Test
fun windowFloorsAtDefaultForNormalFrameRates() {
// 24fps → 4 × 42ms = 168ms, floored to 1000ms
@@ -38,7 +37,6 @@ class ResumeStallPolicyTest {
assertEquals(1000L, ResumeStallPolicy.checkWindowMs(formatFps = null, detectedFps = null, speed = 1f))
}
@Test
fun advancingFramesAreHealthy() {
assertEquals(
@@ -9,16 +9,39 @@ class SubtitleViewLayoutTest {
@Test
fun letterboxUsesVisibleVideoRectForTextAndBitmapSubtitles() {
val text = textDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT)
val bitmap = bitmapDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT)
val bitmap = bitmapDimensions()
assertEquals(SubtitleViewDimensions(1920, 1080), text)
assertEquals(SubtitleViewDimensions(1920, 1080), bitmap)
}
@Test
fun croppedVideoUsesBitmapCompositionPlaneAspect() {
// #1945: 3840x1604 video with a 1920x1080 PGS plane in a 2400x1080 container.
val planeAspect = SubtitleViewLayout.bitmapPlaneAspect(
bitmapWidth = 480,
bitmapHeight = 100,
cueWidthFraction = 480f / 1920f,
cueHeightFraction = 100f / 1080f
)
assertEquals(
SubtitleViewDimensions(1781, 1002),
SubtitleViewLayout.bitmapDimensions(
containerWidth = 2400,
containerHeight = 1080,
videoWidth = 3840,
videoHeight = 1604,
pixelRatio = 1f,
planeAspect = planeAspect
)
)
}
@Test
fun coverKeepsTextOnScreenAndBitmapSubtitlesFullyVisible() {
val text = textDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_ZOOM)
val bitmap = bitmapDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_ZOOM)
val bitmap = bitmapDimensions()
assertEquals(SubtitleViewDimensions(2424, 1080), text)
assertEquals(SubtitleViewDimensions(1920, 1080), bitmap)
@@ -28,7 +51,7 @@ class SubtitleViewLayoutTest {
@Test
fun manualZoomKeepsBitmapSubtitlesFullyVisible() {
val text = textDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT, zoomScale = 1.5f)
val bitmap = bitmapDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT, zoomScale = 1.5f)
val bitmap = bitmapDimensions()
assertEquals(SubtitleViewDimensions(2424, 1080), text)
assertEquals(SubtitleViewDimensions(1920, 1080), bitmap)
@@ -38,7 +61,7 @@ class SubtitleViewLayoutTest {
@Test
fun stretchDoesNotStretchBitmapSubtitlesToScreenAspect() {
val text = textDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FILL)
val bitmap = bitmapDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FILL)
val bitmap = bitmapDimensions()
assertEquals(SubtitleViewDimensions(2424, 1080), text)
assertEquals(SubtitleViewDimensions(1920, 1080), bitmap)
@@ -48,7 +71,7 @@ class SubtitleViewLayoutTest {
@Test
fun anchorToScreenSizesTextToContainerAndKeepsBitmapOnVideoRect() {
val text = textDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT, anchorToScreen = true)
val bitmap = bitmapDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT)
val bitmap = bitmapDimensions()
assertEquals(SubtitleViewDimensions(2424, 1080), text)
assertEquals(SubtitleViewDimensions(1920, 1080), bitmap)
@@ -99,17 +122,13 @@ class SubtitleViewLayoutTest {
anchorToScreen = anchorToScreen
)
private fun bitmapDimensions(
resizeMode: Int,
zoomScale: Float = 1f
): SubtitleViewDimensions? = SubtitleViewLayout.bitmapDimensions(
private fun bitmapDimensions(): SubtitleViewDimensions? = SubtitleViewLayout.bitmapDimensions(
containerWidth = 2424,
containerHeight = 1080,
videoWidth = 1920,
videoHeight = 1080,
pixelRatio = 1f,
resizeMode = resizeMode,
zoomScale = zoomScale
planeAspect = null
)
private fun assertAspectCloseTo16By9(dimensions: SubtitleViewDimensions) {
@@ -67,8 +67,8 @@ class TrueHdMatPackerTest {
/** A burst is exactly 20ms of carrier, which is what makes the PCM-domain accounting downstream correct. */
@Test
fun aBurstIsTwentyMillisecondsOfCarrier() {
val framesPerBurst = TrueHdMatPacker.MAT_PKT_OFFSET / TrueHdMatPacker.CARRIER_BYTES_PER_FRAME
val durationUs = framesPerBurst * 1_000_000L / TrueHdMatPacker.CARRIER_SAMPLE_RATE
val framesPerBurst = TrueHdMatPacker.MAT_PKT_OFFSET / IecCarrier.BYTES_PER_FRAME
val durationUs = framesPerBurst * 1_000_000L / IecCarrier.SAMPLE_RATE
assertEquals(20_000L, durationUs)
}
@@ -166,11 +166,11 @@ class TrueHdMatPackerTest {
val length = TrueHdMatPacker.accessUnitLength(units, 0, units.size)
packer.packAccessUnit(units, 0, length)
assertTrue("the fixture must actually announce the 44.1kHz family", packer.unsupportedRateFamily)
assertTrue("the fixture must actually announce the 44.1kHz family", packer.unsupportedStream)
packer.reset()
assertFalse("reset must clear the flag", packer.unsupportedRateFamily)
assertFalse("reset must clear the flag", packer.unsupportedStream)
assertArrayEquals(
"a clean packer must reproduce the stream after a poisoned one",
golden,
@@ -9,13 +9,24 @@ import androidx.media3.extractor.TrackOutput
import java.io.ByteArrayOutputStream
import java.util.zip.Deflater
import java.util.zip.DeflaterOutputStream
import org.junit.After
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
class ZlibInflatingTrackOutputTest {
@Before
fun enableMedia3TestBoundsChecks() {
ParsableByteArray.setShouldEnforceLimitOnLegacyMethods(true)
}
@After
fun resetMedia3TestBoundsChecks() {
ParsableByteArray.setShouldEnforceLimitOnLegacyMethods(null)
}
@Test
fun activeTransformInflatesChunkedSampleAndPreservesMetadata() {
@@ -0,0 +1,80 @@
package com.edde746.plezy.exoplayer
import java.io.ByteArrayOutputStream
import java.util.zip.Deflater
import java.util.zip.DeflaterOutputStream
import java.util.zip.Inflater
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertNull
import org.junit.Test
/**
* Unit spec for [rewriteZlibTextBlock]: the block header (track-number varint,
* timecode, flags) must survive byte-identically, the payload must inflate, and
* every block the rewriter cannot prove safe must pass through unchanged (null).
*/
class ZlibTextBlockTest {
private val inflater = Inflater()
private fun block(header: ByteArray, payload: ByteArray): ByteArray = header + payload
private fun deflate(bytes: ByteArray): ByteArray {
val target = ByteArrayOutputStream()
DeflaterOutputStream(target, Deflater()).use { it.write(bytes) }
return target.toByteArray()
}
// Track 3 (varint 0x83), relative timecode 0x0102, no lacing.
private val unlacedHeader = byteArrayOf(0x83.toByte(), 0x01, 0x02, 0x00)
@Test
fun inflatesUnlacedBlockPayloadAndPreservesHeader() {
val dialogue = "42,,Default,,0,0,0,,SUBTITLE LINE 1 (0:00:00.00)".toByteArray()
val data = block(unlacedHeader, deflate(dialogue))
val rewritten = rewriteZlibTextBlock(data, data.size, inflater)!!
assertArrayEquals(unlacedHeader + dialogue, rewritten)
}
@Test
fun twoByteTrackNumberVarintIsPreserved() {
val dialogue = "1,,Default,,0,0,0,,hello".toByteArray()
val header = byteArrayOf(0x41, 0x2A, 0x01, 0x02, 0x00) // varint 0x412A = track 298
val data = block(header, deflate(dialogue))
val rewritten = rewriteZlibTextBlock(data, data.size, inflater)!!
assertArrayEquals(header + dialogue, rewritten)
}
@Test
fun lacedBlockPassesThrough() {
val laced = byteArrayOf(0x83.toByte(), 0x01, 0x02, 0x06) // EBML lacing bits set
val data = block(laced, deflate("payload".toByteArray()))
assertNull(rewriteZlibTextBlock(data, data.size, inflater))
}
@Test
fun corruptStreamPassesThrough() {
val data = block(unlacedHeader, byteArrayOf(0x44, 0x69, 0x61, 0x6C)) // "Dial", not zlib
assertNull(rewriteZlibTextBlock(data, data.size, inflater))
}
@Test
fun truncatedStreamPassesThrough() {
val compressed = deflate("a longer payload that spans several deflate symbols".toByteArray())
val truncated = compressed.copyOf(compressed.size - 4)
val data = block(unlacedHeader, truncated)
assertNull(rewriteZlibTextBlock(data, data.size, inflater))
}
@Test
fun headerOnlyBlockPassesThrough() {
assertNull(rewriteZlibTextBlock(unlacedHeader, unlacedHeader.size, inflater))
}
}
@@ -0,0 +1,170 @@
package com.edde746.plezy.exoplayer
import androidx.media3.common.C
import androidx.media3.common.DataReader
import androidx.media3.common.MimeTypes
import androidx.media3.common.util.ParsableByteArray
import androidx.media3.extractor.DefaultExtractorInput
import androidx.media3.extractor.Extractor
import androidx.media3.extractor.ExtractorOutput
import androidx.media3.extractor.PositionHolder
import androidx.media3.extractor.SeekMap
import androidx.media3.extractor.TrackOutput
import androidx.media3.extractor.text.CueDecoder
import androidx.media3.extractor.text.DefaultSubtitleParserFactory
import com.edde746.plezy.libass.media.AssHandler
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
/**
* Extracts the committed fixtures one ASS subtitle track muxed by mkvmerge with
* `--compression 0:zlib` (ContentCompAlgo 0, the anime-release convention that
* broke #2023) and an identical uncompressed mux and verifies the zlib block
* payloads are inflated *before* MatroskaExtractor's subtitle sample assembly.
*
* Regenerate with:
* mkvmerge -o zlib_ssa.mkv --compression 0:zlib repro.ass
* mkvmerge -o plain_ssa.mkv --compression 0:none repro.ass
* where repro.ass holds 45 two-second "SUBTITLE LINE N (H:MM:SS.00)" events.
*
* Robolectric provides real android.util/android.os implementations
* MatroskaExtractor uses SparseArray and CueDecoder uses Parcel, both of which
* are no-op stubs on plain JVM.
*/
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
class ZlibTextSubtitleExtractionTest {
private class CapturedSample(val timeUs: Long, val data: ByteArray)
private class FakeTrackOutput : TrackOutput {
val formats = mutableListOf<androidx.media3.common.Format>()
val samples = mutableListOf<CapturedSample>()
private var buf = ByteArray(64 * 1024)
private var bufLen = 0
override fun format(format: androidx.media3.common.Format) {
formats.add(format)
}
override fun sampleData(input: DataReader, length: Int, allowEndOfInput: Boolean, sampleDataPart: Int): Int {
ensureCapacity(bufLen + length)
val read = input.read(buf, bufLen, length)
if (read > 0) bufLen += read
return read
}
override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) {
ensureCapacity(bufLen + length)
data.readBytes(buf, bufLen, length)
bufLen += length
}
override fun sampleMetadata(timeUs: Long, flags: Int, size: Int, offset: Int, cryptoData: TrackOutput.CryptoData?) {
val start = bufLen - offset - size
samples.add(CapturedSample(timeUs, buf.copyOfRange(start, start + size)))
if (offset == 0) bufLen = 0
}
private fun ensureCapacity(needed: Int) {
if (buf.size < needed) buf = buf.copyOf(maxOf(needed, buf.size * 2))
}
}
private class FakeExtractorOutput : ExtractorOutput {
val tracks = mutableMapOf<Int, FakeTrackOutput>()
override fun track(id: Int, type: Int): TrackOutput = tracks.getOrPut(id) { FakeTrackOutput() }
override fun endTracks() {}
override fun seekMap(seekMap: SeekMap) {}
}
private class ByteArrayDataReader(private val data: ByteArray) : DataReader {
var position = 0L
override fun read(buffer: ByteArray, offset: Int, length: Int): Int {
if (position >= data.size) return C.RESULT_END_OF_INPUT
val toRead = minOf(length, data.size - position.toInt())
System.arraycopy(data, position.toInt(), buffer, offset, toRead)
position += toRead
return toRead
}
}
private fun extract(resource: String): FakeExtractorOutput {
val data = checkNotNull(javaClass.getResourceAsStream(resource)) {
"fixture $resource missing from test resources"
}.use { it.readBytes() }
// DefaultSubtitleParserFactory (not AssSubtitleParserFactory) so the SSA track
// transcodes to decodable media3 cues instead of loading native libass.
val extractor = ZlibMatroskaExtractor(DefaultSubtitleParserFactory(), AssHandler())
val output = FakeExtractorOutput()
extractor.init(output)
val reader = ByteArrayDataReader(data)
var input = DefaultExtractorInput(reader, 0, data.size.toLong())
val seekPosition = PositionHolder()
while (true) {
when (extractor.read(input, seekPosition)) {
Extractor.RESULT_END_OF_INPUT -> return output
Extractor.RESULT_SEEK -> {
reader.position = seekPosition.position
input = DefaultExtractorInput(reader, seekPosition.position, data.size.toLong())
}
else -> {}
}
}
}
private class DecodedCue(val startTimeUs: Long, val durationUs: Long, val text: String)
private fun decodeCues(output: FakeExtractorOutput): List<DecodedCue> {
val track = output.tracks.values.single()
val format = track.formats.last()
assertEquals(MimeTypes.APPLICATION_MEDIA3_CUES, format.sampleMimeType)
assertEquals(MimeTypes.TEXT_SSA, format.codecs)
val decoder = CueDecoder()
return track.samples.map { sample ->
val cues = decoder.decode(sample.timeUs, sample.data, 0, sample.data.size)
DecodedCue(
cues.startTimeUs,
cues.durationUs,
cues.cues.joinToString("\n") { it.text.toString() }
)
}
}
@Test
fun zlibCompressedAssDialogueIsInflatedToParseableCues() {
val cues = decodeCues(extract("/zlib_ssa.mkv"))
assertEquals(45, cues.size)
assertEquals("SUBTITLE LINE 1 (0:00:00.00)", cues.first().text)
assertEquals(0L, cues.first().startTimeUs)
assertEquals(2_000_000L, cues.first().durationUs)
assertEquals("SUBTITLE LINE 45 (0:01:28.00)", cues.last().text)
assertEquals(88_000_000L, cues.last().startTimeUs)
cues.forEachIndexed { index, cue ->
assertEquals(index * 2_000_000L, cue.startTimeUs)
assertTrue("cue $index text: ${cue.text}", cue.text.startsWith("SUBTITLE LINE ${index + 1} "))
}
}
@Test
fun zlibAndPlainMuxesProduceIdenticalCues() {
val zlib = decodeCues(extract("/zlib_ssa.mkv"))
val plain = decodeCues(extract("/plain_ssa.mkv"))
assertEquals(plain.size, zlib.size)
plain.zip(zlib).forEachIndexed { index, (expected, actual) ->
assertEquals("startTimeUs of cue $index", expected.startTimeUs, actual.startTimeUs)
assertEquals("durationUs of cue $index", expected.durationUs, actual.durationUs)
assertEquals("text of cue $index", expected.text, actual.text)
}
}
}
@@ -0,0 +1,38 @@
package com.edde746.plezy.mpv
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
/** Boundaries are the contract; rationale on [DemuxerBudget]. */
class DemuxerBudgetTest {
private val mib = 1024L * 1024L
@Test
fun `unknown heap class keeps mpv defaults`() {
assertNull(DemuxerBudget.forHeapClassMB(0))
assertNull(DemuxerBudget.forHeapClassMB(-1))
}
@Test
fun `small heap class gets the tight tier`() {
val budget = DemuxerBudget.forHeapClassMB(256)!!
assertEquals(32 * mib, budget.aheadBytes)
assertEquals(16 * mib, budget.backBytes)
}
@Test
fun `mid heap class gets the middle tier`() {
assertEquals(64 * mib, DemuxerBudget.forHeapClassMB(257)!!.aheadBytes)
val budget = DemuxerBudget.forHeapClassMB(512)!!
assertEquals(64 * mib, budget.aheadBytes)
assertEquals(32 * mib, budget.backBytes)
}
@Test
fun `large heap class gets the full tier`() {
val budget = DemuxerBudget.forHeapClassMB(513)!!
assertEquals(100 * mib, budget.aheadBytes)
assertEquals(48 * mib, budget.backBytes)
}
}
@@ -0,0 +1,199 @@
package com.edde746.plezy.mpv
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* P5 has no compatible base layer: on a device without native DV it must
* leave the video plane for gpu-next software reshaping, and nothing else
* may be routed (wrong-colors class verified on a Pixel 7). The vo target
* matrix keeps gpu-next away from hardware sessions (#2010) while giving
* the reshaping path the only vo that composites RPU metadata (#1902).
*/
class GpuVoPolicyTest {
@Test
fun `P5 without native support is routed`() {
assertTrue(GpuVoPolicy.needsDvReshaping(5L, "auto", canPlayP5Natively = false))
}
@Test
fun `P5 with native support stays on the plane`() {
assertFalse(GpuVoPolicy.needsDvReshaping(5L, "auto", canPlayP5Natively = true))
}
@Test
fun `base-layer-compatible profiles are never routed`() {
// P7/P8 strip to an HDR10/HLG base layer; non-DV content has no profile.
assertFalse(GpuVoPolicy.needsDvReshaping(7L, "auto", canPlayP5Natively = false))
assertFalse(GpuVoPolicy.needsDvReshaping(8L, "auto", canPlayP5Natively = false))
assertFalse(GpuVoPolicy.needsDvReshaping(null, "auto", canPlayP5Natively = false))
}
@Test
fun `explicit conversion modes are user overrides and stay native`() {
for (mode in listOf("disabled", "native", "dv81", "hevc", "hevc_strip")) {
assertFalse(mode, GpuVoPolicy.needsDvReshaping(5L, mode, canPlayP5Natively = false))
}
}
@Test
fun `hdr tone-mapping is needed only for a PQ or HLG signal on a non-HDR display`() {
assertTrue(GpuVoPolicy.needsHdrToneMapping("pq", displaySupportsHdr = false))
assertTrue(GpuVoPolicy.needsHdrToneMapping("hlg", displaySupportsHdr = false))
// An HDR display scans the signal out itself.
assertFalse(GpuVoPolicy.needsHdrToneMapping("pq", displaySupportsHdr = true))
assertFalse(GpuVoPolicy.needsHdrToneMapping("hlg", displaySupportsHdr = true))
// SDR transfers need no mapping, and mpv reports none before the first
// frame of a file.
assertFalse(GpuVoPolicy.needsHdrToneMapping("bt.1886", displaySupportsHdr = false))
assertFalse(GpuVoPolicy.needsHdrToneMapping("srgb", displaySupportsHdr = false))
assertFalse(GpuVoPolicy.needsHdrToneMapping(null, displaySupportsHdr = false))
assertFalse(GpuVoPolicy.needsHdrToneMapping("", displaySupportsHdr = false))
}
@Test
fun `only direct mediacodec output can stay on the plane`() {
// -copy also reads frames back into system memory, so it leaves too.
assertTrue(GpuVoPolicy.needsSoftwareRender("no"))
assertTrue(GpuVoPolicy.needsSoftwareRender("mediacodec-copy"))
assertFalse(GpuVoPolicy.needsSoftwareRender("mediacodec"))
// Unreported until the decoder initializes: stay on the plane.
assertFalse(GpuVoPolicy.needsSoftwareRender(null))
assertFalse(GpuVoPolicy.needsSoftwareRender(""))
}
@Test
fun `a software-decoding session targets gpu, not gpu-next`() {
assertEquals("gpu", GpuVoPolicy.targetFor(setOf(GpuVoPolicy.REASON_SW_DECODE)))
assertEquals("gpu", GpuVoPolicy.targetFor(setOf(GpuVoPolicy.REASON_SHADERS)))
assertEquals(
"gpu",
GpuVoPolicy.targetFor(setOf(GpuVoPolicy.REASON_SHADERS, GpuVoPolicy.REASON_SW_DECODE))
)
}
@Test
fun `no reasons keeps the video plane`() {
assertNull(GpuVoPolicy.targetFor(emptySet()))
}
@Test
fun `High 10 without a hardware profile is software-decoded up front`() {
assertTrue(GpuVoPolicy.needsSoftwareDecode("h264", "High 10", hardwareHigh10 = false, hardwareAv1 = true))
assertTrue(GpuVoPolicy.needsSoftwareDecode("h264", "High 10 Intra", hardwareHigh10 = false, hardwareAv1 = true))
assertEquals("gpu", GpuVoPolicy.targetFor(setOf(GpuVoPolicy.REASON_CODEC_SW_DECODE)))
}
@Test
fun `hardware supported and unrelated streams retain the configured decoder`() {
// A decoder that advertises the profile gets to try.
assertFalse(GpuVoPolicy.needsSoftwareDecode("h264", "High 10", hardwareHigh10 = true, hardwareAv1 = false))
// 8-bit profiles, other codecs, and streams whose container carries no
// profile (Annex B transport streams) are not routed.
assertFalse(GpuVoPolicy.needsSoftwareDecode("h264", "High", hardwareHigh10 = false, hardwareAv1 = false))
assertFalse(GpuVoPolicy.needsSoftwareDecode("h264", "Constrained Baseline", hardwareHigh10 = false, hardwareAv1 = false))
assertFalse(GpuVoPolicy.needsSoftwareDecode("hevc", "Main 10", hardwareHigh10 = false, hardwareAv1 = false))
assertFalse(GpuVoPolicy.needsSoftwareDecode("h264", null, hardwareHigh10 = false, hardwareAv1 = false))
assertFalse(GpuVoPolicy.needsSoftwareDecode("h264", "", hardwareHigh10 = false, hardwareAv1 = false))
assertFalse(GpuVoPolicy.needsSoftwareDecode(null, "High 10", hardwareHigh10 = false, hardwareAv1 = false))
}
@Test
fun `AV1 bypasses software MediaCodec even without a reported profile`() {
assertTrue(GpuVoPolicy.needsSoftwareDecode("av1", "Main", hardwareHigh10 = true, hardwareAv1 = false))
assertTrue(GpuVoPolicy.needsSoftwareDecode("av1", null, hardwareHigh10 = true, hardwareAv1 = false))
assertTrue(GpuVoPolicy.needsSoftwareDecode("av1", "", hardwareHigh10 = true, hardwareAv1 = false))
assertFalse(GpuVoPolicy.needsSoftwareDecode("av1", "Main", hardwareHigh10 = false, hardwareAv1 = true))
}
// The per-file policies run inside on_preloaded, before mpv selects a
// track, so the track they decide for comes from the pending selection.
@Test
fun `auto selection follows mpv's pending choice, not track-list order`() {
// Cover art first, the default-flagged feature second: mpv picks 2.
assertEquals(2L, GpuVoPolicy.pendingVideoTrackId("auto", "2", listOf(1L, 2L)))
assertEquals(1L, GpuVoPolicy.pendingVideoTrackId("auto", "1", listOf(1L, 2L)))
}
@Test
fun `explicit vid answers on its own`() {
assertEquals(2L, GpuVoPolicy.pendingVideoTrackId("2", pendingVid = null, videoTrackIds = listOf(1L, 2L)))
// A user's explicit choice is never re-selected, even when mpv would
// pick differently.
assertEquals(1L, GpuVoPolicy.pendingVideoTrackId("1", "2", listOf(1L, 2L)))
// No such track: mpv selects nothing, so nothing is routed.
assertNull(GpuVoPolicy.pendingVideoTrackId("7", "2", listOf(1L, 2L)))
}
@Test
fun `no video selection yields no track`() {
assertNull(GpuVoPolicy.pendingVideoTrackId("no", "1", listOf(1L, 2L)))
assertNull(GpuVoPolicy.pendingVideoTrackId("auto", "no", listOf(1L, 2L)))
assertNull(GpuVoPolicy.pendingVideoTrackId("auto", "1", emptyList()))
}
@Test
fun `without the pending-vid property the first track is the fallback`() {
assertEquals(1L, GpuVoPolicy.pendingVideoTrackId("auto", null, listOf(1L, 2L)))
assertEquals(1L, GpuVoPolicy.pendingVideoTrackId(null, null, listOf(1L, 2L)))
assertNull(GpuVoPolicy.pendingVideoTrackId("auto", null, emptyList()))
}
@Test
fun `cheap render tier needs a GL vo on a driver without norm16`() {
assertTrue(GpuVoPolicy.needsCheapRenderTier(glVoActive = true, textureNorm16 = false))
// The plane never scales in GL; a capable GPU keeps mpv's defaults.
assertFalse(GpuVoPolicy.needsCheapRenderTier(glVoActive = false, textureNorm16 = false))
assertFalse(GpuVoPolicy.needsCheapRenderTier(glVoActive = true, textureNorm16 = true))
}
@Test
fun `cheap tier replaces only options still at their mpv default`() {
for ((option, defaults) in GpuVoPolicy.MPV_DEFAULT_RENDER_OPTIONS) {
for (default in defaults) assertTrue(option, GpuVoPolicy.isDefaultRenderOption(option, default))
// A user's mpv.conf value, or an unreadable option, is left alone.
assertFalse(option, GpuVoPolicy.isDefaultRenderOption(option, "ewa_lanczos"))
assertFalse(option, GpuVoPolicy.isDefaultRenderOption(option, null))
}
assertEquals(GpuVoPolicy.CHEAP_RENDER_OPTIONS.keys, GpuVoPolicy.MPV_DEFAULT_RENDER_OPTIONS.keys)
// cscale's default is "inherit", which mpv 0.41 reads back as empty.
assertTrue(GpuVoPolicy.isDefaultRenderOption("cscale", ""))
assertFalse(GpuVoPolicy.isDefaultRenderOption("scale", ""))
}
@Test
fun `dv reshaping targets gpu-next even alongside other reasons`() {
assertEquals("gpu-next", GpuVoPolicy.targetFor(setOf(GpuVoPolicy.REASON_DV_RESHAPE)))
assertEquals(
"gpu-next",
GpuVoPolicy.targetFor(setOf(GpuVoPolicy.REASON_SHADERS, GpuVoPolicy.REASON_DV_RESHAPE))
)
}
@Test
fun `shaders and chain failure target the hardware-safe gpu vo`() {
assertEquals("gpu", GpuVoPolicy.targetFor(setOf(GpuVoPolicy.REASON_SHADERS)))
assertEquals("gpu", GpuVoPolicy.targetFor(setOf(GpuVoPolicy.REASON_CHAIN_FAILURE)))
assertEquals(
"gpu",
GpuVoPolicy.targetFor(setOf(GpuVoPolicy.REASON_SHADERS, GpuVoPolicy.REASON_CHAIN_FAILURE))
)
}
@Test
fun `hdr tone-mapping targets gpu but yields to dv reshaping`() {
assertEquals("gpu", GpuVoPolicy.targetFor(setOf(GpuVoPolicy.REASON_HDR_SDR)))
assertEquals(
"gpu",
GpuVoPolicy.targetFor(setOf(GpuVoPolicy.REASON_HDR_SDR, GpuVoPolicy.REASON_SHADERS))
)
assertEquals(
"gpu-next",
GpuVoPolicy.targetFor(setOf(GpuVoPolicy.REASON_HDR_SDR, GpuVoPolicy.REASON_DV_RESHAPE))
)
}
}
@@ -0,0 +1,43 @@
package com.edde746.plezy.mpv
import com.edde746.plezy.libmpv.EndFileReason
import com.edde746.plezy.libmpv.LogLevel
import com.edde746.plezy.libmpv.LogMessage
import com.edde746.plezy.libmpv.MpvError
import com.edde746.plezy.libmpv.MpvEvent
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class MpvEndFileDiagnosticsTest {
private val diagnostics = MpvEndFileDiagnostics()
@Test
fun `an AO failure ends the file with the audio-output cause and the last error line`() {
diagnostics.onStartFile()
diagnostics.onLogMessage(LogMessage("cplayer", LogLevel.Error, "Audio output stopped responding; stopping playback."))
val data = diagnostics.onEndFile(MpvEvent.EndFile(EndFileReason.Error, 7, MpvError.AoInitFailed))
assertEquals(
mapOf(
"sourceId" to 7L,
"reason" to EndFileReason.Error.id,
"message" to "Audio output stopped responding; stopping playback.",
"cause" to MpvEndFileDiagnostics.CAUSE_AUDIO_OUTPUT_FAILED
),
data
)
}
@Test
fun `other errors carry no cause so Dart keeps its generic handling`() {
val data = diagnostics.onEndFile(MpvEvent.EndFile(EndFileReason.Error, 7, MpvError.LoadingFailed))
assertNull(data?.get("cause"))
}
@Test
fun `a clean stop never reports a cause even after an earlier error line`() {
diagnostics.onLogMessage(LogMessage("ao/audiotrack", LogLevel.Error, "AudioTrack.write failed with -32"))
val data = diagnostics.onEndFile(MpvEvent.EndFile(EndFileReason.Stop, 7))
assertEquals(mapOf("sourceId" to 7L, "reason" to EndFileReason.Stop.id), data)
}
}
@@ -7,11 +7,11 @@ import android.os.Looper
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.widget.FrameLayout
import com.edde746.plezy.libmpv.EndFileReason
import com.edde746.plezy.libmpv.LogLevel
import com.edde746.plezy.libmpv.LogMessage
import com.edde746.plezy.libmpv.MpvEvent
import com.edde746.plezy.shared.AudioFocusManager
import dev.jdtech.mpv.EndFileReason
import dev.jdtech.mpv.LogLevel
import dev.jdtech.mpv.LogMessage
import dev.jdtech.mpv.MpvEvent
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodCall
@@ -24,6 +24,7 @@ import java.util.concurrent.atomic.AtomicInteger
import kotlinx.coroutines.suspendCancellableCoroutine
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
@@ -48,6 +49,56 @@ class MpvPlayerPluginTest {
assertNull(result.successValue)
}
@Test
fun commandWithoutNativePlayerReportsFailureInsteadOfSilentSuccess() {
// A load that never reached mpv produces no source; answering success
// would leave Dart waiting on a start-file that never comes.
val plugin = MpvPlayerPlugin()
installCore(plugin, testCore(null))
val result = RecordingResult()
plugin.onMethodCall(MethodCall("command", mapOf("args" to listOf("loadfile", "x", "replace"))), result)
awaitCompletion(result)
assertEquals("COMMAND_FAILED", result.errorCode)
assertEquals(1, result.completionCount)
assertNull(result.successValue)
}
@Test
fun audioSpdifCodecsWithoutContextAnswersEmptySoMpvDecodes() {
// mpv force-passthroughs every codec named in audio-spdif with no decode fallback, so
// with no context to inspect the audio route the only safe answer is "" (#1703, #1991).
val result = RecordingResult()
MpvPlayerPlugin().onMethodCall(MethodCall("getAudioSpdifCodecs", null), result)
assertEquals("", result.successValue)
assertNull(result.errorCode)
assertEquals(1, result.completionCount)
}
@Test
fun hardwareDecodeSessionsUseTheMediaCodecVoWithGpuFallback() {
// Rationale on MpvPlayerCore.initialVideoOutput.
assertEquals("mediacodec,gpu", MpvPlayerCore.initialVideoOutput(hardwareDecoding = true))
assertEquals("gpu,gpu-next", MpvPlayerCore.initialVideoOutput(hardwareDecoding = false))
}
@Test
fun hdrSurfaceIsWantedOnlyForPqAndHlgTransfers() {
// Rationale on MpvPlayerCore.wantsHdrSurface: both render into a PQ
// target; anything else stays on the sRGB surface, which renders every
// content correctly.
assertTrue(MpvPlayerCore.wantsHdrSurface("smpte2084"))
assertTrue(MpvPlayerCore.wantsHdrSurface("arib-std-b67"))
assertFalse(MpvPlayerCore.wantsHdrSurface("bt709"))
assertFalse(MpvPlayerCore.wantsHdrSurface("bt1886"))
assertFalse(MpvPlayerCore.wantsHdrSurface("unknown"))
assertFalse(MpvPlayerCore.wantsHdrSurface(""))
assertFalse(MpvPlayerCore.wantsHdrSurface(null))
}
@Test
fun setPropertyWithoutCoreReportsNotInitializedForVideoAndAudio() {
for (plugin in listOf(MpvPlayerPlugin(), MpvAudioPlayerPlugin())) {
@@ -598,6 +649,53 @@ class MpvPlayerPluginTest {
assertEquals(0, pending.size)
}
@Test
fun staleDisposeIsAcknowledgedWithoutTearingDownTheCore() {
// A dispose whose instanceId is not the core creator's lost the ownership
// race to a successor; tearing the core down anyway would kill that
// successor's session. It must be acknowledged as a no-op instead.
val plugin = MpvPlayerPlugin()
installCore(plugin, testCore { _, _ -> })
setPluginField(plugin, "coreInstanceId", 2L)
val result = RecordingResult()
plugin.onMethodCall(MethodCall("dispose", mapOf("instanceId" to 1)), result)
awaitCompletion(result)
assertNull(result.errorCode)
assertNotNull(getPluginField(plugin, "playerCore"))
assertEquals(2L, getPluginField(plugin, "coreInstanceId"))
}
@Test
fun matchingDisposeTearsDownTheCoreAndClearsTheToken() {
val plugin = MpvPlayerPlugin()
installCore(plugin, testCore { _, _ -> })
setPluginField(plugin, "coreInstanceId", 7L)
val result = RecordingResult()
plugin.onMethodCall(MethodCall("dispose", mapOf("instanceId" to 7)), result)
awaitCompletion(result)
assertNull(result.errorCode)
assertNull(getPluginField(plugin, "playerCore"))
assertNull(getPluginField(plugin, "coreInstanceId"))
}
@Test
fun tokenlessDisposeKeepsLegacySemanticsAndTearsDownTheCore() {
val plugin = MpvPlayerPlugin()
installCore(plugin, testCore { _, _ -> })
setPluginField(plugin, "coreInstanceId", 7L)
val result = RecordingResult()
plugin.onMethodCall(MethodCall("dispose", null), result)
awaitCompletion(result)
assertNull(result.errorCode)
assertNull(getPluginField(plugin, "playerCore"))
}
@Test
fun configDetachThenEngineDetachTearsDownVideoCoreAndPendingInitOnce() {
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
@@ -676,15 +774,53 @@ class MpvPlayerPluginTest {
}
@Test
fun setLogLevelReportsUnsupported() {
fun setLogLevelWithoutCoreReportsNotInitializedForVideoAndAudio() {
for (plugin in listOf(MpvPlayerPlugin(), MpvAudioPlayerPlugin())) {
val result = RecordingResult()
plugin.onMethodCall(MethodCall("setLogLevel", mapOf("level" to "warn")), result)
assertEquals("NOT_INITIALIZED", result.errorCode)
assertEquals(1, result.completionCount)
assertNull(result.successValue)
}
}
@Test
fun setLogLevelRejectsMissingOrNonStringLevel() {
for (level in listOf(null, 42)) {
val result = RecordingResult()
MpvPlayerPlugin().onMethodCall(MethodCall("setLogLevel", mapOf("level" to level)), result)
assertEquals("INVALID_ARGS", result.errorCode)
assertEquals(1, result.completionCount)
}
}
@Test
fun disposeCompletesQueuedLogLevelChangeOnceWithoutAnActiveNativePlayer() {
val blockerStarted = CountDownLatch(1)
val releaseBlocker = CountDownLatch(1)
val core = testCore { _, _ ->
blockerStarted.countDown()
check(releaseBlocker.await(2, TimeUnit.SECONDS))
}
val plugin = MpvPlayerPlugin()
installCore(plugin, core)
val result = RecordingResult()
try {
core.setProperty("block", "value")
assertTrue(blockerStarted.await(1, TimeUnit.SECONDS))
plugin.onMethodCall(MethodCall("setLogLevel", mapOf("level" to "v")), result)
core.dispose()
} finally {
releaseBlocker.countDown()
}
awaitCompletion(result)
MpvPlayerPlugin().onMethodCall(
MethodCall("setLogLevel", mapOf("level" to "warn")),
result
)
assertEquals("UNSUPPORTED", result.errorCode)
assertEquals("NOT_INITIALIZED", result.errorCode)
assertEquals(1, result.completionCount)
assertNull(result.successValue)
}
@@ -696,10 +832,11 @@ class MpvPlayerPluginTest {
assertEquals(
mapOf(
"sourceId" to 73L,
"reason" to 4,
"message" to "Invalid data found when processing input"
),
diagnostics.onEndFile(MpvEvent.EndFile(EndFileReason.Error))
diagnostics.onEndFile(MpvEvent.EndFile(EndFileReason.Error, 73L))
)
}
@@ -709,9 +846,10 @@ class MpvPlayerPluginTest {
diagnostics.onLogMessage(LogMessage("ffmpeg", LogLevel.Error, "old failure"))
diagnostics.onStartFile()
assertEquals(mapOf("reason" to 0), diagnostics.onEndFile(MpvEvent.EndFile(EndFileReason.Eof)))
assertEquals(mapOf("reason" to 4), diagnostics.onEndFile(MpvEvent.EndFile(EndFileReason.Error)))
assertNull(diagnostics.onEndFile(MpvEvent.EndFile(null)))
assertEquals(mapOf("reason" to 0), diagnostics.onEndFile(MpvEvent.EndFile(EndFileReason.Eof, null)))
assertEquals(mapOf("reason" to 4), diagnostics.onEndFile(MpvEvent.EndFile(EndFileReason.Error, null)))
assertEquals(mapOf("sourceId" to 81L), diagnostics.onEndFile(MpvEvent.EndFile(null, 81L)))
assertNull(diagnostics.onEndFile(MpvEvent.EndFile(null, null)))
}
@Test
@@ -723,6 +861,7 @@ class MpvPlayerPluginTest {
plugin.onEvent(
"end-file",
mapOf(
"sourceId" to 92L,
"reason" to 4,
"message" to "Failed to open stream"
)
@@ -733,6 +872,7 @@ class MpvPlayerPluginTest {
"type" to "event",
"name" to "end-file",
"data" to mapOf(
"sourceId" to 92L,
"reason" to 4,
"message" to "Failed to open stream"
)
@@ -741,6 +881,52 @@ class MpvPlayerPluginTest {
)
}
@Test
fun sourceQualifiedLifecycleAndPropertiesKeepTheirDequeueIdentity() {
val sink = RecordingEventSink()
val plugin = MpvPlayerPlugin()
plugin.onListen(null, sink)
plugin.onMethodCall(
MethodCall(
"observeProperty",
mapOf("name" to "time-pos", "format" to "double", "id" to 7)
),
RecordingResult()
)
plugin.onPropertyChange("time-pos", 0.0)
plugin.onEvent("start-file", mapOf("sourceId" to 202L))
plugin.onEvent("file-loaded", mapOf("sourceId" to 202L))
plugin.onPropertyChange("time-pos", 12.5, 101L)
plugin.onEvent(
"playback-restart",
mapOf("sourceId" to 202L, "positionSeconds" to 18.75)
)
assertEquals(
listOf(
listOf(7, 0.0, null),
mapOf(
"type" to "event",
"name" to "start-file",
"data" to mapOf("sourceId" to 202L)
),
mapOf(
"type" to "event",
"name" to "file-loaded",
"data" to mapOf("sourceId" to 202L)
),
listOf(7, 12.5, 101L),
mapOf(
"type" to "event",
"name" to "playback-restart",
"data" to mapOf("sourceId" to 202L, "positionSeconds" to 18.75)
)
),
sink.successValues
)
}
private fun propertyCall() = MethodCall(
"setProperty",
mapOf("name" to "volume", "value" to "50")
@@ -867,6 +1053,130 @@ class MpvPlayerPluginTest {
getBoolean(core)
}
private fun invokeSetGpuVoRequirement(core: MpvPlayerCore, reason: String, active: Boolean) {
MpvPlayerCore::class.java
.getDeclaredMethod("setGpuVoRequirement", String::class.java, Boolean::class.javaPrimitiveType)
.apply {
isAccessible = true
invoke(core, reason, active)
}
}
@Test
fun voTargetFollowsTheActiveReasonSet() {
// Reason precedence through the real property-write path: DV reshaping
// outranks HDR-on-SDR, dropping the winner falls back to the reason still
// active, and dropping the last one returns the session to the plane.
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
val writes = ConcurrentLinkedQueue<Pair<String, String>>()
val core = MpvPlayerCore(activity, audioOnly = false, propertyWriter = { name, value ->
writes.add(name to value)
})
setBoolean(core, "isInitialized", true)
fun lastVo(): String? = writes.toList().lastOrNull { it.first == "vo" }?.second
// HDR-on-SDR raises first, then the DV router wins the arbitration.
invokeSetGpuVoRequirement(core, GpuVoPolicy.REASON_HDR_SDR, true)
invokeSetGpuVoRequirement(core, GpuVoPolicy.REASON_DV_RESHAPE, true)
awaitCondition { lastVo() == "gpu-next" }
assertEquals("gpu-next", lastVo())
// Dropping the winning reason must fall back to the one still active,
// not to the plane.
invokeSetGpuVoRequirement(core, GpuVoPolicy.REASON_DV_RESHAPE, false)
awaitCondition { lastVo() == "gpu" }
assertEquals("gpu", lastVo())
// Last reason dropping returns the session to the video plane.
invokeSetGpuVoRequirement(core, GpuVoPolicy.REASON_HDR_SDR, false)
awaitCondition { lastVo() == "mediacodec" }
assertEquals("mediacodec", lastVo())
}
@Test
fun hwdecWritesParkWhileAPerFileHoldIsActive() {
// While DV P5 reshaping or Hi10 routing holds hwdec at `no`, a session
// write of a hardware value must not reach mpv (it would re-enable the
// decoder that was just refused) but must be kept for the restore.
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
val writes = ConcurrentLinkedQueue<Pair<String, String>>()
val core = MpvPlayerCore(activity, audioOnly = false, propertyWriter = { name, value ->
writes.add(name to value)
})
setBoolean(core, "isInitialized", true)
setBoolean(core, "hwdecHeld", true)
var outcome: Result<Unit>? = null
core.setProperty("hwdec", "mediacodec,mediacodec-copy") { outcome = it }
awaitCondition { outcome != null }
assertTrue(outcome!!.isSuccess)
assertTrue(writes.isEmpty())
val parked = MpvPlayerCore::class.java.getDeclaredField("parkedHwdec").run {
isAccessible = true
@Suppress("UNCHECKED_CAST")
(get(core) as java.util.concurrent.atomic.AtomicReference<String?>).get()
}
assertEquals("mediacodec,mediacodec-copy", parked)
// Once the hold is gone, hwdec writes flow through again.
setBoolean(core, "hwdecHeld", false)
outcome = null
core.setProperty("hwdec", "no") { outcome = it }
awaitCondition { outcome != null }
assertEquals(listOf("hwdec" to "no"), writes.toList())
}
@Test
fun dvConversionModeMapsOntoForkDecoderOptions() {
// The app-level `dv-conversion-mode` property must translate to the fork
// FFmpeg hevc_mediacodec options, mirroring the ExoPlayer DoviBridge
// modes. Robolectric reports no Dolby Vision display, so `auto` takes the
// no-DV branch deterministically.
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
val writes = ConcurrentLinkedQueue<Pair<String, String>>()
val core = MpvPlayerCore(activity, audioOnly = false, propertyWriter = { name, value ->
writes.add(name to value)
})
fun apply(mode: String): Result<Unit> {
writes.clear()
var outcome: Result<Unit>? = null
core.setProperty("dv-conversion-mode", mode) { outcome = it }
awaitCondition { outcome != null }
return outcome!!
}
assertTrue(apply("auto").isSuccess)
assertEquals(listOf("vd-lavc-o" to "dolby_vision=0,dv_p7_mode=strip"), writes.toList())
assertTrue(apply("disabled").isSuccess)
assertEquals(listOf("vd-lavc-o" to "dolby_vision=1,dv_p7_mode=native"), writes.toList())
assertTrue(apply("dv81").isSuccess)
assertEquals(listOf("vd-lavc-o" to "dolby_vision=1,dv_p7_mode=convert"), writes.toList())
assertTrue(apply("hevc_strip").isSuccess)
assertEquals(listOf("vd-lavc-o" to "dolby_vision=1,dv_p7_mode=strip"), writes.toList())
val invalid = apply("bogus")
assertTrue(invalid.isFailure)
assertTrue(writes.isEmpty())
}
@Test
fun decoderOptionsMergeKeepsUserEntriesFirst() {
// The property interface cannot append to a list option, so the write
// replaces it wholesale: a user's own mpv.conf `vd-lavc-o` entries must
// survive, with the app's keys last (FFmpeg keeps the last duplicate).
assertEquals(
"threads=4,dolby_vision=1",
MpvPlayerCore.mergeDecoderOptions("threads=4", "dolby_vision=1")
)
assertEquals("dolby_vision=1", MpvPlayerCore.mergeDecoderOptions(null, "dolby_vision=1"))
assertEquals("dolby_vision=1", MpvPlayerCore.mergeDecoderOptions(" ", "dolby_vision=1"))
}
private fun awaitQueueEntry(
queue: ConcurrentLinkedQueue<Pair<String, String>>,
expected: Pair<String, String>
@@ -928,9 +1238,11 @@ class MpvPlayerPluginTest {
private class RecordingEventSink : EventChannel.EventSink {
var successValue: Any? = null
val successValues = mutableListOf<Any?>()
override fun success(event: Any?) {
successValue = event
successValues += event
}
override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) = Unit
@@ -0,0 +1,32 @@
package com.edde746.plezy.mpv
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class OsdPlanePolicyTest {
@Test
fun `full resolution leaves the plane tracking its view`() {
assertNull(OsdPlanePolicy.fixedSizeFor(1920, 1080, 1f))
}
@Test
fun `fractions shrink both dimensions by the same scale`() {
assertEquals(OsdPlanePolicy.Size(1440, 810), OsdPlanePolicy.fixedSizeFor(1920, 1080, 0.75f))
assertEquals(OsdPlanePolicy.Size(960, 540), OsdPlanePolicy.fixedSizeFor(1920, 1080, 0.5f))
assertEquals(OsdPlanePolicy.Size(640, 360), OsdPlanePolicy.fixedSizeFor(1920, 1080, 1f / 3f))
}
@Test
fun `odd results round down to even`() {
// 1/3 of 1000 is 333.3: rounds to 333, then to the even 332.
assertEquals(OsdPlanePolicy.Size(332, 250), OsdPlanePolicy.fixedSizeFor(1000, 750, 1f / 3f))
}
@Test
fun `unlaid-out views and nonsense scales are ignored`() {
assertNull(OsdPlanePolicy.fixedSizeFor(0, 0, 0.5f))
assertNull(OsdPlanePolicy.fixedSizeFor(1920, 1080, 0f))
assertNull(OsdPlanePolicy.fixedSizeFor(1920, 1080, 1.5f))
}
}
@@ -0,0 +1,72 @@
package com.edde746.plezy.mpv
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class VideoRectPolicyTest {
@Test
fun `contain letterboxes wide content inside the container`() {
// 2.39:1 content on a 16:9 container: full width, bars top and bottom.
val size = VideoRectPolicy.sizeFor(1920, 1080, 2390, 1000)!!
assertEquals(1920, size.width)
assertEquals(803, size.height)
assertTrue(size.height < 1080)
}
@Test
fun `contain pillarboxes tall content inside the container`() {
val size = VideoRectPolicy.sizeFor(1920, 1080, 1000, 2390)!!
assertEquals(1080, size.height)
assertTrue(size.width < 1920)
}
@Test
fun `panscan 1 fills the container so the image is cropped, not letterboxed`() {
// The regression this exists for: cover used to be a no-op on the plane.
val size = VideoRectPolicy.sizeFor(1920, 1080, 2390, 1000, panscan = 1f)!!
assertTrue("cover must reach the container height", size.height >= 1080)
assertTrue("width must overflow and be clipped", size.width > 1920)
}
@Test
fun `panscan interpolates between contain and cover`() {
val contain = VideoRectPolicy.sizeFor(1920, 1080, 2390, 1000)!!
val half = VideoRectPolicy.sizeFor(1920, 1080, 2390, 1000, panscan = 0.5f)!!
val cover = VideoRectPolicy.sizeFor(1920, 1080, 2390, 1000, panscan = 1f)!!
assertTrue(half.height > contain.height)
assertTrue(half.height < cover.height)
}
@Test
fun `video-zoom is a log2 factor on top of the fit`() {
val base = VideoRectPolicy.sizeFor(1920, 1080, 1920, 1080)!!
val doubled = VideoRectPolicy.sizeFor(1920, 1080, 1920, 1080, videoZoomLog2 = 1f)!!
val halved = VideoRectPolicy.sizeFor(1920, 1080, 1920, 1080, videoZoomLog2 = -1f)!!
assertEquals(base.width * 2, doubled.width)
assertEquals(base.width / 2, halved.width)
}
@Test
fun `cover fills a container whose aspect is wildly mismatched`() {
// Scope content in a portrait container: cover/fit exceeds 4, which a
// fit-relative clamp would truncate back into letterboxing.
val size = VideoRectPolicy.sizeFor(1080, 2400, 2390, 1000, panscan = 1f)!!
assertTrue("height must reach the container", size.height >= 2400)
}
@Test
fun `an absurd zoom is bounded rather than allocating an unbounded surface`() {
val fit = VideoRectPolicy.sizeFor(1920, 1080, 1920, 1080)!!
val absurd = VideoRectPolicy.sizeFor(1920, 1080, 1920, 1080, videoZoomLog2 = 12f)!!
assertEquals(fit.width * 4, absurd.width)
}
@Test
fun `unknown dimensions yield no size instead of a degenerate one`() {
assertNull(VideoRectPolicy.sizeFor(0, 1080, 1920, 1080))
assertNull(VideoRectPolicy.sizeFor(1920, 1080, 0, 0))
assertNull(VideoRectPolicy.sizeFor(1920, 0, 1920, 1080))
}
}
@@ -0,0 +1,149 @@
package com.edde746.plezy.shared
import com.edde746.plezy.shared.DisplayModeSelector.ModeInfo
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Test
class DisplayModeSelectorTest {
// A typical 4K TV: panel-native modes plus lower-resolution HDMI modes.
private val uhd60 = ModeInfo(1, 3840, 2160, 60f)
private val uhd50 = ModeInfo(2, 3840, 2160, 50f)
private val uhd24 = ModeInfo(3, 3840, 2160, 23.976f)
private val fhd60 = ModeInfo(4, 1920, 1080, 60f)
private val fhd50 = ModeInfo(5, 1920, 1080, 50f)
private val fhd24 = ModeInfo(6, 1920, 1080, 23.976f)
private val hd60 = ModeInfo(7, 1280, 720, 60f)
private val sd60 = ModeInfo(8, 720, 480, 60f)
private val allModes = listOf(uhd60, uhd50, uhd24, fhd60, fhd50, fhd24, hd60, sd60)
private fun select(
fps: Float,
current: ModeInfo = uhd60,
modes: List<ModeInfo> = allModes,
videoWidth: Int = 0,
videoHeight: Int = 0,
matchResolution: Boolean = false
) = DisplayModeSelector.findBestMode(fps, current, modes, videoWidth, videoHeight, matchResolution)
// --- Resolution matching ---
@Test
fun resolutionMatchingPicksNativeResolutionAndRate() {
val selection = select(23.976f, videoWidth = 1920, videoHeight = 1080, matchResolution = true)
assertEquals(fhd24, selection?.mode)
}
@Test
fun resolutionOnlyRequestKeepsCurrentRefreshRate() {
val selection = select(0f, videoWidth = 1920, videoHeight = 1080, matchResolution = true)
assertEquals(fhd60, selection?.mode)
}
@Test
fun resolutionMatchingNeverDownscalesTheVideo() {
// 1080p-class anamorphic content is wider than 720p even though shorter:
// the smallest containing mode is 1080p, not 720p.
val selection = select(0f, videoWidth = 1920, videoHeight = 800, matchResolution = true)
assertEquals(fhd60, selection?.mode)
}
@Test
fun resolutionWinsOverCadenceWhenNativeResolutionHasNoMatchingRate() {
// No 720p24 mode exists; the 720p video still lands on 720p (TV upscales)
// instead of widening back out to a 24 Hz mode at another resolution.
val selection = select(23.976f, videoWidth = 1280, videoHeight = 720, matchResolution = true)
assertEquals(hd60, selection?.mode)
}
@Test
fun panelNativeContentStaysAtPanelResolution() {
val selection = select(23.976f, videoWidth = 3840, videoHeight = 2160, matchResolution = true)
assertEquals(uhd24, selection?.mode)
}
@Test
fun panelNativeResolutionOnlyRequestNeedsNoSwitch() {
val selection = select(0f, videoWidth = 3840, videoHeight = 2160, matchResolution = true)
assertEquals(uhd60, selection?.mode) // caller sees modeId == current and skips
}
@Test
fun sourceLargerThanPanelFallsBackToCadencePolicy() {
val selection = select(23.976f, videoWidth = 7680, videoHeight = 4320, matchResolution = true)
assertEquals(uhd24, selection?.mode) // Tier-1 refresh-only switch
}
@Test
fun sourceLargerThanPanelWithoutFpsHasNoTarget() {
assertNull(select(0f, videoWidth = 7680, videoHeight = 4320, matchResolution = true))
}
@Test
fun resolutionMatchingWithoutDimensionsBehavesLikeCadenceOnly() {
val selection = select(23.976f, matchResolution = true)
assertEquals(uhd24, selection?.mode)
}
@Test
fun resolutionOnlyPrefersRateClosestToCurrent() {
// From a 50 Hz current mode, a resolution-only switch keeps 50 Hz.
val selection = select(0f, current = uhd50, videoWidth = 1920, videoHeight = 1080, matchResolution = true)
assertEquals(fhd50, selection?.mode)
}
// --- Cadence-only policy (matchResolution off): pre-existing behaviour ---
@Test
fun cadenceMatchingStaysAtCurrentResolution() {
val selection = select(23.976f, videoWidth = 1920, videoHeight = 1080)
assertEquals(uhd24, selection?.mode)
}
@Test
fun cadenceTierTwoAllowsResolutionChangeButNeverBelowVideo() {
// Panel has no 4K@24; only 1080p@24 remains for 1080p content.
val modes = listOf(uhd60, uhd50, fhd60, fhd24, hd60)
val selection = select(23.976f, modes = modes, videoWidth = 1920, videoHeight = 1080)
assertEquals(fhd24, selection?.mode)
}
@Test
fun cadenceTierTwoRequiresKnownDimensions() {
val modes = listOf(uhd60, uhd50, fhd60, fhd24, hd60)
assertNull(select(23.976f, modes = modes))
}
@Test
fun invalidFpsWithoutResolutionRequestHasNoTarget() {
assertNull(select(0f, videoWidth = 1920, videoHeight = 1080))
}
@Test
fun multipleRateCountsAsCadenceMatch() {
// 30 fps on a 60 Hz mode is a clean 2x pulldown; current 60 Hz mode wins.
val selection = select(29.97f, current = uhd60, modes = listOf(uhd60, uhd50))
assertNotNull(selection)
assertEquals(uhd60, selection?.mode)
}
@Test
fun exactRateBeatsMultipleRate() {
val uhd30 = ModeInfo(9, 3840, 2160, 29.97f)
val selection = select(29.97f, modes = allModes + uhd30)
assertEquals(uhd30, selection?.mode)
}
// --- matchRefreshRate ---
@Test
fun refreshRateMatchClassifiesExactMultipleAndMiss() {
assertEquals(0, DisplayModeSelector.matchRefreshRate(23.976f, 23.976f)?.priority)
assertEquals(1, DisplayModeSelector.matchRefreshRate(59.94f, 29.97f)?.priority)
assertNull(DisplayModeSelector.matchRefreshRate(60f, 23.976f))
assertNull(DisplayModeSelector.matchRefreshRate(60f, 0f))
assertNull(DisplayModeSelector.matchRefreshRate(0f, 24f))
}
}
@@ -0,0 +1,94 @@
package com.edde746.plezy.shared
import android.app.Activity
import android.os.Handler
import android.os.Looper
import java.time.Duration
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
/**
* Teardown ordering for frame-rate matching (#2172): restoring the display
* mode while the display is still signaling HDR folds the HDR exit and the
* mode change into one slow HDMI renegotiation. An HDR session therefore
* defers the restore; an SDR session restores immediately.
*/
@RunWith(RobolectricTestRunner::class)
class FrameRateManagerRestoreTest {
private fun buildManager(activity: Activity): FrameRateManager = FrameRateManager(activity, Handler(Looper.getMainLooper()))
private fun preferredModeId(activity: Activity): Int = activity.window.attributes.preferredDisplayModeId
private fun applyPreferredMode(activity: Activity, modeId: Int) {
val attrs = activity.window.attributes
attrs.preferredDisplayModeId = modeId
activity.window.attributes = attrs
}
@Test
fun sdrClearRestoresTheDefaultModeImmediately() {
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
val manager = buildManager(activity)
applyPreferredMode(activity, 4)
manager.clearVideoFrameRate(hdrActive = false)
assertEquals(0, preferredModeId(activity))
}
@Test
fun hdrClearDefersTheRestoreUntilTheHdrExitSettles() {
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
val manager = buildManager(activity)
applyPreferredMode(activity, 4)
manager.clearVideoFrameRate(hdrActive = true)
// Still at the content mode: the surface teardown must commit the HDR
// exit before the mode change renegotiates the link.
assertEquals(4, preferredModeId(activity))
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(500))
assertEquals(0, preferredModeId(activity))
}
@Test
fun newSwitchRequestCancelsAPendingDeferredRestore() {
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
val manager = buildManager(activity)
applyPreferredMode(activity, 4)
manager.clearVideoFrameRate(hdrActive = true)
// A new session's request arrives before the deferred restore fires.
manager.setVideoFrameRate(fps = 23.976f, videoDurationMs = 0L, extraDelayMs = 0L) { }
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(500))
// The stale restore must not clobber whatever the new request applied.
// (Robolectric's display has no matching mode, so the request itself
// leaves the window untouched; only the cancelled restore could zero it.)
assertNotEquals(0, preferredModeId(activity))
}
@Test
fun hdrClearWithNoAppliedModePostsNoRestore() {
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
val manager = buildManager(activity)
applyPreferredMode(activity, 7)
// Simulate "nothing applied by us": manager sees modeId 0.
applyPreferredMode(activity, 0)
manager.clearVideoFrameRate(hdrActive = true)
// A later, externally applied mode must not be clobbered by a stale
// deferred restore from a session that never switched.
applyPreferredMode(activity, 7)
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(500))
assertEquals(7, preferredModeId(activity))
}
}
@@ -1,5 +1,6 @@
package com.edde746.plezy.shared
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
@@ -60,4 +61,18 @@ class MediaCodecQueryTest {
assertFalse(MediaCodecQuery.isHardwareAccelerated(28, true, "OMX.google.h264.decoder"))
assertTrue(MediaCodecQuery.isHardwareAccelerated(28, false, "OMX.qcom.video.decoder.avc"))
}
@Test
fun mapsGatedCodecsToTheMimeTypesDecodersAdvertise() {
assertEquals(
mapOf("hevc" to true, "av1" to true),
MediaCodecQuery.hardwareVideoDecodeSupport(
setOf("video/avc", "video/hevc", "video/av01", "audio/mp4a-latm")
)
)
assertEquals(
mapOf("hevc" to true, "av1" to false),
MediaCodecQuery.hardwareVideoDecodeSupport(setOf("video/avc", "video/hevc"))
)
}
}
@@ -4,6 +4,7 @@ import android.app.Activity
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.ViewGroup
import android.widget.FrameLayout
import org.junit.Assert.assertEquals
@@ -41,4 +42,27 @@ class PlayerSurfaceHostTest {
assertEquals(FrameLayout.LayoutParams.MATCH_PARENT, surface.layoutParams.width)
assertEquals(FrameLayout.LayoutParams.MATCH_PARENT, surface.layoutParams.height)
}
@Test
fun letterboxAreaIsCoveredByABufferlessPunchSurfaceBeneathTheVideo() {
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
activity.setContentView(FrameLayout(activity))
val callback = object : SurfaceHolder.Callback {
override fun surfaceCreated(holder: SurfaceHolder) = Unit
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) = Unit
override fun surfaceDestroyed(holder: SurfaceHolder) = Unit
}
val container = PlayerSurfaceHost.createContainer(activity)
val punch = container.getChildAt(0)
assertTrue(punch is SurfaceView)
assertEquals(FrameLayout.LayoutParams.MATCH_PARENT, punch.layoutParams.width)
assertEquals(FrameLayout.LayoutParams.MATCH_PARENT, punch.layoutParams.height)
// Cores append their surfaces after createContainer, so video (and the mpv
// OSD plane) always land above the punch layer in drawing order.
val video = PlayerSurfaceHost.createVideoSurface(activity, callback)
container.addView(video)
assertTrue(container.indexOfChild(video) > container.indexOfChild(punch))
}
}
+81
View File
@@ -0,0 +1,81 @@
#!/usr/bin/env python3
"""Regenerates the DTS-HD MA packer fixtures (#1988).
FFmpeg has no DTS-HD MA encoder, so the access-unit fixture is synthesized: real
DTS core frames from FFmpeg's `dca` encoder, each followed by a hand-built
extension substream (EXSS) whose header fields are coherent enough for FFmpeg's
DCA parser to glue core+EXSS into one access unit. The IEC 61937 wrapping never
inspects EXSS payload bytes, only the sync word and size fields, so this pins
the same wire format genuine Master Audio does.
One mid-stream access unit is oversized so `ffmpeg -f spdif` overflows the
burst and strips to core-only for `dtshd_fallback_time` (60s, i.e. the rest of
the fixture) the golden therefore also pins the strip-and-hold behavior.
Usage (from this directory):
ffmpeg -y -f lavfi -i "aevalsrc=0.3*sin(2*PI*440*t)|0.3*sin(2*PI*554*t)|0.3*sin(2*PI*659*t)|0.2*sin(2*PI*220*t)|0.25*sin(2*PI*330*t)|0.25*sin(2*PI*392*t):s=48000:d=0.15" \
-c:a dca -strict experimental -f dts /tmp/dts_core.dts
python3 dtshd_fixture_generator.py /tmp/dts_core.dts
ffmpeg -y -f dts -i dtshd_ma_access_units.bin -c:a copy \
-f spdif -dtshd_rate 768000 dtshd_ma_iec61937_golden.bin
"""
import struct
import sys
CORE_SYNC = 0x7FFE8001
EXSS_SYNC = 0x64582025
# Payload bytes past which a 32768-byte burst (512 samples at 48kHz on the
# 768kHz HBR carrier) overflows: 32768 - 8 preamble - 12 start code/length.
BURST_CAPACITY = 32768 - 8 - 12
NORMAL_EXSS_SIZE = 2020
# Large enough that core (1884) + EXSS exceeds the burst capacity.
OVERSIZED_EXSS_SIZE = BURST_CAPACITY
OVERSIZED_AU_INDEX = 4
def build_exss(size: int) -> bytes:
"""A minimal EXSS frame: sync, then the narrow (bHeaderSizeType=0) header.
Bit layout after the 32-bit sync: UserDefinedBits(8), nExtSSIndex(2),
bHeaderSizeType(1), nuBits4Header(8) = header bytes - 1,
nuBits4ExSSFsize(16) = frame bytes - 1. Everything else is padding the
parser and packer never read.
"""
header_size = 16
bits = 0
bits = (bits << 8) | 0 # UserDefinedBits
bits = (bits << 2) | 0 # nExtSSIndex
bits = (bits << 1) | 0 # bHeaderSizeType
bits = (bits << 8) | (header_size - 1)
bits = (bits << 16) | (size - 1)
packed = bits.to_bytes(5, "big") # 35 bits, left-aligned below
body = bytearray(size)
struct.pack_into(">I", body, 0, EXSS_SYNC)
shifted = int.from_bytes(packed, "big") << (40 - 35)
body[4:9] = shifted.to_bytes(5, "big")
return bytes(body)
def main() -> None:
core = open(sys.argv[1], "rb").read()
out = bytearray()
offset = 0
index = 0
while offset + 9 <= len(core):
sync = struct.unpack_from(">I", core, offset)[0]
assert sync == CORE_SYNC, hex(sync)
b24 = (core[offset + 5] << 16) | (core[offset + 6] << 8) | core[offset + 7]
fsize = ((b24 >> 4) & 0x3FFF) + 1
out += core[offset : offset + fsize]
exss_size = OVERSIZED_EXSS_SIZE if index == OVERSIZED_AU_INDEX else NORMAL_EXSS_SIZE
out += build_exss(exss_size)
offset += fsize
index += 1
open("dtshd_ma_access_units.bin", "wb").write(out)
print(f"{index} access units, {len(out)} bytes")
if __name__ == "__main__":
main()
Binary file not shown.
Binary file not shown.
+3 -3
View File
@@ -12,7 +12,7 @@ android {
compileSdk = 36
// Matches the app's latest stable NDK so every project-owned native library
// is built with the same 16 KB page-size-capable libc++ toolchain. That copy
// is NOT what ships: the app packages the libmpv AAR's newer copy with top
// is NOT what ships: the app packages the mpv-build tarball's newer copy with top
// merge priority (see app/build.gradle.kts packaging { jniLibs } + sourceSets).
ndkVersion = "29.0.14206865"
@@ -54,8 +54,8 @@ kotlin {
dependencies {
implementation("androidx.annotation:annotation:1.10.0")
implementation("androidx.annotation:annotation-experimental:1.6.0")
implementation("androidx.media3:media3-exoplayer:1.10.1")
implementation("androidx.media3:media3-ui:1.10.1")
implementation("androidx.media3:media3-exoplayer:1.11.0")
implementation("androidx.media3:media3-ui:1.11.0")
testImplementation("junit:junit:4.13.2")
}
@@ -89,6 +89,9 @@ class AssRender(nativeAss: Long, private val lock: ReentrantLock) {
lock.withLock { this.track = track }
}
/** False after [setTrack] with null (subtitles disabled) — renders would return null. */
val hasTrack: Boolean get() = lock.withLock { track != null }
fun setFontScale(scale: Float) {
generation.incrementAndGet()
withNative { nativeAssRenderSetFontScale(it, scale) }
@@ -313,8 +313,9 @@ internal class AssAtlasPipeline(
/**
* Re-renders the last requested position for renderer state changes (margins,
* use-margins) that must become visible while playback is paused. Safe during
* playback: the next video frame's [requestRender] supersedes it (latest-wins).
* use-margins, a disabled track) that must become visible while playback is
* paused. Safe during playback: the next video frame's [requestRender]
* supersedes it (latest-wins).
*/
fun invalidate() {
libassThread.invalidate()
@@ -582,6 +583,12 @@ private class AtlasLibassThread(
@Volatile private var lastRequestedPtsUs = UNSET
private var contentSeqCounter = 0L
/** True once any payload reached the GL thread — the overlay may be showing content. */
private var hasEverPosted = false
/** State generation a trackless blank clear was posted for; MIN_VALUE = none pending. */
private var tracklessClearedGeneration = Long.MIN_VALUE
// Thread-confined; created on first render so non-ASS playback never allocates.
private var engine: SpecRenderEngine? = null
private var engineStateGeneration = Long.MIN_VALUE
@@ -760,7 +767,22 @@ private class AtlasLibassThread(
val waitMs = (tDrain - request.enqueueNs) / 1_000_000
// Before any ASS render exists (SRT/VTT or no subs) do nothing — this also
// keeps the slot buffers unallocated for non-ASS playback.
if (assHandler.render == null) return
val render = assHandler.render ?: return
if (!render.hasTrack) {
// Subtitles were disabled mid-cue: every render now returns null, so no
// payload would ever reach the GL thread again and the last swapped cue
// would sit on the overlay until playback ends (#1884). Swap one explicit
// blank frame instead. Keyed on the state generation ([AssRender.setTrack]
// bumped it) so a clear the GL thread drops as stale is retried by the
// next request; reset below once a track is live again.
val tracklessGeneration = stateGeneration()
if (hasEverPosted && tracklessClearedGeneration != tracklessGeneration) {
tracklessClearedGeneration = tracklessGeneration
postBlankClear(request, tracklessGeneration)
}
return
}
tracklessClearedGeneration = Long.MIN_VALUE
val slots = acquireSlots()
val generation = stateGeneration()
val engine = ensureEngine(slots, generation)
@@ -790,6 +812,7 @@ private class AtlasLibassThread(
payload.requestSeq = request.sequence
payload.stateGeneration = generation
onFrameReady(payload)
hasEverPosted = true
if (AssAtlasPipelineConfig.TIMING_LOGS) {
Log.d(
TAG,
@@ -828,6 +851,29 @@ private class AtlasLibassThread(
maybePrefetch(engine, slots, pts, pinned)
}
/**
* Hands the GL thread a zero-quad payload [AtlasRenderer.onDrawFrame] clears
* and draws nothing so a cue still on screen when its track is disabled goes
* away immediately instead of outliving the selection (#1884).
*/
private fun postBlankClear(request: PendingFrame, generation: Long) {
val slots = acquireSlots()
// Never rewrite the slot the GL thread may still be reading (slotCount >= 2).
val payload = slots.payloads.first { it.slotIndex != glTakenSlot() }
payload.frame = AssAtlasFrame(0, 0, 0, 0, 0)
payload.contentSeq = ++contentSeqCounter
payload.sourcePresentationTimeUs = request.sourcePtsUs
payload.presentationTimeUs = request.ptsUs
payload.releaseTimeNs = request.releaseNs
payload.phaseLeadUs = request.phaseLeadUs
payload.requestSeq = request.sequence
payload.stateGeneration = generation
onFrameReady(payload)
if (AssAtlasPipelineConfig.TIMING_LOGS) {
Log.d(TAG, "trackless-clear req=${request.sequence} pts=${request.ptsUs / 1000}ms gen=$generation")
}
}
/** Start time of the last event boundary we cache-warmed (libass/track ms). */
private var lastPrefetchedStartMs = Long.MIN_VALUE
@@ -45,7 +45,8 @@ class AssSubtitleSurfaceView(
pipeline?.requestRender(presentationTimeUs, releaseTimeNs)
}
/** Re-renders the last position, e.g. after margin changes while paused. */
/** Re-renders the last position margin changes while paused, or clearing a
* still-visible cue right after subtitles were disabled (#1884). */
fun invalidateSubtitles() {
pipeline?.invalidate()
}

Some files were not shown because too many files have changed in this diff Show More