Compare commits

..
287 Commits
Author SHA1 Message Date
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
edde746 fe3460ad12 fix(linux): drop the unreachable 8-bit render-context retry
The retry added while chasing the 2.13.0 hwdec regression never fires:
mpv probes hwdec interop lazily at the first decode attempt, and its
failure does not fail mpv_render_context_create, so the deep config never
gets rejected and the 8-bit tier is never reached. The actual regression
was the libmpv build losing the DRM providers, fixed in the previous
commit. Remove the dead retry and its prefer_deep plumbing, and correct
the pre-flight comment that claimed the interop probe runs at context
creation.
2026-08-14 21:49:46 +02:00
edde746 ae001d9ff3 fix(linux): restore VAAPI hardware decode and AV1 software fallback in the bundled libmpv
Hardware decoding stopped working for Linux users on 2.13.0 (Fedora 44
report): every source decodes in software, and AV1 plays black video with
audio. Two defects in the pinned libmpv build.

First, mpv's meson 'drm' feature silently disabled itself because the CI
builder lacks libdisplay-info, and every VAAPI path that does not depend
on a display server is derived from it: vaapi-copy's standalone render-node
device (the path 2.12.1 worked on) and the GL dmabuf interop for direct
vaapi. With only the Wayland VA provider compiled in, a machine whose
Wayland VA display fails to initialize has no fallback, and vaapi-copy
has an empty provider list - every source lands on software decoding.
Pin -Ddrm=enabled, -Dvaapi-drm=enabled, -Degl=enabled and
-Dvaapi-wayland=enabled, and add libdisplay-info-dev to the CI package
lists, so a missing piece fails the build instead of shipping silent
software decode.

Second, the bundled static FFmpeg has no AV1 software decoder: its native
av1 codec is hardware-accelerated only, so once hwdec fails there is no AV1
path at all - every packet errors, video hits EOF, the plane goes black
while audio keeps playing. Pin dav1d 1.5.4 (both VideoLAN remotes agree on
the tag object and root commit), build it static before ffmpeg, and pass
--enable-libdav1d.

The build-plan stub test now asserts the hwdec feature flags, the dav1d
static build, and ffmpeg's libdav1d. Verified in an ubuntu:24.04 container
with the production flag sets: meson reports drm, vaapi-drm, vaapi-wayland,
egl and dmabuf-interop-gl enabled, and ffmpeg configures CONFIG_LIBDAV1D=yes
with the AV1 VAAPI hwaccel.

close #1874
2026-08-14 21:49:41 +02:00
edde746 18c9f710bb style(linux): clang-format the native rendering changes 2026-08-14 19:50:28 +02:00
edde746 7937a7e30a style(dart): apply dart format to the Linux rendering changes 2026-08-14 19:30:32 +02:00
edde746 991184b451 fix(linux): repair native compile errors caught by the CI build
The first GitHub Actions build of the Linux path failed on six issues the
macOS host could not catch:

- HandleFrameDone is a static handler; CancelFrameAckWatchdog() needed the
  explicit self-> qualification.
- handle_texture_ready_result/handle_ready_timeout call
  release_video_resources before its definition; forward-declared.
- finish_leg captured self without using it (Werror).
- CanCommandOutputProperties was private; made public for the kUnknown
  live-core check.
- MPV_ERROR_UNKNOWN does not exist in libmpv; the timeout now reports
  MPV_ERROR_UNSUPPORTED (any non-success serves the latch; the log line
  names the reason).
- The hdr-tone-mapping error path referenced the handler's FlValue value
  inside an async lambda; an owned std::string copy is captured instead.
- The texture register-failure response used a heap string freed before the
  handler responded; use a literal.
2026-08-14 19:29:39 +02:00
edde746 c3dbbf6479 test(music): implement Player.textureId on the fake audio player 2026-08-14 18:20:12 +02:00
edde746 f56264dcce test(player): cover embedded-VO ownership, colour sanitization and styling refusals
Three new Linux startup cases, one isolate each (a second VideoPlayerScreen
in one isolate never reaches initialize):

- A custom mpv config naming vo/gpu-context/gpu-api cannot detach the
  embedded renderer: the writes are withheld by name while ordinary entries
  (sub-scale) still land.
- Unparseable stored subtitle colours (named, 3-digit hex) reach the wire
  canonicalized to the defaults, proving the OPT_COLOR sanitization.
- A refused sub-color write no longer aborts initialization: the write is
  attempted, contained, and playback continues past the styling block.
2026-08-14 18:18:09 +02:00
edde746 9cdfe7591e feat(linux): restore the Flutter-texture path as the SDR fallback
2.13.0 deleted the display-agnostic EGL/Flutter-texture renderer and made
the native Wayland plane the only path, hard-rejecting every session that
cannot host one - X11, XWayland (SteamOS Gaming Mode runs native apps
through Gamescope's XWayland), or a plane whose EGL bootstrap failed. This
restores the 2.11.0 texture path from git history as the fallback:

- Re-add mpv_texture.cc/.h and mpv_gpu_bootstrap.cc/.h (2.11.0 verbatim):
  an FlTextureGL whose populate renders mpv into an offscreen FBO sampled
  by Flutter via an EGL image.
- MpvPlayer gains the texture-mode render-context API (InitRenderContext,
  HasRenderContext, GetEglDisplay/Context, Render(w,h,fbo)) beside the
  plane's InitRenderContextForSurface/RenderToSurface. The isolated ES 2.0
  context on Flutter's display and the X11 display param are exactly the
  2.11.0 configuration hardware decode demonstrably worked in.
- initialize now tries the plane first and falls back to the texture path
  when it cannot be brought up, returning the texture id (Dart's 2.11.0
  'result is int' contract) with waitForVideoReady gating playback until
  the GPU bootstrap settles. Both paths share one mpv core, so the
  plane/texture decision precedes render-context creation.
- hdr-enabled/hdr-tone-mapping are intercepted in texture mode (no plane,
  no HDR); the HDR toggle hides itself via isHDRSupported.
- New Linux setting 'Video rendering mode' (Automatic / Texture) forces
  the fallback - the user-visible workaround for plane-only trouble and
  for the hwdec interop regression, plus translations in all locales.

SDR only on the fallback, matching 2.11.0; the plane path is unchanged.
2026-08-14 18:16:32 +02:00
edde746 48f365ab30 fix(linux): bound HDR transactions and restore hwdec interop fallback
Three failure modes in the 2.13.0 Wayland path, three fixes:

- The mpv leg of an HDR transaction had no timeout: the surface watchdog
  re-armed while it ran, but the HDR method call stayed unanswered when mpv
  never replied, leaving the transaction queue stuck behind a ghost forever.
  A 5 s timeout (sharing the surface's horizon) aborts the transition,
  withdraws any description, resumes presentation, and answers the request
  exactly once via a shared latch; a late mpv reply self-heals through the
  stale-token re-apply path.

- The kUnknown quarantine hid the plane for the whole session when mpv
  stopped answering - the AV1-transparent report was a plane hidden this
  way while sound kept playing. Hiding is now reserved for a core that is
  genuinely going away; a live one presents undescribed (sRGB by protocol),
  and a playback restart clears the quarantine so one poisoned source
  cannot hide every later one. Product decision: visible-wrong beats
  invisible.

- hwdec's dmabuf interop probe runs at mpv_render_context_create time
  against the plane's fresh EGL display/context, and drivers that fail it
  on a deep config silently land every source on software decoding (the
  Fedora 44 report; 2.12.1 created the context on Flutter's display). The
  prerequisites are now logged explicitly at creation, and a failed render
  context is retried once on the 8-bit config tier - the 2.12.1-equivalent
  configuration - with HDR off by the depth gate.
2026-08-14 18:11:14 +02:00
edde746 093109ae09 fix(linux): bound plane presentation against unacknowledged frames
Present() arms wl_surface.frame and frame_pending_ is cleared only by the
frame callback. Compositors are entitled to stop acknowledging frames for
occluded or minimized surfaces - wlroots-lineage compositors (Hyprland) do
exactly that - and nothing bounded the wait: one missed callback froze the
plane on its last buffer forever, because every later render bailed on
frame_pending(). That is the 2.13.0 black-video report on Hyprland: the
first commit is the pre-allocated 1x1 (or pre-video black) buffer, fully
occluded by the opaque Flutter surface, and the callback it armed never
arrives.

Two changes, one stall:

- A 500 ms frame-acknowledgement watchdog in Present(): on expiry the dead
  callback is withdrawn and a fresh present is asked for, so the plane
  re-commits instead of sitting on the latch. A miss budget (5) stops
  poking a surface the compositor is still ignoring; a real
  acknowledgement resets it.

- The very first present is refused until mpv actually has a frame: the
  first forced render happens at setVideoRect time, before anything is
  decoded, and committing that empty buffer is exactly the commit an
  occluded surface ignores. The sticky plane_needs_render flag keeps the
  owed resize refresh pending until content exists, so the first present
  still happens at the right size the moment the first frame lands.
2026-08-14 18:11:06 +02:00
edde746 14cae85931 fix(player): never fail playback on preference writes; keep vo authoritative
mpv 0.40's OPT_COLOR parser rejects anything but #RRGGBB/#AARRGGBB, so a
stored subtitle colour that does not parse made mpv refuse the write with
MPV_ERROR_PROPERTY_FORMAT — and the bare await in _runPlayerInitializationAttempt
turned that into the initialization error screen on every open. Subtitle
styling, volume-max, and the pre-open defaults (start/pause/sid) are now
sanitized (colours canonicalized to hex with fallback to the default) and
non-fatal, matching the existing hdr-enabled tolerance policy: a refused
preference write must never become "this session cannot play video".

The user mpv.conf editor is applied as runtime mpv_set_property writes, and
vo/gpu-context/gpu-api were not withheld, so a vo=gpu-next line re-created
mpv's output as a separate uncontrollable window and orphaned the embedded
render context. Add the VO family to the Linux-owned property set with a
key-aware skip log, a native reject for vo != libmpv on the video core (the
render API is OpenGL-only; gpu-next is windowed by construction), and a hint
in the mpv.conf editor explaining why, with translations across all locales.
2026-08-14 18:07:16 +02:00
edde746 9090ad6283 fix(linux): name refused property writes and surface the hwdec path
The SET_PROPERTY_FAILED error surfaced to Dart carries only mpv's own text
("unsupported format for accessing property"), which names the failure
mode, never the property. Every report of a refused write is therefore a
guessing game. Include name=value in the error description on all three
setProperty branches (generic, hdr-enabled, hdr-tone-mapping) and warn with
the same pair from MpvPlayer::SetPropertyAsync so the HDR transaction's
target-* writes — which never reach the channel — are attributable too.

mpv_request_log_messages is a single global level, and the vaapi probe and
"Using software decoding" fallback are MSGL_INFO, so at "warn" a silently
software-decoding session leaves no trace in the app log. Raise the request
level to "info" and observe hwdec-current natively, logging every decode
path transition from the player instead of relying on an overlay readout.
2026-08-14 18:07:09 +02:00
edde746 8f9ffc76eb fix(emby): show scrub previews from the /Videos/{id}/index.bif transport
Scrubbing an Emby video showed no preview thumbnails on the timeline
while Plex and Jellyfin both worked: Emby's scrubThumbnails capability
was off, so the player never attempted a load. It was off because the
4.9.5 test server answered the preview endpoints with empty payloads —
its extraction task had not run.

Emby's preview transport is a Roku-format BIF at
/Videos/{id}/index.bif?Width=320, the same wire format Plex serves, so
the existing BIF parser handles it unchanged. Enable the capability and
route Emby previews through the shared BifThumbnailService, whose load
now takes a bytes callback instead of a Plex-typed client. MediaBrowser
sources also carry videoAspectRatio from the video stream so the
tooltip sizes itself to the stream. A server without extracted frames
still answers a header-only BIF, which parses to zero frames and keeps
the tooltip suppressed.

close #1930
2026-08-14 13:36:29 +02:00
edde746 12d9865a41 fix(subtitles): render Korean glyphs on the MPV path via bundled Hangul font
GoNotoCurrent lacks Hangul syllables, and the Android libmpv build has no
fontconfig/system-font fallback, so libass could not resolve any Korean
glyph and subtitles rendered as boxes. Ship a Hangul subset of
GoNotoKurrent-Regular beside the default font in the extracted subtitle
fonts directory; libass picks it up as fallback by glyph coverage.

close #1932
2026-08-14 13:02:26 +02:00
edde746 688bfdacb4 fix(profiles): keep offline downloads visible when a profile's servers are unreachable
Switching to a profile whose only server is offline verified the PIN,
failed the bind with zero reachable servers, and rolled back to the
previous profile — whose scope owns none of the downloads. The Downloads
UI then showed nothing while the files and pinned metadata sat intact on
disk. Startup offline mode only covered the cold-start bind, so such a
profile could never be entered while its server was away.

The binder now classifies a settled bind failure as connectivity-only
when the profile expected servers, reached none, and none were
auth-rejected (snapshotting auth markers before the visibility sweep,
which clears them via removeServer). On such a failure,
switchProfileFromUi keeps the profile active when it owns downloads
instead of rolling back; OfflineModeProvider drives the offline UI from
the empty visible-server set. Auth failures, PIN cancels, and
downloads-free profiles keep the existing rollback and error snackbar.

close #1927
2026-08-14 12:20:20 +02:00
edde746 cd4432f27c fix(auth): keep polling Plex PIN after transient network errors 2026-08-14 12:20:20 +02:00
edde746 5f6d9dc610 fix(navigation): keep the sidebar Libraries section collapsed across restarts
Collapsing Libraries in the sidebar only lasted until the app closed. The
next launch always came back expanded, which buries the rest of the nav
menu for anyone running a lot of libraries.

The expansion flag was plain widget state on SideNavigationRailState. It
survived tab navigation only because MainScreen pins the rail with a
GlobalKey, and died on relaunch, profile switch or a layout change. It now
lives in the librariesSectionExpanded preference, so the rail reads and
writes the persisted value and follows a settings reset or import too.

close #1896
2026-08-13 21:44:25 +02:00
edde746 ce151a91e8 fix(player): show AAC instead of mp4a.40.2 in ExoPlayer track labels
ExoPlayer reports RFC 6381 codec IDs (mp4a.40.2, ec-3, dtsc) where mpv
reports ffmpeg names, so the audio track picker and performance overlay
showed raw identifiers instead of friendly names on the ExoPlayer path.

Normalize RFC 6381 audio IDs in CodecUtils.formatAudioCodec, route the
performance overlay's audio codec through it, and cover the video IDs
(hvc1/hev1, av01, vp09) that fell through the overlay's matcher.

close #1899
2026-08-13 21:23:08 +02:00
edde746 922789c014 fix(tv): stop the server session when a backgrounded TV releases the player
On Fire OS, standby never freezes a backgrounded app, so the paused
heartbeats that kept a suspended session "alive and resumable" pinned it
in the server dashboard indefinitely. The live session bought nothing:
the restore path already performs a fresh playback decision.

When the TV background grace expires, stop the heartbeat timer (its
paused tick also keeps a Plex transcode session alive) and report the
session stopped before releasing the native pipeline, since stop()
resets the player state the report reads. Standby entry can drop Wi-Fi
into power-save and mutations never fail over, so a failed terminal
report is redelivered on a bounded schedule, gated on actual backend
delivery and on the suspend still standing so a restored session is
never reported stopped.

close #1911
2026-08-13 20:34:12 +02:00
edde746 a49f506a0b fix(tv): keep quality labels visible when rating badges crowd the detail line
On TV, a movie carrying a full set of attributed scores pushed the resolution and audio labels past the right edge of the detail metadata line, which silently clipped them.

The line now sheds its least useful parts when it overflows -- surplus rating badges first, then the whole ratings slot, then quality labels -- instead of hard-clipping the tail. It also leads with the year instead of the redundant "Movie"/"TV Show" label, matching the desktop hero chip order, and the Discover spotlight line gets the same fitting. Branded badge icons are pinned to their SVG viewBox aspect so the fit is measured exactly.

close #1893
2026-08-13 02:29:01 +02:00
edde746 8cdf04122f fix(tv): pause on the first Select press after skipping the intro
After activating Skip Intro with the remote, the next Select only raised
the player controls and pausing took a second press. The skip button
autofocuses on TV, and every path that hides it dropped focus out of the
controls subtree - the screen node reclaimed the remote and its self-heal
consumed the next key to raise the chrome instead of toggling playback.

Hand the remote back to the player surface whenever the skip button
disappears while focused: after a skip seek, when the playhead leaves the
marker window, and when the auto-dismiss timer hides the button. The
credits-at-end path is exempt because the play-next flow requests its own
focus.

close #1890
2026-08-12 23:03:44 +02:00
edde746 3e1481c238 fix(windows): bundle the MSVC runtime so an outdated redist stops crashing launch
A user's plezy.exe 2.13.0 crashed on every launch with an access violation
in C:\WINDOWS\SYSTEM32\MSVCP140.dll 14.29.30139.0 (VS 2019-era redist). CI
builds with the current VS 2022 toolset, and since 17.10 std::mutex uses a
constexpr layout that an older msvcp140.dll misreads, so the app dies inside
the DLL before the first frame. Nothing shipped the runtime: the bundle,
installer, portable archive, and MSIX all relied on whatever redist the
machine happened to have.

Install the MSVC runtime DLLs next to plezy.exe via
InstallRequiredSystemLibraries; app-local copies precede System32 in the DLL
search order, so the bundled version always wins. One install rule covers the
installer, portable 7z, and MSIX, which all package the Release directory.
The Windows bundle verification in build.yml now requires msvcp140.dll and
vcruntime140.dll so a silently missing redist dir fails CI instead of
shipping.
2026-08-12 23:00:36 +02:00
YorickandGitHub 0d24240af4 fix(linux): defer buffer_scale until first frame is presented (#1876)
* fix(linux): defer buffer_scale until the first frame is presented

The video plane's wl_egl_window starts as a 1x1 placeholder. When playback starts, SetRect() sends wl_surface.set_buffer_scale(2) and resizes the window, but mesa commits the EGL surface's pre-allocated 1x1 back buffer on the first eglSwapBuffers. A 1x1 buffer is not an integer multiple of scale 2, so the compositor raises WL_SURFACE_ERROR_INVALID_SIZE, tears down the Wayland connection and plezy exits (issue #1872). At display scale 100% the same 1x1 buffer is legal, which is why that workaround worked.

Defer sending the new scale until after the first commit: the first buffer is 1x1 at scale 1 (always legal), then the scale change lands on the wire and applies to the next commit, whose buffer mesa allocates at the resized window size. The one-frame 1x1 flash is mpv's black first frame - imperceptible.

* fix(linux): gate buffer_scale on a first-frame latch, reset state on destroy

Address review: buffer_attached_ cannot represent "first frame
presented" - DetachBuffer() clears it while the committed scale stays
on the wire, leaving a crash path (present at scale 2, detach, move to
a scale-1 display, then a swap commits a scale-1 buffer while scale 2
is still active).

Replace it with first_frame_presented_, set once a frame has been
presented and cleared only when the wl_surface is torn down, so scale
changes queue even with no buffer attached. Reset scale_sent_ to 1 in
Destroy() too: a freshly created wl_surface starts at scale 1, and a
stale value would suppress the first scale request after recreation.
2026-08-12 11:18:36 +02:00
edde746 9769c4e092 chore: bump MPVKit to 1.0.20 2026-08-12 08:56:33 +02:00
edde746 f291425f20 fix(tvos): increase AVFoundation presentation lead 2026-08-12 02:22:44 +02:00
1c1bba7e27 Update installation instructions for Arch Linux (#1870)
* Update installation instructions for Arch Linux

Arch now maintains an official package for plezy.

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-08-12 01:50:40 +02:00
edde746 26e98e898d fix(desktop): reserve root Escape for leaving fullscreen instead of quitting
Physical-keyboard Escape at root Home now exits window fullscreen on
Windows and Linux the way it already did on macOS, and never arms the
press-back-again quit — so Escape aimed at fullscreen can't close the
app. Remotes, gamepad B, and system back keep the double-press exit.

close #1748
2026-08-11 11:15:51 +02:00
edde746 6663353895 fix(player): retry episode advances that fail on a transient server blip
An EOF-driven advance does one cold metadata fetch with a single endpoint
failover and no transient retry. When connectivity to the server drops for
the ~20s that fetch needs (issue log: both plex.direct endpoints connect
timed out, then the running stream's own TLS socket died), the reload
rolled back to the finished episode's last frame: black screen, progress
bar parked at the end, no way forward but the transport controls - while
pressing Next by hand seconds later succeeded. The per-item metadata cache
row could not absorb the blip either, because adjacency comes from queue
containers, so the next episode's row is cold at the exact moment the
transition needs it.

Three changes:

- A failed in-place reload now records its classified failure reason, and
  an advance that ran with the completion latch set re-presents the Play
  Next prompt when that reason is serverUnavailable. With auto-play
  enabled the countdown re-fires the advance up to two times before the
  prompt goes manual-only; Watch Together sessions and mid-episode Next
  presses (whose rolled-back stream is still valid) keep the existing
  handling. playNextRetryPresentation owns the decision and is unit-tested.

- Committing adjacency now best-effort prefetches the next episode's full
  metadata row through fetchItem, which writes the exact row playback
  initialization falls back to on both backends (Plex: same cache key and
  full playback query shape; Jellyfin: the /Users/{uid}/Items/{id} row the
  playback bundle reads). A warm row turns a blip at the transition into a
  normal start.

- JellyfinClient.fetchItem's documented "pure transport error -> cached
  row" fallback was dead code: the HTTP layer wraps transport errors into
  MediaServerHttpException, which the first catch rethrew unconditionally.
  Status-less, non-cancelled failures now take the fallback; answered
  requests (401/403/5xx) and cancellations surface unchanged.

Verified with new contract tests (Plex: cold row fails transiently ->
fetchItem primes -> the same failing fetch serves playback from cache;
Jellyfin: primed row survives a transport failure into fetchPlaybackBundle)
plus the full test/screens/video_player and test/services suites and
analyzer parity.

close #1867
2026-08-11 09:08:07 +02:00
edde746 83c50d93a2 fix(subtitles): flatten atlas-overflow ASS frames into an RGBA composite
Signs built from hundreds of overlapping paint-stroke drawings (masked
smartphone screens and similar typesetting) sum to far more bitmap area
than the paged ALPHA_8 atlas can hold: the issue sample needs 5 pages of
16M px at 1080p and 19 at 4K against the 4-page cap, so the packer
dropped the painter-order tail - the sign's text and late mask strokes.

Move the packer out of the JNI file into AssPack.c (pure C, compilable
against a desktop libass for verification) and add a composite fallback:
when a frame can never fit MAX_ATLAS_PAGES pages or the vertex budget,
blend the image list CPU-side into one premultiplied RGBA rect over the
union bounding box - O(frame area) instead of O(sum of image areas) -
and draw it as a single quad through a new MODE_COMPOSITE path in the
GL renderer. Oversized composites reuse the existing grow-and-re-render
contract; the atlas fast path is byte-identical for every frame that fits.

Verified with a desktop harness compiling the shipped AssPack.c against
fork libass 0.18.3 and the issue sample: all atlas-mode frames byte-match
the previous packer, the sign's frames composite with zero truncation and
byte-match a reference full-frame blend at 1080p and 4K, and the
multi-page composite grow path round-trips.

close #1868
2026-08-11 08:41:56 +02:00
edde746 3a704a2b9b fix(player): seek Plex transcodes in-band instead of pre-warming at the resume offset
A quality switch or resumed open at a nonzero position sent offset=T on the
HLS start URL, waited for the readiness probe to touch the segment at T, and
then had mpv seek to T anyway. mpv's stream probing always reads segment zero
first, and a Plex segment request is a seek, so the transcoder was dragged
through seek(T) -> seek(0) -> seek(T) within seconds of the open. Measured
against PMS 1.43, a segment response that races such a restart can be left
open with headers sent and no data or error, and ffmpeg's HLS segment reads
have no default timeout, so playback buffered forever after the first frame
(issue #1859). Starting the session plain and letting the player's start=T
request the resume segment performs the one unavoidable transcoder seek.

The offset request parameter, the readiness probe, and the probe-only
getStatus HTTP helper are removed; live TV time-shift keeps its own offset
path. Transcode opens now also set an explicit network-timeout with
demuxer-level reconnect options: mpv's stream-layer reconnect settings never
reach ffmpeg's HLS segment fetches, so a silently hung segment response now
times out after 20s and is re-requested on a fresh connection instead of
buffering indefinitely. Verified against a live PMS (resume plays from the
requested position) and a stall harness (hung segment re-requested at 20s
with no content skip).
2026-08-10 23:04:35 +02:00
edde746 aff6b6576f fix(player): offer the TrueHD MAT carrier on API 29-32 routes
Carrier-or-decode gated the carrier on getDirectPlaybackSupport, which only
exists on API 33, so every older route force-decoded TrueHD - including
routes that bitstreamed it before the carrier existed. The #1863 Fire TV
Stick 4K Max is Fire OS 8 (API 30): its HDMI route advertises raw TrueHD
and IEC 61937 at 8 channels, 2.12.1 passed TrueHD through, and 2.13.0 hands
the same stream to the FFmpeg decoder. The Shield is API 30 as well.

API 29-32 now asks AudioTrack.isDirectPlaybackSupported about the exact
192kHz/7.1 IEC tuple before offering the carrier. It is coarser than the
API 33 probe - it cannot tell bitstream from offload - but an IEC 61937
track is PCM-shaped by definition, so direct support means the route
carries the frames. getMinBufferSize stays as the precondition on every
tier, and a route that still lies fails AudioTrack initialisation, which
the audio recovery path already answers by blocking direct output and
force-decoding in place. Below API 29 nothing can vouch for the tuple, so
the carrier is still not offered and TrueHD decodes as before.

The tier decision is split from the platform probes so it is unit-testable;
each probe is consulted only on the tiers where its API exists.
2026-08-10 22:54:17 +02:00
edde746 d19ec625cd fix(tv): remove the background Watch Next refresh
2.13.0's ShelfRefreshWorker boots a second headless FlutterEngine in
the app process to refresh the launcher row every six hours. Its
foreground guard is checked only once at worker start, so launching the
app during a run leaves two engines sharing a low-RAM TV for up to 90
seconds, and a failed run retries with backoff. Suspected of
destabilizing the compositor on the 32-bit TCL panel in #1862. The tvOS
Top Shelf live fetch is unaffected and stays.

The foreground sync pipeline keeps the row fresh while the app runs, as
before 2.13.0. Updated devices still carry the persisted periodic job,
which would wake the process once more only to fail instantiating the
deleted class; the package-replaced receiver now cancels it.
2026-08-10 22:30:51 +02:00
edde746 c2bd1d28fd fix(subtitles): load external subtitle files with the media whether or not selected
Since a1b6a8971 only the selected sidecar attached at open, so mpv's
track-list carried one external subtitle and the track sheet could only
offer the rest as primary source switches - tap-and-hold on a
non-selected external track selected it as primary instead of secondary.

Real external files are cheap static fetches, so Jellyfin, Plex direct
play, and offline discovery now mark them preload and they ride along in
sub-files at open, keeping every external track selectable as a
secondary subtitle without a reopen. Embedded rows extracted on a
transcode stay lazy: extraction can stall behind the transcoder, which
is exactly what used to trip the sidecar open guard.

close #1860
2026-08-10 21:23:55 +02:00
edde746 ea356a6112 fix(plex): use fMP4 HLS for video transcodes so HEVC presets stop corrupting
Non-Original presets advertised hevc inside the mpegts HLS target; a Plex
Pass server with HEVC encoding enabled obliges, and its HEVC encode -> TS
segmenter path emits parameter sets mpv rejects ("PPS changed between
slices"). The VOD target now requests fragmented MP4 (verified against
PMS 1.22-1.43), retrying once with an H.264-only TS profile when a
server's decision does not echo the mp4 container back, and falling back
to direct play when neither is honoured. Live TV keeps its own TS target:
live sessions copy broadcast hevc/mpeg2video streams, a path the encoder
bug does not touch.

Presets also now send the videoResolution/videoQuality caps their labels
promise; previously only the bitrate limitation went out, so a "1080p
8 Mbps" preset delivered 2160p at a starved 8 Mbps.

close #1859
2026-08-10 20:38:45 +02:00
edde746 69fadc220d chore: clean up code comments 2026-08-10 20:28:41 +02:00
edde746 5611c6785a chore: bump version to 2.13.0 (129) 2026-08-10 19:03:03 +02:00
edde746 01279e5fbb fix(automotive): stop blocking parked playback when the car service has no verdict
CarRestrictionsMonitor.bind() treated a null getCurrentCarUxRestrictions() as
a restricted verdict with supported = true. Dart then latched the restricted
state, every play path refused to start, and on a car that stays parked no
restriction transition ever arrives to correct it — video never played for the
whole session. This is the failure mode behind the Play Automotive rejection of
version code 128 ("unable to play video content"): a review bench whose car
service tracks no restrictions for the resolved display gets exactly that null.

A missing verdict now stays pending instead: Dart keeps lifecycle gating
(parked, foregrounded video plays; while driving the platform blocks the
activity, so DD-2/DD-3 still hold), the registered listener adopts the first
real verdict, and every later getState retries the read. Listener registration
is identity-guarded because retries re-enter bind() with the same cached
manager instance.

Verified on an API 34 Automotive emulator: CarRestrictionsMonitorTest passes on
both connect routes, parked playback starts, driving pauses it behind the OS
blocking screen, and parking again leaves it paused until the user resumes.
2026-08-10 19:00:50 +02:00
edde746 369c6279d6 fix(i18n): translate the player, downloads and server-setup text left in English
A Portuguese user reported "Skip Intro" rendering in English on Android TV.
The locale files were not the problem - all 22 were structurally complete.
skip_marker_button.dart simply never imported strings.g.dart and assigned
'Skip Intro' / 'Skip Credits' / 'Next Episode' as plain literals. An audit of
lib/ found ~120 more sites in the same state, in four shapes that need
different fixes:

A literal in a file that never imported the i18n layer is the easy one -
skip_marker_button, performance_stats, track_label_builder and codec_utils all
render text with no `t` in the file at all. TrackLabelBuilder._compose now takes
a fallbackLabel builder instead of an English fallbackPrefix, so the caller
supplies t.audioTracks.track / t.videoControls.subtitleTrack and every unnamed
audio and subtitle row in the track menus is localized.

English reaching the user through an exception message is the widest one, and
it needs care: MediaServerException.message feeds both toString() - logs and
Sentry grouping - and verbatim UI display. Localizing it in place would make
bug-report logs follow the user's locale and split one Sentry issue into 22.
The MediaServer and Seerr families instead gain a nullable `display` alongside
the English `message`, and the six screens that print these errors read
`display ?? message`. PlaybackException keeps the opposite rule, because it
already carries a PlaybackFailureReason for logic and classifyPlaybackFailure
already builds it from t.messages: its stragglers are localized at the throw
site. That also removes the literal "Exception: " prefix Live TV users saw on
a tune failure, since PlaybackException.toString() returns the bare message.

Localized parts hand-concatenated with bare English are the shape no search for
Text('...') can find: '${t.common.pause} auto-scroll' on the home carousel,
'${day} at ${time}' on the Live TV schedule row, and an actor-screen count that
hand-rolled its plural as `n == 1 ? 'title' : 'titles'` - wrong for ru and pl
regardless of translation, now a real Slang plural.

Finally a literal assigned to provider state that a widget renders later:
DownloadProgress.errorMessage, and the four background_downloader notification
bodies, which sit inside a plugin config call where no widget-shaped search
reaches them.

Two things surfaced while converting. track_chapter_controls compared a track
label against 'Audio Track N' to swap in a localized version; once the builder
localized its own fallback that branch became unreachable, so it and the
orphaned _joinTrackLabel are gone. And discovery_view's PeerError fallback arm
looks like a leak but is not - its producers already localize, and a test says
so - so it stays as it is.

All 21 non-base locales are translated, including the 21 keys left empty by
earlier commits that were falling back to English. No locale has an empty value.

scripts/check_hardcoded_strings.py guards the three shapes a structural check
can see, and runs in ci_checks.sh after translation hygiene. Its first draft
passed its own tests while missing this very bug, because 'Skip Intro' is bound
to a local rather than handed to Text(); the name-bound rule that closes that
gap is restricted to phrase-shaped literals, or it cannot tell copy from the
identifiers this codebase binds constantly ('cast_row', 'auto', 'liveTv'). It
cannot see English inside a throw or assigned to a provider field - neither is
distinguishable from a log message without dataflow analysis - and the docstring
says so. label: and actionLabel: are deliberately unscanned: here they name a
diagnostic operation, and a check that is chronically red is a check that gets
switched off.

One commit rather than one per area: the keys, the 22 locale files and the
generated output are a single unit, and any partial split fails the repo's own
unused-key scan on the way through.

close #1856
2026-08-10 15:32:43 +02:00
edde746 3177290083 chore: bump MPVKit to 1.0.19
Picks up two vo_avfoundation fixes: keep the displayed frame across
seek resets, and refuse Core Image geometry rendering for Dolby
Vision passthrough frames (defense in depth - the app already keeps
mpv video-zoom at 0 on iOS/tvOS and zooms the display layer instead).
2026-08-10 14:50:05 +02:00
edde746 a0269c6feb fix(player): keep HDR/Dolby Vision through zoom on iOS and tvOS
Nonzero mpv video-zoom flips vo_avfoundation into a per-frame Core
Image re-render that destroys HDR/DV passthrough - DV frames render
near-black on tvOS (verified on Apple TV 4K, DV P7->8.1 content:
panel luma mean 0.0 zoomed vs 87-103 unzoomed at locked exposure).

Zoom now scales the AVSampleBufferDisplayLayer itself (a
sublayerTransform on the container is ignored by the video plane)
via the existing Player.setVideoZoom seam, and VideoFilterManager
pins the mpv property to 0 on backends with native zoom. The layer
tree at 100% stays identical to before: clipping engages only while
zoomed, and updateFrame sizes the layer via bounds/position, which
frame= decomposes to anyway.

macOS keeps the property path (gpu-next zooms losslessly in-shader);
Android is untouched.
2026-08-10 14:17:40 +02:00
github-actions[bot] f2ef15806a chore: update cask to 2.13.0 2026-08-10 08:32:01 +00:00
1030 changed files with 61310 additions and 20289 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
+31 -5
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
@@ -36,7 +41,7 @@ env:
libharfbuzz-dev libepoxy-dev libegl-dev libgl-dev libgnutls28-dev libpipewire-0.3-dev
libva-dev libvdpau-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev
libxss-dev libxpresent-dev libxkbcommon-dev libpulse-dev libdbus-1-dev libdrm-dev
libgbm-dev libwayland-dev wayland-protocols liblcms2-dev libmujs-dev liblua5.2-dev
libdisplay-info-dev libgbm-dev libwayland-dev wayland-protocols liblcms2-dev libmujs-dev liblua5.2-dev
ruby ruby-dev rubygems build-essential rpm libarchive-tools imagemagick libcurl4-openssl-dev
jobs:
@@ -271,13 +276,11 @@ jobs:
MACOS_CERTIFICATE_PASSWORD: ${{ secrets.MACOS_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
run: |
# Create temporary keychain
KEYCHAIN_PATH=$RUNNER_TEMP/build.keychain
security create-keychain -p "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH
security set-keychain-settings -lut 21600 $KEYCHAIN_PATH
security unlock-keychain -p "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH
# Import certificate to keychain
CERTIFICATE_PATH=$RUNNER_TEMP/certificate.p12
echo "$MACOS_CERTIFICATE_BASE64" | base64 --decode -o $CERTIFICATE_PATH
security import $CERTIFICATE_PATH -k $KEYCHAIN_PATH -P "$MACOS_CERTIFICATE_PASSWORD" -T /usr/bin/codesign
@@ -494,6 +497,11 @@ jobs:
"data/app.so"
"data/icudtl.dat"
"data/flutter_assets/NativeAssetsManifest.json"
# MSVC runtime bundled by InstallRequiredSystemLibraries in
# windows/CMakeLists.txt; without it the app crashes at startup on
# machines whose system-wide redist is older than the CI toolset.
"msvcp140.dll"
"vcruntime140.dll"
)
$forbiddenFiles = @(
"plezy.lib"
@@ -857,7 +865,7 @@ 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
@@ -876,6 +884,21 @@ jobs:
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
@@ -1040,5 +1063,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 }}
+7 -6
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: |
@@ -317,7 +317,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: |
@@ -657,7 +658,7 @@ jobs:
libasound2-dev libass-dev libfreetype-dev libfontconfig-dev libfribidi-dev \
libharfbuzz-dev libegl-dev libgl-dev libgnutls28-dev libpipewire-0.3-dev \
libva-dev libxkbcommon-dev libpulse-dev libdbus-1-dev libdrm-dev \
libgbm-dev libwayland-dev wayland-protocols liblcms2-dev libmujs-dev \
libdisplay-info-dev libgbm-dev libwayland-dev wayland-protocols liblcms2-dev libmujs-dev \
liblua5.2-dev rpm libarchive-tools imagemagick ruby-dev build-essential
sudo gem install fpm --version 1.17.0 --no-document
+1 -3
View File
@@ -18,9 +18,7 @@ migrate_working_dir/
*.iws
.idea/
# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
# Keep .vscode/ available for contributors' local configuration.
#.vscode/
# Flutter/Dart/Pub related
+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/
@@ -22,8 +22,8 @@ tags:
- pressKey: "Remote Dpad Up"
- pressKey: "Remote Dpad Right"
- pressKey: "Remote Dpad Right"
# The grid row must be matchable before the sort sheet opens, otherwise the
# occlusion assertion below would pass for the wrong reason.
# Wait for the row before opening the sheet so occlusion is tested against the
# grid, not an absent or stale match.
- extendedWaitUntil:
visible: "(?s).*Alpha Archive.*"
timeout: 15000
@@ -31,9 +31,8 @@ tags:
- extendedWaitUntil:
visible: "Title"
timeout: 10000
# The host renders the grid, the barrier, and the sheet in one Stack and never
# unmounts the grid, so before 8e1904dd wrapped the barrier in BlockSemantics
# an occluded row still read as visible to accessibility and to Maestro.
# The grid remains mounted under the Stack; BlockSemantics is required for
# occluded rows to disappear from Maestro's accessibility tree.
- assertNotVisible: "(?s).*Alpha Archive.*"
- pressKey: "Remote Dpad Center"
- pressKey: "Remote Dpad Left"
@@ -16,13 +16,9 @@ tags:
visible: "(?s)^(Play|Resume).*$"
commands:
- pressKey: "Remote Dpad Center"
# The TV player opens with its chrome down so the OSD and timebar never sit
# over the opening seconds of the picture (#1765), so the Pause button can no
# longer stand in for "the player has finished loading". Wait for the detail
# screen to go first: the labelled spinner is necessarily up the moment the
# player route owns the frame, and it only clears once playback reports its
# first frame or gives up, so this can never advance before the media opens.
# A give-up lands on the transport assertions below, which is where it belongs.
# TV playback starts with chrome hidden (#1765), so wait for its loading label
# rather than treating the Pause button as readiness. A failed open reaches the
# transport assertions below.
- extendedWaitUntil:
notVisible: "Overview"
timeout: 30000
@@ -30,18 +26,14 @@ tags:
notVisible: "Loading video"
timeout: 30000
- assertNotVisible: "(?s)^(Play|Pause)$"
# Hardware transport keys drive playback without raising the chrome (#1676):
# the player answers with a centred disc (pause) or a side readout (seek), never the
# full chrome, so subtitles stay readable.
# Pause first — it also freezes the clip, so the seek assertions below cannot
# race the end of a short fixture item.
# Transport keys keep chrome hidden (#1676); pause first so seeks cannot race
# the end of this short fixture.
- pressKey: "Remote Media Play Pause"
- extendedWaitUntil:
visible: "Paused"
timeout: 10000
- assertNotVisible: "(?s)^Play$"
# D-pad seeking reports through the skip badge, never the scrub bar, and
# consecutive presses in one direction stack into a running total.
# D-pad seeks use the cumulative skip badge, not the scrub bar.
- pressKey: "Remote Dpad Right"
- extendedWaitUntil:
visible: "(?s)^Seek forward 10 seconds$"
@@ -56,7 +48,7 @@ tags:
visible: "Playing"
timeout: 10000
- assertNotVisible: "(?s)^Pause$"
# Select stays the deliberate way to bring the chrome back.
# Select is the explicit way to restore the chrome.
- pressKey: "Remote Dpad Center"
- extendedWaitUntil:
visible: "(?s)^(Play|Pause)$"
@@ -7,10 +7,8 @@ tags:
- playback
---
- runFlow: ../subflows/onboard_jellyfin_tv.yaml
# Reach Search with the D-pad, the way 10_tv_settings_navigation.yaml does. A
# tap here flips InputModeTracker into pointer mode, which collapses the rail
# to icons and leaves no "Search" label to hit — and a percentage coordinate
# does not survive the jump from a phone in forced TV mode to a 4K television.
# Reach Search by D-pad: taps switch to pointer mode and hide the TV rail label,
# while percentage coordinates are not portable across TV sizes.
- pressKey: "Remote Dpad Left"
- extendedWaitUntil:
visible: "Search"
@@ -38,11 +36,8 @@ tags:
- waitForAnimationToEnd:
timeout: 5000
- tapOn: "(?s)^Play S1E1$"
# The TV player opens with its chrome down (#1765), so the Pause button can no
# longer stand in for "the player has finished loading". Wait for the detail
# screen to go first: the labelled spinner is necessarily up the moment the
# player route owns the frame, and it only clears once playback reports its
# first frame or gives up, so this can never advance before the media opens.
# The player starts with chrome hidden (#1765); wait for its loading label
# rather than using Pause as readiness.
- extendedWaitUntil:
notVisible: "(?s)^Play S1E1$"
timeout: 30000
@@ -51,9 +46,7 @@ tags:
timeout: 30000
- pressKey: "Remote Media Fast Forward"
- pressKey: "Remote Media Fast Forward"
# Gate on the prompt's own Cancel action, the label the iOS branch below taps.
# "Next Episode" is the credits skip button at this point in the episode, so
# waiting on it would let Back fire before the prompt ever opened.
# Wait for Cancel, not Next Episode (the credits-skip action), before pressing Back.
- extendedWaitUntil:
visible: "(?s)^Cancel$"
timeout: 20000
@@ -8,10 +8,8 @@ tags:
---
- runFlow: ../subflows/onboard_jellyfin.yaml
- tapOn: "(?s)^Libraries.*"
# Every seeded alphabet title carries the same dateadded, so which of them the
# "Recently Added" rail returns is not stable across scans. This flow only
# needs some playable movie, so accept any of them rather than pinning one and
# failing whenever the tie-break lands elsewhere.
# All seeded titles share dateadded, so accept any playable Recently Added movie
# instead of relying on an unstable tie-break.
- extendedWaitUntil:
visible: "(?s).*(?:Alpha Archive|Bravo Beacon|Charlie Circuit|Delta Drive|Echo Engine|Foxtrot Frame|Gamma Garden|Hotel Horizon|India Index|Juliet Junction|Kilo Key|Lima Loop|Mike Matrix|November Node|Oscar Orbit|Papa Pipeline|Quebec Queue|Romeo Relay|Sierra Signal|Tango Track|Uniform Update|Victor View|Whiskey Widget|Xray XML|Yankee Yield|Zulu Zone).*, movie, .*"
timeout: 15000
@@ -7,20 +7,9 @@ tags:
- settings
- sheets
---
# Guards 8e1904dd and c48cbf70 together.
#
# On a phone, Settings is a pushed route. Before c48cbf70 it carried no
# OverlaySheetHost, so Manage Libraries fell back to showModalBottomSheet and a
# single Back tore down the sheet *and* Settings. Before 8e1904dd the host
# answered the platform pop with a TV-only dedup marker that could already be
# spent, stranding the sheet open with no way out. Either defect fails the
# "Manage Libraries is still there after one Back" assertion below.
#
# The same commit blocks semantics behind the barrier, so the occlusion
# assertions pin that an open sheet actually hides the rows underneath.
# Pristine state on purpose. The TV regressions in the same CI group leave
# "Force TV mode" enabled, and this flow asserts the handheld Settings route,
# so it must not inherit whichever layout the previous flow left behind.
# Guards 8e1904dd and c48cbf70: phone Settings must host the sheet so one Back
# dismisses only the sheet, while BlockSemantics hides rows behind the barrier.
# Start clean because preceding TV flows may leave Force TV mode enabled.
- runFlow: ../subflows/onboard_jellyfin.yaml
- runFlow: ../subflows/open_settings.yaml
- assertVisible: "(?s)^Services.*"
@@ -29,10 +18,8 @@ tags:
- extendedWaitUntil:
visible: "Maestro Movies"
timeout: 15000
# The barrier swallows every pointer event, so the rows behind it must leave
# the semantics tree too. Without BlockSemantics an occluded row still reads as
# visible and a tap on it lands on the barrier instead. "Manage Libraries" is
# excluded on purpose: it is also the sheet's own title.
# The barrier removes covered rows from semantics; the sheet title remains
# visible because it belongs to the sheet.
- assertNotVisible: "(?s)^Services.*"
- assertNotVisible: "(?s)^Video Playback.*"
- assertNotVisible: "(?s)^Appearance.*"
@@ -41,15 +28,13 @@ tags:
- waitForAnimationToEnd:
timeout: 3000
- assertNotVisible: "Maestro Movies"
# One Back closed only the sheet: Settings is still the current route.
- extendedWaitUntil:
visible: "(?s)^Manage Libraries.*"
timeout: 10000
- assertVisible: "(?s)^Services.*"
- assertVisible: "(?s)^Video Playback.*"
- assertNotVisible: "Discover"
# Reopening proves the host did not strand the one-shot dedup marker: a second
# dismissal has to work exactly like the first.
# Reopening verifies the one-shot pop deduplication marker was not stranded.
- tapOn: "(?s)^Manage Libraries.*"
- extendedWaitUntil:
visible: "Maestro Movies"
@@ -7,20 +7,10 @@ tags:
- playback
- subtitles
---
# Guards 468d6804. When a source advertises tracks the native list has not
# produced yet, TrackManager arms an automatic selection pass with a 5s first
# attempt and a 25s deadline. A user pick made inside that window used to only
# persist the preference, leaving the pass armed, so the choice snapped back to
# the server/profile preferred track up to ~30s later. The pick now retires the
# pending pass, and the wait below is long enough to outlive both timers.
#
# Fixture: Codec H264 EAC3 Multisub advertises three E-AC-3 audio streams
# (Hindi and Japanese flagged default, English not) and 36 SRT subtitle
# streams, so both picks below are genuine changes away from the automatic one.
# Pristine state on purpose, for two reasons: the TV regressions in the same
# CI group leave "Force TV mode" enabled, and a remembered track selection
# from an earlier run would pre-select the very rows this flow picks, making
# every assertion below vacuous.
# Guards 468d6804: a user pick must retire TrackManager's pending automatic
# selection pass, or the server preference can overwrite it up to 30s later.
# The codec fixture supplies non-default audio and subtitle choices, and clean
# state prevents remembered selections from making the assertions vacuous.
- runFlow: ../subflows/onboard_jellyfin.yaml
- runFlow:
file: ../subflows/open_codec_sample.yaml
@@ -7,16 +7,9 @@ tags:
- settings
- i18n
---
# Guards 7677d159 and 100d7729. AppLocale is switched over exhaustively in
# appearance_settings_screen.dart, so a missing arm is a compile error, but a
# locale whose JSON never reached the generator ships a picker entry that falls
# back to English. Selecting Turkish and reading root-level navigation labels
# proves the generated locale is wired end to end.
#
# This flow mutates a persisted pref, and the app language decides every
# selector after the tap, so it starts from a cleared install rather than
# ensure_onboarded: a run that dies mid-flow must not leave the next flow
# hunting for English strings in a Turkish tree.
# Guards 7677d159 and 100d7729: selecting Turkish and reading root navigation
# labels proves the generated locale is wired end to end. Start clean because
# the language preference persists and affects every later selector.
- runFlow: ../subflows/onboard_jellyfin.yaml
- runFlow: ../subflows/open_settings.yaml
- tapOn: "(?s)^Appearance.*"
@@ -54,9 +47,7 @@ tags:
- assertVisible: "Keşfet"
- assertNotVisible: "(?s)^Libraries.*"
- assertNotVisible: "Discover"
# Walk back through the Turkish tree and restore English. The pref outlives a
# plain launchApp, so leaving the device in Turkish would break every later
# flow in the suite.
# Restore English before leaving the device; the locale preference outlives launchApp.
- repeat:
times: 3
while:
@@ -7,21 +7,11 @@ tags:
- tv
- settings
---
# Guards ef310459 and the Apple-only gates touched by 6c14049e, and pins TV
# settings navigation generally.
#
# It deliberately does NOT guard the 15b54e2e density change. That commit took
# every settings row from ~80dp to ~61dp, but the rows below the fold stay in
# the semantics tree either way, so this flow passes identically on both sides
# of it — measured, not assumed. A real guard would need a pixel `height`
# assertion, and Maestro has no DPR-relative form, so pinning one here would
# only hold for the box it was written on. Row geometry belongs to
# test/widgets/setting_tile_test.dart.
#
# Every step uses D-pad keys, never taps. InputModeTracker flips to pointer
# mode on the first touch event and the TV number spinner only builds in
# keyboard mode, so a single tapOn anywhere above would silently swap the
# spinner for a plain text field.
# Guards ef310459 and the Apple-only gates touched by 6c14049e.
# This flow intentionally does not pin 15b54e2e's row density: semantics stay
# stable across that change, and Maestro has no DPR-relative height assertion.
# Use D-pad only; a tap switches InputModeTracker to pointer mode and removes
# the TV number spinner.
- runFlow: ../subflows/onboard_jellyfin_tv_device.yaml
- pressKey: "Remote Dpad Left"
- extendedWaitUntil:
+4 -14
View File
@@ -1,20 +1,10 @@
appId: com.edde746.plezy
---
# Reach a signed-in Home without paying for onboarding that already happened.
#
# `onboard_jellyfin.yaml` clears app state and retypes the server URL and
# credentials, which measures ~59s per flow on a Pixel 7 and dominates every
# flow that only needs "signed in, on Home". A plain `launchApp` keeps stored
# data and cold-starts straight back to Home, which measures ~16s.
#
# The guard keeps each flow runnable on its own: when no session is stored --
# a fresh install, or a run after the logout flow -- "Discover" is absent and
# this falls through to the real onboarding. Flows that must prove onboarding
# itself, or that need pristine state, keep calling onboard_jellyfin.yaml.
# Reach a signed-in Home without repeating onboarding. A plain launch preserves
# stored state (~16s versus ~59s for retyping credentials); fall back to full
# onboarding when no session exists so each flow remains runnable alone.
- launchApp
# Settle on a known screen first. Branching straight off `launchApp` races the
# splash: "Discover" has not rendered yet, the guard reads it as absent, and
# every flow pays for a full re-onboarding it did not need.
# Wait for the splash to resolve before deciding whether onboarding is needed.
- extendedWaitUntil:
visible: "(?s)^(?:Discover|Sign in with Plex|Connect to Jellyfin|Wait).*"
timeout: 30000
+2 -4
View File
@@ -10,10 +10,8 @@ appId: com.edde746.plezy
- extendedWaitUntil:
visible: "(?s)^(?:Connect to Jellyfin|Wait).*"
timeout: 30000
# A miss on `tapOn ... optional: true` still runs Maestro's full element
# search before giving up, which measured 3s here and 7.8s for "Sign in"
# on every onboarding. These taps normally find nothing, so gate them on
# a single visibility check instead.
# Optional taps still pay Maestro's full search cost when they miss; guard them
# with one visibility check instead.
- runFlow:
when:
visible: "Wait"
@@ -1,12 +1,7 @@
appId: com.edde746.plezy
---
# Onboarding for a device that already reports itself as a TV.
#
# `onboard_jellyfin_tv.yaml` exists for the phone emulator CI runs on: it
# onboards through the handheld layout and then walks Settings to flip
# "Force TV mode". A real Android TV box takes the TV layout from the first
# frame, so that walk has no handheld chrome to tap and the toggle would only
# re-assert what PlatformDetector already reports.
# Onboard a device that reports itself as a TV; unlike the phone flow, it starts
# in TV layout and needs no Force TV mode walk.
- retry:
maxRetries: 1
commands:
@@ -32,9 +27,8 @@ appId: com.edde746.plezy
- tapOn: "(?s)Server URLs.*"
- inputText: ${JELLYFIN_URL}
- tapOn: "Find server"
# A TV-sized layout offers Quick Connect first because typing on a remote is
# slow. The code path needs a second device to approve, so fall back to the
# username form the phone flow already uses.
# Quick Connect is awkward on a remote and needs another device, so use the
# username form as fallback.
- extendedWaitUntil:
visible: "(?s)^(?:Username|Cancel)$"
timeout: 30000
+2 -4
View File
@@ -17,10 +17,8 @@ appId: com.edde746.plezy
platform: Android
commands:
- hideKeyboard
# A card announces its watch state three ways, and the codec samples keep a
# resume position on the server once any earlier flow has played them, so the
# partial form has to be accepted for this subflow to be re-runnable against a
# fixture container that is not thrown away between suites.
# Codec cards retain watch state and resume position between flows, so accept
# any valid watch-state label to keep this subflow rerunnable.
- extendedWaitUntil:
visible: "(?s)^${SAMPLE_TITLE}, movie, (?:watched|unwatched|[0-9]+ percent watched)$"
timeout: 15000
+2 -6
View File
@@ -1,11 +1,7 @@
appId: com.edde746.plezy
---
# Reach Settings from a signed-in Home on a phone layout.
#
# The profile menu is itself an overlay sheet on the MainScreen host, so a tap
# issued while the previous route is still settling opens nothing. The guarded
# repeat re-opens the menu instead of failing the flow, matching the pattern
# already used by flows/07_profiles_settings.yaml.
# Reach phone Settings from signed-in Home. The profile menu is an overlay
# sheet; retry while the previous route settles.
- extendedWaitUntil:
visible: "Discover"
timeout: 30000
+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.
+2 -2
View File
@@ -1,6 +1,6 @@
cask "plezy" do
version "2.12.1"
sha256 "7a5e30d125d5a379108bf691ae8ce5e2af0a1acf98ee40897909a9576ebe3ef9"
version "2.17.0"
sha256 "318b9ac0ff0d239b3edbad57a44c008e7aaf0c5623bc2c595407fce2987ba5e4"
url "https://github.com/edde746/plezy/releases/download/#{version}/plezy-macos.dmg"
name "Plezy"
+4 -4
View File
@@ -38,9 +38,9 @@ Package managers:
brew tap edde746/plezy https://github.com/edde746/plezy
brew install --cask plezy
```
- [AUR](https://aur.archlinux.org/packages/plezy-bin) (Arch Linux) - Community maintained by [@jianglai](https://github.com/jianglai):
- [Pacman](https://archlinux.org/packages/extra/x86_64/plezy/) (Arch Linux) - Official package:
```bash
yay -S plezy-bin
sudo pacman -S plezy
```
- **WinGet** (Windows):
```bash
@@ -148,7 +148,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 +190,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
+11 -5
View File
@@ -4,6 +4,13 @@ analyzer:
exclude:
- "**/*.g.dart"
- "**/*.freezed.dart"
- build/**
- android/**
- ios/**
- web/**
- windows/**
- macos/**
- linux/**
linter:
rules:
@@ -15,8 +22,7 @@ linter:
prefer_final_in_for_each: true
avoid_print: true
# Do not register DCL as an analyzer plugin: its analyzer 10 integration crashes
# on Linux. CI invokes the supported check-unused commands explicitly.
# DCL's analyzer 10 plugin crashes on Linux; CI runs check-unused commands directly.
dart_code_linter:
rules-exclude:
- "test/**"
@@ -27,7 +33,7 @@ dart_code_linter:
- package:dart_code_linter/presets/recommended.yaml
rules:
# --- Flutter rules (on top of recommended) ---
# Flutter-specific rules.
- avoid-border-all
- avoid-shrink-wrap-in-lists
- avoid-expanded-as-spacer
@@ -37,7 +43,7 @@ dart_code_linter:
- prefer-define-hero-tag
- use-setstate-synchronously
# --- Additional useful Dart rules ---
# Additional Dart rules.
- avoid-cascade-after-if-null
- avoid-collection-methods-with-unrelated-types
- avoid-unnecessary-type-assertions
@@ -48,7 +54,7 @@ dart_code_linter:
- prefer-enums-by-name
- prefer-commenting-analyzer-ignores
# --- Disable noisy rules from recommended preset ---
# Disabled noisy rules.
- no-magic-number: false
- avoid-dynamic: false
- format-comment: false
+9 -7
View File
@@ -64,7 +64,7 @@ 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"
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"
@@ -132,7 +132,7 @@ val prepareMpvFfmpegDevelopment = tasks.register("prepareMpvFfmpegDevelopment")
val aar = File(mpvDir, mpvAar)
val manifest = File(mpvFfmpegDevelopmentDir, ".manifest")
val abis = listOf("arm64-v8a", "armeabi-v7a", "x86", "x86_64")
val libraries = listOf("avcodec", "avutil", "swresample")
val libraries = listOf("avcodec", "avformat", "avutil", "swresample")
inputs.file(aar)
inputs.property("ffmpegVersion", mpvFfmpegVersion)
inputs.property("sourceUrl", mpvFfmpegSourceUrl)
@@ -145,6 +145,7 @@ val prepareMpvFfmpegDevelopment = tasks.register("prepareMpvFfmpegDevelopment")
outputs.files(
File(mpvFfmpegDevelopmentDir, "include/libavcodec/avcodec.h"),
File(mpvFfmpegDevelopmentDir, "include/libavutil/avconfig.h"),
File(mpvFfmpegDevelopmentDir, "include/libavformat/avformat.h"),
File(mpvFfmpegDevelopmentDir, "include/libswresample/swresample.h"),
manifest
)
@@ -182,7 +183,7 @@ val prepareMpvFfmpegDevelopment = tasks.register("prepareMpvFfmpegDevelopment")
} catch (error: Exception) {
throw GradleException("Failed to extract FFmpeg $mpvFfmpegVersion headers", error)
}
listOf("libavcodec", "libavutil", "libswresample").forEach { library ->
listOf("libavcodec", "libavformat", "libavutil", "libswresample").forEach { library ->
project.copy {
from(File(extractedSource, library)) {
include("*.h")
@@ -206,6 +207,7 @@ val prepareMpvFfmpegDevelopment = tasks.register("prepareMpvFfmpegDevelopment")
from(zipTree(aar)) {
include(
"jni/*/libavcodec.so",
"jni/*/libavformat.so",
"jni/*/libavutil.so",
"jni/*/libswresample.so"
)
@@ -336,8 +338,6 @@ android {
defaultConfig {
applicationId = "com.edde746.plezy"
// You can update the following values to match your application needs.
// For more information, see: https://flutter.dev/to/review-gradle-config.
minSdk = 25 // Fire OS 6.x (API 25); overrides libmpv-android's minSdk=26
targetSdk = flutter.targetSdkVersion
versionCode = flutter.versionCode
@@ -518,8 +518,10 @@ dependencies {
// Android TV Watch Next integration
implementation("androidx.tvprovider:tvprovider:1.1.0")
// Periodic Watch Next background refresh (ShelfRefreshWorker). Same version
// background_downloader pins, so the merged classpath stays coherent.
// Only used to cancel the legacy periodic shelf refresh job (2.13.0's
// removed ShelfRefreshWorker) that WorkManager persisted on updated
// devices. Same version background_downloader pins, so the merged
// classpath stays coherent.
implementation("androidx.work:work-runtime-ktx:2.11.0")
// Media3 ExoPlayer for Android
+11
View File
@@ -18,3 +18,14 @@
# growOutputBuffer's JNI descriptor names this type, so it may not be renamed either.
-keep class androidx.media3.decoder.SimpleDecoderOutputBuffer { *; }
# ffmpeg_demuxer_jni.cc resolves the AVIO input proxy's callbacks by name
# (FindClass on the interface, GetMethodID for position/read/readAt/length).
# Keeping the interface members pins the names on every implementation,
# including the anonymous proxy inside FfmpegExtractor.
-keep interface com.edde746.plezy.exoplayer.FfmpegDemuxerJni$Input {
long position();
int read(byte[], int);
int readAt(long, byte[], int);
long length();
}
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application>
<!-- Serves a test asset over content:// so instrumentation covers the
SAF/ContentDataSource read path. Exported because the test body
runs in the app's process while this provider lives in the
androidTest APK's own uid; it serves nothing but this APK's own
assets. Merged into the androidTest APK, never into the app. -->
<provider
android:name="com.edde746.plezy.exoplayer.FixtureContentProvider"
android:authorities="com.edde746.plezy.test.fixtures"
android:exported="true" />
</application>
</manifest>
@@ -0,0 +1,117 @@
package com.edde746.plezy.exoplayer;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Serves a test asset over a {@code content://} URI so instrumentation can exercise media3's
* {@code ContentDataSource} read path.
*
* <p>A download stored through SAF reaches the player as {@code content://} and is read with
* {@code openAssetFileDescriptor} — a different reopen story than a plain file:
* {@code FfmpegRandomAccessSource} has to open a <em>second</em> descriptor on the document while
* the loader still holds one. Nothing else in the app produces that shape on demand, and MediaStore
* would leave rows on the device.
*
* <p>The provider owns the whole fixture: a test body runs in the <em>app's</em> process and cannot
* write into this APK's data directory, so handing it a path could never work. It copies the named
* asset into its own cache and returns a read-only descriptor, which crosses the uid boundary fine.
*
* <p>Java rather than Kotlin on purpose: hosting this provider starts a process for the test APK
* alone, and the Kotlin stdlib the instrumentation normally borrows from the app is not on that
* process's classpath.
*/
public final class FixtureContentProvider extends ContentProvider {
public static final String AUTHORITY = "com.edde746.plezy.test.fixtures";
/** @param asset path inside this APK's assets, e.g. {@code ffmpeg/seek_cued.mkv}. */
public static Uri uriFor(String asset) {
return new Uri.Builder().scheme("content").authority(AUTHORITY).path(asset).build();
}
@Override
public boolean onCreate() {
return true;
}
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
String path = uri.getPath();
if (path == null || path.length() <= 1) {
throw new FileNotFoundException("no asset in " + uri);
}
String asset = path.substring(1);
Context context = getContext();
if (context == null) {
throw new FileNotFoundException("provider has no context");
}
File cached = new File(context.getCacheDir(), asset.replace('/', '-'));
if (!cached.isFile()) {
copyAsset(context, asset, cached);
}
return ParcelFileDescriptor.open(cached, ParcelFileDescriptor.MODE_READ_ONLY);
}
private static void copyAsset(Context context, String asset, File target) throws FileNotFoundException {
File staging = null;
try {
context.getCacheDir().mkdirs();
staging = File.createTempFile("fixture-", null, context.getCacheDir());
try (InputStream source = context.getAssets().open(asset);
OutputStream sink = new FileOutputStream(staging)) {
byte[] buffer = new byte[64 * 1024];
for (int read = source.read(buffer); read != -1; read = source.read(buffer)) {
sink.write(buffer, 0, read);
}
}
// Publish atomically so a concurrent open never sees a short file.
if (!staging.renameTo(target) && !target.isFile()) {
throw new IOException("could not publish " + target);
}
} catch (IOException e) {
FileNotFoundException failure = new FileNotFoundException("could not stage asset " + asset);
failure.initCause(e);
throw failure;
} finally {
if (staging != null && staging.isFile()) {
staging.delete();
}
}
}
@Override
public String getType(Uri uri) {
return "video/x-matroska";
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
return null;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return 0;
}
}
@@ -0,0 +1,116 @@
package com.edde746.plezy.exoplayer
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import java.io.File
import java.io.RandomAccessFile
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
/**
* Asserts the demuxer's JNI byte source stays reachable under R8.
*
* `ffmpeg_demuxer_jni.cc` resolves [FfmpegDemuxerJni.Input] by name — `FindClass`
* on the interface, then `GetMethodID` for `position`, `read`, `readAt` and
* `length`. Nothing in Kotlin calls those methods, so R8 may rename or remove
* them while every debug check still passes; the AVIO callbacks would then fail
* on the first read and every container would fall back to media3's extractors.
* That is the same failure shape as #1703, which shipped.
*
* Run against the `minified` build type (`-Pplezy.testBuildType=minified`); on an
* unminified variant it can only ever pass. Deliberately touches no media3 API,
* so the only keep rules it depends on are the ones under test.
*/
@RunWith(AndroidJUnit4::class)
class FfmpegDemuxerReachabilityTest {
@Test
fun avioCallbacksResolveAndServeBothSequentialAndIndexReads() {
assertTrue("ffmpeg demuxer JNI library is unavailable", FfmpegDemuxerJni.available)
val fixture = copyFixture()
val input = FileInput(fixture)
try {
// nativeOpen drives the whole handshake: FindClass on Input, GetMethodID
// for all four methods, then avio reads served back through them. A
// shrunk or renamed member makes this fail instead of returning streams.
val code = FfmpegDemuxerJni.nativeOpen(input)
assertEquals("nativeOpen failed (${input.lastError ?: "no java error"})", 0, code)
assertTrue("demuxer reported no streams", FfmpegDemuxerJni.nativeStreamCount() > 0)
assertTrue("position was never called", input.positionCalls > 0)
// Header parsing is sequential, so it only proves read()/position()/length().
// readAt() is the member nothing in the app calls except this interface's
// own implementation, and it is what an index seek runs on.
val durationUs = FfmpegDemuxerJni.nativeDurationUs()
assertTrue("fixture duration unknown", durationUs > 0)
val seek = FfmpegDemuxerJni.nativeSeek(durationUs / 2)
assertTrue("nativeSeek failed with $seek (${input.lastError ?: "no java error"})", seek >= 0)
assertTrue("readAt was never called for the index read", input.readAtCalls > 0)
} finally {
FfmpegDemuxerJni.nativeClose()
input.close()
fixture.delete()
}
}
private fun copyFixture(): File {
val instrumentation = InstrumentationRegistry.getInstrumentation()
val cacheDir = instrumentation.targetContext.cacheDir.also { it.mkdirs() }
val output = File.createTempFile("ffmpeg-reachability-", ".mkv", cacheDir)
instrumentation.context.assets.open(FIXTURE).use { source ->
output.outputStream().use(source::copyTo)
}
return output
}
/** Byte source with no media3 involvement, so R8 has nothing else to keep. */
private class FileInput(file: File) : FfmpegDemuxerJni.Input {
private val handle = RandomAccessFile(file, "r")
private val total = file.length()
var readAtCalls = 0
private set
var positionCalls = 0
private set
override var lastError: String? = null
override fun position(): Long {
positionCalls++
return handle.filePointer
}
override fun read(buf: ByteArray, length: Int): Int {
val read = handle.read(buf, 0, length)
return if (read < 0) 0 else read
}
override fun readAt(position: Long, buf: ByteArray, length: Int): Int {
readAtCalls++
val restore = handle.filePointer
return try {
if (position >= total) return 0
handle.seek(position)
val read = handle.read(buf, 0, length)
if (read < 0) 0 else read
} finally {
handle.seek(restore)
}
}
override fun length(): Long = total
fun close() = handle.close()
}
private companion object {
/** The cued fixture from [FfmpegExtractorSeekTest]: a SeekHead plus Cues at the end. */
const val FIXTURE = "ffmpeg/seek_cued.mkv"
}
}
@@ -0,0 +1,135 @@
package com.edde746.plezy.exoplayer
import android.content.Context
import android.net.Uri
import android.os.Handler
import android.os.HandlerThread
import androidx.media3.common.MediaItem
import androidx.media3.common.PlaybackException
import androidx.media3.common.Player
import androidx.media3.datasource.DataSpec
import androidx.media3.datasource.DefaultDataSource
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.source.ProgressiveMediaSource
import androidx.media3.extractor.ExtractorsFactory
import androidx.media3.extractor.text.DefaultSubtitleParserFactory
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.edde746.plezy.libass.media.AssHandler
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
/**
* End-to-end regression coverage for #2088: audio demuxed by FfmpegExtractor
* must reach MediaCodec with the per-codec csd shapes media3's own extractors
* emit. With raw ffmpeg extradata as the only csd buffer, Android's Opus
* decoders consume the first two real packets as codec delay / seek pre-roll
* and then silently discard every decoded sample — the player never leaves
* STATE_BUFFERING, which this test observes as a playback timeout.
*
* The extractors factory contains only FfmpegExtractor, so a fixture that
* falls back to media3's extractors fails instead of passing vacuously.
*/
@RunWith(AndroidJUnit4::class)
class FfmpegExtractorAudioCsdPlaybackTest {
@Test
fun opusPlaysToEnd() {
playToEnd("ffmpeg/stereo_opus.mka")
}
@Test
fun vorbisPlaysToEnd() {
playToEnd("ffmpeg/stereo_vorbis.mka")
}
@Test
fun flacPlaysToEnd() {
playToEnd("ffmpeg/stereo.flac")
}
private fun playToEnd(fixture: String) {
val instrumentation = InstrumentationRegistry.getInstrumentation()
val context = instrumentation.targetContext
val fixtureFile = copyFixture(instrumentation.context, context, fixture)
val playbackThread = HandlerThread("ffmpeg-csd-test").apply { start() }
val handler = Handler(playbackThread.looper)
val completed = CountDownLatch(1)
val playerReference = AtomicReference<ExoPlayer>()
val errorReference = AtomicReference<Throwable>()
handler.post {
try {
val fixtureUri = Uri.fromFile(fixtureFile)
val ffmpegOnlyExtractors = ExtractorsFactory {
val extractor = FfmpegExtractor.create(
{ FfmpegDemuxerPolicy.Preference.FFMPEG },
DvConversionMode.DISABLED,
DefaultSubtitleParserFactory(),
AssHandler(),
FfmpegRandomAccessSource(DefaultDataSource.Factory(context)) { DataSpec(fixtureUri) }
)
assertNotNull("FFmpeg demuxer JNI library is unavailable", extractor)
arrayOf(extractor!!)
}
val player = ExoPlayer.Builder(context, PlezyRenderersFactory(context))
.setLooper(playbackThread.looper)
.build()
playerReference.set(player)
player.addListener(object : Player.Listener {
override fun onPlayerError(error: PlaybackException) {
errorReference.set(error)
completed.countDown()
}
override fun onPlaybackStateChanged(playbackState: Int) {
if (playbackState == Player.STATE_ENDED) {
completed.countDown()
}
}
})
val source = ProgressiveMediaSource.Factory(
DefaultDataSource.Factory(context),
ffmpegOnlyExtractors
).createMediaSource(MediaItem.fromUri(fixtureUri))
player.setMediaSource(source)
player.prepare()
player.play()
} catch (error: Throwable) {
errorReference.set(error)
completed.countDown()
}
}
val finished = completed.await(20, TimeUnit.SECONDS)
val released = CountDownLatch(1)
handler.post {
playerReference.get()?.release()
playbackThread.quitSafely()
released.countDown()
}
val teardownFinished = released.await(5, TimeUnit.SECONDS)
playbackThread.join(5_000)
val fixtureDeleted = fixtureFile.delete()
assertTrue("Player teardown timed out for $fixture", teardownFinished)
assertTrue("Playback timed out for $fixture", finished)
assertNull("Playback failed for $fixture", errorReference.get())
assertTrue("Fixture cleanup failed for $fixture", fixtureDeleted)
}
private fun copyFixture(instrumentationContext: Context, targetContext: Context, fixture: String): File {
val output = File.createTempFile("ffmpeg-csd-fixture-", null, targetContext.cacheDir)
instrumentationContext.assets.open(fixture).use { input ->
output.outputStream().use(input::copyTo)
}
return output
}
}
@@ -0,0 +1,357 @@
package com.edde746.plezy.exoplayer
import android.content.Context
import android.net.Uri
import androidx.media3.common.C
import androidx.media3.common.DataReader
import androidx.media3.common.Format
import androidx.media3.common.util.ParsableByteArray
import androidx.media3.datasource.DataSource
import androidx.media3.datasource.DataSpec
import androidx.media3.datasource.DefaultDataSource
import androidx.media3.datasource.TransferListener
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 androidx.media3.extractor.text.DefaultSubtitleParserFactory
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.edde746.plezy.libass.media.AssHandler
import java.io.File
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
/**
* Regression coverage for #2096 and for the seam that caused it.
*
* libavformat resolves seeks through its own index, reading it via
* [FfmpegRandomAccessSource]. When that read cannot be served, matroskadec
* burns its one-shot Cues parse and every later seek degrades to libavformat's
* linear generic scan — which is what buffered a resume for minutes. The cued
* fixture here has the same geometry as the file from the report (front
* SeekHead, Cues at 99.5% of the file), so a scan is trivially distinguishable
* from an index seek: it has to read most of the file.
*/
@RunWith(AndroidJUnit4::class)
class FfmpegExtractorSeekTest {
private companion object {
// Regenerate with:
// ffmpeg -f lavfi -i "testsrc=size=160x120:rate=10:duration=30" \
// -c:v libx264 -g 10 -pix_fmt yuv420p -preset veryfast seek_cued.mkv
// mkvmerge --no-cues -o seek_cueless.mkv seek_cued.mkv
// The cued fixture keeps ffmpeg's default layout: a SeekHead at byte 52
// pointing at Cues written after the clusters, at 99.5% of the file.
const val CUED = "ffmpeg/seek_cued.mkv"
const val CUELESS = "ffmpeg/seek_cueless.mkv"
/** The fixtures are 30 s at 10 fps with a keyframe every second. */
const val TARGET_US = 25_000_000L
const val KEYFRAME_TOLERANCE_US = 1_500_000L
}
@Test
fun cuedSeekLandsOnTheTargetWithoutWalkingTheFile() {
withHarness(CUED) { harness ->
harness.pumpUntilSampleDelivered()
assertTrue(
"playback should start at the beginning, got ${harness.lastSampleUs}us",
harness.lastSampleUs < 500_000L
)
harness.resetByteCounter()
harness.seekTo(TARGET_US)
val landed = harness.pumpUntilSampleAtLeast(TARGET_US - KEYFRAME_TOLERANCE_US)
assertTrue("no sample delivered after seeking to ${TARGET_US}us", landed)
assertTrue(
"seek landed at ${harness.lastSampleUs}us, expected within " +
"${KEYFRAME_TOLERANCE_US}us of ${TARGET_US}us",
harness.lastSampleUs <= TARGET_US + KEYFRAME_TOLERANCE_US
)
// An index seek reads the Cues plus the target cluster. A generic scan
// has to read everything up to 83% of the file to get here.
val budget = harness.fixtureSize / 3
assertTrue(
"seek read ${harness.bytesRead} bytes of a ${harness.fixtureSize}-byte file; " +
"expected under $budget (index seek, not a scan)",
harness.bytesRead < budget
)
// Reopening per read would mean one request per 64 KB in steady state.
assertTrue("random-access opens after seek: ${harness.randomAccessOpens}", harness.randomAccessOpens <= 4)
}
}
/**
* Without Cues libavformat falls back to its generic scan, exactly as media3's
* own MatroskaExtractor scans clusters. That is slow but it must still land on
* the target rather than stalling or silently delivering from the wrong place.
*/
@Test
fun cuelessSeekStillReachesTheTarget() {
withHarness(CUELESS) { harness ->
harness.pumpUntilSampleDelivered()
harness.seekTo(TARGET_US)
val landed = harness.pumpUntilSampleAtLeast(TARGET_US - KEYFRAME_TOLERANCE_US)
assertTrue("cueless seek to ${TARGET_US}us delivered nothing", landed)
assertTrue(
"cueless seek landed at ${harness.lastSampleUs}us",
harness.lastSampleUs <= TARGET_US + KEYFRAME_TOLERANCE_US
)
}
}
/**
* A download stored through SAF arrives as `content://`, which media3 reads
* with `openAssetFileDescriptor`. The demuxer's index reads therefore have to
* open a second descriptor on the same document while the loader still holds
* one — the case a `file://` fixture cannot prove.
*/
@Test
fun cuedSeekLandsOnTheTargetThroughAContentUri() {
withHarness(CUED, contentUri = true) { harness ->
harness.pumpUntilSampleDelivered()
harness.resetByteCounter()
harness.seekTo(TARGET_US)
val landed = harness.pumpUntilSampleAtLeast(TARGET_US - KEYFRAME_TOLERANCE_US)
assertTrue("no sample delivered after a content:// seek to ${TARGET_US}us", landed)
assertTrue(
"content:// seek landed at ${harness.lastSampleUs}us",
harness.lastSampleUs <= TARGET_US + KEYFRAME_TOLERANCE_US
)
assertTrue(
"content:// index read opened no descriptor of its own",
harness.randomAccessOpens > 0
)
val budget = harness.fixtureSize / 3
assertTrue(
"content:// seek read ${harness.bytesRead} bytes of a ${harness.fixtureSize}-byte file; " +
"expected under $budget (index seek, not a scan)",
harness.bytesRead < budget
)
}
}
@Test
fun playbackFromTheStartDeliversEverySampleFromTheBeginning() {
withHarness(CUED) { harness ->
val timestamps = harness.pumpSamples(count = 40)
assertTrue("expected samples from the start, got ${timestamps.size}", timestamps.size >= 40)
assertTrue("first sample at ${timestamps.first()}us", timestamps.first() < 500_000L)
// Delivery is in decode order, which is not presentation order once the
// encoder emits B-frames; what must hold is that the set of samples is
// gapless from zero (this fixture is a steady 10 fps).
val sorted = timestamps.sorted()
assertEquals(sorted.indices.map { it * 100_000L }, sorted)
}
}
private fun withHarness(fixture: String, contentUri: Boolean = false, block: (Harness) -> Unit) {
val instrumentation = InstrumentationRegistry.getInstrumentation()
val context = instrumentation.targetContext
val file = copyFixture(instrumentation.context, context, fixture)
// The content:// case reads the same asset back through the provider, which
// keeps its own copy: this process cannot write into the test APK's dirs.
val uri = if (contentUri) FixtureContentProvider.uriFor(fixture) else Uri.fromFile(file)
val harness = Harness(context, file, uri)
try {
harness.prepare()
block(harness)
} finally {
harness.close()
file.delete()
}
}
private fun copyFixture(instrumentationContext: Context, targetContext: Context, fixture: String): File {
val cacheDir = targetContext.cacheDir.also { it.mkdirs() }
val output = File.createTempFile("ffmpeg-seek-fixture-", ".mkv", cacheDir)
instrumentationContext.assets.open(fixture).use { input ->
output.outputStream().use(input::copyTo)
}
return output
}
/**
* Minimal stand-in for ProgressiveMediaPeriod's loader: it opens the data
* source, feeds an ExtractorInput, and honours RESULT_SEEK by re-opening —
* the same contract media3 implements in ExtractingLoadable.load().
*/
private class Harness(context: Context, fixture: File, private val uri: Uri) {
val fixtureSize = fixture.length()
private val counting = CountingDataSourceFactory(DefaultDataSource.Factory(context))
private val io = FfmpegRandomAccessSource(counting) { DataSpec(uri) }
private val output = CapturingOutput()
private val positionHolder = PositionHolder()
private val extractor = requireNotNull(
FfmpegExtractor.create(
{ FfmpegDemuxerPolicy.Preference.FFMPEG },
DvConversionMode.DISABLED,
DefaultSubtitleParserFactory(),
AssHandler(),
io
)
) { "native ffmpeg demuxer unavailable" }
private var dataSource: DataSource? = null
private var input: ExtractorInput? = null
private var opensBaseline = 0
val lastSampleUs: Long
get() = output.lastSampleUs
val bytesRead: Long
get() = counting.bytesRead
val randomAccessOpens: Int
get() = io.openCount - opensBaseline
fun prepare() {
openAt(0)
assertTrue("fixture should be sniffed by the ffmpeg demuxer", extractor.sniff(input!!))
input!!.resetPeekPosition()
extractor.init(output)
}
fun resetByteCounter() {
counting.reset()
opensBaseline = io.openCount
}
fun seekTo(timeUs: Long) {
// media3 restarts the load at the SeekMap's byte hint, then calls seek()
// on the loader thread before the next read.
val hint = output.seekMap?.getSeekPoints(timeUs)?.first?.position ?: 0L
openAt(hint)
extractor.seek(hint, timeUs)
}
fun pumpUntilSampleDelivered(): Boolean {
val before = output.sampleCount
return pump { output.sampleCount > before }
}
fun pumpUntilSampleAtLeast(timeUs: Long): Boolean = pump { output.lastSampleUs >= timeUs }
fun pumpSamples(count: Int): List<Long> {
pump { output.sampleTimestamps.size >= count }
return output.sampleTimestamps.toList()
}
private fun pump(until: () -> Boolean): Boolean {
repeat(200_000) {
if (until()) return true
when (extractor.read(input!!, positionHolder)) {
Extractor.RESULT_SEEK -> openAt(positionHolder.position)
Extractor.RESULT_END_OF_INPUT -> return until()
else -> Unit
}
}
return until()
}
private fun openAt(position: Long) {
dataSource?.close()
val source = counting.createDataSource()
val remaining = source.open(DataSpec.Builder().setUri(uri).setPosition(position).build())
dataSource = source
input = DefaultExtractorInput(
source,
position,
if (remaining == C.LENGTH_UNSET.toLong()) C.LENGTH_UNSET.toLong() else position + remaining
)
}
fun close() {
extractor.release()
dataSource?.close()
}
}
private class CapturingOutput : ExtractorOutput {
val sampleTimestamps = mutableListOf<Long>()
var seekMap: SeekMap? = null
private set
val sampleCount: Int
get() = sampleTimestamps.size
val lastSampleUs: Long
get() = sampleTimestamps.lastOrNull() ?: C.TIME_UNSET
override fun track(id: Int, type: Int): TrackOutput = CapturingTrack(type, sampleTimestamps)
override fun endTracks() = Unit
override fun seekMap(seekMap: SeekMap) {
this.seekMap = seekMap
}
}
private class CapturingTrack(private val type: Int, private val timestamps: MutableList<Long>) : TrackOutput {
private val scratch = ByteArray(64 * 1024)
override fun format(format: Format) = Unit
override fun sampleData(input: DataReader, length: Int, allowEndOfInput: Boolean): Int = sampleData(input, length, allowEndOfInput, TrackOutput.SAMPLE_DATA_PART_MAIN)
override fun sampleData(input: DataReader, length: Int, allowEndOfInput: Boolean, sampleDataPart: Int): Int {
val read = input.read(scratch, 0, minOf(length, scratch.size))
return if (read == C.RESULT_END_OF_INPUT) 0 else read
}
override fun sampleData(data: ParsableByteArray, length: Int) {
sampleData(data, length, TrackOutput.SAMPLE_DATA_PART_MAIN)
}
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?) {
if (type == C.TRACK_TYPE_VIDEO) timestamps.add(timeUs)
}
}
/** Counts every byte the demuxer pulls, through either read path. */
private class CountingDataSourceFactory(private val delegate: DataSource.Factory) : DataSource.Factory {
@Volatile private var counter = 0L
val bytesRead: Long
get() = counter
fun reset() {
counter = 0L
}
override fun createDataSource(): DataSource = Counting(delegate.createDataSource())
private inner class Counting(private val inner: DataSource) : DataSource {
override fun open(dataSpec: DataSpec): Long = inner.open(dataSpec)
override fun read(buffer: ByteArray, offset: Int, length: Int): Int {
val read = inner.read(buffer, offset, length)
if (read > 0) counter += read
return read
}
override fun addTransferListener(transferListener: TransferListener) = inner.addTransferListener(transferListener)
override fun getUri(): Uri? = inner.uri
override fun getResponseHeaders(): Map<String, List<String>> = inner.responseHeaders
override fun close() = inner.close()
}
}
}
@@ -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(context)) {
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)
-13
View File
@@ -9,17 +9,14 @@
<!-- Allow minSdk=25 despite libmpv-android declaring minSdk=26 -->
<uses-sdk tools:overrideLibrary="dev.jdtech.mpv" />
<!-- Internet access permissions -->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
<!-- PIP and media session foreground service permissions -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK"/>
<uses-permission android:name="android.permission.REORDER_TASKS"/>
<!-- Background download notifications and foreground service -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC"/>
@@ -30,15 +27,11 @@
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" tools:node="remove" />
<!-- Android TV support (not required, but allow detection) -->
<uses-feature android:name="android.software.leanback" android:required="false" />
<!-- Android TV Watch Next integration -->
<uses-permission android:name="com.android.providers.tv.permission.WRITE_EPG_DATA"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<!-- Touchscreen not required for TV -->
<uses-feature android:name="android.hardware.touchscreen" android:required="false" />
<!-- Android Automotive OS support -->
<uses-feature android:name="android.hardware.type.automotive" android:required="false" />
<application
@@ -63,10 +56,6 @@
android:configChanges="orientation|keyboardHidden|keyboard|navigation|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
@@ -77,7 +66,6 @@
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
<!-- Allow app to appear in Android TV launcher -->
<category android:name="android.intent.category.LEANBACK_LAUNCHER"/>
</intent-filter>
<!-- Deep link handler for Watch Next items -->
@@ -88,7 +76,6 @@
<data android:scheme="plezy" android:host="play"/>
</intent-filter>
</activity>
<!-- FileProvider for sharing downloaded files with external players -->
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.edde746.plezy.fileprovider"
+4 -2
View File
@@ -19,20 +19,22 @@ else()
target_link_libraries(dovi_bridge log)
endif()
foreach(ffmpeg_library avcodec avutil swresample)
foreach(ffmpeg_library avcodec avformat avutil swresample)
add_library(${ffmpeg_library} SHARED IMPORTED)
set_target_properties(${ffmpeg_library} PROPERTIES
IMPORTED_LOCATION "${MPV_FFMPEG_ROOT}/native/${ANDROID_ABI}/lib${ffmpeg_library}.so")
endforeach()
add_library(ffmpegJNI SHARED
media3_ffmpeg_decoder/ffmpeg_jni.cc)
media3_ffmpeg_decoder/ffmpeg_jni.cc
media3_ffmpeg_demuxer/ffmpeg_demuxer_jni.cc)
target_compile_features(ffmpegJNI PRIVATE cxx_std_17)
target_include_directories(ffmpegJNI PRIVATE
"${MPV_FFMPEG_ROOT}/include"
"${CMAKE_CURRENT_SOURCE_DIR}/media3_ffmpeg_decoder")
target_link_libraries(ffmpegJNI
avcodec
avformat
avutil
swresample
android
@@ -0,0 +1,952 @@
/*
* Copyright (c) 2026 Plezy
*
* libavformat demuxing for media3. Wraps an AVFormatContext whose AVIOContext
* is served by a media3 ExtractorInput, so FFmpeg parses the container while
* media3 keeps owning decoders, renderers, and the whole playback surface.
*
* The seam used to be seeking. media3's Extractor is a pull API: an extractor
* cannot move the input; it returns RESULT_SEEK and the loader re-opens the
* data source. libavformat expects random access and seeks whenever it pleases
* (MP4 moov at end of file, AVI idx1, MKV Cues, MPEG-PS binary search), so
* serving it from the loader alone meant unwinding the in-flight libavformat
* call on every backward jump and replaying the whole open — which a
* one-shot lazy parse like matroska's Cues cannot survive (#2096).
*
* libavformat now gets what it actually requires: the Kotlin side hands this
* shim a random-access byte source (FfmpegRandomAccessSource), so every AVIO
* read succeeds at the position libavformat asked for and nothing is ever
* unwound. Two paths serve reads, chosen per read:
*
* - The loader's ExtractorInput when it already stands at that position. This
* is the steady state for sample delivery, and it keeps media3's byte
* accounting, back-pressure and load-error policy in charge of streaming.
* - The random-access source otherwise (header, index, post-seek jumps).
*
* Kotlin nudges the loader back into step after a jump by returning
* RESULT_SEEK to nativeLogicalPosition(); that is an optimization, never a
* correctness requirement, so no budgets or retries guard it.
*/
#include <android/log.h>
#include <jni.h>
#include <cmath>
#include <cstring>
#include <vector>
extern "C" {
#ifdef __cplusplus
#define __STDC_CONSTANT_MACROS
#ifdef _STDINT_H
#undef _STDINT_H
#endif
#include <stdint.h>
#endif
#include <libavcodec/avcodec.h>
#include <libavcodec/bsf.h>
#include <libavformat/avformat.h>
#include <libavutil/dict.h>
#include <libavutil/display.h>
#include <libavutil/dovi_meta.h>
#include <libavutil/error.h>
#include <libavutil/rational.h>
}
#define LOG_TAG "ffmpeg_demuxer"
#define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__))
#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__))
#define LOGD(...) ((void)__android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__))
namespace {
// readPacket() result codes written to out[0]. Negative values are raw
// AVERROR codes; ERR_JAVA signals the byte source threw and Kotlin must
// rethrow the stored IOException.
const jint CODE_PACKET = 0;
const jint CODE_EOF = 1;
const jint CODE_GROW = 2;
const jint ERR_NOT_OPEN = -101;
const jint ERR_JAVA = -102;
// streamInfo() long[] layout. Keep in sync with FfmpegDemuxerJni.kt.
const int INFO_TRACK_TYPE = 0; // 0 video, 1 audio, 2 text, -1 unsupported
const int INFO_WIDTH = 1;
const int INFO_HEIGHT = 2;
const int INFO_PAR_NUM = 3;
const int INFO_PAR_DEN = 4;
const int INFO_FPS_NUM = 5;
const int INFO_FPS_DEN = 6;
const int INFO_SAMPLE_RATE = 7;
const int INFO_CHANNELS = 8;
const int INFO_PCM_ENCODING = 9; // media3 C.ENCODING_* value, -1 when n/a
const int INFO_ROTATION = 10;
const int INFO_SELECTION_FLAGS = 11;
const int INFO_ROLE_FLAGS = 12;
const int INFO_BITRATE = 13;
const int INFO_DOVI_PROFILE = 14; // DV profile from dvcC/dvvC side data, -1 when none
const int INFO_DOVI_LEVEL = 15;
const int INFO_LATM = 16; // 1 when the audio stream is LOAS/LATM-framed AAC
const int INFO_LENGTH = 17;
// Android AudioFormat encoding constants (media3 C.ENCODING_* mirror them).
const jint PCM_ENCODING_NONE = -1;
const jint PCM_ENCODING_8BIT = 3;
const jint PCM_ENCODING_16BIT = 2;
const jint PCM_ENCODING_FLOAT = 4;
const jint PCM_ENCODING_24BIT_PACKED = 21;
const jint PCM_ENCODING_32BIT = 22;
const jint PCM_ENCODING_ALAW = 11;
const jint PCM_ENCODING_ULAW = 12;
// media3 C.SELECTION_FLAG_* and C.ROLE_FLAG_* values.
const jint SELECTION_FLAG_DEFAULT = 1;
const jint SELECTION_FLAG_FORCED = 2;
const jint ROLE_FLAG_MAIN = 1;
const jint ROLE_FLAG_DESCRIPTION = 64; // C.ROLE_FLAG_DESCRIPTION
const jint ROLE_FLAG_HARD_OF_HEARING = 512; // C.ROLE_FLAG_HARD_OF_HEARING
constexpr jint kReadChunkBytes = 64 * 1024;
struct DemuxState {
JavaVM* vm = nullptr;
jobject input = nullptr;
jmethodID midPosition = nullptr;
jmethodID midRead = nullptr;
jmethodID midReadAt = nullptr;
jmethodID midLength = nullptr;
jbyteArray readBuffer = nullptr;
AVFormatContext* format = nullptr;
AVIOContext* avio = nullptr;
bool opened = false;
// Byte position libavformat will read next. Authoritative: the AVIO seek
// callback moves it, and both read paths serve exactly this offset.
int64_t logicalPos = 0;
// format->start_time in microseconds; subtracted from delivered pts so
// media3's zero-based timeline matches the duration we report (MPEG-PS/TS
// containers commonly start at a nonzero PCR).
int64_t startTimeUs = 0;
AVPacket* packet = nullptr;
AVPacket* filteredPacket = nullptr;
// A packet that outgrew the Java-side buffer: already read and filtered,
// waiting for redelivery after CODE_GROW. Without this flag the retry's
// av_read_frame would silently drop it.
bool packetPending = false;
// Annex-B conversion for H264/HEVC streams stored length-prefixed
// (matroska/mp4 family); one context per stream, null when none needed.
AVBSFContext** bsf = nullptr;
unsigned nbStreams = 0;
bool javaError = false;
};
// One demuxer at a time: a player session owns exactly one progressive source
// and the extractor releases its state before another can open.
DemuxState* gState = nullptr;
JavaVM* gVm = nullptr;
// Serializes JNI entry points against closeState: the fallback path can
// release the player while the loader thread is inside a native call, and
// deleting DemuxState under it is a use-after-free (observed as a scudo
// invalid-chunk abort during MPV fallback teardown).
pthread_mutex_t gStateMutex = PTHREAD_MUTEX_INITIALIZER;
struct StateLock {
StateLock() { pthread_mutex_lock(&gStateMutex); }
~StateLock() { pthread_mutex_unlock(&gStateMutex); }
};
JNIEnv* envFor() {
JNIEnv* env = nullptr;
if (gVm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) return nullptr;
return env;
}
bool javaPending(JNIEnv* env) { return env->ExceptionCheck() == JNI_TRUE; }
void javaClear(JNIEnv* env) {
if (env->ExceptionCheck() == JNI_TRUE) env->ExceptionClear();
}
jlong callPosition(JNIEnv* env, DemuxState* s) { return env->CallLongMethod(s->input, s->midPosition); }
jlong callLength(JNIEnv* env, DemuxState* s) { return env->CallLongMethod(s->input, s->midLength); }
// Returns bytes read, 0 at end of input, or -1 when the input failed (the
// Kotlin proxy stored the IOException message).
jint callRead(JNIEnv* env, DemuxState* s, jint length) {
jint n = env->CallIntMethod(s->input, s->midRead, s->readBuffer, length);
if (javaPending(env)) {
javaClear(env);
s->javaError = true;
return -1;
}
return n;
}
// Same contract as callRead, but at an absolute position: the Kotlin source
// reopens its handle when the position is not where it stands.
jint callReadAt(JNIEnv* env, DemuxState* s, int64_t position, jint length) {
jint n = env->CallIntMethod(s->input, s->midReadAt, static_cast<jlong>(position), s->readBuffer, length);
if (javaPending(env)) {
javaClear(env);
s->javaError = true;
return -1;
}
return n;
}
int avioReadPacket(void* opaque, uint8_t* buf, int bufSize) {
DemuxState* s = static_cast<DemuxState*>(opaque);
JNIEnv* env = envFor();
if (env == nullptr) return AVERROR(EIO);
if (bufSize <= 0) return 0;
const jint want = bufSize < kReadChunkBytes ? bufSize : kReadChunkBytes;
// Prefer the loader's input when it already stands here: those bytes then
// count as media3's own load progress, which is what drives its buffering
// and back-pressure. Anywhere else, read at the absolute position.
const int64_t inputPos = callPosition(env, s);
if (javaPending(env)) {
javaClear(env);
s->javaError = true;
return AVERROR(EIO);
}
const jint n = inputPos == s->logicalPos ? callRead(env, s, want) : callReadAt(env, s, s->logicalPos, want);
if (s->javaError) return AVERROR(EIO);
if (n < 0) return AVERROR(EIO);
if (n == 0) return AVERROR_EOF;
env->GetByteArrayRegion(s->readBuffer, 0, n, reinterpret_cast<jbyte*>(buf));
s->logicalPos += n;
return n;
}
int64_t avioSeek(void* opaque, int64_t offset, int whence) {
DemuxState* s = static_cast<DemuxState*>(opaque);
JNIEnv* env = envFor();
if (env == nullptr) return AVERROR(EIO);
whence &= ~AVSEEK_FORCE;
if (whence == AVSEEK_SIZE) {
int64_t length = callLength(env, s);
if (javaPending(env)) {
javaClear(env);
s->javaError = true;
return -1;
}
return length < 0 ? -1 : length;
}
int64_t target;
if (whence == SEEK_CUR) {
target = s->logicalPos + offset;
} else if (whence == SEEK_END) {
int64_t length = callLength(env, s);
if (javaPending(env)) {
javaClear(env);
s->javaError = true;
return AVERROR(EIO);
}
if (length < 0) return AVERROR(EIO);
target = length + offset;
} else {
target = offset;
}
// Pure bookkeeping: the next read serves this position from whichever path
// can, so a seek can no longer fail or need reconciling. avio invalidates
// its own buffers after this successful callback.
s->logicalPos = target;
return target;
}
// Probing (ffio_ensure_seekback) can swap the AVIO buffer for a larger
// allocation and free the original, so the pointer handed to
// avio_alloc_context may be stale. Free whichever buffer the context
// currently holds, exactly once.
void freeAvio(DemuxState* s) {
if (s->avio == nullptr) return;
av_freep(&s->avio->buffer);
avio_context_free(&s->avio);
}
void closeState() {
DemuxState* s = gState;
if (s == nullptr) return; // Close without (or after) an open is a no-op.
JNIEnv* env = envFor();
if (s->filteredPacket != nullptr) {
av_packet_free(&s->filteredPacket);
}
if (s->bsf != nullptr) {
for (unsigned i = 0; i < s->nbStreams; i++) {
if (s->bsf[i] != nullptr) av_bsf_free(&s->bsf[i]);
}
av_freep(&s->bsf);
}
if (s->packet != nullptr) {
av_packet_free(&s->packet);
}
if (s->format != nullptr) {
avformat_close_input(&s->format);
}
freeAvio(s);
if (env != nullptr && s->input != nullptr) {
if (s->readBuffer != nullptr) env->DeleteGlobalRef(s->readBuffer);
env->DeleteGlobalRef(s->input);
}
delete s;
gState = nullptr;
}
const char* videoMime(AVCodecID id) {
switch (id) {
case AV_CODEC_ID_H264:
return "video/avc";
case AV_CODEC_ID_HEVC:
return "video/hevc";
case AV_CODEC_ID_MPEG4:
return "video/mp4v-es";
case AV_CODEC_ID_MPEG2VIDEO:
return "video/mpeg2";
case AV_CODEC_ID_MJPEG:
return "video/mjpeg";
case AV_CODEC_ID_VP8:
return "video/x-vnd.on2.vp8";
case AV_CODEC_ID_VP9:
return "video/x-vnd.on2.vp9";
case AV_CODEC_ID_AV1:
return "video/av01";
case AV_CODEC_ID_H263:
return "video/3gpp";
default:
return nullptr;
}
}
const char* audioMime(AVCodecID id, jint* pcmEncoding) {
*pcmEncoding = PCM_ENCODING_NONE;
switch (id) {
case AV_CODEC_ID_AAC:
return "audio/mp4a-latm";
case AV_CODEC_ID_AAC_LATM:
// LOAS/LATM framing. Kotlin wraps the track with LatmTrackOutput, which
// unwraps to raw AAC access units and emits the real decoder Format;
// this mime only marks the stream as supported.
return "audio/mp4a-latm";
case AV_CODEC_ID_MP3:
return "audio/mpeg";
case AV_CODEC_ID_MP2:
return "audio/mpeg-L2";
case AV_CODEC_ID_AC3:
return "audio/ac3";
case AV_CODEC_ID_EAC3:
return "audio/eac3";
case AV_CODEC_ID_DTS:
return "audio/vnd.dts";
case AV_CODEC_ID_TRUEHD:
return "audio/true-hd";
case AV_CODEC_ID_FLAC:
return "audio/flac";
case AV_CODEC_ID_OPUS:
return "audio/opus";
case AV_CODEC_ID_VORBIS:
return "audio/vorbis";
case AV_CODEC_ID_ALAC:
return "audio/alac";
case AV_CODEC_ID_AMR_NB:
return "audio/amr";
case AV_CODEC_ID_AMR_WB:
return "audio/amr-wb";
case AV_CODEC_ID_PCM_S16LE:
*pcmEncoding = PCM_ENCODING_16BIT;
return "audio/raw";
case AV_CODEC_ID_PCM_S16BE:
*pcmEncoding = PCM_ENCODING_16BIT;
return "audio/raw";
case AV_CODEC_ID_PCM_S8:
*pcmEncoding = PCM_ENCODING_8BIT;
return "audio/raw";
case AV_CODEC_ID_PCM_U8:
*pcmEncoding = PCM_ENCODING_8BIT;
return "audio/raw";
case AV_CODEC_ID_PCM_S24LE:
*pcmEncoding = PCM_ENCODING_24BIT_PACKED;
return "audio/raw";
case AV_CODEC_ID_PCM_S32LE:
*pcmEncoding = PCM_ENCODING_32BIT;
return "audio/raw";
case AV_CODEC_ID_PCM_F32LE:
*pcmEncoding = PCM_ENCODING_FLOAT;
return "audio/raw";
case AV_CODEC_ID_PCM_F32BE:
*pcmEncoding = PCM_ENCODING_FLOAT;
return "audio/raw";
case AV_CODEC_ID_PCM_ALAW:
*pcmEncoding = PCM_ENCODING_ALAW;
return "audio/raw";
case AV_CODEC_ID_PCM_MULAW:
*pcmEncoding = PCM_ENCODING_ULAW;
return "audio/raw";
default:
return nullptr;
}
}
const char* subtitleMime(AVCodecID id) {
switch (id) {
case AV_CODEC_ID_SUBRIP:
return "application/x-subrip";
case AV_CODEC_ID_ASS:
case AV_CODEC_ID_SSA:
return "text/x-ssa";
case AV_CODEC_ID_WEBVTT:
return "text/vtt";
case AV_CODEC_ID_HDMV_PGS_SUBTITLE:
return "application/pgs";
case AV_CODEC_ID_DVD_SUBTITLE:
// media3's VobsubParser takes the .idx text (Matroska CodecPrivate,
// surfaced verbatim as extradata) as initialization data and the raw
// SPU payloads as samples — exactly what this path delivers.
return "application/vobsub";
default:
// DVB subtitles are deliberately dropped: media3's DvbParser expects
// the TS/PMT 5-byte config, not Matroska CodecPrivate, and DVB rides
// TS in practice — which stays on media3's extractor.
return nullptr;
}
}
// Maps an attachment ordinal to its stream index. Attachment payloads
// (embedded fonts) ride extradata and are fully parsed during
// avformat_open_input; these streams never produce packets.
int attachmentStreamIndex(AVFormatContext* format, jint ordinal) {
jint seen = 0;
for (unsigned i = 0; i < format->nb_streams; i++) {
AVCodecParameters* params = format->streams[i]->codecpar;
if (params->codec_type != AVMEDIA_TYPE_ATTACHMENT) continue;
if (params->extradata == nullptr || params->extradata_size <= 0) continue;
if (seen++ == ordinal) return static_cast<int>(i);
}
return -1;
}
} // namespace
extern "C" {
JNIEXPORT jstring JNICALL
Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeProbeFormat(JNIEnv* env, jobject thiz, jbyteArray header) {
StateLock lock;
jsize size = env->GetArrayLength(header);
std::vector<uint8_t> padded(static_cast<size_t>(size) + AVPROBE_PADDING_SIZE, 0);
env->GetByteArrayRegion(header, 0, size, reinterpret_cast<jbyte*>(padded.data()));
AVProbeData probe{};
probe.buf = padded.data();
probe.buf_size = size;
probe.filename = "";
int score = 0;
const AVInputFormat* format = av_probe_input_format2(&probe, 1, &score);
if (format == nullptr || score <= 0) return nullptr;
return env->NewStringUTF(format->name);
}
// Returns 0 on success or a negative AVERROR (ERR_JAVA when the byte source
// itself threw). The stream count is NOT the return value: positive counts
// would share the result-code namespace, so callers use nativeStreamCount().
JNIEXPORT jint JNICALL
Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeOpen(JNIEnv* env, jobject thiz, jobject input) {
StateLock lock;
if (gVm == nullptr) {
env->GetJavaVM(&gVm);
av_log_set_level(AV_LOG_ERROR);
}
if (gState == nullptr) {
gState = new DemuxState();
gState->vm = gVm;
}
DemuxState* s = gState;
// FindClass on the declared interface (not GetObjectClass on the concrete
// proxy): JNI dispatches interface method IDs virtually, and the named
// class is what the shrinker keep in proguard-rules.pro pins.
jclass inputClass = env->FindClass("com/edde746/plezy/exoplayer/FfmpegDemuxerJni$Input");
if (inputClass == nullptr) {
javaClear(env);
return ERR_NOT_OPEN;
}
jmethodID midPosition = env->GetMethodID(inputClass, "position", "()J");
jmethodID midRead = env->GetMethodID(inputClass, "read", "([BI)I");
jmethodID midReadAt = env->GetMethodID(inputClass, "readAt", "(J[BI)I");
jmethodID midLength = env->GetMethodID(inputClass, "length", "()J");
env->DeleteLocalRef(inputClass);
if (midPosition == nullptr || midRead == nullptr || midReadAt == nullptr || midLength == nullptr) {
javaClear(env);
return ERR_NOT_OPEN;
}
// A fresh open replaces any previous proxy binding.
if (s->input != nullptr) {
if (s->readBuffer != nullptr) env->DeleteGlobalRef(s->readBuffer);
env->DeleteGlobalRef(s->input);
s->input = nullptr;
s->readBuffer = nullptr;
}
s->input = env->NewGlobalRef(input);
s->midPosition = midPosition;
s->midRead = midRead;
s->midReadAt = midReadAt;
s->midLength = midLength;
jbyteArray readBuffer = env->NewByteArray(kReadChunkBytes);
s->readBuffer = static_cast<jbyteArray>(env->NewGlobalRef(readBuffer));
env->DeleteLocalRef(readBuffer);
if (s->packet == nullptr) {
s->packet = av_packet_alloc();
s->filteredPacket = av_packet_alloc();
if (s->packet == nullptr || s->filteredPacket == nullptr) return AVERROR(ENOMEM);
}
// One AVIOContext per item: a stale buffer or a sticky error from the
// previous item must not leak into this open, and reallocating is cheaper
// than reasoning about which of libavformat's internal fields to reset.
freeAvio(s);
constexpr int kAvioBufferSize = 64 * 1024;
unsigned char* avioBuffer = static_cast<unsigned char*>(av_malloc(kAvioBufferSize));
if (avioBuffer == nullptr) return AVERROR(ENOMEM);
s->avio = avio_alloc_context(
avioBuffer, kAvioBufferSize, /*write_flag=*/0, s, avioReadPacket,
/*write_packet=*/nullptr, avioSeek);
if (s->avio == nullptr) {
av_freep(&avioBuffer);
return AVERROR(ENOMEM);
}
s->javaError = false;
s->packetPending = false;
s->logicalPos = 0;
// Nothing is ever resumed across calls now: every read succeeds at the
// position libavformat asked for, so open_input and find_stream_info each
// run once, to completion.
avformat_close_input(&s->format);
s->opened = false;
s->format = avformat_alloc_context();
if (s->format == nullptr) return AVERROR(ENOMEM);
s->format->pb = s->avio;
// Generate missing PTS: some raw streams (MPEG-TS after a seek) present
// packets without timestamps that media3 cannot schedule.
s->format->flags |= AVFMT_FLAG_GENPTS;
int err = avformat_open_input(&s->format, "", nullptr, nullptr);
if (s->javaError) return ERR_JAVA;
if (err < 0) {
LOGW("avformat_open_input failed: %d", err);
return err;
}
err = avformat_find_stream_info(s->format, nullptr);
if (s->javaError) return ERR_JAVA;
if (err < 0) {
LOGW("avformat_find_stream_info failed: %d", err);
return err;
}
// Zero-base the timeline: delivered pts subtract this so media3 sees
// [0, duration] even when the container starts at a nonzero PCR/PTS.
s->startTimeUs = s->format->start_time != AV_NOPTS_VALUE ? s->format->start_time : 0;
s->opened = true;
bool anySupported = false;
for (unsigned i = 0; i < s->format->nb_streams; i++) {
AVStream* stream = s->format->streams[i];
AVCodecID codecId = stream->codecpar->codec_id;
jint pcmEncoding;
bool supported = videoMime(codecId) != nullptr || audioMime(codecId, &pcmEncoding) != nullptr ||
subtitleMime(codecId) != nullptr;
// ID3/MKV attached pictures surface as video streams; media3 cannot
// render them as tracks.
if (stream->attached_pic.size > 0) supported = false;
if (!supported) {
LOGW("Dropping stream %u: unsupported codec %s", i, avcodec_get_name(codecId));
stream->discard = AVDISCARD_ALL;
} else {
anySupported = true;
}
}
if (!anySupported) {
// Fail fast so the session falls back (mpv decodes WMV and friends)
// instead of buffering an empty track list forever.
LOGW("No supported streams; refusing container");
avformat_close_input(&s->format);
s->opened = false;
return AVERROR(ENOSYS);
}
// MediaCodec requires Annex-B start-code framing for H264/HEVC, while the
// matroska/mp4 family stores length-prefixed NAL units and libavformat
// hands those through verbatim (ffmpeg muxers insert the same
// *_mp4toannexb bitstream filters in this situation). Filter those streams
// here so every packet leaving the shim is decoder-ready, and adopt the
// filter's rewritten parameters so extradata surfaces as Annex-B csd too.
if (s->bsf != nullptr) {
for (unsigned i = 0; i < s->nbStreams; i++) {
if (s->bsf[i] != nullptr) av_bsf_free(&s->bsf[i]);
}
av_freep(&s->bsf);
}
s->nbStreams = s->format->nb_streams;
s->bsf = static_cast<AVBSFContext**>(av_calloc(s->nbStreams, sizeof(*s->bsf)));
if (s->bsf == nullptr) return AVERROR(ENOMEM);
for (unsigned i = 0; i < s->nbStreams; i++) {
AVCodecID codecId = s->format->streams[i]->codecpar->codec_id;
const char* filterName = codecId == AV_CODEC_ID_H264 ? "h264_mp4toannexb"
: codecId == AV_CODEC_ID_HEVC ? "hevc_mp4toannexb"
// AVI-family MPEG-4 ASP commonly packs several VOPs into one chunk;
// hardware decoders silently drop those stacks (observed as a decoder
// hang with zero output), so unpack them like every ffmpeg pipeline.
: codecId == AV_CODEC_ID_MPEG4 ? "mpeg4_unpack_bframes"
: nullptr;
const AVBitStreamFilter* filter = av_bsf_get_by_name(filterName);
AVBSFContext* ctx = nullptr;
if (filter == nullptr || av_bsf_alloc(filter, &ctx) < 0 ||
avcodec_parameters_copy(ctx->par_in, s->format->streams[i]->codecpar) < 0) {
if (ctx != nullptr) av_bsf_free(&ctx);
continue;
}
ctx->time_base_in = s->format->streams[i]->time_base;
if (av_bsf_init(ctx) < 0) {
av_bsf_free(&ctx);
continue;
}
avcodec_parameters_copy(s->format->streams[i]->codecpar, ctx->par_out);
s->format->streams[i]->time_base = ctx->time_base_out;
s->bsf[i] = ctx;
}
return 0; // Success; prepareTracks() reads the count via nativeStreamCount().
}
JNIEXPORT void JNICALL Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeClose(JNIEnv* env, jobject thiz) {
StateLock lock;
closeState();
}
JNIEXPORT jint JNICALL Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeStreamCount(JNIEnv* env, jobject thiz) {
StateLock lock;
if (gState == nullptr || gState->format == nullptr) return ERR_NOT_OPEN;
return static_cast<jint>(gState->format->nb_streams);
}
JNIEXPORT jlong JNICALL Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeDurationUs(JNIEnv* env, jobject thiz) {
StateLock lock;
if (gState == nullptr || gState->format == nullptr) return -1;
int64_t duration = gState->format->duration;
return duration == AV_NOPTS_VALUE ? -1 : duration;
}
// Returns true when the stream is usable and filled the out arrays.
JNIEXPORT jboolean JNICALL Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeStreamInfo(
JNIEnv* env, jobject thiz, jint index, jlongArray numbers, jobjectArray strings) {
StateLock lock;
if (gState == nullptr || gState->format == nullptr || index < 0 ||
index >= static_cast<jint>(gState->format->nb_streams)) {
return JNI_FALSE;
}
AVStream* stream = gState->format->streams[index];
AVCodecParameters* params = stream->codecpar;
jint trackType;
const char* mime = nullptr;
jint pcmEncoding = PCM_ENCODING_NONE;
switch (params->codec_type) {
case AVMEDIA_TYPE_VIDEO:
trackType = 0;
mime = videoMime(params->codec_id);
break;
case AVMEDIA_TYPE_AUDIO:
trackType = 1;
mime = audioMime(params->codec_id, &pcmEncoding);
break;
case AVMEDIA_TYPE_SUBTITLE:
trackType = 2;
mime = subtitleMime(params->codec_id);
break;
default:
return JNI_FALSE;
}
if (mime == nullptr) return JNI_FALSE;
jlong info[INFO_LENGTH] = {};
info[INFO_TRACK_TYPE] = trackType;
info[INFO_WIDTH] = params->width;
info[INFO_HEIGHT] = params->height;
AVRational par = params->sample_aspect_ratio;
if (par.num <= 0 || par.den <= 0) par = stream->sample_aspect_ratio;
info[INFO_PAR_NUM] = par.num > 0 ? par.num : 1;
info[INFO_PAR_DEN] = par.num > 0 ? par.den : 1;
AVRational fps = stream->avg_frame_rate;
info[INFO_FPS_NUM] = fps.num > 0 ? fps.num : 0;
info[INFO_FPS_DEN] = fps.num > 0 ? fps.den : 0;
info[INFO_SAMPLE_RATE] = params->sample_rate > 0 ? params->sample_rate : -1;
info[INFO_CHANNELS] = params->ch_layout.nb_channels > 0 ? params->ch_layout.nb_channels : -1;
info[INFO_PCM_ENCODING] = pcmEncoding;
info[INFO_LATM] = params->codec_id == AV_CODEC_ID_AAC_LATM ? 1 : 0;
jint rotation = 0;
AVPacketSideData* sideData = nullptr;
for (int i = 0; i < params->nb_coded_side_data; i++) {
if (params->coded_side_data[i].type == AV_PKT_DATA_DISPLAYMATRIX) {
sideData = &params->coded_side_data[i];
break;
}
}
if (sideData != nullptr) {
double angle = av_display_rotation_get(reinterpret_cast<const int32_t*>(sideData->data));
if (!std::isnan(angle)) rotation = static_cast<jint>(-lround(angle));
}
info[INFO_ROTATION] = rotation;
jint selectionFlags = 0;
jint roleFlags = 0;
if (stream->disposition & AV_DISPOSITION_DEFAULT) selectionFlags |= SELECTION_FLAG_DEFAULT;
if (stream->disposition & AV_DISPOSITION_FORCED) selectionFlags |= SELECTION_FLAG_FORCED;
if (stream->disposition & AV_DISPOSITION_HEARING_IMPAIRED) roleFlags |= ROLE_FLAG_HARD_OF_HEARING;
if (stream->disposition & AV_DISPOSITION_VISUAL_IMPAIRED) roleFlags |= ROLE_FLAG_DESCRIPTION;
if (selectionFlags == 0 && trackType != 2) roleFlags |= ROLE_FLAG_MAIN;
info[INFO_SELECTION_FLAGS] = selectionFlags;
info[INFO_ROLE_FLAGS] = roleFlags;
info[INFO_BITRATE] = params->bit_rate > 0 ? params->bit_rate : -1;
// Dolby Vision configuration (dvcC/dvvC), surfaced by libavformat as an
// unpacked AVDOVIDecoderConfigurationRecord — one byte per field, not the
// bit-packed ISOBMFF box layout. Kotlin mirrors media3's DolbyVisionConfig
// to publish video/dolby-vision plus the RFC 6381 codecs string.
info[INFO_DOVI_PROFILE] = -1;
info[INFO_DOVI_LEVEL] = -1;
for (int i = 0; i < params->nb_coded_side_data; i++) {
AVPacketSideData* sd = &params->coded_side_data[i];
if (sd->type == AV_PKT_DATA_DOVI_CONF && sd->size >= sizeof(AVDOVIDecoderConfigurationRecord)) {
const AVDOVIDecoderConfigurationRecord* dovi =
reinterpret_cast<const AVDOVIDecoderConfigurationRecord*>(sd->data);
info[INFO_DOVI_PROFILE] = dovi->dv_profile;
info[INFO_DOVI_LEVEL] = dovi->dv_level;
break;
}
}
env->SetLongArrayRegion(numbers, 0, INFO_LENGTH, info);
const char* language = nullptr;
const char* label = nullptr;
if (stream->metadata != nullptr) {
AVDictionaryEntry* entry = av_dict_get(stream->metadata, "language", nullptr, 0);
if (entry != nullptr) language = entry->value;
entry = av_dict_get(stream->metadata, "title", nullptr, 0);
if (entry != nullptr) label = entry->value;
}
env->SetObjectArrayElement(strings, 0, env->NewStringUTF(mime));
env->SetObjectArrayElement(strings, 1, language != nullptr ? env->NewStringUTF(language) : nullptr);
env->SetObjectArrayElement(strings, 2, label != nullptr ? env->NewStringUTF(label) : nullptr);
return JNI_TRUE;
}
JNIEXPORT jbyteArray JNICALL
Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeStreamExtradata(JNIEnv* env, jobject thiz, jint index) {
StateLock lock;
if (gState == nullptr || gState->format == nullptr || index < 0 ||
index >= static_cast<jint>(gState->format->nb_streams)) {
return nullptr;
}
AVCodecParameters* params = gState->format->streams[index]->codecpar;
// libavformat carries the AVI stream's WAVEFORMATEX header as MP3
// extradata. MediaCodec mp3 decoders expect either no csd or the two-byte
// ISO header, and report a WAVEFORMATEX blob as corrupt input
// (C2_CORRUPTED on the first work item), so drop it.
if (params->codec_id == AV_CODEC_ID_MP3) return nullptr;
if (params->extradata == nullptr || params->extradata_size <= 0) return nullptr;
jbyteArray result = env->NewByteArray(params->extradata_size);
env->SetByteArrayRegion(result, 0, params->extradata_size, reinterpret_cast<const jbyte*>(params->extradata));
return result;
}
JNIEXPORT jint JNICALL
Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeAttachmentCount(JNIEnv* env, jobject thiz) {
StateLock lock;
if (gState == nullptr || gState->format == nullptr) return 0;
jint count = 0;
while (attachmentStreamIndex(gState->format, count) >= 0) count++;
return count;
}
// Fills strings with [filename, mimetype] and returns the payload size in
// bytes, or -1 when the ordinal is out of range.
JNIEXPORT jlong JNICALL Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeAttachmentInfo(
JNIEnv* env, jobject thiz, jint ordinal, jobjectArray strings) {
StateLock lock;
if (gState == nullptr || gState->format == nullptr) return -1;
int index = attachmentStreamIndex(gState->format, ordinal);
if (index < 0) return -1;
AVStream* stream = gState->format->streams[index];
const char* filename = nullptr;
const char* mimetype = nullptr;
if (stream->metadata != nullptr) {
AVDictionaryEntry* entry = av_dict_get(stream->metadata, "filename", nullptr, 0);
if (entry != nullptr) filename = entry->value;
entry = av_dict_get(stream->metadata, "mimetype", nullptr, 0);
if (entry != nullptr) mimetype = entry->value;
}
env->SetObjectArrayElement(strings, 0, filename != nullptr ? env->NewStringUTF(filename) : nullptr);
env->SetObjectArrayElement(strings, 1, mimetype != nullptr ? env->NewStringUTF(mimetype) : nullptr);
return stream->codecpar->extradata_size;
}
JNIEXPORT jbyteArray JNICALL
Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeAttachmentData(JNIEnv* env, jobject thiz, jint ordinal) {
StateLock lock;
if (gState == nullptr || gState->format == nullptr) return nullptr;
int index = attachmentStreamIndex(gState->format, ordinal);
if (index < 0) return nullptr;
AVCodecParameters* params = gState->format->streams[index]->codecpar;
jbyteArray result = env->NewByteArray(params->extradata_size);
if (result == nullptr) return nullptr;
env->SetByteArrayRegion(result, 0, params->extradata_size, reinterpret_cast<const jbyte*>(params->extradata));
return result;
}
// Reads one packet. out[0] carries the result code; on CODE_PACKET the packet
// bytes were written into the byte array and out carries
// [1]=streamIndex [2]=ptsUs (start-time normalized; packets without any
// timestamp are dropped, media3 cannot schedule them) [3]=flags [4]=size
// [5]=packet position in input coordinates [6]=durationUs (-1 unknown).
JNIEXPORT jint JNICALL Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeReadPacket(
JNIEnv* env, jobject thiz, jbyteArray buffer, jlongArray out) {
StateLock lock;
DemuxState* s = gState;
if (s == nullptr || !s->opened || s->format == nullptr) return ERR_NOT_OPEN;
jint capacity = env->GetArrayLength(buffer);
jlong result[7] = {};
s->javaError = false;
while (true) {
if (s->packetPending) {
// Oversized packet held across a CODE_GROW round trip: deliver it now
// instead of reading (and losing) a new frame.
s->packetPending = false;
} else {
av_packet_unref(s->packet);
int err = av_read_frame(s->format, s->packet);
if (err == AVERROR_EOF) {
result[0] = CODE_EOF;
env->SetLongArrayRegion(out, 0, 7, result);
return CODE_EOF;
}
if (err < 0 || s->javaError) {
result[0] = s->javaError ? ERR_JAVA : err;
env->SetLongArrayRegion(out, 0, 7, result);
return s->javaError ? ERR_JAVA : err;
}
if (s->packet->size <= 0) continue;
if (s->format->streams[s->packet->stream_index]->discard >= AVDISCARD_ALL) continue;
AVBSFContext* bsf = s->bsf != nullptr && s->packet->stream_index < static_cast<int>(s->nbStreams)
? s->bsf[s->packet->stream_index]
: nullptr;
if (bsf != nullptr) {
// send consumes the packet reference; move the filtered result back so
// the delivery code below keeps a single code path.
int filterErr = av_bsf_send_packet(bsf, s->packet);
if (filterErr >= 0) {
av_packet_unref(s->packet);
filterErr = av_bsf_receive_packet(bsf, s->filteredPacket);
if (filterErr == AVERROR(EAGAIN)) continue;
if (filterErr < 0) {
result[0] = filterErr;
env->SetLongArrayRegion(out, 0, 7, result);
return filterErr;
}
av_packet_move_ref(s->packet, s->filteredPacket);
} else {
result[0] = filterErr;
env->SetLongArrayRegion(out, 0, 7, result);
return filterErr;
}
}
}
int size = s->packet->size;
if (size > capacity) {
s->packetPending = true;
result[0] = CODE_GROW;
result[4] = size;
env->SetLongArrayRegion(out, 0, 7, result);
return CODE_GROW;
}
env->SetByteArrayRegion(buffer, 0, size, reinterpret_cast<const jbyte*>(s->packet->data));
AVStream* stream = s->format->streams[s->packet->stream_index];
int64_t ptsUs;
if (s->packet->pts != AV_NOPTS_VALUE) {
ptsUs = av_rescale_q(s->packet->pts, stream->time_base, AVRational{1, 1000000});
} else if (s->packet->dts != AV_NOPTS_VALUE) {
ptsUs = av_rescale_q(s->packet->dts, stream->time_base, AVRational{1, 1000000});
} else {
// No timestamp even after GENPTS: media3 cannot schedule the sample,
// and delivering data without metadata would corrupt the sample queue.
continue;
}
ptsUs -= s->startTimeUs;
result[0] = CODE_PACKET;
result[1] = s->packet->stream_index;
result[2] = ptsUs;
result[3] = (s->packet->flags & AV_PKT_FLAG_KEY) != 0 ? 1 : 0;
result[4] = size;
result[5] = s->packet->pos >= 0 ? s->packet->pos : 0;
result[6] =
s->packet->duration > 0 ? av_rescale_q(s->packet->duration, stream->time_base, AVRational{1, 1000000}) : -1;
env->SetLongArrayRegion(out, 0, 7, result);
return CODE_PACKET;
}
}
JNIEXPORT jlong JNICALL
Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeLogicalPosition(JNIEnv* env, jobject thiz) {
StateLock lock;
DemuxState* s = gState;
if (s == nullptr || !s->opened) return -1;
return static_cast<jlong>(s->logicalPos);
}
// Seeks to a presentation time (media3 timeline microseconds, start-time
// normalized). Called on the loader thread, where blocking IO belongs:
// libavformat reads its own index through the random-access source, so this
// either lands on the target keyframe or reports that the container has no
// usable index.
JNIEXPORT jint JNICALL
Java_com_edde746_plezy_exoplayer_FfmpegDemuxerJni_nativeSeek(JNIEnv* env, jobject thiz, jlong timeUs) {
StateLock lock;
DemuxState* s = gState;
if (s == nullptr || !s->opened || s->format == nullptr) return ERR_NOT_OPEN;
s->javaError = false;
// Any packet parked for a CODE_GROW retry belongs to the pre-seek stream.
s->packetPending = false;
if (s->bsf != nullptr) {
for (unsigned i = 0; i < s->nbStreams; i++) {
if (s->bsf[i] != nullptr) av_bsf_flush(s->bsf[i]);
}
}
const int64_t ts = timeUs + s->startTimeUs;
const int err = avformat_seek_file(s->format, -1, INT64_MIN, ts, ts, 0);
if (s->javaError) return ERR_JAVA;
if (err < 0) {
LOGW("seek to %lld failed: %d", (long long)ts, err);
return err;
}
LOGD("seek to %lld: logical=%lld", (long long)ts, (long long)s->logicalPos);
return 0;
}
} // extern "C"
@@ -119,7 +119,6 @@ class MainActivity : FlutterActivity() {
}
}
// Auto PiP state
private var autoPipReady = false
private var autoPipWidth: Int = 16
private var autoPipHeight: Int = 9
@@ -883,7 +882,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" -> {
@@ -202,14 +202,31 @@ class CarRestrictionsMonitor(
Log.w(TAG, "Car service is ready but has no UX restrictions manager")
return
}
manager = uxManager
// Register before reading, per the platform's own guidance: registration subscribes to future
// changes only, it does not replay the current one. Reading first would drop a transition that
// lands between the two binder calls, and publishing the stale "parked" afterwards would then
// override lifecycle gating and permit audio for the whole drive.
uxManager.registerListener { restrictions: CarUxRestrictions -> publish(restrictions.isRequiresDistractionOptimization) }
supported = true
publish(uxManager.currentCarUxRestrictions?.isRequiresDistractionOptimization ?: true)
//
// Identity-guarded because a retry re-enters bind() with the same manager instance (Car caches
// managers until the service dies): a second registration is at best redundant and at worst a
// platform refusal. `manager` is assigned after the listener sticks, so it only ever names a
// manager that is actually observing the vehicle.
if (manager !== uxManager) {
uxManager.registerListener { restrictions: CarUxRestrictions -> adoptVerdict(restrictions.isRequiresDistractionOptimization) }
manager = uxManager
}
val current = uxManager.currentCarUxRestrictions
if (current == null) {
// The service holds no restrictions for this display (yet). Claiming a verdict here would
// publish the restricted default with `supported = true`, and on a car that then stays
// parked no transition ever arrives to correct it — playback would refuse to start for the
// whole session. Stay pending instead: Dart keeps lifecycle gating (parked, foregrounded
// video plays; while driving the platform blocks the activity), the listener above adopts
// the first real verdict, and every later getState retries this read.
Log.w(TAG, "Car service has no UX restrictions for this display; keeping lifecycle gating until it answers")
return
}
adoptVerdict(current.isRequiresDistractionOptimization)
} catch (error: Throwable) {
// Registration is the failure the caller's retry is meant to survive, so keep the connection
// owned (it is in `car`) and report nothing rather than half-observing the vehicle.
@@ -219,6 +236,12 @@ class CarRestrictionsMonitor(
}
}
/** A real verdict from the vehicle: only now may callers trust [requiresDistractionOptimization]. */
private fun adoptVerdict(restricted: Boolean) {
supported = true
publish(restricted)
}
/**
* Drops a dead car service. The [Car] itself is kept: its `BIND_AUTO_CREATE` binding is what
* reconnects, and disconnecting would end that for good.
@@ -1,12 +1,14 @@
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
import android.os.Build
import android.util.Log
import androidx.annotation.OptIn
import androidx.annotation.RequiresApi
import androidx.media3.common.AudioAttributes
import androidx.media3.common.C
import androidx.media3.common.MimeTypes
@@ -29,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.
@@ -45,13 +79,17 @@ internal fun isPcmEncoding(encoding: Int): Boolean = when (encoding) {
/**
* mpv `audio-spdif` codec names and the exact platform encoding a route must
* advertise to carry that bitstream.
*
* Only the codecs mpv's audiotrack AO can physically carry are listed. That AO opens every
* spdif format as a stereo `ENCODING_IEC61937` track and clamps the track rate to
* `getNativeOutputSampleRate` (the 48kHz mixer rate), so E-AC3 (a 192kHz burst), TrueHD
* (192kHz/8ch MAT) and DTS-HD MA (192kHz/8ch) can never leave that AO intact. Naming one
* anyway force-passes the codec into a track that cannot carry it (#1991); those streams
* decode to PCM instead, like every other unnamed codec.
*/
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
"dts" to C.ENCODING_DTS
)
/**
@@ -60,23 +98,36 @@ private val MPV_SPDIF_CODECS: List<Pair<String, Int>> = listOf(
* 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 an IEC
* 61937 track carries.
*/
internal fun mpvSpdifCodecs(supportsEncoding: (Int) -> Boolean): String = MPV_SPDIF_CODECS
.filter { (_, encoding) -> supportsEncoding(encoding) }
.joinToString(",") { (codec, _) -> codec }
/** [mpvSpdifCodecs] resolved against the audio route [context] is currently routed to. */
/**
* [mpvSpdifCodecs] resolved against the audio route [context] is currently routed to.
*
* Two conditions, both required:
* - The route must accept the exact track shape mpv opens for spdif output — stereo
* IEC 61937 at the 48kHz mixer rate ([supportsMpvIecShape]). Advertising the raw AC3/DTS
* encodings only says the receiver decodes them, not that the HAL takes an IEC 61937
* AudioTrack: #1991's Shield bitstreams AC3 through ExoPlayer's raw path while every mpv
* spdif attempt strands playback on a dead audio output, leaving nothing but AAC playable.
* - The receiver must decode the codec itself — the raw encoding on the current
* [AudioCapabilities] — because IEC 61937 is transport, not transcoding.
*/
// 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 {
if (!supportsMpvIecShape(context)) {
Log.i(TAG, "Route takes no stereo IEC 61937 track; mpv will decode instead of bitstreaming")
return ""
}
val audioAttributes = AudioAttributes.Builder()
.setContentType(C.AUDIO_CONTENT_TYPE_MOVIE)
.setUsage(C.USAGE_MEDIA)
@@ -90,8 +141,29 @@ internal fun supportedMpvSpdifCodecs(context: Context): String {
return mpvSpdifCodecs(capabilities::supportsEncoding)
}
/** The track shape mpv's audiotrack AO opens for spdif output: stereo IEC 61937 at the mixer rate. */
private const val MPV_IEC_SAMPLE_RATE = 48_000
private const val MPV_IEC_CHANNEL_COUNT = 2
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 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
@@ -99,41 +171,115 @@ 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, where the API exists,
* `getDirectPlaybackSupport` proves the route will actually bitstream it rather than silently
* decode or wedge.
* 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.
*
* The oracle is tiered by what the platform offers:
* - API 33+: `getDirectPlaybackSupport`, whose bitstream flag also rules out offload-only answers.
* - API 29–32: `AudioTrack.isDirectPlaybackSupported` for the same tuple. Coarser — it cannot tell
* bitstream from offload — but an IEC 61937 track is PCM-shaped by definition, so direct support
* 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.
* - API 24–28: 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(context: Context): Boolean {
// getMinBufferSize alone is not sufficient. On a Shield it answers yes for the 192kHz/7.1 IEC
// tuple and the AudioTrack then fails to initialise; it reports that a buffer can be sized, not
// that the route will carry the format. Without getDirectPlaybackSupport there is no way to tell
// the two apart, so below API 33 the carrier is not offered and TrueHD decodes as before.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return false
internal fun supportsIecCarrier(context: Context): Boolean = iecRouteSupported(
sdkInt = Build.VERSION.SDK_INT,
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 &&
iecBitstreamSupported(iecProbeFormat(IecCarrier.SAMPLE_RATE, AudioFormat.CHANNEL_OUT_7POINT1_SURROUND))
},
directPlaybackSupported = {
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) }
)
val rate = TrueHdMatPacker.CARRIER_SAMPLE_RATE
val mask = AudioFormat.CHANNEL_OUT_7POINT1_SURROUND
val sizedOk = try {
AudioTrack.getMinBufferSize(rate, mask, AudioFormat.ENCODING_IEC61937) > 0
} catch (error: Exception) {
false
}
if (!sizedOk) return false
return try {
val audioAttributes = AudioAttributes.Builder()
.setContentType(C.AUDIO_CONTENT_TYPE_MOVIE)
.setUsage(C.USAGE_MEDIA)
.build()
.getPlatformAudioAttributes()
val probe = AudioFormat.Builder()
.setEncoding(AudioFormat.ENCODING_IEC61937)
.setChannelMask(mask)
.setSampleRate(rate)
.build()
val support = AudioManager.getDirectPlaybackSupport(probe, audioAttributes)
(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)
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 29–32, and
* [hdmiRouteAdvertised] (explicit HDMI `AudioDeviceInfo` advertisement) on 24–28 (#1991).
*/
internal fun iecRouteSupported(
sdkInt: Int,
canSizeBuffer: () -> Boolean,
bitstreamSupported: () -> Boolean,
directPlaybackSupported: () -> Boolean,
hdmiRouteAdvertised: () -> Boolean
): Boolean = when {
// ENCODING_IEC61937 itself only exists from API 24.
sdkInt < Build.VERSION_CODES.N -> false
!canSizeBuffer() -> false
sdkInt >= Build.VERSION_CODES.TIRAMISU -> bitstreamSupported()
sdkInt >= Build.VERSION_CODES.Q -> directPlaybackSupported()
else -> hdmiRouteAdvertised()
}
private fun canSizeIecBuffer(sampleRate: Int, channelMask: Int): Boolean = try {
AudioTrack.getMinBufferSize(sampleRate, channelMask, AudioFormat.ENCODING_IEC61937) > 0
} catch (error: Exception) {
false
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
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 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 iecDirectPlaybackSupported(format: AudioFormat): Boolean = try {
AudioTrack.isDirectPlaybackSupported(format, movieAudioAttributes())
} catch (error: Exception) {
Log.w(TAG, "IEC 61937 route probe failed; not offering bitstream output", error)
false
}
/**
* 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 = AudioFormat.Builder()
.setEncoding(AudioFormat.ENCODING_IEC61937)
.setChannelMask(channelMask)
.setSampleRate(sampleRate)
.build()
private fun movieAudioAttributes(): android.media.AudioAttributes = AudioAttributes.Builder()
.setContentType(C.AUDIO_CONTENT_TYPE_MOVIE)
.setUsage(C.USAGE_MEDIA)
.build()
.getPlatformAudioAttributes()
@@ -1,169 +0,0 @@
package com.edde746.plezy.exoplayer
import android.util.Log
import androidx.media3.common.C
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.SeekPoint
import androidx.media3.extractor.TrackOutput
/**
* Extractor wrapper that enables approximate seeking for MKV files without Cues.
*
* 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.
*/
@androidx.media3.common.util.UnstableApi
class CuelessSeekExtractorWrapper(
private val delegate: Extractor
) : Extractor {
companion object {
private const val TAG = "CuelessSeek"
// MKV Cluster element ID: 0x1F43B675 (4-byte EBML Class-D ID)
private val CLUSTER_ID = byteArrayOf(0x1F, 0x43, 0xB6.toByte(), 0x75)
private const val SCAN_BUFFER_SIZE = 8192
// Max bytes to scan for a Cluster boundary before giving up
private const val MAX_SCAN_BYTES = 1024 * 1024 // 1 MB
}
private var inputLength: Long = C.LENGTH_UNSET.toLong()
private var needsClusterResync = false
private var isApproximateSeeking = false
private var pendingSeekTimeUs: Long = C.TIME_UNSET
override fun sniff(input: ExtractorInput): Boolean = delegate.sniff(input)
override fun init(output: ExtractorOutput) {
delegate.init(SeekInterceptingOutput(output))
}
override fun read(input: ExtractorInput, seekPosition: PositionHolder): Int {
if (inputLength == C.LENGTH_UNSET.toLong()) {
inputLength = input.length
}
if (needsClusterResync) {
needsClusterResync = false
return scanForCluster(input, seekPosition)
}
return delegate.read(input, seekPosition)
}
override fun seek(position: Long, timeUs: Long) {
if (isApproximateSeeking && position > 0) {
needsClusterResync = true
pendingSeekTimeUs = timeUs
}
delegate.seek(position, timeUs)
}
override fun release() = delegate.release()
/**
* Scan forward from the current input position to find the next MKV Cluster
* element ID (0x1F43B675). Returns [Extractor.RESULT_SEEK] with the Cluster's
* byte position so ExoPlayer repositions the DataSource there.
*/
private fun scanForCluster(input: ExtractorInput, seekPosition: PositionHolder): Int {
val buffer = ByteArray(SCAN_BUFFER_SIZE)
var totalScanned = 0L
// Carry over last 3 bytes across buffer boundaries to detect split IDs
var carry = ByteArray(0)
while (totalScanned < MAX_SCAN_BYTES) {
val toRead = minOf(SCAN_BUFFER_SIZE, (MAX_SCAN_BYTES - totalScanned).toInt())
val bytesRead: Int
try {
bytesRead = input.read(buffer, 0, toRead)
} catch (_: Exception) {
break
}
if (bytesRead == C.RESULT_END_OF_INPUT) break
// Combine carry + new data for scanning
val scanData = if (carry.isNotEmpty()) carry + buffer.copyOf(bytesRead) else buffer.copyOf(bytesRead)
for (i in 0..scanData.size - 4) {
if (scanData[i] == CLUSTER_ID[0] &&
scanData[i + 1] == CLUSTER_ID[1] &&
scanData[i + 2] == CLUSTER_ID[2] &&
scanData[i + 3] == CLUSTER_ID[3]
) {
// Compute the absolute byte position of this Cluster
val clusterPosition = input.position - bytesRead - carry.size + i
Log.d(TAG, "Found Cluster at byte $clusterPosition (scanned ${totalScanned + i} bytes)")
seekPosition.position = clusterPosition
delegate.seek(clusterPosition, pendingSeekTimeUs)
pendingSeekTimeUs = C.TIME_UNSET
return Extractor.RESULT_SEEK
}
}
// Keep last 3 bytes as carry for next iteration
carry = if (scanData.size >= 3) scanData.copyOfRange(scanData.size - 3, scanData.size) else scanData.copyOf()
totalScanned += bytesRead
}
// Failed to find a Cluster — fall back to position 0
Log.w(TAG, "No Cluster found after scanning $totalScanned bytes, resetting to start")
seekPosition.position = 0
delegate.seek(0, 0)
return Extractor.RESULT_SEEK
}
/**
* ExtractorOutput wrapper that intercepts [seekMap] calls to replace
* [SeekMap.Unseekable] with an approximate proportional SeekMap.
*/
private inner class SeekInterceptingOutput(
private val delegate: ExtractorOutput
) : ExtractorOutput {
override fun track(id: Int, type: Int): TrackOutput = delegate.track(id, type)
override fun endTracks() = delegate.endTracks()
override fun seekMap(seekMap: SeekMap) {
if (seekMap is SeekMap.Unseekable) {
val durationUs = seekMap.durationUs
if (durationUs != C.TIME_UNSET && durationUs > 0) {
Log.i(TAG, "Replacing Unseekable with approximate SeekMap (duration=${durationUs / 1_000_000}s)")
isApproximateSeeking = true
delegate.seekMap(ApproximateSeekMap(durationUs))
return
}
}
// File has real Cues or unknown duration — pass through
isApproximateSeeking = false
delegate.seekMap(seekMap)
}
}
/**
* Approximate SeekMap that estimates byte positions proportionally.
* Used when the MKV has no Cues but has a known duration.
*/
private inner class ApproximateSeekMap(
private val durationUs: Long
) : SeekMap {
override fun isSeekable(): Boolean = true
override fun getDurationUs(): Long = durationUs
override fun getSeekPoints(timeUs: Long): SeekMap.SeekPoints {
val length = inputLength
if (length == C.LENGTH_UNSET.toLong() || durationUs <= 0) {
return SeekMap.SeekPoints(SeekPoint(0, 0))
}
val clampedTimeUs = timeUs.coerceIn(0, durationUs)
val position = (clampedTimeUs.toDouble() / durationUs * length).toLong().coerceIn(0, length)
return SeekMap.SeekPoints(SeekPoint(clampedTimeUs, position))
}
}
}
@@ -0,0 +1,26 @@
package com.edde746.plezy.exoplayer
/**
* RFC 6381 codecs strings for Dolby Vision tracks, mirroring media3's
* `DolbyVisionConfig.parse` profile table so the FFmpeg demux path publishes
* the same format media3's own MP4/Matroska extractors would: recognized
* profiles get `video/dolby-vision` plus this string, unrecognized profiles
* keep the base codec's format untouched.
*/
internal object DoviCodecs {
/**
* Codecs string for a DOVIDecoderConfigurationRecord's [profile]/[level],
* or null when media3 does not recognize the profile (the track then plays
* as its base codec).
*/
fun rfc6381(profile: Int, level: Int): String? {
val prefix = when (profile) {
4, 5, 7, 8 -> "dvhe"
9 -> "dvav"
10 -> "dav1"
else -> return null
}
return "%s.%02d.%02d".format(prefix, profile, level)
}
}
@@ -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()
}
}
@@ -64,6 +64,7 @@ import androidx.media3.extractor.DefaultExtractorsFactory
import androidx.media3.extractor.mkv.MatroskaExtractor
import androidx.media3.extractor.mp4.FragmentedMp4Extractor
import androidx.media3.extractor.mp4.Mp4Extractor
import androidx.media3.extractor.text.SubtitleTranscodingExtractorOutput
import androidx.media3.extractor.ts.TsExtractor
import androidx.media3.ui.AspectRatioFrameLayout
import androidx.media3.ui.CaptionStyleCompat
@@ -71,6 +72,7 @@ import androidx.media3.ui.SubtitleView
import com.edde746.plezy.AndroidRuntimeDiagnostics
import com.edde746.plezy.libass.media.AssHandler
import com.edde746.plezy.libass.media.parser.AssSubtitleParserFactory
import com.edde746.plezy.libass.media.text.AssSubtitleExtractorOutput
import com.edde746.plezy.libass.media.widget.AssSubtitleSurfaceView
import com.edde746.plezy.shared.AudioFocusManager
import com.edde746.plezy.shared.DeviceQuirks
@@ -218,6 +220,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 +231,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 +322,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
@@ -551,6 +563,18 @@ class ExoPlayerCore(private val activity: Activity) :
@Volatile private var activeDoviMp4Wrapper: DoviExtractorWrapper? = null
// The FFmpeg extractor from the current session; getStats reads its
// measured audio bitrate for the playing item.
@Volatile private var activeFfmpegExtractor: FfmpegExtractor? = null
// Container-demuxer placement; read per media item when extractors are built.
@Volatile private var demuxerPreference: FfmpegDemuxerPolicy.Preference = FfmpegDemuxerPolicy.Preference.FFMPEG
fun setDemuxerMode(mode: String) {
demuxerPreference = FfmpegDemuxerPolicy.fromWire(mode)
emitLog("info", "init", "demuxer mode: ${demuxerPreference.wireName}")
}
private fun getConfiguredDvMode(): DvConversionMode {
val override = debugDvModeOverride
if (override != null) return override
@@ -568,7 +592,10 @@ class ExoPlayerCore(private val activity: Activity) :
// Read-ahead depth, as the wire name Dart sends. Kept a String because `LoadControlPolicy`
// is internal and this function is not; unrecognised names resolve to Auto, which is also
// the default (#1816).
bufferTier: String = "auto"
bufferTier: String = "auto",
// Whether FFmpeg demuxes ahead of media3's extractors. Wire values from
// [FfmpegDemuxerPolicy.Preference]; unrecognised resolves to FFmpeg.
demuxerMode: String = "ffmpeg"
): Boolean {
if (isInitialized) {
Log.d(TAG, "Already initialized")
@@ -577,6 +604,7 @@ class ExoPlayerCore(private val activity: Activity) :
tunnelingUserEnabled = tunnelingEnabled
this.audioPassthroughEnabled = audioPassthroughEnabled
demuxerPreference = FfmpegDemuxerPolicy.fromWire(demuxerMode)
this.dvMode = getConfiguredDvMode()
DoviBridge.logSupportSummary(activity)
Log.i(
@@ -718,54 +746,106 @@ class ExoPlayerCore(private val activity: Activity) :
}
httpDataSourceFactory = httpFactory
dataSourceFactory = DefaultDataSource.Factory(activity, httpFactory)
// libavformat owns its own seeking, so the demuxer reads through a
// random-access source (FfmpegRandomAccessSource). Recording the DataSpec
// media3 opens lets it clone that spec — same URI, cache key, flags and
// request headers — instead of re-deriving one.
val recordingFactory = RecordingDataSourceFactory(dataSourceFactory!!)
val extractorsFactory = DefaultExtractorsFactory()
// High-bitrate Plex DVR MPEG-TS recordings can have sparse PCR packets; the default
// 600-packet window may leave duration unknown and seeking disabled.
.setTsExtractorTimestampSearchBytes(TS_TIMESTAMP_SEARCH_PACKETS * TsExtractor.TS_PACKET_SIZE)
// Raw subtitle samples from MatroskaExtractor: the external text
// pipeline below feeds libass dialogue first and then re-adds cue
// transcoding — with the internal wrapper enabled the dialogue bytes
// would already be consumed before our wrapper could see them.
.setMatroskaExtractorFlags(MatroskaExtractor.FLAG_EMIT_RAW_SUBTITLE_DATA)
// Inline buildWithAssSupport to retain AssHandler reference for font scale control.
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.
// 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 {
val currentDvMode = this.dvMode
val doviEnabled = currentDvMode != DvConversionMode.DISABLED
extractorsFactory.createExtractors().map { extractor ->
when {
extractor is MatroskaExtractor -> {
val assExtractor = ZlibMatroskaExtractor(assParserFactory, handler)
val inner = if (doviEnabled) {
DoviExtractorWrapper(assExtractor, currentDvMode) { level, prefix, message ->
emitLog(level, prefix, message)
}.also {
activeDoviMkvWrapper = it
// Wrap extractors: FFmpeg demuxes the containers media3 is weak at
// (primary, before the list) and anything media3 cannot sniff (catch-all,
// behind it); give MatroskaExtractor the same libass/transcoding text
// pipeline so the media3 fallback (ffmpeg unavailable, media3-only
// preference) keeps ASS rendering; wrap MKV/MP4 extractors with the DV
// converter when enabled.
// Reads this.dvMode and this.demuxerPreference each time (not captured) so
// DV7→8.1 retry and demuxer-mode changes can reload without
// reinitializing the player.
val wrappedExtractorsFactory = object : androidx.media3.extractor.ExtractorsFactory {
// media3's progressive path always supplies the item URI. Without one
// the demuxer cannot be handed random access, so FFmpeg stays out
// rather than failing later on its first index jump.
override fun createExtractors(): Array<androidx.media3.extractor.Extractor> {
Log.w(TAG, "[init] extractors: no item uri, ffmpeg demuxer unavailable")
return buildExtractors(null)
}
override fun createExtractors(
uri: Uri,
responseHeaders: Map<String, List<String>>
): Array<androidx.media3.extractor.Extractor> = buildExtractors(uri)
private fun buildExtractors(uri: Uri?): Array<androidx.media3.extractor.Extractor> {
val currentDvMode = this@ExoPlayerCore.dvMode
val doviEnabled = currentDvMode != DvConversionMode.DISABLED
val currentDemuxerPreference = this@ExoPlayerCore.demuxerPreference
Log.i(TAG, "[init] extractors: demuxer=${currentDemuxerPreference.wireName}")
// media3 invokes the factory once per item and reuses the extractor
// instances, so the sniff reads the live preference instead of a
// captured one.
val liveDemuxerPreference = { this@ExoPlayerCore.demuxerPreference }
val ffmpegFirst = listOfNotNull(
uri?.let { itemUri ->
val io = FfmpegRandomAccessSource(dataSourceFactory!!) { recordingFactory.specFor(itemUri) }
FfmpegExtractor.create(
liveDemuxerPreference,
currentDvMode,
subtitleParserFactory,
handler,
io
)?.also { activeFfmpegExtractor = it }
}
)
return (
ffmpegFirst + extractorsFactory.createExtractors().map { extractor ->
when {
extractor is MatroskaExtractor -> {
val withTextPipeline = OutputWrappingExtractor(extractor) { out ->
AssSubtitleExtractorOutput(SubtitleTranscodingExtractorOutput(out, subtitleParserFactory), handler)
}
if (doviEnabled) {
DoviExtractorWrapper(withTextPipeline, currentDvMode) { level, prefix, message ->
emitLog(level, prefix, message)
}.also {
activeDoviMkvWrapper = it
}
} else {
withTextPipeline
}
}
} else {
assExtractor
}
// Wrap with approximate seeking for MKV files without Cues
CuelessSeekExtractorWrapper(inner)
}
doviEnabled && (extractor is Mp4Extractor || extractor is FragmentedMp4Extractor) -> {
DoviExtractorWrapper(extractor, currentDvMode) { level, prefix, message ->
emitLog(level, prefix, message)
}.also {
activeDoviMp4Wrapper = it
doviEnabled && (extractor is Mp4Extractor || extractor is FragmentedMp4Extractor) -> {
DoviExtractorWrapper(extractor, currentDvMode) { level, prefix, message ->
emitLog(level, prefix, message)
}.also {
activeDoviMp4Wrapper = it
}
}
else -> extractor
}
}
else -> extractor
}
}.toTypedArray()
).toTypedArray()
}
}
val mediaSourceFactory = DefaultMediaSourceFactory(dataSourceFactory!!, wrappedExtractorsFactory)
.setSubtitleParserFactory(assParserFactory)
val mediaSourceFactory = DefaultMediaSourceFactory(recordingFactory, wrappedExtractorsFactory)
.setSubtitleParserFactory(subtitleParserFactory)
playbackMediaSourceFactory = mediaSourceFactory
// Wrap text renderers with subtitle delay support
@@ -1110,11 +1190,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 +1330,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 +1868,7 @@ class ExoPlayerCore(private val activity: Activity) :
videoWidth,
videoHeight,
pixelRatio,
resizeMode,
videoZoomScale
bitmapSubtitlePlaneAspect
)
activity.runOnUiThread {
@@ -2293,7 +2393,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 +2515,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 && supportsIecCarrier(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 +2773,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 +2812,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 +3534,7 @@ class ExoPlayerCore(private val activity: Activity) :
externalSubtitleUris.clear()
externalSubtitleContainerUris.clear()
lastSubtitleCues = emptyList()
bitmapSubtitlePlaneAspect = null
hadSelectedTextTrack = false
audioTrackGroupMap.clear()
subtitleTrackGroupMap.clear()
@@ -3645,6 +3799,7 @@ class ExoPlayerCore(private val activity: Activity) :
dv7RetryAttempted = override != null
activeDoviMkvWrapper = null
activeDoviMp4Wrapper = null
activeFfmpegExtractor = null
val debugMode = override?.name ?: "AUTO"
emitLog("info", "dv-debug", "P7 DV conversion mode set to $debugMode (active=$dvMode)")
reloadCurrentMediaForDvMode()
@@ -3681,6 +3836,7 @@ class ExoPlayerCore(private val activity: Activity) :
lastDvPlaybackInfo = null
activeDoviMkvWrapper = null
activeDoviMp4Wrapper = null
activeFfmpegExtractor = null
stopFrameWatchdog()
cancelDecoderHangCheck()
cancelResumeStallWatchdog()
@@ -4044,6 +4200,7 @@ class ExoPlayerCore(private val activity: Activity) :
extraDelayMs: Long,
videoWidth: Int,
videoHeight: Int,
matchResolution: Boolean,
onComplete: (switched: Boolean) -> Unit
) {
val mgr = frameRateManager
@@ -4051,7 +4208,7 @@ 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() {
@@ -4146,7 +4303,12 @@ class ExoPlayerCore(private val activity: Activity) :
"audioMimeType" to audioFormat?.sampleMimeType,
"audioSampleRate" to audioFormat?.sampleRate,
"audioChannels" to audioFormat?.channelCount,
"audioBitrate" to audioFormat?.bitrate,
// Container-declared bitrate when present; otherwise the FFmpeg
// demuxer's measured value (Matroska rarely carries BPS tags — #2063).
"audioBitrate" to (
audioFormat?.bitrate?.takeIf { it > 0 }
?: audioFormat?.id?.let { activeFfmpegExtractor?.measuredAudioBitrateBps(it) }
),
"audioDecoderName" to audioDecoderInitName,
"audioOutputEncoding" to audioTrackConfig?.encoding,
"audioOutputChannels" to audioTrackConfig?.channelConfig?.let { Integer.bitCount(it) },
@@ -258,6 +258,7 @@ class ExoPlayerPlugin :
"setBoxFitMode" -> handleSetBoxFitMode(call, result)
"setVideoZoom" -> handleSetVideoZoom(call, result)
"setDvConversionMode" -> handleSetDvConversionMode(call, result)
"setDemuxerMode" -> handleSetDemuxerMode(call, result)
"setAudioNormalization" -> handleSetAudioNormalization(call, result)
"setAudioPassthrough" -> handleSetAudioPassthrough(call, result)
"setAudioDownmix" -> handleSetAudioDownmix(call, result)
@@ -296,7 +297,7 @@ class ExoPlayerPlugin :
// 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 tunnelingEnabled = call.argument<Boolean>("tunnelingEnabled") ?: false
val dvConversionMode = call.argument<String>("dvConversionMode") ?: "auto"
val audioPassthroughEnabled = call.argument<Boolean>("audioPassthroughEnabled") ?: false
val assVideoLatencyFrames = call.argument<Int>("assVideoLatencyFrames") ?: 0
@@ -304,6 +305,7 @@ class ExoPlayerPlugin :
// 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"
val demuxerMode = call.argument<String>("demuxerMode") ?: "ffmpeg"
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.
@@ -348,7 +350,8 @@ class ExoPlayerPlugin :
bufferSizeAuto = bufferSizeAuto,
tunnelingEnabled = tunnelingEnabled,
audioPassthroughEnabled = audioPassthroughEnabled,
bufferTier = bufferTier
bufferTier = bufferTier,
demuxerMode = demuxerMode
)
if (!success) {
if (playerCore === core) playerCore = null
@@ -1015,14 +1018,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)
}
}
@@ -1136,6 +1144,18 @@ class ExoPlayerPlugin :
} ?: result.error("NO_ACTIVITY", "Activity not available", null)
}
private fun handleSetDemuxerMode(call: MethodCall, result: MethodChannel.Result) {
val mode = call.argument<String>("mode")
if (mode == null) {
result.error("INVALID_ARGS", "Missing 'mode'", null)
return
}
activity?.runOnUiThread {
playerCore?.setDemuxerMode(mode)
result.success(null)
} ?: result.error("NO_ACTIVITY", "Activity not available", null)
}
private fun handleSetAudioNormalization(call: MethodCall, result: MethodChannel.Result) {
val enabled = call.argument<Boolean>("enabled")
if (enabled == null) {
@@ -1312,8 +1332,10 @@ class ExoPlayerPlugin :
val observedProps = observedProperties.toList()
val bufferSize = configuredBufferSizeBytes
// vo is owned by MpvPlayerCore's init: the fallback core hardware-decodes
// (hwdec below), so it gets the legacy gpu VO — gpu-next under mediacodec
// fails every frame on Tegra (#2010) and reshapes no DV anyway.
core.setProperty("hwdec", "mediacodec,mediacodec-copy")
core.setProperty("vo", "gpu")
core.setProperty("ao", "audiotrack")
if (bufferSize != null && bufferSize > 0) {
@@ -0,0 +1,134 @@
package com.edde746.plezy.exoplayer
import androidx.annotation.OptIn
import androidx.media3.common.MimeTypes
import androidx.media3.common.ParserException
import androidx.media3.common.util.UnstableApi
import androidx.media3.container.OpusUtil
/**
* Shapes ffmpeg codec extradata into the per-codec initializationData layout
* media3's audio decode paths consume. MediaCodecAudioRenderer maps the list
* entries verbatim to MediaCodec csd-0/1/2 and the bundled FfmpegAudioDecoder
* rebuilds avcodec extradata from the same entries, so both expect the shapes
* media3's own extractors emit — not raw ffmpeg extradata:
*
* - Opus: [OpusHead, codec delay ns, seek pre-roll ns]. Android's Opus
* decoders consume their first three input buffers as exactly this
* configuration; given only OpusHead they read the first two real packets
* as delay/pre-roll and then silently discard every decoded sample, which
* stalled the audio clock at 0 until the MPV fallback fired (#2088).
* - Vorbis: [identification header, setup header], split out of the
* Xiph-laced blob the way MatroskaExtractor's parseVorbisCodecPrivate does.
* - FLAC: the "fLaC"-marked STREAMINFO stream MediaCodec documents; ffmpeg
* surfaces a bare or block-headed STREAMINFO depending on the container.
*
* Everything else (AAC ASC, ALAC cookie, passthrough codecs) already matches
* media3's single-entry shape and passes through. MP3's WAVEFORMATEX blob is
* dropped on the JNI side before it reaches this shaping.
*/
@OptIn(UnstableApi::class)
internal object FfmpegAudioCsd {
// RFC 7845 section 5.1: the identification header is at least 19 bytes;
// OpusUtil reads the pre-skip field at offsets 10-11.
private const val OPUS_HEADER_MIN_BYTES = 19
private val FLAC_STREAM_MARKER = byteArrayOf(0x66, 0x4C, 0x61, 0x43) // "fLaC"
private const val FLAC_STREAM_INFO_SIZE = 34
private const val FLAC_BLOCK_HEADER_SIZE = 4
private const val FLAC_LAST_BLOCK_FLAG = 0x80
fun initializationData(mime: String, extradata: ByteArray): List<ByteArray> = when (mime) {
MimeTypes.AUDIO_OPUS -> opus(extradata)
MimeTypes.AUDIO_VORBIS -> vorbis(extradata)
MimeTypes.AUDIO_FLAC -> flac(extradata)
else -> listOf(extradata)
}
private fun opus(extradata: ByteArray): List<ByteArray> {
if (extradata.size < OPUS_HEADER_MIN_BYTES) {
throw malformed("Opus extradata is not an identification header: ${extradata.size} bytes")
}
// [OpusHead, pre-skip ns, 80 ms default seek pre-roll ns] — the same
// shape media3's Matroska/Ogg/MP4 extractors publish.
return OpusUtil.buildInitializationData(extradata)
}
/**
* Splits the Xiph-laced header blob (identification, comment, setup) into
* media3's [identification header, setup header] pair, mirroring media3
* 1.11.0 MatroskaExtractor.parseVorbisCodecPrivate.
*/
private fun vorbis(extradata: ByteArray): List<ByteArray> {
try {
if (extradata[0].toInt() != 0x02) throw malformed("Vorbis extradata is not Xiph-laced headers")
var offset = 1
var idHeaderLength = 0
while (extradata[offset].toInt() and 0xFF == 0xFF) {
idHeaderLength += 0xFF
offset++
}
idHeaderLength += extradata[offset++].toInt() and 0xFF
var commentHeaderLength = 0
while (extradata[offset].toInt() and 0xFF == 0xFF) {
commentHeaderLength += 0xFF
offset++
}
commentHeaderLength += extradata[offset++].toInt() and 0xFF
if (extradata[offset].toInt() != 0x01) throw malformed("Vorbis identification header not found")
val idHeader = extradata.copyOfRange(offset, offset + idHeaderLength)
offset += idHeaderLength
if (extradata[offset].toInt() != 0x03) throw malformed("Vorbis comment header not found")
offset += commentHeaderLength
if (extradata[offset].toInt() != 0x05) throw malformed("Vorbis setup header not found")
return listOf(idHeader, extradata.copyOfRange(offset, extradata.size))
} catch (e: IndexOutOfBoundsException) {
throw malformed("Vorbis extradata truncated")
}
}
/**
* Normalizes to the "fLaC"-marked metadata stream. MediaCodec's decoder
* feeds csd-0 straight into libFLAC, which requires the stream marker;
* ffmpeg's canonical FLAC extradata is the bare 34-byte STREAMINFO, and
* some demuxers keep the 4-byte metadata block header in front of it.
*/
private fun flac(extradata: ByteArray): List<ByteArray> {
if (startsWithFlacMarker(extradata)) return listOf(extradata)
if (extradata.size == FLAC_STREAM_INFO_SIZE) {
val blockHeader = byteArrayOf(
(FLAC_LAST_BLOCK_FLAG or 0).toByte(), // last-metadata-block, type 0 = STREAMINFO
0x00,
0x00,
FLAC_STREAM_INFO_SIZE.toByte()
)
return listOf(FLAC_STREAM_MARKER + blockHeader + extradata)
}
val declaredLength = if (extradata.size >= FLAC_BLOCK_HEADER_SIZE) {
((extradata[1].toInt() and 0xFF) shl 16) or
((extradata[2].toInt() and 0xFF) shl 8) or
(extradata[3].toInt() and 0xFF)
} else {
-1
}
if (extradata[0].toInt() and 0x7F == 0 &&
declaredLength == FLAC_STREAM_INFO_SIZE &&
extradata.size >= FLAC_BLOCK_HEADER_SIZE + FLAC_STREAM_INFO_SIZE
) {
return listOf(FLAC_STREAM_MARKER + extradata)
}
throw malformed("FLAC extradata is not a STREAMINFO block: ${extradata.size} bytes")
}
private fun startsWithFlacMarker(extradata: ByteArray): Boolean {
if (extradata.size < FLAC_STREAM_MARKER.size) return false
for (i in FLAC_STREAM_MARKER.indices) {
if (extradata[i] != FLAC_STREAM_MARKER[i]) return false
}
return true
}
private fun malformed(message: String): ParserException = ParserException.createForMalformedContainer(message, null)
}
@@ -0,0 +1,139 @@
package com.edde746.plezy.exoplayer
import androidx.annotation.OptIn
import androidx.media3.common.util.UnstableApi
/**
* JNI surface for the libavformat demuxer shim (`cpp/media3_ffmpeg_demuxer`).
*
* One demuxer exists per process, owned by whichever [FfmpegExtractor] is
* currently open — Plezy plays at most one progressive source at a time, and
* every other playback mode (HLS/DASH, music) stays on media3's own sources.
*
* The long[] layouts mirror the constants documented in
* `ffmpeg_demuxer_jni.cc`; keep both sides in sync.
*/
@OptIn(UnstableApi::class)
internal object FfmpegDemuxerJni {
/** Byte source the AVIO callbacks read through while a native call is in flight. */
interface Input {
/** Current byte position of the loader's [androidx.media3.extractor.ExtractorInput]. */
fun position(): Long
/**
* Reads up to [length] bytes from the loader's input at its current
* position. Returns the number of bytes read, `0` at end of input, or `-1`
* after storing the failure in [lastError].
*/
fun read(buf: ByteArray, length: Int): Int
/**
* Reads up to [length] bytes at absolute [position], wherever the loader
* stands. Same return contract as [read]. This is what lets libavformat
* seek its own index without the shim unwinding the in-flight call.
*/
fun readAt(position: Long, buf: ByteArray, length: Int): Int
/** Total input length in bytes, or `-1` when unknown. */
fun length(): Long
var lastError: String?
}
// readPacket out[] indices.
const val OUT_CODE = 0
const val OUT_STREAM_INDEX = 1
const val OUT_PTS_US = 2
const val OUT_FLAGS = 3
const val OUT_SIZE = 4
const val OUT_POSITION = 5
const val OUT_DURATION_US = 6
const val OUT_LENGTH = 7
// Result codes written to out[OUT_CODE]; negative values are raw AVERRORs.
const val CODE_PACKET = 0
const val CODE_EOF = 1
const val CODE_GROW = 2
const val ERR_JAVA = -102
// streamInfo long[] layout.
const val INFO_TRACK_TYPE = 0
const val INFO_WIDTH = 1
const val INFO_HEIGHT = 2
const val INFO_PAR_NUM = 3
const val INFO_PAR_DEN = 4
const val INFO_FPS_NUM = 5
const val INFO_FPS_DEN = 6
const val INFO_SAMPLE_RATE = 7
const val INFO_CHANNELS = 8
const val INFO_PCM_ENCODING = 9
const val INFO_ROTATION = 10
const val INFO_SELECTION_FLAGS = 11
const val INFO_ROLE_FLAGS = 12
const val INFO_BITRATE = 13
const val INFO_DOVI_PROFILE = 14
const val INFO_DOVI_LEVEL = 15
const val INFO_LATM = 16
const val INFO_LENGTH = 17
val available: Boolean = try {
System.loadLibrary("ffmpegJNI")
true
} catch (_: UnsatisfiedLinkError) {
false
}
/** Probes container bytes; returns the ffmpeg short name ("avi", "asf", …) or null. */
external fun nativeProbeFormat(header: ByteArray): String?
/**
* Opens the demuxer against [input]. Returns 0 on success or a negative
* AVERROR ([ERR_JAVA] when the input itself failed). The stream count is read
* separately via [nativeStreamCount]; it must not ride the same namespace as
* result codes.
*/
external fun nativeOpen(input: Input): Int
external fun nativeClose()
external fun nativeStreamCount(): Int
/** Total duration in microseconds, or -1 when unknown. */
external fun nativeDurationUs(): Long
/** Fills [numbers]/[strings] for [index]; false when the stream is unusable. */
external fun nativeStreamInfo(index: Int, numbers: LongArray, strings: Array<String?>): Boolean
/** Codec initialization data (extradata), or null. */
external fun nativeStreamExtradata(index: Int): ByteArray?
/** Number of attachment streams (embedded fonts and friends) with payloads. */
external fun nativeAttachmentCount(): Int
/**
* Fills [strings] with [filename, mimetype] for attachment [ordinal] and
* returns the payload size in bytes, or -1 when out of range. Lets Kotlin
* enforce font budgets before copying any bytes across the boundary.
*/
external fun nativeAttachmentInfo(ordinal: Int, strings: Array<String?>): Long
/** Attachment payload bytes, or null. */
external fun nativeAttachmentData(ordinal: Int): ByteArray?
/**
* Reads one packet into [buffer], filling [out]. See the shim header
* comment for the result contract.
*/
external fun nativeReadPacket(buffer: ByteArray, out: LongArray): Int
/** Byte position libavformat will read next, or -1 when not open. */
external fun nativeLogicalPosition(): Long
/**
* Seeks to [timeUs] (media3 timeline microseconds, i.e. start-time
* normalized). The demuxer resolves the byte position itself through its own
* index. Returns 0 on success, or a negative AVERROR when the container has
* no usable index and libavformat refused the seek.
*/
external fun nativeSeek(timeUs: Long): Int
}
@@ -0,0 +1,27 @@
package com.edde746.plezy.exoplayer
/**
* Decides whether the FFmpeg demuxer sits ahead of media3's own extractors.
*
* FFmpeg demuxes every progressive container by default. media3's bundled
* extractors were weak exactly where this app kept accumulating container
* patches — AVI (XviD packed-bitstream timestamps, missing VOL csd — issue
* #2052), ASF/WMV (no extractor at all), MPEG-PS/VOB (no extractor), and
* Matroska (zlib-compressed subtitles, LOAS/LATM audio as A_MS/ACM, cueless
* seeking, font attachments) — and libavformat handles all of it natively.
* media3's extractors stay behind FFmpeg in the list, so a container FFmpeg
* fails to sniff still reaches media3's parsers. [Preference.MEDIA3_ONLY] is
* the user-facing escape hatch in case a file misbehaves on the FFmpeg path.
*/
internal object FfmpegDemuxerPolicy {
enum class Preference(val wireName: String) {
FFMPEG("ffmpeg"),
MEDIA3_ONLY("media3")
}
/** Unknown wire values (including the retired "auto") resolve to FFmpeg. */
fun fromWire(value: String?): Preference = Preference.entries.firstOrNull { it.wireName == value } ?: Preference.FFMPEG
/** Whether the FFmpeg extractor placed before media3's list demuxes at all. */
fun enabled(preference: Preference): Boolean = preference == Preference.FFMPEG
}
@@ -0,0 +1,574 @@
package com.edde746.plezy.exoplayer
import android.util.Log
import androidx.annotation.OptIn
import androidx.media3.common.C
import androidx.media3.common.Format
import androidx.media3.common.MimeTypes
import androidx.media3.common.ParserException
import androidx.media3.common.util.ParsableByteArray
import androidx.media3.common.util.UnstableApi
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.SeekPoint
import androidx.media3.extractor.TrackOutput
import androidx.media3.extractor.text.SubtitleParser
import androidx.media3.extractor.text.SubtitleTranscodingExtractorOutput
import com.edde746.plezy.libass.media.AssFonts
import com.edde746.plezy.libass.media.AssHandler
import com.edde746.plezy.libass.media.text.AssSubtitleExtractorOutput
import java.io.IOException
/**
* Demuxes progressive containers with libavformat and feeds the packets to
* media3's renderers, so FFmpeg's container coverage replaces media3's on the
* paths where it is weak (AVI/XviD timestamps and VOL csd — #2052 — ASF/WMV,
* MPEG-PS) and where the app accumulated Matroska patches (zlib-compressed
* subtitles, LOAS/LATM audio, cueless seeking) without giving up any of the
* renderer-side work (passthrough carriers, DV sanitizing, libass rendering
* with embedded fonts, subtitle latency calibration).
*
* Text tracks are emitted in the exact sample shape media3's
* MatroskaExtractor writes (see [FfmpegSubtitleSamples]); the output chain
* composed in [init] then feeds libass dialogue and transcodes cues the same
* way the media3 Matroska path does.
*
* Seeking: libavformat resolves seeks itself, reading its own index through
* [FfmpegRandomAccessSource]. media3's byte hints are ignored, nothing is ever
* unwound, and the loader is merely nudged to follow along so that sample
* delivery keeps streaming on its connection (see [alignLoader]).
*
* The instance sits before media3's extractors and sniffs everything FFmpeg
* can probe while [FfmpegDemuxerPolicy] enables it; media3's list behind it
* is the fallback for anything FFmpeg cannot open.
*/
@OptIn(UnstableApi::class)
internal class FfmpegExtractor private constructor(
private val preferenceSupplier: () -> FfmpegDemuxerPolicy.Preference,
private val dvMode: DvConversionMode,
private val subtitleParserFactory: SubtitleParser.Factory,
private val assHandler: AssHandler,
private val io: FfmpegRandomAccessSource
) : Extractor {
companion object {
private const val TAG = "FfmpegExtractor"
private const val SNIFF_BYTES = 64 * 1024
private const val INITIAL_PACKET_BUFFER_BYTES = 2 * 1024 * 1024
/** Null when the native library is unavailable. */
fun create(
preferenceSupplier: () -> FfmpegDemuxerPolicy.Preference,
dvMode: DvConversionMode,
subtitleParserFactory: SubtitleParser.Factory,
assHandler: AssHandler,
io: FfmpegRandomAccessSource
): FfmpegExtractor? = if (FfmpegDemuxerJni.available) {
FfmpegExtractor(preferenceSupplier, dvMode, subtitleParserFactory, assHandler, io)
} else {
null
}
}
private lateinit var output: ExtractorOutput
private var currentInput: ExtractorInput? = null
private val inputProxy = object : FfmpegDemuxerJni.Input {
override fun position(): Long = currentInput?.position ?: 0L
override fun read(buf: ByteArray, length: Int): Int {
val input = currentInput ?: return 0
lastError = null
return try {
val read = input.read(buf, 0, length)
if (read == C.RESULT_END_OF_INPUT) 0 else read
} catch (e: IOException) {
lastError = e.message ?: "demuxer input failed"
-1
}
}
override fun readAt(position: Long, buf: ByteArray, length: Int): Int {
lastError = null
return try {
io.readAt(position, buf, length)
} catch (e: IOException) {
lastError = e.message ?: "demuxer random access read failed"
-1
}
}
override fun length(): Long {
val fromLoader = currentInput?.length ?: C.LENGTH_UNSET.toLong()
if (fromLoader != C.LENGTH_UNSET.toLong()) return fromLoader
// Length-less loader open (progressive live stream): fall back to
// whatever a random-access open already resolved.
val resolved = io.length()
return if (resolved == C.LENGTH_UNSET.toLong()) -1L else resolved
}
override var lastError: String? = null
}
private var opened = false
private var doviOutputWrapper: DoviExtractorOutputWrapper? = null
private var durationUs = C.TIME_UNSET
private var trackOutputs: Array<TrackOutput?> = emptyArray()
private var packetBytes = ByteArray(INITIAL_PACKET_BUFFER_BYTES)
private val packetParsable = ParsableByteArray()
private val packetOut = LongArray(FfmpegDemuxerJni.OUT_LENGTH)
private val prefixParsable = ParsableByteArray()
// Per-stream text handling picked in prepareTracks; parallel to trackOutputs.
private var subtitleKinds: Array<SubtitleKind> = emptyArray()
private val latmOutputs = ArrayList<LatmTrackOutput>()
// Per-audio-stream measured bitrate, parallel to trackOutputs. Written by
// the loader thread, read by ExoPlayerCore.getStats on another thread.
@Volatile private var bitrateMeters: Array<StreamBitrateMeter?> = emptyArray()
// Set by seek(), applied by the next read(): media3 calls both on the loader
// thread, but only read() is allowed to throw IOException and the demuxer's
// seek reads its index.
private var pendingSeekUs = C.TIME_UNSET
private var deliveredAnyPacket = false
private val sniffScratch = ByteArray(SNIFF_BYTES)
override fun sniff(input: ExtractorInput): Boolean {
// media3 materializes the extractor array once per player session, so the
// policy must be read live at sniff time — a preference captured at
// construction would freeze for the session.
if (!FfmpegDemuxerPolicy.enabled(preferenceSupplier())) return false
val probed = probe(input) ?: return false
Log.i(TAG, "sniff accepted $probed")
return true
}
private fun probe(input: ExtractorInput): String? {
// create() only builds instances when the native library loaded.
input.resetPeekPosition()
return try {
val filled =
input.peekFully(
sniffScratch,
/* offset= */
0,
sniffScratch.size,
/* allowEndOfInput= */
true
)
if (!filled) return null
FfmpegDemuxerJni.nativeProbeFormat(sniffScratch)?.lowercase()
} catch (_: Throwable) {
// A sniffer must never take playback down: media3 escalates anything
// that is not an IOException into a fatal loader error.
null
} finally {
input.resetPeekPosition()
}
}
override fun init(output: ExtractorOutput) {
// media3 reuses extractor instances across sources; drop the previous
// item's demuxer and byte source so this open starts clean.
releaseDemuxer()
// Same composition as the MP4/MKV paths: DoviConvertingTrackOutput
// inspects each video track's codecs string and passes non-DV through.
val doviWrapped = if (dvMode != DvConversionMode.DISABLED) {
// The wrapper forwards emitLog into each converting track output; the
// playback-info hook stays wired to the MKV/MP4 wrappers, so nothing to
// capture here.
DoviExtractorOutputWrapper(
output,
dvMode,
emitLog = { level, prefix, message ->
Log.println(if (level == "error") Log.ERROR else Log.INFO, TAG, "$prefix $message")
},
onVideoTrackWrapped = { _ -> }
).also { doviOutputWrapper = it }
} else {
doviOutputWrapper = null
output
}
// Text pipeline, extractor-outward: raw media3-shape samples first hit
// AssTrackOutput (libass dialogue feed), then the transcoding wrapper
// parses them into cue samples. media3 does NOT wrap third-party
// extractors' outputs; without this wrapper no text track would ever
// reach the renderer as cues.
this.output = AssSubtitleExtractorOutput(
SubtitleTranscodingExtractorOutput(doviWrapped, subtitleParserFactory),
assHandler
)
}
override fun read(input: ExtractorInput, seekPosition: PositionHolder): Int {
currentInput = input
try {
if (!opened) openStreams()
applyPendingSeek()
alignLoader(input)?.let { position ->
seekPosition.position = position
return Extractor.RESULT_SEEK
}
// Aligned: the loader serves the samples, so nothing needs a second
// handle open until the demuxer jumps again.
if (io.isOpen) io.close()
return readPacket()
} catch (e: Throwable) {
Log.w(TAG, "read threw at input=${input.position}", e)
throw e
} finally {
currentInput = null
}
}
/**
* Byte position the loader should move to, or null when it already stands
* where libavformat reads.
*
* Reads outside the loader's window are served by [io] regardless, so this
* is an optimization, never a correctness requirement: it keeps sample
* delivery on media3's own connection, which is what drives its byte
* accounting, back-pressure (ProgressiveMediaPeriod watches the input
* position) and load-error policy. Nothing here needs a retry budget.
*/
private fun alignLoader(input: ExtractorInput): Long? {
val demuxerPosition = FfmpegDemuxerJni.nativeLogicalPosition()
if (demuxerPosition < 0 || demuxerPosition == input.position) return null
val length = input.length
// Opening a range at or past the end is a failed request, not an
// alignment; let the read report end of input instead.
if (length != C.LENGTH_UNSET.toLong() && demuxerPosition >= length) return null
return demuxerPosition
}
/**
* Records the target; [read] performs it. media3's byte position is its
* SeekMap guess and is deliberately ignored — libavformat picks the byte
* position from its own index.
*/
override fun seek(position: Long, timeUs: Long) {
Log.i(TAG, "extractor seek timeUs=$timeUs opened=$opened")
doviOutputWrapper?.resetTracks()
// Buffered LOAS bytes belong to the pre-seek stream; the StreamMuxConfig
// survives so audio resumes without waiting for the next config.
for (latm in latmOutputs) latm.reset()
pendingSeekUs = timeUs
}
private fun applyPendingSeek() {
val target = pendingSeekUs
if (target == C.TIME_UNSET) return
pendingSeekUs = C.TIME_UNSET
// media3 issues seek(0) before the first read of every item; a demuxer
// that has not delivered a packet yet is already at the start, and
// seeking would throw away find_stream_info's buffered packets and
// re-read the header region.
if (target == 0L && !deliveredAnyPacket) return
val code = FfmpegDemuxerJni.nativeSeek(target)
if (code == FfmpegDemuxerJni.ERR_JAVA) {
throw IOException(inputProxy.lastError ?: "demuxer input failed")
}
if (code != 0) {
// No usable index in this container: libavformat keeps delivering from
// where it stands and the renderers decode-discard toward the target,
// which is what media3's own extractors do for a cueless file.
Log.w(TAG, "demuxer refused seek to ${target}us: $code")
}
}
override fun release() {
releaseDemuxer()
}
private fun releaseDemuxer() {
if (opened) {
opened = false
FfmpegDemuxerJni.nativeClose()
}
io.close()
pendingSeekUs = C.TIME_UNSET
deliveredAnyPacket = false
// media3's extractors may demux a later item while this instance keeps
// the previous one's stream layout; a stale measurement must not leak
// into stats.
bitrateMeters = emptyArray()
}
/**
* Measured average bitrate (bps) of the audio stream whose index matches
* [formatId] (this extractor sets `Format.id` to the stream index), or null
* when this instance is not demuxing that stream. Fallback for containers
* that declare no per-track bitrate (#2063).
*/
fun measuredAudioBitrateBps(formatId: String?): Int? {
val index = formatId?.toIntOrNull() ?: return null
return bitrateMeters.getOrNull(index)?.bitrateBps()
}
private fun openStreams() {
when (val code = FfmpegDemuxerJni.nativeOpen(inputProxy)) {
0 -> {
prepareTracks()
opened = true
Log.i(TAG, "ffmpeg demuxer ready: ${trackOutputs.count { it != null }} tracks")
}
FfmpegDemuxerJni.ERR_JAVA -> throw IOException(inputProxy.lastError ?: "demuxer input failed")
else -> throw malformed("ffmpeg demuxer open failed: $code")
}
}
private enum class SubtitleKind { NONE, SSA, SUBRIP, VTT }
private fun prepareTracks() {
val count = FfmpegDemuxerJni.nativeStreamCount()
durationUs = FfmpegDemuxerJni.nativeDurationUs().takeIf { it >= 0 } ?: C.TIME_UNSET
trackOutputs = arrayOfNulls(count)
subtitleKinds = Array(count) { SubtitleKind.NONE }
bitrateMeters = arrayOfNulls(count)
latmOutputs.clear()
// Fonts go in before any text track exists so AssHandler's store flushes
// them into libass when the first ASS track is created.
deliverFontAttachments()
val numbers = LongArray(FfmpegDemuxerJni.INFO_LENGTH)
val strings = arrayOfNulls<String>(3)
var primaryVideo = -1
var primaryAudio = -1
for (index in 0 until count) {
if (!FfmpegDemuxerJni.nativeStreamInfo(index, numbers, strings)) continue
val mime = strings[0] ?: continue
val trackType = when (numbers[FfmpegDemuxerJni.INFO_TRACK_TYPE]) {
0L -> C.TRACK_TYPE_VIDEO
1L -> C.TRACK_TYPE_AUDIO
2L -> C.TRACK_TYPE_TEXT
else -> continue
}
val builder = Format.Builder()
.setId(index.toString())
.setSampleMimeType(mime)
.setLanguage(strings[1])
.setLabel(strings[2])
.setSelectionFlags(numbers[FfmpegDemuxerJni.INFO_SELECTION_FLAGS].toInt())
.setRoleFlags(numbers[FfmpegDemuxerJni.INFO_ROLE_FLAGS].toInt())
.setAverageBitrate(numbers[FfmpegDemuxerJni.INFO_BITRATE].toInt())
val extradata = FfmpegDemuxerJni.nativeStreamExtradata(index)
if (extradata != null) {
// Audio csd is codec-specific in media3 (see FfmpegAudioCsd); raw
// extradata is only correct for video (already Annex-B via the JNI
// bitstream filter) and text tracks.
builder.setInitializationData(
if (trackType == C.TRACK_TYPE_AUDIO) {
FfmpegAudioCsd.initializationData(mime, extradata)
} else {
listOf(extradata)
}
)
}
when (trackType) {
C.TRACK_TYPE_VIDEO -> {
// A Dolby Vision config record rides the stream as side data.
// Mirror media3's MP4/Matroska extractors: recognized profiles
// publish video/dolby-vision with the RFC 6381 codecs string, so
// DoviConvertingTrackOutput's P7 conversion, the P8 passthrough
// path, and the renderer's HEVC fallback engage exactly as they do
// on the media3 demux path.
val doviProfile = numbers[FfmpegDemuxerJni.INFO_DOVI_PROFILE].toInt()
if (doviProfile >= 0) {
val doviLevel = numbers[FfmpegDemuxerJni.INFO_DOVI_LEVEL].toInt().coerceAtLeast(0)
val doviCodecs = DoviCodecs.rfc6381(doviProfile, doviLevel)
if (doviCodecs != null) {
builder.setCodecs(doviCodecs)
builder.setSampleMimeType(MimeTypes.VIDEO_DOLBY_VISION)
}
Log.i(TAG, "video track $index: doviProfile=$doviProfile doviLevel=$doviLevel codecs=$doviCodecs baseMime=$mime")
}
val width = numbers[FfmpegDemuxerJni.INFO_WIDTH].toInt()
val height = numbers[FfmpegDemuxerJni.INFO_HEIGHT].toInt()
builder
.setWidth(width)
.setHeight(height)
.setRotationDegrees(numbers[FfmpegDemuxerJni.INFO_ROTATION].toInt())
val parNum = numbers[FfmpegDemuxerJni.INFO_PAR_NUM]
val parDen = numbers[FfmpegDemuxerJni.INFO_PAR_DEN]
if (parNum > 0 && parDen > 0 && parNum != parDen) {
builder.setPixelWidthHeightRatio(parNum.toFloat() / parDen.toFloat())
}
val fpsNum = numbers[FfmpegDemuxerJni.INFO_FPS_NUM]
val fpsDen = numbers[FfmpegDemuxerJni.INFO_FPS_DEN]
if (fpsNum > 0 && fpsDen > 0) {
builder.setFrameRate(fpsNum.toFloat() / fpsDen.toFloat())
}
if (primaryVideo < 0) {
primaryVideo = index
// libass needs the storage size before the first render; the
// Matroska path published it from the Tracks element the same way.
if (width > 0 && height > 0) assHandler.setVideoSize(width, height)
}
}
C.TRACK_TYPE_AUDIO -> {
builder
.setSampleRate(numbers[FfmpegDemuxerJni.INFO_SAMPLE_RATE].toInt())
.setChannelCount(numbers[FfmpegDemuxerJni.INFO_CHANNELS].toInt())
val pcmEncoding = numbers[FfmpegDemuxerJni.INFO_PCM_ENCODING].toInt()
if (pcmEncoding >= 0) builder.setPcmEncoding(pcmEncoding)
if (primaryAudio < 0) primaryAudio = index
bitrateMeters[index] = StreamBitrateMeter()
}
C.TRACK_TYPE_TEXT -> {
val kind = when (mime) {
MimeTypes.TEXT_SSA -> SubtitleKind.SSA
MimeTypes.APPLICATION_SUBRIP -> SubtitleKind.SUBRIP
MimeTypes.TEXT_VTT -> SubtitleKind.VTT
else -> SubtitleKind.NONE
}
subtitleKinds[index] = kind
if (kind == SubtitleKind.SSA) {
// Embedded ASS reaches libass as per-sample dialogue, never as a
// whole file: AssSubtitleParserFactory keys embedded handling off
// the Matroska container mime, and AssHeaderParser reads the
// header from initializationData[1] — the exact layout media3's
// MatroskaExtractor publishes.
builder.setContainerMimeType(MimeTypes.VIDEO_MATROSKA)
if (extradata != null) {
builder.setInitializationData(
listOf(FfmpegSubtitleSamples.SSA_DIALOGUE_FORMAT, extradata)
)
}
}
}
}
val rawOutput = output.track(index, trackType)
val trackOutput = if (trackType == C.TRACK_TYPE_AUDIO && numbers[FfmpegDemuxerJni.INFO_LATM] == 1L) {
// LOAS/LATM-framed AAC: unwrap to raw access units; the wrapper
// swallows this placeholder Format and emits the real one parsed from
// the StreamMuxConfig.
LatmTrackOutput(rawOutput, index).also { latmOutputs.add(it) }
} else {
rawOutput
}
trackOutput.format(builder.build())
trackOutputs[index] = trackOutput
}
output.endTracks()
output.seekMap(SeekMapImpl())
}
/** Hands embedded font attachments to libass, under the shared budgets. */
private fun deliverFontAttachments() {
val count = FfmpegDemuxerJni.nativeAttachmentCount()
if (count <= 0) return
var acceptedBytes = 0L
val meta = arrayOfNulls<String>(2)
for (ordinal in 0 until count) {
val size = FfmpegDemuxerJni.nativeAttachmentInfo(ordinal, meta)
if (size <= 0) continue
val name = meta[0] ?: continue
val mime = meta[1] ?: continue
if (mime !in AssFonts.fontMimeTypes) continue
val rejectionReason = AssFonts.rejectionReason(size, acceptedBytes)
if (rejectionReason != null) {
Log.w(TAG, "Skipping embedded font: $rejectionReason (bytes=$size, accepted=$acceptedBytes)")
continue
}
val data = FfmpegDemuxerJni.nativeAttachmentData(ordinal) ?: continue
acceptedBytes += size
assHandler.addFont(name, data)
}
}
private fun readPacket(): Int {
while (true) {
val code = FfmpegDemuxerJni.nativeReadPacket(packetBytes, packetOut)
when (code) {
FfmpegDemuxerJni.CODE_PACKET -> {
val streamIndex = packetOut[FfmpegDemuxerJni.OUT_STREAM_INDEX].toInt()
val size = packetOut[FfmpegDemuxerJni.OUT_SIZE].toInt()
val trackOutput = trackOutputs.getOrNull(streamIndex) ?: continue
val ptsUs = packetOut[FfmpegDemuxerJni.OUT_PTS_US]
val isKeyframe = packetOut[FfmpegDemuxerJni.OUT_FLAGS] and 1L != 0L
val subtitleKind = subtitleKinds.getOrNull(streamIndex) ?: SubtitleKind.NONE
if (subtitleKind != SubtitleKind.NONE) {
// Text samples carry their duration inside the sample text, in
// media3's MatroskaExtractor shape; a sample without a duration
// cannot be displayed (same skip media3 performs).
val sampleDurationUs = packetOut[FfmpegDemuxerJni.OUT_DURATION_US]
if (sampleDurationUs <= 0) {
Log.w(TAG, "Skipping subtitle sample with no duration (stream=$streamIndex)")
continue
}
val prefix = when (subtitleKind) {
SubtitleKind.SSA -> FfmpegSubtitleSamples.ssaPrefix(sampleDurationUs)
SubtitleKind.SUBRIP -> FfmpegSubtitleSamples.subripPrefix(sampleDurationUs)
else -> FfmpegSubtitleSamples.vttPrefix(sampleDurationUs)
}
prefixParsable.reset(prefix, prefix.size)
trackOutput.sampleData(prefixParsable, prefix.size)
packetParsable.reset(packetBytes, size)
trackOutput.sampleData(packetParsable, size)
trackOutput.sampleMetadata(
ptsUs,
C.BUFFER_FLAG_KEY_FRAME,
prefix.size + size,
/* offset= */
0,
/* cryptoData= */
null
)
return Extractor.RESULT_CONTINUE
}
packetParsable.reset(packetBytes, size)
trackOutput.sampleData(packetParsable, size)
// Native drops packets without any timestamp, so ptsUs is always real.
trackOutput.sampleMetadata(
ptsUs,
if (isKeyframe) C.BUFFER_FLAG_KEY_FRAME else 0,
size,
/* offset= */
0,
/* cryptoData= */
null
)
deliveredAnyPacket = true
bitrateMeters.getOrNull(streamIndex)?.onPacket(ptsUs, size)
return Extractor.RESULT_CONTINUE
}
FfmpegDemuxerJni.CODE_EOF -> return Extractor.RESULT_END_OF_INPUT
FfmpegDemuxerJni.CODE_GROW -> {
val required = packetOut[FfmpegDemuxerJni.OUT_SIZE].toInt()
packetBytes = ByteArray(required + 64 * 1024)
}
FfmpegDemuxerJni.ERR_JAVA ->
throw IOException(inputProxy.lastError ?: "demuxer input failed")
else -> throw malformed("ffmpeg demuxer read failed: $code")
}
}
}
private fun malformed(message: String): ParserException = ParserException.createForMalformedContainer(message, null)
private inner class SeekMapImpl : SeekMap {
override fun isSeekable(): Boolean = this@FfmpegExtractor.durationUs != C.TIME_UNSET
/**
* The demuxer owns seek resolution: it reads its own index and lands on
* the right keyframe by itself, so there is no second index here to keep
* consistent. The byte position exists only to satisfy the interface —
* [alignLoader] moves the loader to wherever libavformat actually ended
* up, on the read that follows the seek.
*/
override fun getSeekPoints(timeUs: Long): SeekMap.SeekPoints = SeekMap.SeekPoints(SeekPoint(timeUs, 0))
// Qualified on purpose: bare `durationUs` binds to the inherited Java
// getter as a synthetic property (this.getDurationUs()) and recurses.
override fun getDurationUs(): Long = this@FfmpegExtractor.durationUs
}
}
@@ -0,0 +1,167 @@
package com.edde746.plezy.exoplayer
import android.net.Uri
import androidx.annotation.OptIn
import androidx.media3.common.C
import androidx.media3.common.util.UnstableApi
import androidx.media3.datasource.DataSource
import androidx.media3.datasource.DataSpec
import androidx.media3.datasource.TransferListener
import java.io.IOException
/**
* Random-access byte source for the libavformat demuxer.
*
* libavformat demuxers own their own IO: they jump to the end of the file for an
* index (matroska Cues, MP4 moov, AVI idx1), back to the header, and binary
* search (MPEG-PS) whenever they please. media3's [
* androidx.media3.extractor.ExtractorInput] is forward-only — an extractor may
* only ask the loader to re-open elsewhere and be invoked again — so serving
* libavformat from the loader alone means every backward jump has to unwind the
* in-flight libavformat call and replay it, which is what the demuxer shim used
* to do (and what made a matroska Cues read unrecoverable, #2096).
*
* This class removes the mismatch instead of working around it: reads outside
* the loader's window open a second [DataSource] from the same factory media3
* uses, positioned exactly where libavformat asked. Cronet, download caches,
* SAF and the item's own request headers therefore still apply, because the
* [DataSpec] is cloned from the one media3 opened for this item.
*
* Sequential sample delivery deliberately does not come through here: it stays
* on the loader's connection so media3 keeps its byte accounting, back-pressure
* and load-error policy (see [FfmpegExtractor]). This source is opened for
* header/index bursts and closed again as soon as the loader is back in step.
*/
@OptIn(UnstableApi::class)
internal class FfmpegRandomAccessSource(
private val factory: DataSource.Factory,
private val specProvider: () -> DataSpec?
) {
private var source: DataSource? = null
/** Absolute position the open handle returns next; [C.INDEX_UNSET] when closed. */
private var handlePosition = C.INDEX_UNSET.toLong()
private var resolvedLength = C.LENGTH_UNSET.toLong()
private var opens = 0
/** Handles opened so far; the tests assert an index seek does not walk the file. */
val openCount: Int
get() = synchronized(this) { opens }
val isOpen: Boolean
get() = synchronized(this) { source != null }
/**
* Reads up to [length] bytes at absolute [position]. Returns the number of
* bytes read, or 0 at end of input. Reopens the underlying source whenever
* the requested position is not where the current handle stands, which is the
* only way to move backwards on a byte stream.
*/
fun readAt(position: Long, buffer: ByteArray, length: Int): Int = synchronized(this) {
if (length <= 0) return 0
val handle = handleAt(position)
val read = handle.read(buffer, 0, length)
if (read == C.RESULT_END_OF_INPUT) return 0
handlePosition = position + read
read
}
/**
* Total resource length once some open has resolved it, else
* [C.LENGTH_UNSET]. Never performs IO of its own: the extractor prefers the
* length media3 already resolved for the loader.
*/
fun length(): Long = synchronized(this) { resolvedLength }
fun close() = synchronized(this) {
closeHandle()
handlePosition = C.INDEX_UNSET.toLong()
}
private fun handleAt(position: Long): DataSource {
val existing = source
if (existing != null && handlePosition == position) return existing
closeHandle()
val spec = specProvider() ?: throw IOException("ffmpeg demuxer has no data spec for random access")
// Clone rather than subrange: the recorded spec carries the loader's own
// position, and subrange() is relative to it.
val positioned = spec.buildUpon()
.setPosition(position)
.setLength(C.LENGTH_UNSET.toLong())
.build()
val created = factory.createDataSource()
val remaining = try {
created.open(positioned)
} catch (e: Throwable) {
closeQuietly(created)
throw e
}
source = created
handlePosition = position
opens++
if (remaining != C.LENGTH_UNSET.toLong()) resolvedLength = position + remaining
return created
}
private fun closeHandle() {
source?.let { closeQuietly(it) }
source = null
}
private fun closeQuietly(dataSource: DataSource) {
try {
dataSource.close()
} catch (_: IOException) {
// Closing a handle we are abandoning cannot fail the read that replaces it.
}
}
}
/**
* [DataSource.Factory] that remembers the [DataSpec] media3 opened for each
* item, so [FfmpegRandomAccessSource] can clone it — same URI, cache key, flags
* and request headers — instead of re-deriving one and silently losing, say, a
* download's cache key.
*
* Keyed by URI because ExoPlayer prepares the next item's period while the
* current one is still loading; the demuxer must never read the next item's
* bytes.
*/
@OptIn(UnstableApi::class)
internal class RecordingDataSourceFactory(private val delegate: DataSource.Factory) : DataSource.Factory {
private val specs = object : LinkedHashMap<Uri, DataSpec>(8, 0.75f, false) {
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Uri, DataSpec>): Boolean = size > MAX_TRACKED_ITEMS
}
fun specFor(uri: Uri): DataSpec? = synchronized(specs) { specs[uri] }
override fun createDataSource(): DataSource = RecordingDataSource(delegate.createDataSource())
private fun record(dataSpec: DataSpec) {
synchronized(specs) { specs[dataSpec.uri] = dataSpec }
}
private inner class RecordingDataSource(private val inner: DataSource) : DataSource {
override fun open(dataSpec: DataSpec): Long {
record(dataSpec)
return inner.open(dataSpec)
}
override fun read(buffer: ByteArray, offset: Int, length: Int): Int = inner.read(buffer, offset, length)
override fun addTransferListener(transferListener: TransferListener) = inner.addTransferListener(transferListener)
override fun getUri(): Uri? = inner.uri
override fun getResponseHeaders(): Map<String, List<String>> = inner.responseHeaders
override fun close() = inner.close()
}
private companion object {
const val MAX_TRACKED_ITEMS = 4
}
}
@@ -0,0 +1,46 @@
package com.edde746.plezy.exoplayer
import java.util.Locale
/**
* Builds text subtitle samples in the exact shape media3's MatroskaExtractor
* writes, so the same downstream consumers work behind the FFmpeg demuxer:
* the bundled SsaParser/SubripParser/WebvttParser (via
* SubtitleTranscodingExtractorOutput) and AssTrackOutput's dialogue feed.
*
* MatroskaExtractor prefixes each raw payload with a synthetic header whose
* *second* timecode carries the sample duration (BlockDuration), while the
* first stays zero; parsers reconstruct absolute times as sampleTimeUs +
* parsedStart. FFmpeg hands us the same raw payloads (an ASS packet is the
* MKV block: "ReadOrder,Layer,Style,...,Text"; SubRip/WebVTT packets are the
* bare cue text), so only the prefix needs synthesizing.
*/
internal object FfmpegSubtitleSamples {
val SSA_DIALOGUE_FORMAT: ByteArray =
"Format: Start, End, ReadOrder, Layer, Style, Name, MarginL, MarginR, MarginV, Effect, Text"
.toByteArray(Charsets.UTF_8)
/** `Dialogue: 0:00:00:00,H:MM:SS:CC,` — centiseconds, ':' separator (media3's SSA shape). */
fun ssaPrefix(durationUs: Long): ByteArray = "Dialogue: 0:00:00:00,${timecode(durationUs, "%01d:%02d:%02d:%02d", 10_000)},"
.toByteArray(Charsets.UTF_8)
/** `1\n00:00:00,000 --> HH:MM:SS,mmm\n` — a complete SRT cue header. */
fun subripPrefix(durationUs: Long): ByteArray = "1\n00:00:00,000 --> ${timecode(durationUs, "%02d:%02d:%02d,%03d", 1_000)}\n"
.toByteArray(Charsets.UTF_8)
/** `WEBVTT\n\n00:00:00.000 --> HH:MM:SS.mmm\n` — a one-cue WebVTT document header. */
fun vttPrefix(durationUs: Long): ByteArray = "WEBVTT\n\n00:00:00.000 --> ${timecode(durationUs, "%02d:%02d:%02d.%03d", 1_000)}\n"
.toByteArray(Charsets.UTF_8)
private fun timecode(timeUs: Long, format: String, lastValueDivisor: Long): String {
val hours = timeUs / 3_600_000_000L
var remainder = timeUs - hours * 3_600_000_000L
val minutes = remainder / 60_000_000L
remainder -= minutes * 60_000_000L
val seconds = remainder / 1_000_000L
remainder -= seconds * 1_000_000L
val lastValue = remainder / lastValueDivisor
return String.format(Locale.US, format, hours, minutes, seconds, lastValue)
}
}
@@ -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,7 +42,7 @@ 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. */
@@ -49,39 +52,39 @@ internal class TrueHdCarrierSink(
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,8 +109,6 @@ internal class TrueHdCarrierSink(
@Volatile
private var mismatchGeneration = -1
// --- Selection ---
/**
* True when this format should ride the carrier.
*
@@ -116,11 +117,11 @@ 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
@@ -138,15 +139,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
@@ -155,45 +156,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() -> 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() -> 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)
}
}
// --- Stream path: active delegate only ---
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)
@@ -215,37 +239,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
@@ -255,10 +272,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()
}
@@ -283,11 +325,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 ---
@@ -319,23 +362,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
@@ -343,7 +386,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()
@@ -405,7 +448,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()
@@ -1,65 +0,0 @@
package com.edde746.plezy.exoplayer
import androidx.media3.extractor.ExtractorOutput
import androidx.media3.extractor.SeekMap
import androidx.media3.extractor.TrackOutput
import androidx.media3.extractor.mkv.MatroskaExtractor
/** MKV CodecID for Microsoft ACM compatibility mode. */
private const val CODEC_ID_ACM = "A_MS/ACM"
/**
* MatroskaExtractor.init is final and extractorOutput private; subclasses swap
* in wrapping outputs via reflection once the Segment element starts (shared
* with ZlibMatroskaExtractor).
*/
internal val matroskaExtractorOutputField by lazy {
MatroskaExtractor::class.java.getDeclaredField("extractorOutput").apply {
isAccessible = true
}
}
/** WAVEFORMATEX format tag for LOAS/LATM-wrapped AAC (WAVE_FORMAT_MPEG_LOAS). */
private const val WAVE_FORMAT_MPEG_LOAS = 0x1602
/**
* Returns whether a track is LOAS/LATM AAC muxed as A_MS/ACM — ffmpeg's
* fallback mapping for aac_latm, which Matroska has no native codec ID for.
* The WAVEFORMATEX wFormatTag is the first 2 bytes (LE) of CodecPrivate.
*/
fun isLoasAcmTrack(codecId: String?, codecPrivate: ByteArray?): Boolean = codecId == CODEC_ID_ACM &&
codecPrivate != null &&
codecPrivate.size >= 2 &&
((codecPrivate[0].toInt() and 0xFF) or ((codecPrivate[1].toInt() and 0xFF) shl 8)) == WAVE_FORMAT_MPEG_LOAS
/**
* ExtractorOutput wrapper that wraps marked tracks with [LatmTrackOutput].
* Call [markNextTrackLatm] before the parent extractor creates the track
* (i.e. before super.endMasterElement(ID_TRACK_ENTRY)).
*/
class LatmExtractorOutputWrapper(
private val delegate: ExtractorOutput
) : ExtractorOutput {
private var nextTrackIsLatm = false
private val latmOutputs = mutableListOf<LatmTrackOutput>()
fun markNextTrackLatm() {
nextTrackIsLatm = true
}
/** Resets LATM parser state after an extractor seek. */
fun resetTracks() {
latmOutputs.forEach { it.reset() }
}
override fun track(id: Int, type: Int): TrackOutput {
val original = delegate.track(id, type)
if (!nextTrackIsLatm) return original
nextTrackIsLatm = false
return LatmTrackOutput(original, id).also { latmOutputs.add(it) }
}
override fun endTracks() = delegate.endTracks()
override fun seekMap(seekMap: SeekMap) = delegate.seekMap(seekMap)
}
@@ -0,0 +1,31 @@
package com.edde746.plezy.exoplayer
import androidx.media3.common.util.UnstableApi
import androidx.media3.extractor.Extractor
import androidx.media3.extractor.ExtractorInput
import androidx.media3.extractor.ExtractorOutput
import androidx.media3.extractor.PositionHolder
/**
* Delegates everything to [delegate] but hands it a wrapped [ExtractorOutput].
* Used to compose the text pipeline (libass dialogue feed + subtitle cue
* transcoding) around media3's raw-subtitle MatroskaExtractor without
* subclassing or reflection.
*/
@UnstableApi
internal class OutputWrappingExtractor(
private val delegate: Extractor,
private val wrap: (ExtractorOutput) -> ExtractorOutput
) : Extractor {
override fun sniff(input: ExtractorInput): Boolean = delegate.sniff(input)
override fun init(output: ExtractorOutput) = delegate.init(wrap(output))
override fun read(input: ExtractorInput, seekPosition: PositionHolder): Int = delegate.read(input, seekPosition)
override fun seek(position: Long, timeUs: Long) = delegate.seek(position, timeUs)
override fun release() = delegate.release()
override fun getUnderlyingImplementation(): Extractor = delegate.underlyingImplementation
}
@@ -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 500–1000ms 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,17 @@ class PlezyRenderersFactory(context: Context) : DefaultRenderersFactory(context)
audioDiagnosticsLogger
)
return TrueHdCarrierSink(
return IecCarrierSink(
defaultSink = processedSink,
carrierSink = buildCarrierSink(context, bufferSizeProvider),
carrierRouteAvailable = { supportsTrueHdMatCarrier(context) },
carrierRouteAvailable = { supportsIecCarrier(context) },
directOutputBlocked = { format -> shouldBlockDirectAudioOutput?.invoke(format) == true },
log = audioDiagnosticsLogger
).also { trueHdCarrierSink = it }
).also { iecCarrierSink = it }
}
/**
* 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
@@ -0,0 +1,65 @@
package com.edde746.plezy.exoplayer
/**
* Rolling average bitrate of one demuxed stream, measured from packet sizes
* over their presentation-time span — the same source of truth mpv uses for
* its `audio-bitrate` property. It exists because containers frequently
* declare no per-track bitrate (Matroska without BPS statistics tags), which
* left the performance overlay with nothing to show (#2063).
*
* Fed from the loader thread ([onPacket]) and read from the stats path
* ([bitrateBps]); both are synchronized. The measurement follows the demux
* position, which runs ahead of the playhead by the buffered duration —
* acceptable for a diagnostics overlay.
*/
internal class StreamBitrateMeter(private val windowUs: Long = DEFAULT_WINDOW_US) {
private val ptsUsQueue = ArrayDeque<Long>()
private val sizeQueue = ArrayDeque<Int>()
private var windowBytes = 0L
@Synchronized
fun onPacket(ptsUs: Long, sizeBytes: Int) {
if (sizeBytes <= 0) return
// A backwards pts jump is a seek; packets on either side of it do not
// form a contiguous span, so the window restarts.
val last = ptsUsQueue.lastOrNull()
if (last != null && ptsUs < last) reset()
ptsUsQueue.addLast(ptsUs)
sizeQueue.addLast(sizeBytes)
windowBytes += sizeBytes
while (ptsUsQueue.size > 1 && ptsUsQueue.last() - ptsUsQueue.first() > windowUs) {
ptsUsQueue.removeFirst()
windowBytes -= sizeQueue.removeFirst()
}
}
/**
* Average bitrate in bits per second over the current window, or null until
* enough packets span a measurable interval.
*/
@Synchronized
fun bitrateBps(): Int? {
if (ptsUsQueue.size < MIN_PACKETS) return null
val spanUs = ptsUsQueue.last() - ptsUsQueue.first()
if (spanUs <= 0) return null
// The pts span covers the durations of every packet except the last one,
// whose bytes are therefore excluded — a constant-rate stream measures
// exactly its rate.
val bytes = windowBytes - sizeQueue.last()
if (bytes <= 0) return null
return (bytes * 8_000_000L / spanUs).toInt()
}
@Synchronized
fun reset() {
ptsUsQueue.clear()
sizeQueue.clear()
windowBytes = 0L
}
companion object {
private const val DEFAULT_WINDOW_US = 10_000_000L
private const val MIN_PACKETS = 16
}
}
@@ -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,91 +0,0 @@
package com.edde746.plezy.exoplayer
import androidx.media3.common.ParserException
import androidx.media3.extractor.TrackOutput
import java.util.zip.DataFormatException
import java.util.zip.Inflater
/**
* TrackOutput wrapper that inflates zlib-compressed sample data (MKV ContentCompAlgo 0).
* Each MKV block is independently zlib-compressed; this wrapper decompresses per-sample
* between sampleData() and sampleMetadata() calls.
*
* All buffers are reused across samples to minimize GC pressure on the hot path.
*/
class ZlibInflatingTrackOutput(
delegate: TrackOutput
) : BufferedTransformingTrackOutput(
delegate,
INITIAL_BUFFER_SIZE,
INFLATE_CHUNK,
MAX_COMPRESSED_SAMPLE_SIZE
) {
companion object {
private const val INITIAL_BUFFER_SIZE = 256 * 1024
private const val INFLATE_CHUNK = 64 * 1024
private const val MAX_COMPRESSED_SAMPLE_SIZE = 16 * 1024 * 1024
private const val MAX_INFLATED_SAMPLE_SIZE = 16 * 1024 * 1024
private const val MAX_COMPRESSION_RATIO = 1024L
private const val MIN_RATIO_ALLOWANCE = 1024L * 1024
}
var active = false
private val inflater = Inflater()
private var inflateBuf = ByteArray(INITIAL_BUFFER_SIZE)
private val overflowProbe = ByteArray(1)
override val transformEnabled: Boolean
get() = active
override val transformedBuffer: ByteArray
get() = inflateBuf
override fun transformSample(inputLength: Int, flags: Int): Int {
inflater.reset()
inflater.setInput(inputBuffer, 0, inputLength)
var written = 0
val ratioBound = maxOf(MIN_RATIO_ALLOWANCE, inputLength.toLong() * MAX_COMPRESSION_RATIO)
try {
while (true) {
if (written == inflateBuf.size) {
if (inflateBuf.size < MAX_INFLATED_SAMPLE_SIZE) {
val nextSize = minOf(MAX_INFLATED_SAMPLE_SIZE, inflateBuf.size * 2)
inflateBuf = inflateBuf.copyOf(nextSize)
} else {
val overflow = inflater.inflate(overflowProbe, 0, 1)
if (overflow > 0) {
throw malformed("Inflated sample exceeds the maximum size")
}
if (inflater.finished()) return written
throw stalledInflate()
}
}
val count = inflater.inflate(inflateBuf, written, inflateBuf.size - written)
written += count
if (written.toLong() > ratioBound) {
throw malformed("Inflated sample exceeds the maximum compression ratio")
}
if (inflater.finished()) return written
if (count == 0) throw stalledInflate()
}
} catch (_: DataFormatException) {
// Preserve playback for corrupt subtitle blocks; the raw sample remains bounded
// by MAX_COMPRESSED_SAMPLE_SIZE and matches the pre-hardening fallback.
if (inflateBuf.size < inputLength) inflateBuf = inflateBuf.copyOf(inputLength)
inputBuffer.copyInto(inflateBuf, endIndex = inputLength)
return inputLength
}
}
private fun stalledInflate(): ParserException = when {
inflater.needsDictionary() -> malformed("Zlib-compressed sample requires a dictionary")
inflater.needsInput() -> malformed("Truncated zlib-compressed sample")
else -> malformed("Zlib decompressor made no progress")
}
private fun malformed(message: String, cause: Throwable? = null): ParserException = ParserException.createForMalformedContainer(message, cause)
}
@@ -1,140 +0,0 @@
package com.edde746.plezy.exoplayer
import android.util.Log
import androidx.media3.extractor.ExtractorInput
import androidx.media3.extractor.ExtractorOutput
import androidx.media3.extractor.SeekMap
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
/**
* Extends AssMatroskaExtractor to add support for MKV quirks media3 rejects:
*
* ContentCompAlgo 0 (zlib) — media3 only supports ContentCompAlgo 3 (header
* 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)
*
* 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,
* which unwraps LOAS frames to raw AAC for direct-playing Matroska files.
*/
class ZlibMatroskaExtractor(
subtitleParserFactory: SubtitleParser.Factory,
assHandler: AssHandler
) : AssMatroskaExtractor(subtitleParserFactory, assHandler) {
companion object {
private const val TAG = "ZlibMkvExtractor"
// Matroska EBML element IDs
private const val ID_SEGMENT = 0x18538067
private const val ID_TRACK_ENTRY = 0xAE
private const val ID_CONTENT_COMPRESSION_ALGORITHM = 0x4254
private const val ID_CONTENT_COMPRESSION_SETTINGS = 0x4255
}
private var zlibOutput: ZlibExtractorOutputWrapper? = null
private var latmOutput: LatmExtractorOutputWrapper? = null
private var currentTrackUsesZlib = false
override fun startMasterElement(id: Int, contentPosition: Long, contentSize: Long) {
super.startMasterElement(id, contentPosition, contentSize)
// 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) {
val currentOutput = matroskaExtractorOutputField.get(this) as ExtractorOutput
val latmWrapper = LatmExtractorOutputWrapper(currentOutput)
latmOutput = latmWrapper
val wrapper = ZlibExtractorOutputWrapper(latmWrapper)
zlibOutput = wrapper
matroskaExtractorOutputField.set(this, wrapper)
Log.d(TAG, "Installed zlib+LATM ExtractorOutput wrapper")
}
}
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
}
super.integerElement(id, value)
}
override fun binaryElement(id: Int, contentSize: Int, input: ExtractorInput) {
if (id == ID_CONTENT_COMPRESSION_SETTINGS && currentTrackUsesZlib) {
// Skip ContentCompSettings for zlib tracks — parent would store these as
// sampleStrippedBytes and prepend them to every sample, corrupting output.
input.skipFully(contentSize)
return
}
super.binaryElement(id, contentSize, input)
}
override fun endMasterElement(id: Int) {
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.
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()
}
}
val wasZlib = currentTrackUsesZlib
super.endMasterElement(id)
if (id == ID_TRACK_ENTRY && wasZlib) {
zlibOutput?.activateLast()
currentTrackUsesZlib = false
Log.i(TAG, "Activated zlib inflation for track")
}
}
override fun seek(position: Long, timeUs: Long) {
latmOutput?.resetTracks()
zlibOutput?.resetTracks()
super.seek(position, timeUs)
}
/**
* ExtractorOutput wrapper that wraps all TrackOutputs with ZlibInflatingTrackOutput.
* Tracks are created inactive; activateLast() enables inflation for the most recently
* created track (called when we know a track uses zlib compression).
*/
private class ZlibExtractorOutputWrapper(
private val delegate: ExtractorOutput
) : ExtractorOutput {
private var lastCreatedWrapper: ZlibInflatingTrackOutput? = null
private val trackOutputs = mutableListOf<ZlibInflatingTrackOutput>()
override fun track(id: Int, type: Int): TrackOutput {
val original = delegate.track(id, type)
return ZlibInflatingTrackOutput(original).also {
trackOutputs.add(it)
lastCreatedWrapper = it
}
}
fun activateLast() {
lastCreatedWrapper?.active = true
}
fun resetTracks() {
trackOutputs.forEach { it.resetBufferedData() }
}
override fun endTracks() = delegate.endTracks()
override fun seekMap(seekMap: SeekMap) = delegate.seekMap(seekMap)
}
}
@@ -39,20 +39,48 @@ import kotlinx.coroutines.sync.withLock
class MpvPlayerCore private constructor(
private val context: Context,
private val audioOnly: Boolean,
private val hardwareDecoding: Boolean,
private val propertyWriterOverride: (suspend (String, String) -> Unit)?,
initializedForTesting: Boolean
) : SurfaceHolder.Callback,
SurfacePlayerCore {
constructor(context: Context, audioOnly: Boolean = false) : this(context, audioOnly, null, false)
constructor(
context: Context,
audioOnly: Boolean = false,
hardwareDecoding: Boolean = true
) : this(context, audioOnly, hardwareDecoding, null, false)
internal constructor(
context: Context,
audioOnly: Boolean,
propertyWriter: (suspend (String, String) -> Unit)?
) : this(context, audioOnly, propertyWriter, true)
) : this(context, audioOnly, true, propertyWriter, true)
companion object {
private const val TAG = "MpvPlayerCore"
/**
* The initial `vo` chain, decided by whether this session will hardware-
* decode.
*
* gpu-next (libplacebo) is the only Android path that applies Dolby Vision
* RPU reshaping (#1902), but reshaping only ever happens under software
* decode: FFmpeg's mediacodec wrapper exports no DOVI side data, so a
* hardware-decoded stream renders the untouched base layer on any VO.
* Hardware decode is also where gpu-next breaks: it samples the decoder
* output as a samplerExternalOES that libplacebo declares in both shader
* stages, and the Tegra GLES linker rejects that pair ("struct type
* mismatch between shaders for uniform"), failing every frame — a solid
* blue screen with audio on the Shield (#2010). The in-chain gpu fallback
* cannot catch it because gpu-next initializes fine and only fails
* per-frame renders.
*
* So gpu-next is offered exactly where it can help — sessions that will
* software-decode — and hardware sessions keep the legacy gpu VO. A
* mid-session hwdec fallback to software stays on vo=gpu, which renders
* software frames correctly (the pre-2.15.0 behavior for every session).
*/
internal fun initialVideoOutput(hardwareDecoding: Boolean): String = if (hardwareDecoding) "gpu" else "gpu-next,gpu"
}
/** Video-only paths. The plugin always constructs video cores with the
@@ -96,7 +124,6 @@ class MpvPlayerCore private constructor(
// output (#1482).
private val mpvWriteDispatcher = Dispatchers.IO.limitedParallelism(1)
// Frame rate matching
private var frameRateManager: FrameRateManager? = null
private val handler = Handler(Looper.getMainLooper())
@@ -110,7 +137,6 @@ class MpvPlayerCore private constructor(
if (Looper.myLooper() == Looper.getMainLooper()) block() else mainHandler.post(block)
}
// Audio focus
private var audioFocusManager: AudioFocusManager? = null
@Volatile private var cachedPaused: Boolean = true
@@ -275,7 +301,6 @@ class MpvPlayerCore private constructor(
Log.d(TAG, "SurfaceView added to content view")
}
// Create MpvPlayer on background thread via coroutine
scope.launch {
try {
if (disposing) {
@@ -296,10 +321,12 @@ class MpvPlayerCore private constructor(
setOption("audio-display", "no")
setOption("gapless-audio", "weak")
} else {
setOption("vo", "gpu")
// vo choice is decode-path-dependent; rationale on
// initialVideoOutput. Film grain is left on its `auto` default:
// applied by the VO under gpu-next, by the decoder under gpu.
setOption("vo", initialVideoOutput(hardwareDecoding))
setOption("gpu-context", "android")
setOption("opengl-es", "yes")
setOption("vd-lavc-film-grain", "cpu")
if (displayFpsOverride != null) {
setOption("display-fps-override", displayFpsOverride)
}
@@ -1041,9 +1068,13 @@ class MpvPlayerCore private constructor(
"estimated-vf-fps" to getProperty("estimated-vf-fps"),
"video-bitrate" to getProperty("video-bitrate"),
"hwdec-current" to getProperty("hwdec-current"),
"current-vo" to getProperty("current-vo"),
"audio-codec-name" to getProperty("audio-codec-name"),
"audio-params/samplerate" to getProperty("audio-params/samplerate"),
"audio-params/hr-channels" to getProperty("audio-params/hr-channels"),
"audio-params/format" to getProperty("audio-params/format"),
"current-tracks/audio/demux-samplerate" to getProperty("current-tracks/audio/demux-samplerate"),
"current-tracks/audio/demux-channel-count" to getProperty("current-tracks/audio/demux-channel-count"),
"audio-bitrate" to getProperty("audio-bitrate"),
"total-avsync-change" to getProperty("total-avsync-change"),
"cache-used" to getProperty("cache-used"),
@@ -1174,6 +1205,7 @@ class MpvPlayerCore private constructor(
extraDelayMs: Long,
videoWidth: Int,
videoHeight: Int,
matchResolution: Boolean,
onComplete: (switched: Boolean) -> Unit
) {
val mgr = frameRateManager
@@ -1181,7 +1213,7 @@ class MpvPlayerCore private constructor(
onComplete(false)
return
}
mgr.setVideoFrameRate(fps, videoDurationMs, extraDelayMs, videoWidth, videoHeight) { switched ->
mgr.setVideoFrameRate(fps, videoDurationMs, extraDelayMs, videoWidth, videoHeight, matchResolution) { switched ->
player?.let {
updateDisplayFpsOverride(it, "frame rate switch, switched=$switched") {
onComplete(switched)
@@ -5,6 +5,7 @@ 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
@@ -74,8 +75,6 @@ open class MpvPlayerPlugin(
private var initAttemptCounter = 0
private var activeInitAttempt: Int? = null
// FlutterPlugin
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
applicationContext = binding.applicationContext
channels.attach(binding)
@@ -104,8 +103,6 @@ open class MpvPlayerPlugin(
takeCoreForTeardown()?.dispose()
}
// ActivityAware
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
activity = binding.activity
activityBinding = binding
@@ -141,8 +138,6 @@ open class MpvPlayerPlugin(
Log.d(tag, "Detached from activity for config changes")
}
// EventChannel.StreamHandler
override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
channels.listen(events)
}
@@ -151,11 +146,9 @@ open class MpvPlayerPlugin(
channels.cancel()
}
// MethodChannel.MethodCallHandler
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
when (call.method) {
"initialize" -> handleInitialize(result)
"initialize" -> handleInitialize(call, result)
"dispose" -> handleDispose(result)
"setProperty" -> handleSetProperty(call, result)
"getProperty" -> handleGetProperty(call, result)
@@ -167,6 +160,7 @@ 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)
@@ -176,7 +170,21 @@ open class MpvPlayerPlugin(
}
}
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
// 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
@@ -235,7 +243,7 @@ open class MpvPlayerPlugin(
}
gen = ++sessionGeneration
core = MpvPlayerCore(coreContext, audioOnly).apply {
core = MpvPlayerCore(coreContext, audioOnly, hardwareDecoding).apply {
delegate = this@MpvPlayerPlugin
}
playerCore = core
@@ -456,14 +464,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)
}
}
@@ -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,24 +19,12 @@ 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
}
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
@@ -46,13 +32,17 @@ class FrameRateManager(
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 +51,24 @@ class FrameRateManager(
extraDelayMs: Long,
videoWidth: Int = 0,
videoHeight: Int = 0,
matchResolution: Boolean = false,
onComplete: (switched: Boolean) -> Unit
) {
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) {
@@ -129,7 +123,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 +143,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 +155,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 +198,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 +219,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 }
}
}
@@ -22,6 +22,7 @@ interface SurfacePlayerCore {
extraDelayMs: Long,
videoWidth: Int,
videoHeight: Int,
matchResolution: Boolean,
onComplete: (switched: Boolean) -> Unit
)
}
@@ -1,140 +0,0 @@
package com.edde746.plezy.watchnext
import android.content.Context
import android.content.pm.PackageManager
import android.util.Log
import androidx.annotation.VisibleForTesting
import androidx.work.Constraints
import androidx.work.CoroutineWorker
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import io.flutter.FlutterInjector
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.dart.DartExecutor
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
/**
* Owns the WorkManager registration for the periodic launcher-shelf refresh.
*
* Registration is best-effort by design: it runs inside the plugin's sync/clear
* result path, and a WorkManager failure must not turn a committed shelf write
* into a channel error.
*/
internal object ShelfRefreshScheduler {
private const val TAG = "ShelfRefreshScheduler"
internal const val WORK_NAME = "plezy_shelf_refresh"
private const val REFRESH_INTERVAL_HOURS = 6L
fun schedule(context: Context) {
try {
val request = PeriodicWorkRequestBuilder<ShelfRefreshWorker>(REFRESH_INTERVAL_HOURS, TimeUnit.HOURS)
.setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
.build()
WorkManager.getInstance(context.applicationContext)
.enqueueUniquePeriodicWork(WORK_NAME, ExistingPeriodicWorkPolicy.KEEP, request)
} catch (e: Exception) {
Log.e(TAG, "Failed to schedule shelf refresh work", e)
}
}
fun cancel(context: Context) {
try {
WorkManager.getInstance(context.applicationContext).cancelUniqueWork(WORK_NAME)
} catch (e: Exception) {
Log.e(TAG, "Failed to cancel shelf refresh work", e)
}
}
}
/**
* Refreshes the Android TV Watch Next row while the app is not running.
*
* Boots a headless [FlutterEngine], runs the Dart `systemShelfBackgroundMain`
* entrypoint (`lib/services/system_shelf_background.dart`), and resolves with
* the bool that isolate reports through the `backgroundSyncComplete` method on
* `com.plezy/watch_next`. The run is hard-capped at [RUN_TIMEOUT_MS]; the
* engine is always destroyed on the main thread, timeout included.
*/
class ShelfRefreshWorker(
appContext: Context,
params: WorkerParameters
) : CoroutineWorker(appContext, params) {
companion object {
private const val TAG = "ShelfRefreshWorker"
internal const val RUN_TIMEOUT_MS = 90_000L
/** Test seam: replaces the headless Flutter launch so tests never boot an engine. */
@Volatile
@VisibleForTesting
internal var engineLauncherOverride: (suspend (Context) -> Boolean)? = null
}
override suspend fun doWork(): Result {
val context = applicationContext
// Same support gate as WatchNextPlugin.handleIsSupported: no leanback
// launcher, no Watch Next row worth refreshing.
if (!context.packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) return Result.success()
// A live engine (the foreground app) owns the shelf and keeps it fresh
// itself; a concurrent headless engine would only fight it for ownership.
if (SystemShelfLifecycle.hasLiveLease()) return Result.success()
val launcher = engineLauncherOverride ?: ::runHeadlessShelfSync
val success = try {
withTimeoutOrNull(RUN_TIMEOUT_MS) { launcher(context) } ?: false
} catch (e: Exception) {
Log.e(TAG, "Background shelf refresh failed", e)
false
}
return if (success) Result.success() else Result.retry()
}
}
private suspend fun runHeadlessShelfSync(context: Context): Boolean {
val appContext = context.applicationContext
val completion = CompletableDeferred<Boolean>()
val engine = withContext(Dispatchers.Main) {
val loader = FlutterInjector.instance().flutterLoader()
if (!loader.initialized()) {
loader.startInitialization(appContext)
}
loader.ensureInitializationComplete(appContext, null)
// The engine constructor auto-registers GeneratedPluginRegistrant plugins
// (shared_preferences, path_provider, connectivity, sqlite, ...);
// WatchNextPlugin is app-local and must be added explicitly.
val engine = FlutterEngine(appContext)
try {
WatchNextPlugin.backgroundSyncCompletionListener = { success ->
completion.complete(success)
}
engine.plugins.add(WatchNextPlugin())
engine.dartExecutor.executeDartEntrypoint(
DartExecutor.DartEntrypoint(
loader.findAppBundlePath(),
"package:plezy/services/system_shelf_background.dart",
"systemShelfBackgroundMain"
)
)
} catch (e: Throwable) {
WatchNextPlugin.backgroundSyncCompletionListener = null
engine.destroy()
throw e
}
engine
}
return try {
completion.await()
} finally {
withContext(NonCancellable + Dispatchers.Main) {
WatchNextPlugin.backgroundSyncCompletionListener = null
engine.destroy()
}
}
}
@@ -3,6 +3,8 @@ package com.edde746.plezy.watchnext
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.work.WorkManager
import java.util.concurrent.Executor
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
@@ -15,6 +17,19 @@ class SystemShelfUpdateReceiver private constructor(
constructor() : this(Executors.newSingleThreadExecutor(), true)
internal constructor(executor: Executor) : this(executor, false)
companion object {
private const val TAG = "SystemShelfUpdateReceiver"
/**
* Unique name of the periodic ShelfRefreshWorker job 2.13.0 shipped and
* enqueued (KEEP, persisted by WorkManager). The worker is gone, so on an
* updated device the persisted job would wake the process once more, fail
* to instantiate the deleted class, and linger as a permanently failed
* record; cancel it on the first update instead.
*/
internal const val LEGACY_SHELF_REFRESH_WORK = "plezy_shelf_refresh"
}
override fun onReceive(context: Context, intent: Intent) {
val action = intent.action
if (action != Intent.ACTION_MY_PACKAGE_REPLACED && action != Intent.ACTION_BOOT_COMPLETED) return
@@ -22,22 +37,25 @@ class SystemShelfUpdateReceiver private constructor(
executor.execute {
try {
val provider = WatchNextProvider.forMaintenance(context.applicationContext)
// Snapshot before maintenance: restoreReadGrants() re-commits the
// granted-URI key even when no sync ever wrote it.
val hadPriorSync = provider.hasPersistedShelfState()
if (action == Intent.ACTION_MY_PACKAGE_REPLACED) {
cancelLegacyShelfRefreshWork(context.applicationContext)
provider.migrateShelfSchema()
} else {
provider.restoreReadGrants()
}
// WorkManager normally survives reboots on its own; re-arming here
// covers force-stop and update edge cases, and only for devices whose
// persisted state says a shelf was actually synced before.
if (hadPriorSync) ShelfRefreshScheduler.schedule(context.applicationContext)
} finally {
pending?.finish()
if (ownsExecutor) (executor as ExecutorService).shutdown()
}
}
}
/** Best-effort by design: shelf maintenance must not die on a WorkManager failure. */
private fun cancelLegacyShelfRefreshWork(context: Context) {
try {
WorkManager.getInstance(context).cancelUniqueWork(LEGACY_SHELF_REFRESH_WORK)
} catch (e: Exception) {
Log.e(TAG, "Failed to cancel legacy shelf refresh work", e)
}
}
}
@@ -27,13 +27,6 @@ class WatchNextPlugin() :
internal const val SCHEMA_VERSION = 3
private var pendingDeepLink: String? = null
// Resolves ShelfRefreshWorker's headless run. The worker installs it
// before launching the background engine and clears it on engine destroy;
// a foreground engine never sets it, so its own channel calls are unaffected.
@Volatile
@JvmStatic
var backgroundSyncCompletionListener: ((Boolean) -> Unit)? = null
fun handleIntent(intent: Intent?): String? {
val data = intent?.data ?: return null
return if (data.scheme == "plezy" && data.authority == "play") {
@@ -111,7 +104,6 @@ class WatchNextPlugin() :
"clear" -> handleClear(call, result)
"remove" -> handleRemove(call, result)
"getInitialDeepLink" -> handleGetInitialDeepLink(result)
"backgroundSyncComplete" -> handleBackgroundSyncComplete(call, result)
else -> result.notImplemented()
}
}
@@ -144,12 +136,7 @@ class WatchNextPlugin() :
val provider = session.provider ?: return@executeOnIo false
val ownership = provider.claimOwnership(owner, generation) ?: return@executeOnIo false
if (!session.isOpen()) return@executeOnIo false
val synced = provider.syncWatchNextPrograms(owner, generation, items, ownership, session::isOpen)
// Only a committed shelf warrants the periodic background refresh; KEEP
// makes re-arming from every foreground sync (and the headless worker's
// own sync) idempotent.
if (synced) ShelfRefreshScheduler.schedule(session.context)
synced
provider.syncWatchNextPrograms(owner, generation, items, ownership, session::isOpen)
}
}
@@ -163,10 +150,7 @@ class WatchNextPlugin() :
val provider = session.provider ?: return@executeOnIo false
val ownership = provider.claimOwnership(owner, generation) ?: return@executeOnIo false
if (!session.isOpen()) return@executeOnIo false
val cleared = provider.clearAll(owner, generation, ownership, session::isOpen)
// A cleared shelf has nothing to refresh; the next successful sync re-arms.
if (cleared) ShelfRefreshScheduler.cancel(session.context)
cleared
provider.clearAll(owner, generation, ownership, session::isOpen)
}
}
@@ -208,12 +192,6 @@ class WatchNextPlugin() :
result.success(contentId)
}
private fun handleBackgroundSyncComplete(call: MethodCall, result: MethodChannel.Result) {
val success = call.arguments as? Boolean ?: false
backgroundSyncCompletionListener?.invoke(success)
result.success(true)
}
private fun parseWatchNextItem(data: Map<String, Any?>): WatchNextProvider.WatchNextItem? {
val contentId = (data["contentId"] as? String)?.takeIf(String::isNotBlank) ?: return null
val title = data["title"] as? String ?: return null
@@ -25,7 +25,6 @@ internal object SystemShelfLifecycle {
private var claimToken = 0L
private var currentOwner = ""
private var currentGeneration = 0L
private var leaseHeld = false
fun acquire(): Lease = acquireIf { true }!!
@@ -36,7 +35,6 @@ internal object SystemShelfLifecycle {
claimToken += 1
currentOwner = ""
currentGeneration = 0
leaseHeld = true
Lease(token)
}
}
@@ -47,19 +45,11 @@ internal object SystemShelfLifecycle {
if (token == lease.token) {
token += 1
claimToken += 1
leaseHeld = false
}
}
}
}
/**
* True while the most recently acquired engine lease has not been
* invalidated — i.e. a live engine (normally the UI) currently owns the
* shelf. ShelfRefreshWorker checks this before booting a headless engine.
*/
fun hasLiveLease(): Boolean = synchronized(lock) { leaseHeld }
fun claim(lease: Lease, ownerId: String, generation: Long): Ownership? = synchronized(operationLock) {
synchronized(lock) {
if (
@@ -140,13 +130,6 @@ class WatchNextProvider internal constructor(
internal fun claimOwnership(ownerId: String, generation: Long): SystemShelfLifecycle.Ownership? = lifecycleLease?.let { SystemShelfLifecycle.claim(it, ownerId, generation) }
/**
* Whether a prior sync's committed state is still on disk. Cleared rows
* ([clearAll]) and schema-migration wipes remove the granted-URI key, so
* this distinguishes "user had a shelf" from "never synced / cleared".
*/
internal fun hasPersistedShelfState(): Boolean = prefs.contains(GRANTED_URIS)
internal fun syncWatchNextPrograms(
ownerId: String,
generation: Long,
@@ -48,38 +48,160 @@ 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 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 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 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 nonDtsMimesNeverConsultTheDtsProbes() {
// Decoder selection runs this predicate for every mime, video included; the probes make
// binder calls and must stay behind the mime gate.
assertFalse(
shouldForceFfmpegDtsDecode(
MimeTypes.VIDEO_H265,
{ throw AssertionError("directOutputBlocked consulted for a non-DTS mime") },
{ throw AssertionError("routeCanBitstreamDts consulted for a non-DTS mime") }
)
)
}
@Test
fun spdifListNamesOnlyCodecsMpvsStereoIecTrackCanCarry() {
// eac3 (a 192kHz burst), truehd and dts-hd (192kHz/8ch) never survive mpv's audiotrack
// AO, which opens every spdif format as a stereo IEC 61937 track at the mixer rate;
// naming them strands playback on a dead audio output (#1991).
assertEquals("ac3,dts", mpvSpdifCodecs { true })
}
@Test
fun spdifListDropsCodecsTheRouteCannotBitstream() {
// Google TV Streamer over HDMI to a Dolby-only sink: AC3/E-AC3 bitstream,
// TrueHD and DTS do not (#1703).
// Google TV Streamer over HDMI to a Dolby-only sink: AC3 bitstreams, DTS does not (#1703).
val dolbyOnlyRoute = setOf(C.ENCODING_AC3, C.ENCODING_E_AC3)
assertEquals("ac3,eac3", mpvSpdifCodecs { encoding -> encoding in dolbyOnlyRoute })
}
@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 })
}
@Test
fun spdifListKeepsDtsHdWhenTheRouteAdvertisesIt() {
val dtsHdRoute = setOf(C.ENCODING_DTS, C.ENCODING_DTS_HD)
assertEquals("dts,dts-hd", mpvSpdifCodecs { encoding -> encoding in dtsHdRoute })
assertEquals("ac3", mpvSpdifCodecs { encoding -> encoding in dolbyOnlyRoute })
}
@Test
fun spdifListIsEmptyForPcmOnlyRoutes() {
assertEquals("", mpvSpdifCodecs { false })
}
@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",
iecRouteSupported(
sdkInt = sdkInt,
canSizeBuffer = { false },
bitstreamSupported = { true },
directPlaybackSupported = { true },
hdmiRouteAdvertised = { true }
)
)
}
}
@Test
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(25, 28)) {
assertEquals(
"api $sdkInt supported=$supported",
supported,
iecRouteSupported(
sdkInt = sdkInt,
canSizeBuffer = { true },
bitstreamSupported = { throw AssertionError("getDirectPlaybackSupport does not exist below API 33") },
directPlaybackSupported = { throw AssertionError("isDirectPlaybackSupported does not exist below API 29") },
hdmiRouteAdvertised = { supported }
)
)
}
}
}
@Test
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,
iecRouteSupported(
sdkInt = 33,
canSizeBuffer = { true },
bitstreamSupported = { supported },
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") }
)
)
}
}
}
@@ -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,8 +28,6 @@ class BufferingStallPolicyTest {
loading = loading
)
// The loader's own state, for the case media3 never answers
@Test
fun aLoaderThatStoppedAskingForDataCountsAsEnoughBuffer() {
// The #1790 shape on a high bitrate stream: the byte cap is full at a couple of seconds, the
@@ -51,8 +49,6 @@ class BufferingStallPolicyTest {
assertEquals(Verdict.STALLED, evaluate(bufferedAheadMs = 2_000L, loading = false, loadControlReady = false))
}
// The load control's own verdict
@Test
fun aByteCappedBufferBelowTheDurationBarIsStillIndicted() {
// The real failure this watchdog exists for, on a high bitrate stream: media3 released playback
@@ -83,8 +79,6 @@ class BufferingStallPolicyTest {
)
}
// Playback speed
@Test
fun aFastForwardNeedsProportionallyMoreMediaBeforeItIsIndicted() {
// Enough media to start at 1x, but the load control measures its bar in playout time, so at 2x
@@ -107,8 +101,6 @@ class BufferingStallPolicyTest {
assertEquals(Verdict.STALLED, evaluate(playbackSpeed = -1f))
}
// Progress
@Test
fun advancingPositionIsHealthy() {
assertEquals(
@@ -138,8 +130,6 @@ class BufferingStallPolicyTest {
assertEquals(Verdict.STALLED, evaluate(currentPositionMs = position - 5_000))
}
// Timeout
@Test
fun frozenPositionWaitsOutTheTimeout() {
assertEquals(Verdict.WAITING, evaluate(elapsedMs = BufferingStallPolicy.STALL_TIMEOUT_MS - 1))
@@ -151,8 +141,6 @@ class BufferingStallPolicyTest {
assertEquals(Verdict.STALLED, evaluate())
}
// Starvation — the loader's problem, not the renderer's
@Test
fun emptyBufferIsStarved() {
assertEquals(Verdict.STARVED, evaluate(bufferedAheadMs = 0))
@@ -203,8 +191,6 @@ class BufferingStallPolicyTest {
)
}
// Stall clock ownership
@Test
fun starvationAndProgressBothRestartTheStallClock() {
assertTrue(BufferingStallPolicy.resetsStallClock(Verdict.STARVED))
@@ -0,0 +1,41 @@
package com.edde746.plezy.exoplayer
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class DoviCodecsTest {
@Test
fun hevcProfilesUseDvhePrefix() {
// Profile 8 level 6 is the stream from #2096: the record's dv_profile and
// dv_level bytes must surface verbatim, matching media3's
// DolbyVisionConfig output for the same file (dvhe.08.06).
assertEquals("dvhe.08.06", DoviCodecs.rfc6381(8, 6))
assertEquals("dvhe.04.09", DoviCodecs.rfc6381(4, 9))
assertEquals("dvhe.05.06", DoviCodecs.rfc6381(5, 6))
// Profile 7 keys DoviConvertingTrackOutput's P7 conversion.
assertEquals("dvhe.07.06", DoviCodecs.rfc6381(7, 6))
}
@Test
fun avcAndAv1ProfilesUseTheirOwnPrefixes() {
assertEquals("dvav.09.05", DoviCodecs.rfc6381(9, 5))
assertEquals("dav1.10.04", DoviCodecs.rfc6381(10, 4))
}
@Test
fun twoDigitLevelsAreNotZeroPadded() {
assertEquals("dvhe.08.10", DoviCodecs.rfc6381(8, 10))
}
@Test
fun unrecognizedProfilesReturnNullSoTheBaseCodecFormatSurvives() {
// Media3's DolbyVisionConfig table: anything it rejects must keep the
// track's plain HEVC/AVC format instead of publishing an unplayable
// video/dolby-vision variant.
assertNull(DoviCodecs.rfc6381(0, 6))
assertNull(DoviCodecs.rfc6381(2, 6))
assertNull(DoviCodecs.rfc6381(6, 6))
assertNull(DoviCodecs.rfc6381(20, 6))
}
}
@@ -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,8 +10,6 @@ class DvBitstreamSanitizerTest {
private val sanitizer = DvBitstreamSanitizer()
// --- HDR10+ SEI stripping (native DV codec path) ---
@Test
fun stripsHdr10PlusPrefixSeiBetweenVclNals() {
val vcl1 = annexBNal(1, byteArrayOf(0x01, 0x02))
@@ -85,8 +83,6 @@ class DvBitstreamSanitizerTest {
assertArrayEquals(original, remainingBytes(buffer))
}
// --- DV RPU/EL stripping (HEVC fallback path) ---
@Test
fun rpuModeStripsRpuAndElButKeepsHdr10PlusSei() {
val vcl = annexBNal(1, byteArrayOf(0x01))
@@ -111,8 +107,6 @@ class DvBitstreamSanitizerTest {
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
}
// --- Buffer handling ---
@Test
fun respectsPositionAndRestoresIt() {
val prefix = byteArrayOf(0xAA.toByte(), 0xBB.toByte())
@@ -245,8 +239,6 @@ class DvBitstreamSanitizerTest {
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
}
// --- Helpers ---
/** 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,8 +24,6 @@ class EndOfStreamPolicyTest {
frameStallMs = frameStallMs
)
// isFinishedFile
@Test
fun stuckPastDurationWithNoPictureIsTheEndOfTheFile() {
// The reported failure: the clock ran a minute past the last frame.
@@ -65,8 +63,6 @@ class EndOfStreamPolicyTest {
assertFalse(isFinishedFile(hasPlaybackOutput = false))
}
// fallbackStartPositionMs
@Test
fun fallbackResumesStrictlyInsideTheMedia() {
// The observed hand-off asked MPV to start 59_816ms past the end.
@@ -0,0 +1,137 @@
package com.edde746.plezy.exoplayer
import androidx.media3.common.MimeTypes
import androidx.media3.common.ParserException
import java.nio.ByteBuffer
import java.nio.ByteOrder
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Assert.assertThrows
import org.junit.Test
/**
* Spec for the per-codec initializationData shapes the ffmpeg demuxer must
* publish so MediaCodec csd-0/1/2 and FfmpegAudioDecoder's extradata
* reconstruction both see what media3's own extractors emit. Regression
* coverage for #2088: Opus with a bare OpusHead csd made Android's decoders
* eat the first two real packets as configuration and discard all output.
*/
class FfmpegAudioCsdTest {
private fun opusHead(preSkip: Int): ByteArray {
val header = ByteArray(19)
"OpusHead".toByteArray(Charsets.US_ASCII).copyInto(header)
header[8] = 1 // version
header[9] = 2 // channel count
header[10] = (preSkip and 0xFF).toByte()
header[11] = (preSkip ushr 8).toByte()
return header
}
private fun nativeOrderLong(bytes: ByteArray): Long = ByteBuffer.wrap(bytes).order(ByteOrder.nativeOrder()).long
@Test
fun opusBuildsThreeCsdBuffers() {
val header = opusHead(preSkip = 312)
val csd = FfmpegAudioCsd.initializationData(MimeTypes.AUDIO_OPUS, header)
assertEquals(3, csd.size)
assertArrayEquals(header, csd[0])
// Pre-skip converted to nanoseconds at the Opus 48 kHz clock.
assertEquals(312L * 1_000_000_000L / 48_000L, nativeOrderLong(csd[1]))
// media3's default seek pre-roll: 3840 samples = 80 ms.
assertEquals(80_000_000L, nativeOrderLong(csd[2]))
}
@Test
fun opusRejectsTruncatedHeader() {
assertThrows(ParserException::class.java) {
FfmpegAudioCsd.initializationData(MimeTypes.AUDIO_OPUS, ByteArray(11))
}
}
private fun xiphLace(length: Int): ByteArray {
val bytes = ArrayList<Byte>()
var remaining = length
while (remaining >= 0xFF) {
bytes.add(0xFF.toByte())
remaining -= 0xFF
}
bytes.add(remaining.toByte())
return bytes.toByteArray()
}
private fun vorbisHeader(type: Int, payloadLength: Int): ByteArray = byteArrayOf(type.toByte()) + "vorbis".toByteArray(Charsets.US_ASCII) + ByteArray(payloadLength)
@Test
fun vorbisSplitsLacedHeadersIntoIdentificationAndSetup() {
val id = vorbisHeader(0x01, payloadLength = 23) // 30 bytes, the real identification header size
val comment = vorbisHeader(0x03, payloadLength = 300) // > 255 exercises the 0xFF lacing
val setup = vorbisHeader(0x05, payloadLength = 40)
val extradata = byteArrayOf(0x02) + xiphLace(id.size) + xiphLace(comment.size) + id + comment + setup
val csd = FfmpegAudioCsd.initializationData(MimeTypes.AUDIO_VORBIS, extradata)
assertEquals(2, csd.size)
assertArrayEquals(id, csd[0])
assertArrayEquals(setup, csd[1])
}
@Test
fun vorbisRejectsNonLacedExtradata() {
assertThrows(ParserException::class.java) {
FfmpegAudioCsd.initializationData(MimeTypes.AUDIO_VORBIS, byteArrayOf(0x01, 0x02, 0x03))
}
}
@Test
fun vorbisRejectsTruncatedExtradata() {
val id = vorbisHeader(0x01, payloadLength = 23)
val truncated = byteArrayOf(0x02) + xiphLace(id.size) + xiphLace(64) + id // headers end early
assertThrows(ParserException::class.java) {
FfmpegAudioCsd.initializationData(MimeTypes.AUDIO_VORBIS, truncated)
}
}
@Test
fun flacWrapsBareStreamInfoInMarkedStream() {
val streamInfo = ByteArray(34) { it.toByte() }
val csd = FfmpegAudioCsd.initializationData(MimeTypes.AUDIO_FLAC, streamInfo)
assertEquals(1, csd.size)
assertArrayEquals(
"fLaC".toByteArray(Charsets.US_ASCII) + byteArrayOf(0x80.toByte(), 0x00, 0x00, 34) + streamInfo,
csd[0]
)
}
@Test
fun flacPrependsMarkerToBlockHeadedStreamInfo() {
val block = byteArrayOf(0x00, 0x00, 0x00, 34) + ByteArray(34) { it.toByte() }
val csd = FfmpegAudioCsd.initializationData(MimeTypes.AUDIO_FLAC, block)
assertEquals(1, csd.size)
assertArrayEquals("fLaC".toByteArray(Charsets.US_ASCII) + block, csd[0])
}
@Test
fun flacKeepsMarkedStreamVerbatim() {
val marked = "fLaC".toByteArray(Charsets.US_ASCII) + byteArrayOf(0x80.toByte(), 0x00, 0x00, 34) + ByteArray(34)
val csd = FfmpegAudioCsd.initializationData(MimeTypes.AUDIO_FLAC, marked)
assertEquals(1, csd.size)
assertSame(marked, csd[0])
}
@Test
fun flacRejectsUnrecognizedExtradata() {
assertThrows(ParserException::class.java) {
FfmpegAudioCsd.initializationData(MimeTypes.AUDIO_FLAC, ByteArray(10))
}
}
@Test
fun otherCodecsPassExtradataThroughAsSingleEntry() {
val asc = byteArrayOf(0x12, 0x10) // AAC-LC 44.1 kHz stereo AudioSpecificConfig
val csd = FfmpegAudioCsd.initializationData(MimeTypes.AUDIO_AAC, asc)
assertEquals(1, csd.size)
assertSame(asc, csd[0])
}
}
@@ -0,0 +1,29 @@
package com.edde746.plezy.exoplayer
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class FfmpegDemuxerPolicyTest {
@Test
fun wireValuesRoundTrip() {
assertEquals(FfmpegDemuxerPolicy.Preference.FFMPEG, FfmpegDemuxerPolicy.fromWire("ffmpeg"))
assertEquals(FfmpegDemuxerPolicy.Preference.MEDIA3_ONLY, FfmpegDemuxerPolicy.fromWire("media3"))
}
@Test
fun unknownWireValuesResolveToFfmpeg() {
assertEquals(FfmpegDemuxerPolicy.Preference.FFMPEG, FfmpegDemuxerPolicy.fromWire(null))
assertEquals(FfmpegDemuxerPolicy.Preference.FFMPEG, FfmpegDemuxerPolicy.fromWire(""))
assertEquals(FfmpegDemuxerPolicy.Preference.FFMPEG, FfmpegDemuxerPolicy.fromWire("bogus"))
// Retired wire value from the container-list era maps to the default.
assertEquals(FfmpegDemuxerPolicy.Preference.FFMPEG, FfmpegDemuxerPolicy.fromWire("auto"))
}
@Test
fun ffmpegDemuxesByDefaultAndMedia3OnlyDisables() {
assertTrue(FfmpegDemuxerPolicy.enabled(FfmpegDemuxerPolicy.Preference.FFMPEG))
assertFalse(FfmpegDemuxerPolicy.enabled(FfmpegDemuxerPolicy.Preference.MEDIA3_ONLY))
}
}
@@ -0,0 +1,222 @@
package com.edde746.plezy.exoplayer
import android.net.Uri
import androidx.media3.common.C
import androidx.media3.datasource.DataSource
import androidx.media3.datasource.DataSpec
import androidx.media3.datasource.TransferListener
import java.io.IOException
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertSame
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
/**
* The demuxer's correctness now rests on this source answering any absolute
* position, so these pin the contract libavformat depends on: a read lands on
* the requested byte, a backward jump reopens rather than returning the wrong
* bytes, and sequential reads do not reopen (which would turn steady-state
* playback into one request per 64 KB).
*/
@RunWith(RobolectricTestRunner::class)
class FfmpegRandomAccessSourceTest {
private val content = ByteArray(4096) { (it % 251).toByte() }
private val uri: Uri = Uri.parse("https://example.test/movie.mkv")
private class FakeDataSource(private val content: ByteArray) : DataSource {
var openedAt: Long = -1
var closed = false
private var position = 0
override fun open(dataSpec: DataSpec): Long {
openedAt = dataSpec.position
position = dataSpec.position.toInt()
return (content.size - position).toLong()
}
override fun read(buffer: ByteArray, offset: Int, length: Int): Int {
if (position >= content.size) return C.RESULT_END_OF_INPUT
val count = minOf(length, content.size - position)
content.copyInto(buffer, offset, position, position + count)
position += count
return count
}
override fun addTransferListener(transferListener: TransferListener) = Unit
override fun getUri(): Uri? = null
override fun getResponseHeaders(): Map<String, List<String>> = emptyMap()
override fun close() {
closed = true
}
}
private inner class FakeFactory : DataSource.Factory {
val created = mutableListOf<FakeDataSource>()
override fun createDataSource(): DataSource = FakeDataSource(content).also { created.add(it) }
}
private fun sourceFor(factory: DataSource.Factory, spec: DataSpec? = DataSpec(uri)) = FfmpegRandomAccessSource(factory) { spec }
@Test
fun readsLandOnTheRequestedAbsolutePosition() {
val factory = FakeFactory()
val source = sourceFor(factory)
val buffer = ByteArray(16)
assertEquals(16, source.readAt(1000, buffer, 16))
assertArrayEquals(content.copyOfRange(1000, 1016), buffer)
assertEquals(1000L, factory.created.single().openedAt)
}
@Test
fun sequentialReadsReuseOneHandle() {
val factory = FakeFactory()
val source = sourceFor(factory)
val buffer = ByteArray(64)
source.readAt(0, buffer, 64)
source.readAt(64, buffer, 64)
source.readAt(128, buffer, 64)
assertEquals(1, source.openCount)
assertArrayEquals(content.copyOfRange(128, 192), buffer)
}
@Test
fun backwardJumpReopensAndReturnsTheRequestedBytes() {
val factory = FakeFactory()
val source = sourceFor(factory)
val buffer = ByteArray(32)
source.readAt(2048, buffer, 32)
// The jump libavformat makes for an index at the end of the file, then back.
assertEquals(32, source.readAt(16, buffer, 32))
assertArrayEquals(content.copyOfRange(16, 48), buffer)
assertEquals(2, source.openCount)
assertTrue("abandoned handle must be closed", factory.created.first().closed)
}
@Test
fun endOfInputReportsZeroWithoutAdvancing() {
val factory = FakeFactory()
val source = sourceFor(factory)
val buffer = ByteArray(8)
assertEquals(0, source.readAt(content.size.toLong(), buffer, 8))
}
@Test
fun lengthResolvesFromAnOpenAndStaysKnown() {
val factory = FakeFactory()
val source = sourceFor(factory)
assertEquals(C.LENGTH_UNSET.toLong(), source.length())
source.readAt(512, ByteArray(8), 8)
assertEquals(content.size.toLong(), source.length())
}
@Test
fun clonedSpecKeepsCacheKeyAndFlagsButTakesOurPosition() {
val recorded = DataSpec.Builder()
.setUri(uri)
.setPosition(9999)
.setLength(1234)
.setKey("download-cache-key")
.setFlags(DataSpec.FLAG_ALLOW_CACHE_FRAGMENTATION)
.setHttpRequestHeaders(mapOf("X-Test" to "1"))
.build()
var openedSpec: DataSpec? = null
val factory = DataSource.Factory {
object : DataSource {
override fun open(dataSpec: DataSpec): Long {
openedSpec = dataSpec
return C.LENGTH_UNSET.toLong()
}
override fun read(buffer: ByteArray, offset: Int, length: Int): Int = C.RESULT_END_OF_INPUT
override fun addTransferListener(transferListener: TransferListener) = Unit
override fun getUri(): Uri? = null
override fun getResponseHeaders(): Map<String, List<String>> = emptyMap()
override fun close() = Unit
}
}
sourceFor(factory, recorded).readAt(4242, ByteArray(4), 4)
val spec = requireNotNull(openedSpec)
assertEquals(4242L, spec.position)
assertEquals(C.LENGTH_UNSET.toLong(), spec.length)
assertEquals("download-cache-key", spec.key)
assertEquals(DataSpec.FLAG_ALLOW_CACHE_FRAGMENTATION, spec.flags)
assertEquals("1", spec.httpRequestHeaders["X-Test"])
assertEquals(uri, spec.uri)
}
@Test
fun readWithoutARecordedSpecFails() {
val source = sourceFor(FakeFactory(), spec = null)
assertThrows(IOException::class.java) { source.readAt(0, ByteArray(4), 4) }
}
@Test
fun closeReleasesTheHandle() {
val factory = FakeFactory()
val source = sourceFor(factory)
source.readAt(0, ByteArray(4), 4)
assertTrue(source.isOpen)
source.close()
assertFalse(source.isOpen)
assertTrue(factory.created.single().closed)
}
@Test
fun recordingFactoryReportsTheSpecMedia3OpenedPerUri() {
val delegate = FakeFactory()
val recorder = RecordingDataSourceFactory(delegate)
val other = Uri.parse("https://example.test/next-episode.mkv")
assertNull(recorder.specFor(uri))
recorder.createDataSource().open(DataSpec.Builder().setUri(uri).setPosition(64).setKey("a").build())
recorder.createDataSource().open(DataSpec.Builder().setUri(other).setPosition(128).build())
// Preloading the next item must not redirect the current demuxer's reads.
assertEquals(64L, recorder.specFor(uri)?.position)
assertEquals("a", recorder.specFor(uri)?.key)
assertEquals(128L, recorder.specFor(other)?.position)
}
@Test
fun recordingFactoryDelegatesReads() {
val delegate = FakeFactory()
val recorder = RecordingDataSourceFactory(delegate)
val buffer = ByteArray(16)
val dataSource = recorder.createDataSource()
dataSource.open(DataSpec.Builder().setUri(uri).setPosition(32).build())
assertEquals(16, dataSource.read(buffer, 0, 16))
assertArrayEquals(content.copyOfRange(32, 48), buffer)
assertSame(delegate.created.single(), delegate.created.first())
}
}
@@ -0,0 +1,53 @@
package com.edde746.plezy.exoplayer
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* Byte-exact spec for the media3-shaped subtitle sample prefixes. The shapes
* mirror media3 1.11.0 MatroskaExtractor's SSA_PREFIX/SUBRIP_PREFIX/VTT_PREFIX
* with the duration patched into the second timecode; SsaParser,
* SubripParser, WebvttParser, and AssTrackOutput all parse these exact bytes.
*/
class FfmpegSubtitleSamplesTest {
private fun string(bytes: ByteArray): String = bytes.toString(Charsets.UTF_8)
@Test
fun ssaPrefixMatchesMatroskaExtractorShape() {
// 1h 2m 3s 450ms -> centiseconds, ':' separator, single-digit hour.
assertEquals(
"Dialogue: 0:00:00:00,1:02:03:45,",
string(FfmpegSubtitleSamples.ssaPrefix(3_723_450_000L))
)
assertEquals("Dialogue: 0:00:00:00,0:00:05:00,", string(FfmpegSubtitleSamples.ssaPrefix(5_000_000L)))
// Sub-centisecond remainders truncate, matching integer division.
assertEquals("Dialogue: 0:00:00:00,0:00:00:99,", string(FfmpegSubtitleSamples.ssaPrefix(999_999L)))
}
@Test
fun subripPrefixIsACompleteCueHeader() {
assertEquals(
"1\n00:00:00,000 --> 01:02:03,450\n",
string(FfmpegSubtitleSamples.subripPrefix(3_723_450_000L))
)
assertEquals("1\n00:00:00,000 --> 00:00:05,000\n", string(FfmpegSubtitleSamples.subripPrefix(5_000_000L)))
}
@Test
fun vttPrefixIsAOneCueDocumentHeader() {
assertEquals(
"WEBVTT\n\n00:00:00.000 --> 01:02:03.450\n",
string(FfmpegSubtitleSamples.vttPrefix(3_723_450_000L))
)
assertEquals("WEBVTT\n\n00:00:00.000 --> 00:00:05.000\n", string(FfmpegSubtitleSamples.vttPrefix(5_000_000L)))
}
@Test
fun ssaDialogueFormatMatchesMedia3Constant() {
assertEquals(
"Format: Start, End, ReadOrder, Layer, Style, Name, MarginL, MarginR, MarginV, Effect, Text",
string(FfmpegSubtitleSamples.SSA_DIALOGUE_FORMAT)
)
}
}
@@ -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,20 +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 })
// --- Selection ---
) = IecCarrierSink(normal, carrier, { routeAvailable }, { blocked })
/**
* TrueHD is the carrier or it is decoded. Falling through to the normal sink would hand media3
@@ -73,6 +92,54 @@ 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()))
}
/** 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() {
@@ -81,8 +148,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
@@ -90,6 +157,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. */
@@ -98,6 +167,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()))
}
/**
@@ -111,7 +181,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))
@@ -132,7 +202,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))
@@ -147,15 +217,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)
}
// --- Rate-family mismatch discovered mid-stream ---
/**
* 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
@@ -167,7 +235,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)
@@ -183,6 +251,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
@@ -192,7 +287,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()
@@ -210,7 +305,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()
@@ -240,7 +335,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,
@@ -265,7 +360,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()
@@ -278,7 +373,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 }
@@ -289,8 +384,6 @@ class TrueHdCarrierSinkTest {
assertTrue(carrierSink.supportsFormat(ac3))
}
// --- Back pressure ---
/**
* 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,
@@ -300,12 +393,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)
}
@@ -315,9 +408,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. */
@@ -325,7 +464,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)
@@ -336,8 +475,6 @@ class TrueHdCarrierSinkTest {
assertTrue(carrierSink.hasPendingData())
}
// --- Routing of controls ---
@Test
fun persistentControlsReachBothDelegates() {
val carrier = FakeSink()
@@ -370,14 +507,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
@@ -386,25 +546,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
}
@@ -424,7 +588,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
@@ -448,12 +613,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
@@ -5,14 +5,7 @@ import androidx.media3.common.DataReader
import androidx.media3.common.Format
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 com.edde746.plezy.libass.media.AssHandler
import com.edde746.plezy.libass.media.parser.AssSubtitleParserFactory
import java.io.EOFException
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
@@ -24,16 +17,17 @@ import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
/**
* Extracts the committed fixture (1s 440Hz sine, AAC-LC 48kHz stereo, LATM/LOAS
* muxed into MKV as A_MS/ACM tag 0x1602) and verifies direct Matroska playback
* unwraps LOAS frames to raw AAC with a synthesized AudioSpecificConfig.
* Drives LatmTrackOutput with LOAS frames from the committed fixture (1s 440Hz
* sine, AAC-LC 48kHz stereo, LATM/LOAS) and verifies it unwraps them to raw
* AAC with a synthesized AudioSpecificConfig. Both demuxer paths deliver LOAS
* this way: the FFmpeg extractor wraps aac_latm tracks directly.
*
* Robolectric provides real android.util.* implementations — MatroskaExtractor
* stores tracks in a SparseArray, which is a no-op stub on plain JVM.
* Robolectric provides real android.util.* implementations for media3's
* internals.
*/
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
class MatroskaLatmSupportTest {
class LatmTrackOutputTest {
private class CapturedSample(val timeUs: Long, val flags: Int, val data: ByteArray)
@@ -71,14 +65,6 @@ class MatroskaLatmSupportTest {
}
}
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
@@ -118,76 +104,46 @@ class MatroskaLatmSupportTest {
return frames
}
private fun extractFixture(): FakeExtractorOutput {
val data = fixtureData()
val assHandler = AssHandler()
val extractor = ZlibMatroskaExtractor(AssSubtitleParserFactory(assHandler), 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 fun placeholderFormat(): Format = Format.Builder()
.setId("1")
.setSampleMimeType(MimeTypes.AUDIO_AAC)
.setLabel("LATM track")
.setLanguage("eng")
.build()
@Test
fun unwrapsLoasAcmTrackToRawAac() {
val output = extractFixture()
fun unwrapsLoasFramesToRawAac() {
val delegate = FakeTrackOutput()
val output = LatmTrackOutput(delegate, 1)
output.format(placeholderFormat())
assertEquals(1, output.tracks.size)
val track = output.tracks.values.first()
val frames = loasFrames(40)
var timeUs = 0L
for (frame in frames) {
output.sampleData(ParsableByteArray(frame), frame.size, TrackOutput.SAMPLE_DATA_PART_MAIN)
output.sampleMetadata(timeUs, C.BUFFER_FLAG_KEY_FRAME, frame.size, 0, null)
timeUs += 21_333
}
// No audio/x-unknown format may reach the queue; the LATM-derived AAC
// format must carry the AudioSpecificConfig for MediaCodec.
assertFalse(track.formats.any { it.sampleMimeType == MimeTypes.AUDIO_UNKNOWN })
val format = track.formats.last()
// The placeholder format must be swallowed; the LATM-derived AAC format
// carries the AudioSpecificConfig and the original track metadata.
val format = delegate.formats.last()
assertEquals(MimeTypes.AUDIO_AAC, format.sampleMimeType)
assertEquals(48000, format.sampleRate)
assertEquals(2, format.channelCount)
assertEquals("1", format.id)
assertEquals("LATM track", format.label)
assertTrue(format.initializationData.isNotEmpty())
assertTrue(format.initializationData[0].isNotEmpty())
// 1s at 48kHz / 1024 samples per AAC frame ≈ 47 frames
assertTrue("expected ~47 samples, got ${track.samples.size}", track.samples.size in 40..55)
// Raw AAC payloads: smaller than the LOAS wrapping, no LOAS syncword,
// keyframe-flagged, monotonic timestamps spanning ~1s.
var prevTimeUs = Long.MIN_VALUE
for (sample in track.samples) {
assertTrue("expected ~40 samples, got ${delegate.samples.size}", delegate.samples.size in 35..40)
for (sample in delegate.samples) {
assertTrue(sample.data.isNotEmpty())
val isLoasSync = sample.data.size >= 2 &&
(sample.data[0].toInt() and 0xFF) == 0x56 &&
(sample.data[1].toInt() and 0xE0) == 0xE0
assertFalse("sample still LOAS-framed", isLoasSync)
assertEquals(C.BUFFER_FLAG_KEY_FRAME, sample.flags and C.BUFFER_FLAG_KEY_FRAME)
assertTrue(sample.timeUs >= prevTimeUs)
prevTimeUs = sample.timeUs
}
val spanUs = track.samples.last().timeUs - track.samples.first().timeUs
assertTrue("expected ~1s span, got ${spanUs}us", spanUs in 800_000..1_200_000)
}
@Test
fun detectsLoasAcmCodecPrivate() {
val loas = byteArrayOf(0x02, 0x16, 0, 0, 0, 0)
assertTrue(isLoasAcmTrack("A_MS/ACM", loas))
// Wrong tag (PCM), wrong codec, or missing private data must not match
assertFalse(isLoasAcmTrack("A_MS/ACM", byteArrayOf(0x01, 0x00, 0, 0)))
assertFalse(isLoasAcmTrack("A_AAC", loas))
assertFalse(isLoasAcmTrack("A_MS/ACM", null))
assertFalse(isLoasAcmTrack("A_MS/ACM", byteArrayOf(0x02)))
assertFalse(isLoasAcmTrack(null, loas))
}
@Test
@@ -205,19 +161,14 @@ class MatroskaLatmSupportTest {
}
@Test
fun preservesStreamMuxConfigAcrossExtractorSeek() {
fun preservesStreamMuxConfigAcrossReset() {
val frames = loasFrames(2)
assertEquals(0, frames[0][3].toInt() and 0x80)
assertEquals(0x80, frames[1][3].toInt() and 0x80)
val delegate = FakeTrackOutput()
val output = LatmTrackOutput(delegate, 1)
output.format(
Format.Builder()
.setId("1")
.setSampleMimeType(MimeTypes.AUDIO_UNKNOWN)
.build()
)
output.format(placeholderFormat())
output.sampleData(ParsableByteArray(frames[0]), frames[0].size, TrackOutput.SAMPLE_DATA_PART_MAIN)
output.sampleMetadata(0, C.BUFFER_FLAG_KEY_FRAME, frames[0].size, 0, null)
@@ -9,8 +9,6 @@ private const val MIB = 1024 * 1024
class LoadControlPolicyTest {
// autoTargetBufferBytes
@Test
fun neverExceedsMedia3sOwnTargetEvenWithHugeMemory() {
assertEquals(
@@ -64,8 +62,6 @@ class LoadControlPolicyTest {
)
}
// readAheadSeconds
@Test
fun readAheadReportsSecondsAtAKnownBitrate() {
// 64MiB of the #1618 stream (103_341 kbps) is ~5.2s — under the 15s minBufferMs, so the
@@ -86,8 +82,6 @@ class LoadControlPolicyTest {
assertNull(LoadControlPolicy.readAheadSeconds(64 * MIB, -1L))
}
// bufferDurations
/**
* 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.
@@ -172,8 +166,6 @@ class LoadControlPolicyTest {
}
}
// BufferTier.fromWire
@Test
fun theWireNamesMatchTheDartNativeValues() {
assertEquals(LoadControlPolicy.BufferTier.LARGE, LoadControlPolicy.BufferTier.fromWire("large"))
@@ -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,8 +52,6 @@ class RawPositionAudioOutputTest {
return output to listener
}
// Release reporting
/**
* 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
@@ -116,8 +114,6 @@ class RawPositionAudioOutputTest {
assertEquals(1, listener.releasedCount)
}
// Reuse
@Test
fun aParkedOutputIsHandedBackForAnIdenticalConfig() {
val delegate = FakeOutputProvider()
@@ -178,8 +174,6 @@ class RawPositionAudioOutputTest {
assertEquals(1, secondListener.underrunCount)
}
// Eviction — the overlap media3 itself tolerates, kept tolerable
/**
* 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
@@ -221,8 +215,6 @@ class RawPositionAudioOutputTest {
assertEquals(1, listener.releasedCount)
}
// Fakes
private class RecordingListener : AudioOutput.Listener {
var releasedCount = 0
var underrunCount = 0
@@ -7,8 +7,6 @@ import org.junit.Test
class ResumeStallPolicyTest {
// checkWindowMs
@Test
fun windowFloorsAtDefaultForNormalFrameRates() {
// 24fps → 4 × 42ms = 168ms, floored to 1000ms
@@ -39,8 +37,6 @@ class ResumeStallPolicyTest {
assertEquals(1000L, ResumeStallPolicy.checkWindowMs(formatFps = null, detectedFps = null, speed = 1f))
}
// evaluate
@Test
fun advancingFramesAreHealthy() {
assertEquals(
@@ -0,0 +1,65 @@
package com.edde746.plezy.exoplayer
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class StreamBitrateMeterTest {
/** Feeds [count] packets of [sizeBytes] every [intervalUs], starting at [startUs]. */
private fun StreamBitrateMeter.feed(count: Int, sizeBytes: Int, intervalUs: Long, startUs: Long = 0L) {
for (i in 0 until count) onPacket(startUs + i * intervalUs, sizeBytes)
}
@Test
fun `constant packet stream measures its bitrate`() {
val meter = StreamBitrateMeter()
// 1200-byte packets every 32 ms: 1200 * 8 / 0.032 = 300 kbps.
meter.feed(count = 32, sizeBytes = 1200, intervalUs = 32_000)
assertEquals(300_000, meter.bitrateBps())
}
@Test
fun `too few packets report nothing`() {
val meter = StreamBitrateMeter()
meter.feed(count = 15, sizeBytes = 1200, intervalUs = 32_000)
assertNull(meter.bitrateBps())
}
@Test
fun `zero pts span reports nothing`() {
val meter = StreamBitrateMeter()
repeat(32) { meter.onPacket(0L, 1200) }
assertNull(meter.bitrateBps())
}
@Test
fun `window drops old packets so a bitrate change is followed`() {
val meter = StreamBitrateMeter(windowUs = 1_000_000)
meter.feed(count = 100, sizeBytes = 1200, intervalUs = 32_000)
// Continue at four times the packet size; after well over a window of
// new packets, only the new rate remains.
meter.feed(count = 100, sizeBytes = 4800, intervalUs = 32_000, startUs = 100 * 32_000L)
assertEquals(1_200_000, meter.bitrateBps())
}
@Test
fun `backwards pts jump resets the window`() {
val meter = StreamBitrateMeter()
meter.feed(count = 32, sizeBytes = 1200, intervalUs = 32_000)
// Seek back: the single post-seek packet must not combine with the
// pre-seek span.
meter.onPacket(0L, 1200)
assertNull(meter.bitrateBps())
meter.feed(count = 31, sizeBytes = 1200, intervalUs = 32_000, startUs = 32_000)
assertEquals(300_000, meter.bitrateBps())
}
@Test
fun `empty packets are ignored`() {
val meter = StreamBitrateMeter()
meter.feed(count = 32, sizeBytes = 1200, intervalUs = 32_000)
meter.onPacket(32 * 32_000L, 0)
assertEquals(300_000, meter.bitrateBps())
}
}
@@ -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,
@@ -1,237 +0,0 @@
package com.edde746.plezy.exoplayer
import androidx.media3.common.C
import androidx.media3.common.DataReader
import androidx.media3.common.Format
import androidx.media3.common.ParserException
import androidx.media3.common.util.ParsableByteArray
import androidx.media3.extractor.TrackOutput
import java.io.ByteArrayOutputStream
import java.util.zip.Deflater
import java.util.zip.DeflaterOutputStream
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Test
class ZlibInflatingTrackOutputTest {
@Test
fun activeTransformInflatesChunkedSampleAndPreservesMetadata() {
val original = ByteArray(512 * 1024) { (it % 251).toByte() }
val compressed = deflate(original)
val delegate = RecordingTrackOutput(retainBytes = true)
val output = ZlibInflatingTrackOutput(delegate).apply { active = true }
val split = compressed.size / 2
output.sampleData(
ParsableByteArray(compressed.copyOfRange(0, split)),
split,
TrackOutput.SAMPLE_DATA_PART_MAIN
)
output.sampleData(
ParsableByteArray(compressed.copyOfRange(split, compressed.size)),
compressed.size - split,
TrackOutput.SAMPLE_DATA_PART_MAIN
)
output.sampleMetadata(42L, C.BUFFER_FLAG_KEY_FRAME, compressed.size, 0, null)
assertArrayEquals(original, delegate.retained.toByteArray())
assertEquals(42L, delegate.timeUs)
assertEquals(C.BUFFER_FLAG_KEY_FRAME, delegate.flags)
assertEquals(original.size, delegate.sampleSize)
assertEquals(0, delegate.offset)
assertEquals(1, delegate.metadataCount)
}
@Test
fun activeTransformUsesMetadataBoundariesForBufferedSamples() {
val first = ByteArray(4096) { (it % 19).toByte() }
val second = ByteArray(2048) { (it % 23).toByte() }
val firstCompressed = deflate(first)
val secondCompressed = deflate(second)
val combined = firstCompressed + secondCompressed
val delegate = RecordingTrackOutput(retainBytes = true)
val output = ZlibInflatingTrackOutput(delegate).apply { active = true }
output.sampleData(ParsableByteArray(combined), combined.size, TrackOutput.SAMPLE_DATA_PART_MAIN)
output.sampleMetadata(1, 0, firstCompressed.size, secondCompressed.size, null)
output.sampleMetadata(2, 0, secondCompressed.size, 0, null)
assertArrayEquals(first + second, delegate.retained.toByteArray())
assertEquals(2, delegate.metadataCount)
}
@Test
fun exactlySixteenMiBInflatedSampleIsAccepted() {
val size = 16 * 1024 * 1024
val compressed = deflateRepeated(size)
val delegate = RecordingTrackOutput()
val output = ZlibInflatingTrackOutput(delegate).apply { active = true }
feed(output, compressed)
assertEquals(size, delegate.byteCount)
assertEquals(size, delegate.sampleSize)
assertEquals(1, delegate.metadataCount)
assertTrue(compressed.size < 64 * 1024)
}
@Test
fun oneByteOverInflatedLimitFailsBeforeDelegation() {
val compressed = deflateRepeated(16 * 1024 * 1024 + 1)
val delegate = RecordingTrackOutput()
val output = ZlibInflatingTrackOutput(delegate).apply { active = true }
assertThrows(ParserException::class.java) { feed(output, compressed) }
assertEquals(0, delegate.byteCount)
assertEquals(0, delegate.metadataCount)
assertTrue(compressed.size < 64 * 1024)
}
@Test
fun excessiveCompressionRatioFailsBeforeInflatedSizeLimit() {
val compressed = deflate(ByteArray(8 * 1024 * 1024))
val delegate = RecordingTrackOutput()
val output = ZlibInflatingTrackOutput(delegate).apply { active = true }
assertThrows(ParserException::class.java) { feed(output, compressed) }
assertEquals(0, delegate.byteCount)
assertEquals(0, delegate.metadataCount)
}
@Test
fun corruptStreamPassesTheBoundedSampleThroughUnchanged() {
val corrupt = byteArrayOf(0, 1, 2, 3)
val delegate = RecordingTrackOutput(retainBytes = true)
val output = ZlibInflatingTrackOutput(delegate).apply { active = true }
feed(output, corrupt)
assertArrayEquals(corrupt, delegate.retained.toByteArray())
assertEquals(corrupt.size, delegate.sampleSize)
assertEquals(1, delegate.metadataCount)
}
@Test
fun truncatedAndDictionaryStreamsFailClosed() {
val valid = deflate(ByteArray(4096) { 7 })
val dictionary = "shared-zlib-dictionary".toByteArray()
val cases = listOf(
valid.copyOf(valid.size - 2),
deflate(ByteArray(4096) { 3 }, dictionary)
)
for (compressed in cases) {
val delegate = RecordingTrackOutput()
val output = ZlibInflatingTrackOutput(delegate).apply { active = true }
assertThrows(ParserException::class.java) { feed(output, compressed) }
assertEquals(0, delegate.byteCount)
assertEquals(0, delegate.metadataCount)
}
}
@Test
fun inactiveWrapperDelegatesBytesAndMetadataUnchanged() {
val bytes = byteArrayOf(9, 8, 7, 6)
val trailing = byteArrayOf(5, 4)
val allBytes = bytes + trailing
val delegate = RecordingTrackOutput(retainBytes = true)
val output = ZlibInflatingTrackOutput(delegate)
output.sampleData(ParsableByteArray(allBytes), allBytes.size, TrackOutput.SAMPLE_DATA_PART_MAIN)
output.sampleMetadata(99L, 3, bytes.size, trailing.size, null)
assertArrayEquals(allBytes, delegate.retained.toByteArray())
assertEquals(bytes.size, delegate.sampleSize)
assertEquals(trailing.size, delegate.offset)
assertEquals(99L, delegate.timeUs)
}
private fun feed(output: ZlibInflatingTrackOutput, compressed: ByteArray) {
output.sampleData(
ParsableByteArray(compressed),
compressed.size,
TrackOutput.SAMPLE_DATA_PART_MAIN
)
output.sampleMetadata(1L, C.BUFFER_FLAG_KEY_FRAME, compressed.size, 0, null)
}
private fun deflate(bytes: ByteArray, dictionary: ByteArray? = null): ByteArray {
val target = ByteArrayOutputStream()
val deflater = Deflater().apply {
if (dictionary != null) setDictionary(dictionary)
}
DeflaterOutputStream(target, deflater).use { it.write(bytes) }
return target.toByteArray()
}
private fun deflateRepeated(size: Int): ByteArray {
val target = ByteArrayOutputStream()
val chunk = ByteArray(8192) { (it % 7).toByte() }
DeflaterOutputStream(target).use { stream ->
var remaining = size
while (remaining > 0) {
val count = minOf(remaining, chunk.size)
stream.write(chunk, 0, count)
remaining -= count
}
}
return target.toByteArray()
}
private class RecordingTrackOutput(
private val retainBytes: Boolean = false
) : TrackOutput {
val retained = ByteArrayOutputStream()
var byteCount = 0
var metadataCount = 0
var timeUs = C.TIME_UNSET
var flags = 0
var sampleSize = -1
var offset = -1
override fun format(format: Format) = Unit
override fun sampleData(
input: DataReader,
length: Int,
allowEndOfInput: Boolean,
sampleDataPart: Int
): Int {
val buffer = ByteArray(length)
val read = input.read(buffer, 0, length)
if (read > 0) record(buffer, read)
return read
}
override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) {
val buffer = ByteArray(length)
data.readBytes(buffer, 0, length)
record(buffer, length)
}
private fun record(buffer: ByteArray, length: Int) {
byteCount += length
if (retainBytes) retained.write(buffer, 0, length)
}
override fun sampleMetadata(
timeUs: Long,
flags: Int,
size: Int,
offset: Int,
cryptoData: TrackOutput.CryptoData?
) {
metadataCount++
this.timeUs = timeUs
this.flags = flags
sampleSize = size
this.offset = offset
}
}
}
@@ -48,6 +48,30 @@ class MpvPlayerPluginTest {
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 hardwareDecodeSessionsKeepTheLegacyGpuVo() {
// gpu-next under hwdec=mediacodec fails every frame on Tegra (the
// cross-stage samplerExternalOES linker bug): solid blue screen with
// audio on the Shield (#2010). DV reshaping — the reason gpu-next exists
// on Android (#1902) — only happens under software decode anyway, so
// gpu-next is offered exactly there and nowhere else.
assertEquals("gpu", MpvPlayerCore.initialVideoOutput(hardwareDecoding = true))
assertEquals("gpu-next,gpu", MpvPlayerCore.initialVideoOutput(hardwareDecoding = false))
}
@Test
fun setPropertyWithoutCoreReportsNotInitializedForVideoAndAudio() {
for (plugin in listOf(MpvPlayerPlugin(), MpvAudioPlayerPlugin())) {
@@ -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))
}
}
@@ -1,286 +0,0 @@
package com.edde746.plezy.watchnext
import android.content.ContentProvider
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.database.Cursor
import android.database.MatrixCursor
import android.net.Uri
import androidx.tvprovider.media.tv.TvContractCompat
import androidx.work.NetworkType
import androidx.work.WorkInfo
import androidx.work.WorkManager
import androidx.work.testing.TestListenableWorkerBuilder
import androidx.work.testing.WorkManagerTestInitHelper
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import java.lang.reflect.Proxy
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executor
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import org.robolectric.shadows.ShadowContentResolver
@RunWith(RobolectricTestRunner::class)
class ShelfRefreshWorkerTest {
private val context: Context get() = RuntimeEnvironment.getApplication()
@Before
fun setUp() {
context.getSharedPreferences("system_shelf_state", 0).edit().clear().commit()
context.cacheDir.resolve("system_shelf_artwork").deleteRecursively()
ShadowContentResolver.registerProviderInternal(TvContractCompat.AUTHORITY, StubTvProvider())
WorkManagerTestInitHelper.initializeTestWorkManager(context)
}
@After
fun tearDown() {
ShelfRefreshWorker.engineLauncherOverride = null
// Leave no live lease behind for the next test in this sandbox.
SystemShelfLifecycle.invalidate(SystemShelfLifecycle.acquire())
context.cacheDir.resolve("system_shelf_artwork").deleteRecursively()
}
@Test
fun successfulSyncSchedulesUniquePeriodicRefreshWithKeepAndNetworkConstraint() {
val plugin = WatchNextPlugin()
val binding = pluginBinding()
plugin.onAttachedToEngine(binding)
try {
val first = ShelfRecordingResult()
plugin.onMethodCall(syncCall(generation = 1), first)
awaitResult(first)
assertEquals(true, first.successValue)
val infos = uniqueWorkInfos()
assertEquals(1, infos.size)
val info = infos.single()
assertEquals(WorkInfo.State.ENQUEUED, info.state)
assertEquals(NetworkType.CONNECTED, info.constraints.requiredNetworkType)
assertEquals(TimeUnit.HOURS.toMillis(6), info.periodicityInfo?.repeatIntervalMillis)
// KEEP: a second successful sync must not replace the pending request.
val second = ShelfRecordingResult()
plugin.onMethodCall(syncCall(generation = 2), second)
awaitResult(second)
assertEquals(true, second.successValue)
assertEquals(info.id, uniqueWorkInfos().single().id)
} finally {
plugin.onDetachedFromEngine(binding)
}
}
@Test
fun clearCancelsScheduledRefresh() {
val plugin = WatchNextPlugin()
val binding = pluginBinding()
plugin.onAttachedToEngine(binding)
try {
val sync = ShelfRecordingResult()
plugin.onMethodCall(syncCall(generation = 1), sync)
awaitResult(sync)
assertEquals(true, sync.successValue)
assertEquals(WorkInfo.State.ENQUEUED, uniqueWorkInfos().single().state)
val clear = ShelfRecordingResult()
plugin.onMethodCall(
MethodCall("clear", mapOf("schemaVersion" to 3, "ownerId" to "owner-a", "generation" to 2L)),
clear
)
awaitResult(clear)
assertEquals(true, clear.successValue)
assertEquals(WorkInfo.State.CANCELLED, uniqueWorkInfos().single().state)
} finally {
plugin.onDetachedFromEngine(binding)
}
}
@Test
fun receiverDoesNotArmRefreshWithoutPersistedShelfState() {
SystemShelfUpdateReceiver(directExecutor).onReceive(context, Intent(Intent.ACTION_BOOT_COMPLETED))
assertTrue(uniqueWorkInfos().isEmpty())
}
@Test
fun receiverRearmsRefreshOnBootWhenShelfStateIsPersisted() {
// granted_uris is only written by a committed sync (clear removes it), so
// its presence — even as an empty set — marks a prior sync.
context.getSharedPreferences("system_shelf_state", 0).edit()
.putStringSet("granted_uris", emptySet())
.putInt("shelf_schema_version", 1)
.commit()
SystemShelfUpdateReceiver(directExecutor).onReceive(context, Intent(Intent.ACTION_BOOT_COMPLETED))
assertEquals(WorkInfo.State.ENQUEUED, uniqueWorkInfos().single().state)
}
@Test
fun receiverRearmsRefreshOnPackageReplacedWhenShelfStateIsPersisted() {
context.getSharedPreferences("system_shelf_state", 0).edit()
.putStringSet("granted_uris", emptySet())
.putInt("shelf_schema_version", 1)
.commit()
SystemShelfUpdateReceiver(directExecutor).onReceive(context, Intent(Intent.ACTION_MY_PACKAGE_REPLACED))
assertEquals(WorkInfo.State.ENQUEUED, uniqueWorkInfos().single().state)
}
@Test
fun workerSkipsWithoutLaunchingEngineWhenLiveEngineHoldsLease() {
shadowOf(context.packageManager).setSystemFeature(PackageManager.FEATURE_LEANBACK, true)
val launched = AtomicBoolean(false)
ShelfRefreshWorker.engineLauncherOverride = {
launched.set(true)
true
}
val lease = SystemShelfLifecycle.acquire()
try {
val result = TestListenableWorkerBuilder<ShelfRefreshWorker>(context).build().startWork().get()
assertEquals(androidx.work.ListenableWorker.Result.success(), result)
assertFalse(launched.get())
} finally {
SystemShelfLifecycle.invalidate(lease)
}
}
@Test
fun workerSkipsWithoutLaunchingEngineOnNonLeanbackDevices() {
val launched = AtomicBoolean(false)
ShelfRefreshWorker.engineLauncherOverride = {
launched.set(true)
true
}
val result = TestListenableWorkerBuilder<ShelfRefreshWorker>(context).build().startWork().get()
assertEquals(androidx.work.ListenableWorker.Result.success(), result)
assertFalse(launched.get())
}
@Test
fun unattendedWorkerRunsInjectedLauncherAndMapsCompletionToResult() {
shadowOf(context.packageManager).setSystemFeature(PackageManager.FEATURE_LEANBACK, true)
val launched = AtomicBoolean(false)
ShelfRefreshWorker.engineLauncherOverride = {
launched.set(true)
true
}
val success = TestListenableWorkerBuilder<ShelfRefreshWorker>(context).build().startWork().get()
assertEquals(androidx.work.ListenableWorker.Result.success(), success)
assertTrue(launched.get())
ShelfRefreshWorker.engineLauncherOverride = { false }
val failure = TestListenableWorkerBuilder<ShelfRefreshWorker>(context).build().startWork().get()
assertEquals(androidx.work.ListenableWorker.Result.retry(), failure)
}
private val directExecutor = Executor { it.run() }
private fun uniqueWorkInfos(): List<WorkInfo> = WorkManager.getInstance(context).getWorkInfosForUniqueWork(ShelfRefreshScheduler.WORK_NAME).get()
private fun syncCall(generation: Long) = MethodCall(
"sync",
mapOf(
"schemaVersion" to 3,
"ownerId" to "owner-a",
"generation" to generation,
"items" to emptyList<Map<String, Any?>>()
)
)
private fun awaitResult(result: ShelfRecordingResult) {
repeat(100) {
shadowOf(android.os.Looper.getMainLooper()).idle()
if (result.completed.await(10, TimeUnit.MILLISECONDS)) return
}
assertTrue("Watch Next result never completed", false)
}
private fun pluginBinding(): FlutterPlugin.FlutterPluginBinding {
val messenger = Proxy.newProxyInstance(
BinaryMessenger::class.java.classLoader,
arrayOf(BinaryMessenger::class.java)
) { _, _, _ -> null } as BinaryMessenger
val constructor = FlutterPlugin.FlutterPluginBinding::class.java.constructors.single()
val arguments = constructor.parameterTypes.map { type ->
when {
Context::class.java.isAssignableFrom(type) -> context
BinaryMessenger::class.java.isAssignableFrom(type) -> messenger
else -> null
}
}.toTypedArray()
return constructor.newInstance(*arguments) as FlutterPlugin.FlutterPluginBinding
}
}
/** Just enough TV provider for an empty-items sync/clear to commit. */
private class StubTvProvider : ContentProvider() {
private val inserted = mutableListOf<ContentValues>()
private var nextRowId = 1L
override fun onCreate(): Boolean = true
override fun insert(uri: Uri, values: ContentValues?): Uri {
inserted += ContentValues(values)
return uri.buildUpon().appendPath((nextRowId++).toString()).build()
}
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {
val deleted = inserted.size
inserted.clear()
return deleted
}
override fun query(
uri: Uri,
projection: Array<out String>?,
selection: String?,
selectionArgs: Array<out String>?,
sortOrder: String?
): Cursor = MatrixCursor(
projection ?: arrayOf(
TvContractCompat.WatchNextPrograms._ID,
TvContractCompat.WatchNextPrograms.COLUMN_INTERNAL_PROVIDER_ID,
TvContractCompat.WatchNextPrograms.COLUMN_INTERNAL_PROVIDER_DATA,
TvContractCompat.WatchNextPrograms.COLUMN_INTENT_URI,
TvContractCompat.PreviewPrograms.COLUMN_POSTER_ART_URI
)
)
override fun getType(uri: Uri): String? = null
override fun update(
uri: Uri,
values: ContentValues?,
selection: String?,
selectionArgs: Array<out String>?
): Int = 0
}
private class ShelfRecordingResult : MethodChannel.Result {
val completed = CountDownLatch(1)
var successValue: Any? = null
override fun success(result: Any?) {
successValue = result
completed.countDown()
}
override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) {
completed.countDown()
}
override fun notImplemented() {
completed.countDown()
}
}
@@ -17,6 +17,13 @@ import android.database.MatrixCursor
import android.net.Uri
import android.os.ParcelFileDescriptor.AutoCloseInputStream
import androidx.tvprovider.media.tv.TvContractCompat
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkInfo
import androidx.work.WorkManager
import androidx.work.Worker
import androidx.work.WorkerParameters
import androidx.work.testing.WorkManagerTestInitHelper
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
@@ -720,6 +727,26 @@ class WatchNextProviderTest {
assertFalse(context.cacheDir.resolve("system_shelf_artwork").exists())
}
@Test
fun packageUpdateCancelsLegacyShelfRefreshWork() {
WorkManagerTestInitHelper.initializeTestWorkManager(context)
val workManager = WorkManager.getInstance(context)
workManager.enqueueUniquePeriodicWork(
SystemShelfUpdateReceiver.LEGACY_SHELF_REFRESH_WORK,
ExistingPeriodicWorkPolicy.KEEP,
PeriodicWorkRequestBuilder<LegacyShelfRefreshStandIn>(6, TimeUnit.HOURS).build()
).result.get()
SystemShelfUpdateReceiver(Executor { command -> command.run() })
.onReceive(context, Intent(Intent.ACTION_MY_PACKAGE_REPLACED))
val states = workManager
.getWorkInfosForUniqueWork(SystemShelfUpdateReceiver.LEGACY_SHELF_REFRESH_WORK)
.get()
.map { it.state }
assertEquals(listOf(WorkInfo.State.CANCELLED), states)
}
@Test
fun providerFailureDeletesNewArtworkAndPreservesCommittedArtwork() {
ScriptedHttpServer(
@@ -1605,3 +1632,15 @@ private class ManualExecutorService : AbstractExecutorService() {
tasks.removeFirst().run()
}
}
/**
* Stands in for the removed ShelfRefreshWorker so the legacy periodic job can
* be enqueued. Public because WorkManager's default factory instantiates
* workers reflectively and cannot access a package-private class.
*/
class LegacyShelfRefreshStandIn(
context: Context,
params: WorkerParameters
) : Worker(context, params) {
override fun doWork(): Result = Result.success()
}

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