Compare commits

..
309 Commits
Author SHA1 Message Date
github-actions[bot] bd83c10b9b chore: bump version to 2.9.0 2026-07-12 22:11:51 +00:00
edde746 e03edad824 fix: prevent async state and platform regressions 2026-07-13 00:03:52 +02:00
edde746 26d14f7cb0 fix(seerr): align request button focus 2026-07-12 22:19:42 +02:00
edde746 b9f828ae88 refactor(livetv): reuse standard hub cards 2026-07-12 22:11:30 +02:00
edde746 098a472670 fix(catalog): restore TV focus navigation 2026-07-12 21:42:27 +02:00
edde746 780a1ea180 fix(ci): restore analyzer and unit checks 2026-07-12 19:55:24 +02:00
edde746 917f6a2839 fix: guard lifecycle-bound state updates 2026-07-12 19:00:28 +02:00
edde746 2101f1d7f0 perf: isolate focus and media rebuilds 2026-07-12 19:00:11 +02:00
edde746 a561777456 perf: reduce state notification fan-out 2026-07-12 18:59:58 +02:00
edde746 b4575c9780 fix: preserve live TV state across refreshes 2026-07-12 18:59:42 +02:00
edde746 0ef1e773bb fix: scope navigation callbacks to active owners 2026-07-12 18:59:27 +02:00
edde746 cd88f73f05 fix: serialize async state transitions 2026-07-12 18:59:14 +02:00
edde746 d1c4ae83eb fix(review): resolve post-consolidation regressions 2026-07-12 17:31:16 +02:00
edde746 858952929b fix(deps): refresh and document native dependencies 2026-07-12 17:31:16 +02:00
edde746 b676ef6c56 refactor(android): harden and share player integration 2026-07-12 17:31:15 +02:00
edde746 a9493f4f0e fix(relay): harden lifecycle and protocol handling 2026-07-12 17:31:15 +02:00
edde746 fe8d405a56 fix(i18n): enforce complete localized coverage 2026-07-12 17:31:14 +02:00
edde746 754c54761a refactor(downloads): consolidate task and metadata flows 2026-07-12 17:31:13 +02:00
edde746 7ecadffdb1 refactor(features): consolidate shared feature primitives 2026-07-12 17:31:13 +02:00
edde746 6506f36843 refactor(app): share client and presentation scaffolds 2026-07-12 17:31:12 +02:00
edde746 97f7508067 refactor(core): consolidate shared app foundations 2026-07-12 17:31:12 +02:00
edde746 a481fc1000 refactor(dialogs): unify text input contract 2026-07-12 08:42:26 +02:00
edde746 b7078448ea refactor(mpv): unify property decoding 2026-07-12 08:42:26 +02:00
edde746 359a6bf02a refactor(live-tv): split optional DVR support 2026-07-12 08:42:25 +02:00
edde746 a5449a1430 refactor(ci): matrix architecture builds 2026-07-12 08:42:25 +02:00
edde746 6182c34448 perf(playlists): bound card inflation 2026-07-12 08:42:25 +02:00
edde746 699e73bcd5 fix(downloads): propagate hierarchical watch state 2026-07-12 08:42:25 +02:00
edde746 352aa04d3e refactor(settings): share preference binding lifecycle 2026-07-12 08:42:25 +02:00
edde746 c81a1f9a97 fix(plex): tolerate malformed activity rows 2026-07-12 08:42:25 +02:00
edde746 34be331024 refactor(media): centralize HDR classification 2026-07-12 08:42:25 +02:00
edde746 ceae98b75f refactor(paging): share continuation loading 2026-07-12 08:42:25 +02:00
edde746 5328865639 refactor(input): share gamepad key simulation 2026-07-12 08:42:24 +02:00
edde746 f78089edf8 refactor(input): share D-pad long press state 2026-07-12 08:42:24 +02:00
edde746 c0d8951677 fix(release): centralize pubspec version parsing 2026-07-12 08:42:24 +02:00
edde746 2e830d3f97 refactor(database): share watch action queries 2026-07-12 08:42:24 +02:00
edde746 649eaa4cce refactor(watch-together): share relay setup 2026-07-12 08:42:24 +02:00
edde746 80344a630f feat(playlists): add picker filtering and TV focus 2026-07-12 08:42:24 +02:00
edde746 2a128777f1 refactor(profiles): centralize Plex token policy 2026-07-12 08:42:24 +02:00
edde746 baf3c41a44 refactor(providers): share coalesced load scheduling 2026-07-12 08:42:24 +02:00
edde746 f7f4e3a992 fix(windows): support structured mpv observations 2026-07-12 08:42:24 +02:00
edde746 6890cd8690 refactor(settings): remove dead shortcut preferences 2026-07-12 08:42:23 +02:00
edde746 c84b8b4792 refactor(downloads): unify deletion and scoped cache handling 2026-07-12 08:42:23 +02:00
edde746 3d36ecf094 fix(mpv): harden native initialization and logging 2026-07-12 08:42:23 +02:00
edde746 eaa60cc2b5 fix(release): resolve package tags once 2026-07-12 08:42:23 +02:00
edde746 de5234b59f refactor(trackers): share username enrichment 2026-07-12 08:42:23 +02:00
edde746 69cf5fb8a1 fix(live-tv): contain retry failures 2026-07-12 08:42:23 +02:00
edde746 a0f153e5ab refactor(symbols): share upload flow 2026-07-12 08:42:23 +02:00
edde746 0135318ded fix(android): include mpv end-file diagnostics 2026-07-12 08:42:22 +02:00
edde746 f4ec6ccf20 fix(settings): guard Atmos diagnostics stop 2026-07-12 08:42:22 +02:00
edde746 5f8d263d63 fix(ci): fail closed on analyzer errors 2026-07-12 08:42:22 +02:00
edde746 242cc8616c feat(settings): expose music quality preset 2026-07-12 08:42:22 +02:00
edde746 2ebc1e250d fix(providers): stop loads after disposal 2026-07-12 08:42:22 +02:00
edde746 5876a602c3 fix(android): surface mpv command failures 2026-07-12 08:42:22 +02:00
edde746 79dabaf125 refactor(watch-together): share host peer IDs 2026-07-12 08:42:22 +02:00
edde746 65d3d8e471 refactor(jellyfin): share auth and time handling 2026-07-12 08:42:22 +02:00
edde746 aa230983d5 refactor(navigation): centralize sidebar focus 2026-07-12 08:42:22 +02:00
edde746 1b9ef3b3b6 fix(discover): avoid progress refresh fanout 2026-07-12 08:42:21 +02:00
edde746 7ed342b345 refactor(watch-together): centralize participant lookup 2026-07-12 08:42:21 +02:00
edde746 29c029f04a refactor(watch-together): share core primitives 2026-07-12 08:42:21 +02:00
edde746 777780926c refactor(paging): share unknown-total sentinel 2026-07-12 08:42:21 +02:00
edde746 f08fceaee0 refactor(json): share scalar adapters 2026-07-12 08:42:21 +02:00
edde746 0ddd0a6c25 refactor(mpv): remove unused seek events 2026-07-12 08:42:21 +02:00
edde746 8a8b4f3a61 refactor: remove unused convenience APIs 2026-07-12 08:42:20 +02:00
edde746 cdec9d1514 refactor(player): centralize chapter traversal 2026-07-12 08:42:20 +02:00
edde746 9da047de70 refactor(cache): centralize non-fatal writes 2026-07-12 08:42:20 +02:00
edde746 18835d92dd refactor(navigation): reuse library icon mapping 2026-07-12 08:42:20 +02:00
edde746 967c25b11d refactor(player): share queue item labels 2026-07-12 08:42:20 +02:00
edde746 877e8880cf refactor(profiles): centralize Plex Home cache codec 2026-07-12 08:42:20 +02:00
edde746 ac9c236b6b refactor(providers): harden server listener state 2026-07-12 08:42:20 +02:00
edde746 df7fa08e40 refactor(focus): centralize focus node ownership 2026-07-12 08:42:20 +02:00
edde746 c58013b818 refactor(downloads): centralize sidecar cleanup 2026-07-12 08:42:20 +02:00
edde746 b925705173 fix(downloads): discard stale profile refreshes 2026-07-12 08:42:19 +02:00
edde746 7a0e838017 fix(profiles): remint empty Plex resource tokens 2026-07-12 08:42:19 +02:00
edde746 bc55aea701 refactor: remove superseded code paths 2026-07-12 08:42:19 +02:00
edde746 dca51a752a refactor(downloads): centralize metadata merging 2026-07-12 08:42:19 +02:00
edde746 0db6eb6f2e fix(downloads): normalize Windows sidecar paths 2026-07-12 08:42:19 +02:00
edde746 d1a67828b6 fix(ci): detect silent tool failures 2026-07-12 08:42:19 +02:00
edde746 048fb77c8c fix(windows): move mpv teardown off platform thread 2026-07-12 08:42:19 +02:00
edde746 a63369c247 fix: close async lifecycle races 2026-07-12 08:42:19 +02:00
edde746 6d94880c2f fix(input): reset long press state safely 2026-07-12 08:42:19 +02:00
edde746 9c6fcbc841 fix(plex): tolerate scalar schema drift 2026-07-12 08:42:18 +02:00
edde746 a809cbbcef fix(plex): surface server failures 2026-07-12 08:42:18 +02:00
edde746 e4b0680158 fix(ci): enforce automation checks 2026-07-12 08:42:18 +02:00
edde746 64db84c3e2 feat(library): default clip libraries to folder grouping
close #966
2026-07-12 03:38:23 +02:00
edde746 4a81246986 build(libass): bump fork to 0.18.3 2026-07-12 00:44:08 +02:00
edde746 a23c7f215c fix(player): tighten staged back navigation 2026-07-11 23:11:25 +02:00
edde746andmoduvoice 5af3a926d7 i18n: complete locale translations
close #1537

Co-authored-by: moduvoice <moduvoicr77@gmail.com>
2026-07-11 22:53:33 +02:00
edde746 2679745941 fix: stop Jellyfin live TV sessions
close #1533
2026-07-11 22:00:05 +02:00
edde746 4443b76145 fix(player): respect visible chrome on back 2026-07-11 17:38:22 +02:00
edde746 3a982c2a7a fix(player): prevent duplicate back actions 2026-07-11 12:59:57 +02:00
edde746 e07172ade4 fix(tvos): enable native EAC3 JOC playback 2026-07-11 12:59:57 +02:00
Ryan ErnestandGitHub c86d40f8dd fix(player): preserve volume when toggling mute (#1532)
* fix(player): preserve volume when toggling mute

Muting now keeps the last volume level memorized. Unmuting restores that level, including amplified values allowed by the configured maximum.

* fix(player): preserve volume for companion remote mute

Route the companion remote through the shared mute transition so it no longer overwrites the persisted volume or restores to 100%. Also correct the Dartdoc formatting for the transition record fields.
2026-07-11 12:46:58 +02:00
edde746 d86e328169 fix(player): unify back navigation
close #1525
2026-07-11 03:23:40 +02:00
edde746 02a032d287 fix(android): reconnect Flutter texture after TV standby 2026-07-11 01:01:08 +02:00
edde746 03651d6c73 fix(exoplayer): unwrap AAC-LATM (LOAS) audio in MKV direct streams
close #1521
2026-07-10 23:23:44 +02:00
edde746 9b6c12d086 style: format playback_open 2026-07-10 21:26:25 +02:00
edde746 c5c7dd614f i18n: translate stream-interrupted snackbar to all locales 2026-07-10 20:27:52 +02:00
edde746 f87d6e5a52 fix(player): keep paused server sessions alive
Report the paused timeline every tick (~10s, matching official clients)
instead of every ~60s, and ping the Plex transcoder keepalive endpoint
alongside it while transcoding — PMS reaps idle transcode sessions that
timeline reports alone historically have not kept alive. Prevents the
transcode-variant of the #1520 stream death; the reporter's direct-play
case is covered by EOF classification and reconnect.
2026-07-10 19:12:36 +02:00
edde746 c885c0c6bc fix(player): intercept spurious mid-file EOF and recover in place
close #1520

Classify player EOF signals against the best-known duration: a mid-file
EOF means the stream died (transcode reaped or idle connection closed
during a long pause), not that the media ended — it must never mark the
item watched, prompt Play Next, or exit a movie. Recover with a bounded
in-place reload at the parked position; if the server is still refusing,
park on the old frame and rebuild the stream on user play/seek or when
the server-status monitor sees it come back online.
2026-07-10 19:11:18 +02:00
edde746 3bf72d7237 fix(player): auto-reconnect network streams on transient HTTP 503
ffmpeg's reconnect gave up on the first HTTP-error response, so a PMS
answering 503 (startup maintenance) after an idle-pause disconnect
surfaced as a clean mid-file EOF instead of riding through the outage.
2026-07-10 19:07:29 +02:00
edde746 d07d849fe4 refactor(player): return an outcome enum from _reloadMediaInPlace
The old bool meant "attempt was current and handled", so callers could
not distinguish a real pre-open failure (old stream still loaded) from
success — the distinction the #1520 recovery needs.
2026-07-10 19:06:51 +02:00
edde746 e6ffc54c56 style: format image_cache_service 2026-07-10 19:06:51 +02:00
edde746 b5d8ff5332 fix(metadata-edit): use 16:9 poster picker for episodes
close #1519
2026-07-10 12:45:35 +02:00
edde746 7509077d63 perf(tv): reduce animated semantics work 2026-07-10 12:07:19 +02:00
edde746 cbabdf2151 fix(images): prevent artwork limiter permit leaks 2026-07-10 12:07:19 +02:00
edde746 1acc83572e perf(tv): reduce navigation rebuilds and artwork fan-out 2026-07-10 12:07:19 +02:00
edde746andl3gitpanda b46107cb58 fix(tv): dismiss on-screen keyboard on companion-remote search submit
close #1514

A query submitted from the companion remote now behaves like a submit
instead of focus-to-type: TvKeyboardController closes an already-open
OSK and lands focus on the input without reopening it, then the shared
handleSearchSubmit path runs the search and focuses the first result.
Also guard DebouncedMediaSearch against selection-only controller
notifications re-arming the debounce into a duplicate fetch.

Co-authored-by: l3gitpanda <12003346+l3gitpanda@users.noreply.github.com>
2026-07-10 08:48:38 +02:00
edde746 1261852514 fix(ci): regenerate Trakt catalog model 2026-07-10 07:32:02 +02:00
edde746 04daf89a20 feat(explore): Explore tab with catalog detail, search, and Seerr requests 2026-07-10 07:10:15 +02:00
edde746 f94b8c6586 feat(settings): Services hub, Seerr sign-in, and all-locale strings 2026-07-10 07:09:29 +02:00
edde746 b4943f8c50 feat(seerr): Seerr API, account provider, and Explore catalog source 2026-07-10 07:08:42 +02:00
edde746 2aa084287d feat(explore): MyAnimeList catalog source 2026-07-10 07:07:54 +02:00
edde746 dcdbbc8483 feat(explore): match catalog items to library content via reverse external-id lookup 2026-07-10 07:07:07 +02:00
edde746 4e6ea5b4c5 feat(trakt): catalog API and shared catalog core (watchlist, discover, recommendations) 2026-07-10 07:06:21 +02:00
edde746 ede80d225f refactor: shared coalescer, profile-scoped prefs key, and form-error helper 2026-07-10 07:05:35 +02:00
edde746 397de2698d feat(livetv): flat M3E card redesign for guide, recordings, and details 2026-07-10 06:41:15 +02:00
edde746 632d2ec16b feat(livetv): let user pick and remember the recording target library
close #1513
2026-07-10 06:41:15 +02:00
edde746 2c13438d71 fix(tv): retain live TV session while backgrounded 2026-07-09 23:22:27 +02:00
edde746 fe5d6d8d96 fix(music): play audio playlists from context menus 2026-07-09 23:22:27 +02:00
edde746 e2ad28ca32 fix(downloads): retain offline media after logout 2026-07-09 23:22:27 +02:00
edde746 ed183a855e ci: track Android Gradle wrapper 2026-07-09 17:55:06 +02:00
edde746 5867809560 fix: resolve Jellyfin, logout, playback, and Android regressions 2026-07-09 17:14:45 +02:00
edde746 a4a2942546 fix(tv): release native AV pipeline when app stays backgrounded
A paused-but-alive player keeps its MediaCodec decoders and tunneled
passthrough AudioTrack while Plezy sits in the background, which can
degrade playback in every other app on shared-pipeline TV SoCs until
force-stop. After a 30s grace on Android TV the player is stopped
(retaining session state); returning reloads in place, or re-tunes the
channel for live TV.
2026-07-09 15:23:29 +02:00
edde746 71d644c4ae fix(macos): stop CPU spin when display sleeps with video paused
When the display/system sleeps with a video paused, the window server
stops completing CAMetalLayer presents and mpv's MoltenVK swapchain wedges,
pinning one core at 100% until the app exits. occlusionState does not
reliably change on display sleep, so observe NSWorkspace screensDidSleep/
Wake to hide the metal layer (and drop the playback activity) while dark,
restoring on wake with a forced redraw when paused to avoid a stale frame.

Pairs with MPVKit v1.0.10, which gates libmpv presentation on the layer's
hidden state (check_visible) so presents actually stop while hidden.
2026-07-09 11:56:13 +02:00
edde746 574b8d524f fix(ios): don't claim audio session at app launch
The non-mixing playback session was activated in didFinishLaunching,
so merely opening the app stopped other apps' audio. Keep the category
configuration; playback start activates the session.
2026-07-07 08:55:26 +02:00
edde746 94852e49cb fix(ios): stop reclaiming audio session while paused in PiP
close #1496

Bumps os_media_controls so the audio session is only activated on
playing-state pushes; paused/metadata pushes no longer re-interrupt
other apps' audio (which caused the 1-2 Hz play/pause loop).
2026-07-07 08:54:31 +02:00
edde746 4a3295b7fd fix(player): handle Plex multi-episode files in up-next and watch state
close #1500
2026-07-06 18:39:45 +02:00
edde746 ef75887504 style: apply analyzer lint fixes across lib
Initializing formals, unawaited() on fire-and-forget futures, unused
import removal, wildcard params, and mounted vs context.mounted.
2026-07-06 15:56:56 +02:00
edde746 49d4b433a7 fix(music): show now-playing rail item only on TV
Desktop already has the mini-player as the way back into the
now-playing screen; the rail item is redundant there.
2026-07-06 15:56:01 +02:00
edde746 5bb8b1b9f2 feat(music): add persistent volume control
Independent of the video player volume; persisted via SettingsService
and re-applied to every audio player instance.
2026-07-06 15:55:06 +02:00
edde746andClaude Fable 5 04c0714881 chore: bump os_media_controls for lock-screen artwork fixes
Pulls edde746/media_controls@71b96f8: iOS/macOS guard async artwork
downloads against track changes (slow art no longer lands on the next
track) and clear stale artwork when a track has none.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-06 15:33:21 +02:00
edde746andClaude Fable 5 5f7925f350 fix(music): scope current-track highlight per server
TrackRow compared bare ids (server-scoped rating keys), so a track on
another server with the same id lit up as currently playing. Compare
globalKey (serverId:id) like the rest of the queue engine.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-06 15:32:26 +02:00
edde746andClaude Fable 5 226be37f85 fix(music): mark only the active sleep timer preset selected
All timed presets shared one 'timed' bool, so arming any of 15/30/60
minutes checkmarked all three. The service now retains the armed
duration (sleepTimerDuration) and the menu marks the matching preset.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-06 15:31:29 +02:00
edde746andClaude Fable 5 32c4810c21 fix(music): resync gapless state when queue edits race the track boundary
A queue edit can un-arm the next entry in the same instant mpv rolls
into it; the resulting transition was dropped as unexpected, leaving the
UI and progress reporting on the finished track for the entire next
file. Remember the cleared arm (generation-gated) so the transition is
still adopted, and handle the armed track no longer being in the queue:
advance to the queue's real next, or park when nothing follows. Also
fixes the latent fallthrough that left the cursor on the finished track
when the armed track vanished from the queue.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-06 15:30:18 +02:00
edde746andClaude Fable 5 28bc4a5df8 feat(player): handle stop/skip/speed media-session commands
The platforms advertise stop, skip forward/backward, and playback-rate
commands by default, but both the music and video handlers silently
dropped them (Android Auto/Bluetooth stop and FF/rewind did nothing;
iOS/macOS showed a dead rate control). setControlsEnabled now manages
those controls: music handles Stop and in-track skips and stops
advertising a speed control; video handles Stop (exit, matching the
companion remote), skips via a shared relative-seek helper, and rate
changes through player.setRate. Skip commands stay off on iOS/macOS
where they would displace the next/previous lock-screen buttons.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-06 15:28:24 +02:00
edde746andClaude Fable 5 73be8ab1c8 fix(music): convert SAF content:// downloads for gapless arming
setNext() appended raw content:// URIs that mpv cannot open, stalling
playback at the SD-card-download track boundary. Convert to fdclose://
like open(), track the armed fd, and reclaim it via a new closeContentFd
method when the entry is dropped unplayed (close only when provably
unconsumed — playlist-pos 0 before and after the remove; leak on doubt).
The playlist-pos pre-check also keeps the clear path from removing the
playing entry when mpv rolls into the armed track mid-clear.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-06 15:26:59 +02:00
edde746 4de38f4b17 fix(music): hide album track numbers in queue rows
Album-relative numbers read as a sorting bug in a mixed-album queue;
the leading slot stays so titles align with the equalizer row.
2026-07-06 12:17:03 +02:00
edde746 adf732a1a1 fix(ui): app-bar tab chip strips scroll instead of overflowing
Shared TabChipStrip replaces the plain Rows in libraries/downloads/live
TV app bars (and live TV's hand-rolled scroll wrapper); chips center
themselves on focus so d-pad reaches off-screen tabs.
2026-07-06 12:17:03 +02:00
edde746 214a7c13dc feat(music): show full play queue with history, YouTube Music style
Queue sheet/panel now renders the whole playback order — dimmed played
tracks above the current one — instead of only up-next. Opens scrolled
to the current track and follows advancement while parked on it.
2026-07-06 11:30:23 +02:00
edde746 fcdef343eb fix(music): sheet safe-area, swipe-to-dismiss, hide mini-player under sheets 2026-07-06 10:51:19 +02:00
edde746 a4d40486c1 fix(music): responsive artist header on desktop
Wide layouts put the circular portrait beside a left-aligned
name/genre/bio/actions block (mirroring the album header) instead of
a centered mobile column floating over the left-hugging albums grid.
2026-07-06 00:23:09 +02:00
edde746 338a53a036 fix(player): comma-safe http header delivery to mpv
mpv's http-header-fields string-list parser splits on commas inside
header values, so X-Plex-Device on Apple hardware (model ids like
Mac17,9) produced a colon-less garbage header line that Plex rejects
with 400 'Error parsing HTTP request' — first hit by music direct play
on macOS, latent in the mpv video path too. Deliver headers via
change-list append items (open) and per-entry -clr/-append loadfile
options (gapless arming), each item verbatim and %len%-quoted against
the outer option-list split.
2026-07-05 23:58:59 +02:00
edde746 4da489d4dc i18n(music): translate music player strings to all locales 2026-07-05 22:16:36 +02:00
edde746 db18ee4b34 feat(music): android background playback via media_controls foreground service
Bumps os_media_controls to 4f4b28f3: MediaStyle foreground service with
a JUnit-tested promote/demote/stop policy, artwork URL download (also
fixes video lock-screen art), and task-removal teardown that can't leak
orphan notifications. The music service opts into background mode per
session and requests POST_NOTIFICATIONS before first playback.
2026-07-05 21:52:58 +02:00
edde746 764345f021 feat(music): audio downloads and music home rows
Album/artist downloads expand to tracks with pinned parent metadata,
aggregate progress, container deletes with reference-counted album
covers, and a Music tab on the downloads screen with fully offline
album playback. Home rows include music libraries (fixes plex hub
items being filtered to video types) and audio playlists join
download/sync rules.
2026-07-05 21:51:37 +02:00
edde746 7d6a747aa7 feat(music): now-playing, mini-player, queue and lyrics UI
Persistent mini-player over the profile navigator (route-aware
suppression, bottom-bar inset), slide-up now-playing screen with
mobile/desktop/TV layouts (blurred-art background, pause shape morphs,
dpad seek chain), queue sheet with reorder/remove/jump, synced lyrics
view, TV rail now-playing item, sleep timer, and audio playlist
playback. Adds download affordances on music surfaces.
2026-07-05 21:50:11 +02:00
edde746 422db75b5b feat(music): mpv audio playback engine with gapless queue service
Audio-only mpv core on every platform (dedicated
com.plezy/mpv_audio_player channels): parameterized android/windows/
linux mpv plugins and a new apple MpvAudioPlayerCore, all skipping
video/window paths (vid=no, audio-display=no, gapless-audio=weak).
MusicPlaybackService drives an in-memory queue with shuffle/repeat,
file-loaded-event gapless arming (property edges coalesce and the
android bridge drops them), per-track progress reporting, OS media
controls, audio focus, sleep timer, and error auto-skip.
PlaybackCoordinator enforces one live native player: starting video
disposes the audio core first.
2026-07-05 19:26:28 +02:00
edde746 05a631415e feat(music): music browsing UI — square cards, library groupings, artist/album screens
Un-gates music libraries; adds CardShape.square plumbing (circular
artists), artists/albums/tracks browse groupings with per-grouping
sorts, audio playlists tab, artist + album detail screens with dpad
track rows, music context-menu actions, and a stub MusicPlaybackService
seam for the upcoming engine.
2026-07-05 17:20:28 +02:00
edde746 fff559da06 feat(music): add music data layer for plex and jellyfin
Backend-neutral fetchArtistAlbums/fetchAlbumTracks/fetchInstantMix/
fetchLyrics, lyrics model + LRC parser, audio quality presets, music
transcode (plex /music universal, jellyfin audio PlaybackInfo profile),
station/InstantMix radio, music search, playlist type derivation, and
audio download resolution.
2026-07-05 15:55:52 +02:00
edde746 c87a9060f9 chore: tidy formatting and local ignores 2026-07-05 14:32:21 +02:00
edde746 ee3c75ba9e fix(playback): remember last played media version for continue watching
close #1492
2026-07-05 14:29:57 +02:00
edde746 90c4fe5458 feat(audio): add Kodi-style stereo downmix with center channel boost 2026-07-05 14:29:57 +02:00
edde746 97901cba87 chore(deps): bump background_downloader 2026-07-05 14:29:57 +02:00
edde746 7f81a0d4fd fix(windows): retry connectivity listener registration outside input-sync calls
INetworkListManagerEvents Advise fails with
RPC_E_CANTCALLOUT_ININPUTSYNCCALL when the platform thread is inside an
input-synchronous call at subscribe time, and an OnListen error can
only surface in Dart as an uncatchable fatal FlutterError. The fork now
retries the registration via a message-loop timer and reports only
persistent failures through the event sink, where stream onError
handlers observe them.
2026-07-05 14:16:05 +02:00
edde746 173117602a fix(android): vendor saf_util with a sound pendingResult lifecycle
saf_util 2.0.0 leaves an already-answered MethodChannel.Result behind
in pendingResult: unrelated activity request codes consume (and answer)
the pending picker, and a failed picker launch replies without clearing
the pending state. The next delivery for request 1001 then replies a
second time — IllegalStateException "Reply already submitted" in
MainActivity.onActivityResult, crashing the process.

Vendored at packages/saf_util (BSD-3) with take-and-clear reply
ownership, request codes scoped to the plugin's own pickers, and a
guarded reply on the teardown race.
2026-07-05 14:16:05 +02:00
edde746 d9130cd932 fix(detail): guard on-deck fallback against a disposed screen
_ensureFallbackOnDeckEpisode is reached through unawaited fetch
continuations and reads providers through State.context — leaving the
screen before the season fetch settled crashed on the null-check in
the context getter.
2026-07-05 14:16:04 +02:00
edde746 be072365fc fix(player): scope event-channel cancel to the owning instance
Player backends share static per-backend EventChannel names, so two
overlapping instances (episode handoff, quick exit/reopen) collide:
the newer instance's listen displaces the older sink, the older
instance's late cancel then tears down the newer stream — silently
freezing its events — and the final cancel earns the engine's
"No active stream to cancel" reply, which the framework can only
report as an uncatchable fatal FlutterError (363 events).

Track the owning instance per channel: only the current owner sends
the native cancel; a displaced instance drops its dead subscription.
Residual benign teardown races are dropped in beforeSend.
2026-07-05 14:16:04 +02:00
edde746 61f7d33fdf fix(profiles): treat vault decrypt failures as lost credentials
A failed MAC check (key/ciphertext divergence: restored backup,
clobbered prefs, racing key generation across isolates) threw from
CredentialVault.reveal on the startup profile-settings path and
crash-looped the app until data was wiped — one device logged 31
fatals in 16 minutes on 2.8.0.

Decrypt failure now means the credential is lost, never a crash:
reveal() returns null, ProfileConnectionRegistry maps it onto the
existing empty-token lazy-fetch sentinel and heals the row so later
boots re-acquire the token instead of re-failing, and
revealConnectionConfig degrades tokens to empty strings without
marking them migrated. Key init also reloads prefs before deciding to
generate and re-reads after writing, adopting whatever landed so all
isolates converge on a single key instead of orphaning ciphertext.
2026-07-05 14:16:04 +02:00
edde746 3766b2c2d3 fix(remote): handle connect failures of losing race candidates
Race candidates created with IOWebSocketChannel.connect fail their
ready future on connect timeout or an unreachable address, and nothing
observed it — web_socket_channel reports connect errors there, so every
losing candidate surfaced as an unhandled fatal (the tracker's single
largest crash source, ~1300 events: bare 5s TimeoutException plus the
recurring no-route-to-host WebSocketChannelExceptions). The stream
listener's onError only covers post-connect errors. Swallow and log the
ready failure per candidate; the race outcome is unaffected.
2026-07-05 14:16:04 +02:00
edde746 0dfe013928 fix(home): include clip libraries in per-library home rows
close #1476
2026-07-05 09:43:34 +02:00
edde746 25c7893a8e fix(windows): report native crashes through the inproc sentry backend
Crashpad uploads minidumps straight to the DSN's /minidump endpoint,
which our tracker does not implement — every native Windows crash
(e.g. faults inside libmpv threads, #1490) was silently dropped.
The inproc handler stackwalks at crash time and reports through the
regular envelope endpoint, and crashpad_handler.exe/crashpad_wer.dll
leave the bundle.
2026-07-05 09:10:46 +02:00
edde746 28ec9cacb2 perf(tv): evict non-adjacent season episode pages on low-end hardware
Visited seasons' 200-item pages were retained for the screen's
lifetime — irrelevant for a 3-season show, tens of MB of Dart heap for
a 30-season one. Low-end TV now keeps the prefetch window (selected
season plus/minus one); evicted seasons transparently refetch through the
existing unloaded-hub path.

Ref #1349
2026-07-05 09:10:46 +02:00
edde746 aaf27a7f9e fix(android): extend the RSS eviction watchdog beyond desktop and log tier signals
Android trim callbacks are best-effort — LMK can kill without ever
delivering one — yet the RSS watchdog only ran on desktop with a fixed
1.5GB bar no 2GB TV box ever reaches before dying. The watchdog now
runs on Android with a threshold scaled to device RAM, an eviction
floor and cooldown against refetch churn, and a lower backgrounded bar
since a paused app is LMK's first candidate.

The logs-screen header and startup line now record the renderer, the
effects tier with its raw hardware signals, and the boot RSS, so
uploaded reports answer whether the reduced tier engaged.

Ref #1349
2026-07-05 09:10:36 +02:00
edde746 0fb0c7fb4c perf(android): cap engine memory pools on low-RAM devices
Flutter's imageCache budget only bounds decoded CPU bitmaps: Skia's GPU
resource cache is sized from the surface area (hundreds of MB on a
4K-composited TV) and the Dart old gen defaults to a large fraction of
physical RAM. Both drive LMK kills on 2GB boxes. Cap them via engine
shell args on hardware matching the reduced-tier triple.

Ref #1349
2026-07-05 09:10:27 +02:00
edde746 f97ab03111 fix(images): bound artwork decodes on both axes and never fetch unsized originals
The decode clamp was height-only, so ultra-wide originals could decode
far past the display budget, and two small-slot fallbacks skipped
server-side resizing entirely — handing multi-megapixel originals to
the decoder behind tiny slots. The TV spotlight background's offline
branch had no decode bound at all. All artwork now flows through a
shared both-axes bound (ResizeImagePolicy.fit: aspect-preserving,
scale-down only), and the reduced tier gets matching thumb/poster
decode caps.

Ref #1349
2026-07-05 09:10:20 +02:00
edde746 3981fac0db feat(settings): surface Manage Libraries and raise the desktop sheet cap
Extract the manage/reorder-libraries sheet from the libraries screen into
a shared widget with a public launcher, and add a settings tile (top
group, gated on having libraries) that opens it. The libraries screen
keeps its side-nav refresh and re-select-on-hide behavior via launcher
hooks; the TV dialog path lives in the launcher so the entry works there
too.

Desktop overlay sheets defaulted to a fixed 400px max height, which left
the reorder sheet ~280px tall. Both default-constraint sites now use 75%
of window height, matching mobile.

close #1468
2026-07-05 09:08:29 +02:00
edde746 4a43ae2771 fix(android): auto-recover frozen video after pause/resume on stalling decoders
Some TV SoCs (Amlogic Mi Box class) stall the MediaCodec output path
after pause/resume: audio and the clock keep advancing but the picture
freezes until a seek flushes the codec. Arm a watchdog on every
transition to playing with a warm decoder; if rendered frames stop
advancing while the position moves, recover with a 250ms seek-back
(same-position seeks are short-circuited without a codec flush),
capped per session and logged for field diagnosis.

close #1454
2026-07-05 09:08:29 +02:00
edde746 c4184c6148 fix(ci): restore sanity checks 2026-07-05 08:34:55 +02:00
edde746 87eaafe3c4 chore(deps): update MPVKit to v1.0.9
close #1420, close #1457, close #1484
2026-07-05 08:15:00 +02:00
edde746 aee48f6956 feat: extend Force TV mode to desktop for home-theater setups
Initialize TvDetectionService on every platform so the existing
force_tv_mode setting drives the 10-foot TV interface on Windows,
macOS, and Linux, and surface the toggle in appearance settings there.

Desktop keeps real-mouse behavior in TV mode: InputModeTracker still
flips between pointer and keyboard modes (cursor hidden while
keyboard-driven), segmented controls keep their hover affordance, and
the settings backup section stays available (only Android TV lacks a
document picker).

Adds PlatformDetector.debugSetIsDesktopOSOverride so TV-device
simulations in widget tests don't inherit the desktop test host's
platform.

close #1409
2026-07-05 07:08:40 +02:00
edde746 3d5a1ec966 fix: build break from Sentry.configureScope FutureOr return
The pinned sentry fork declares configureScope as FutureOr<void>,
which unawaited() rejects; wrap in Future.sync to keep the
fire-and-forget behavior.
2026-07-05 06:49:46 +02:00
edde746 2e4ba352f4 fix: multi-trigger audio recovery after Windows sleep/wake
The two prior attempts at #783 failed for lack of a reliable trigger:
re-setting audio-device to its own value is a no-op, and gating
recovery on audio-device-list changes while current-ao is null never
fires in the real flows (a paused player only discovers the dead
WASAPI session at unpause, when the device list is already stable;
a zombie session that consumes samples silently never goes null).

Replace the single gate with a recovery scheduler on the mpv event
thread, ticked every wait-event timeout:

- WM_POWERBROADCAST resume (both PBT variants, via the plugin's
  existing window-proc delegate) requests unconditional ao-reloads at
  +1.5s and +6s after wake — the only trigger that reaches zombie
  sessions; the second shot covers a first reload landing while the
  audio stack is still restoring. The handoff is a single atomic
  flag: no mpv calls or timers from the platform thread, so there is
  nothing to clean up on dispose.
- current-ao falling to null arms clock-driven retries (budget 5,
  x2 backoff capped at 8s); retries must be clock-driven because a
  failed ao-reload falls back to null without a property change
  event. A device-list change while null refreshes the budget, and
  audio-device-list is now observed natively so recovery does not
  depend on the Dart side.

Every trigger, attempt, and outcome logs as [mpv:audio-recovery] at
warn level so exported logs from the reporter are actionable if this
still misses. Verified with synthetic PBT_APMRESUMEAUTOMATIC while
playing and while paused: full WASAPI reinit both times, audio
restarts on unpause.

Ref #783
2026-07-05 06:49:38 +02:00
edde746 31e8c2e1e0 fix(plex): coerce PlexHomeUser fields against account-API drift
Same clients.plex.tv surface that broke in #1488: /home/users powers
first sign-in and profile setup, so a drifted scalar shape would kill
the whole fetch. Coerce strings, bools, and ints tolerantly instead of
hard-casting.
2026-07-05 06:23:41 +02:00
edde746 96510f8aac fix(plex): tolerate account-API schema drift in profile and switch parsing
Around July 3 plex.tv started returning the profile language-list fields
(defaultAudioLanguages, defaultSubtitleLanguages, mediaReviewsLanguages)
as comma-separated strings instead of arrays. The generated cast threw on
the successful 201 /switch response, dropping the freshly minted Home
user token: every rebind failed, the binder retried a /switch mint every
1-2s, and the app sat permanently in offline mode even after re-signing
in. Accounts without language prefs set were unaffected, which is why
the breakage looked sporadic.

Parse the language lists with a CSV-aware coercion, and make
UserSwitchResponse.fromJson strict only about authToken: decorative
fields now coerce tolerantly and a broken profile blob falls back to
defaults, so account-API drift can never brick token minting again.

close #1488
2026-07-05 06:23:34 +02:00
edde746 6e83aeda88 fix(hubs): drop deleted items from recommended and home continue watching
The library Recommended tab never subscribed to deletion events, so
"Delete from server" left the episode sitting in Continue Watching
until a full reload. Make the tab DeletionAware (remove in place across
all hubs, then resync) and give DiscoverProvider the same subscription
so the home row and hubs drop deleted items too.

close #1486
2026-07-05 05:58:52 +02:00
edde746 7b1c150e18 feat(android): enable impeller on capable TV devices
Impeller was blanket-disabled on TV in e759dafa as a precaution when the
Tensor/NVIDIA fallbacks landed, and #749 (API 30 Fire TV Cube freezing
until the Skia build) validated it. Flutter has since deprecated the
Impeller opt-out, so start walking the disable back where the hardware
can take it: TV devices on Android 12+ with a Vulkan 1.1 driver use
Impeller, while Fire OS (modern API levels on GPUs whose drivers can't
back it up), pre-12 boxes, and the existing NVIDIA/Huawei/e-waste quirks
stay on Skia. Tag Sentry events with the active renderer so TV
regressions are attributable while this rolls out.
2026-07-05 02:28:51 +02:00
KakarottoCakeandedde746 cd8212fb53 perf(tv): cap image cache at 64MB on TV
TV boxes share limited RAM with 4K video decode buffers, so the 100MB
phone budget crowds out the decoder. Low-RAM TVs already on the reduced
tier keep the tighter 48MB cap.

From #1479.
2026-07-05 02:28:43 +02:00
edde746 11f7fd766d perf(library): cut scroll jank in card grids and hub rows
Profile traces showed 100-370ms UI-thread frames while scrolling the
library screen, dominated by rebuilding and inflating media cards.

- Gate per-card focus/pointer chrome on input mode: FocusableWrapper
  skips the scale/border wrappers and creates its AnimationController
  lazily outside keyboard mode, and ClickableCursor plus the card tap
  region only build MouseRegion/InkWell machinery on desktop - TV and
  touch use a bare GestureDetector. Hub cards also drop their outer
  gesture wrapper outside keyboard mode; the card's own tap region
  always won the gesture arena anyway.

- Memoize sliver children (SliverChildMemo): browse/collections grids
  and hub rows return identical widget instances for unchanged items,
  so delegate swaps from pagination, watch-state, and deletion
  setStates no longer rebuild every realized card inside layout. The
  browse tab prunes the memo in lockstep with focus-node eviction so a
  cached card can never resurrect a disposed FocusNode.

- Budget fresh inflation (CardInflationBudget): while a scrollable is
  moving in pointer/touch mode at most one new card inflates per frame,
  the rest render as SkeletonMediaCard and upgrade on following frames.
  Hub rows also stop pre-inflating 250px of off-screen cards on entry.

Device traces: worst frame 373ms -> 103ms, per-card build 3.6ms ->
2.4ms median; remaining row-entry work is spread across frames.
2026-07-05 02:23:42 +02:00
edde746 d80a1ed15a feat: report real device identity to media servers
Resolve platform, hardware model, and friendly device name once via a
shared DeviceIdentityService and send them to both backends: Plex gets
a real X-Plex-Platform plus X-Plex-Device/X-Plex-Device-Name (shown as
Player in dashboards/Tautulli), Jellyfin gets the device name in the
MediaBrowser auth header. Transcode and live-TV decision requests keep
their pinned platform names, which Plex validates server-side.

close #1270
2026-07-05 01:22:20 +02:00
edde746 f1422feff1 fix(detail): rework hero scrim into full-height eased dim 2026-07-05 00:35:36 +02:00
edde746 d7c0af9ad0 fix(player): fit the performance overlay on short screens
Anchor the overlay to the screen and seekbar clearance, widen the card
on height-limited screens so sections pack side by side, and scale down
as a last resort instead of clipping the bottom sections.

close #1469
2026-07-04 23:53:50 +02:00
edde746 87aea49ab6 fix(servers): stop rebinds from flashing an empty home screen after sign-in
Signing in triggered two back-to-back profile rebinds; the second re-added
the same Jellyfin connection, which tore down the live client and aborted
the home screen's in-flight fetches. The aborted pass was committed as
loaded-empty, flashing 'no content available' until the follow-up load
landed. Fix at the root instead of patching the sign-in window:

- addJellyfinConnection now reuses the live client when the connection is
  unchanged (token, deviceId, URL set), matching the existing Plex
  refreshTokensForProfile behavior; material changes still recreate it.
- Cancelled requests are classified end-to-end: the client's
  treat-as-empty helpers rethrow cancellations, and the aggregation
  fan-outs report cancelledServerIds alongside succeededServerIds.
- A fetch pass in which zero servers succeeded is never authoritative:
  it keeps existing content instead of wiping it (also fixes the
  pre-existing blanking of home/sidebar on a totally failed refresh),
  stays in loading while disrupted (cancellation or binding in flight),
  and only commits loaded-empty on a settled failure.
2026-07-04 23:44:38 +02:00
edde746 c8ca8a7875 fix(discover): restore hero indicators and bottom fade on non-TV
The hero dots/pause row was gated on live input mode, so any navigation
key event (Android back key, BT keyboards, gamepad-source noise) hid it
until the next pointer event - on phones it ended up permanently hidden.
Gate on the TV platform instead (issue #600's actual scope); the TV
layout never renders the carousel, so nothing changes there.

The bottom fade lost its guaranteed opaque band when the section-level
gradient was removed (686a61ac): the per-item overlay only reached full
background at the literal last pixel, letting artwork ghost through the
final 15% and read as a hard cut against the content below - worst on
phones, where square hero art is bright at the bottom. Finish the fade
at solid background from the 0.94 stop (~32px band on a phone hero).
2026-07-04 23:18:33 +02:00
edde746 d9b365b012 fix: failing tests 2026-07-04 23:09:41 +02:00
edde746 05e70ab56d chore: remove caddy 2026-07-04 23:09:41 +02:00
edde746 f9abcd44fe fix(playback): hold timeline preview until playback settles at the target
The preview cleared unconditionally 2s after a committed seek; on a device
still buffering, the live position hasn't caught up yet, so the next key
press re-based off the stale position and re-targeted the same spot -
discarding the seek exactly on the slow hardware the coalescing targets.
Re-arm the clear until the live position is near the target, with a 10s
ceiling backstop (same settle pattern as LiveSeekAccumulator).
2026-07-04 22:58:19 +02:00
edde746 3cad91736b fix(playback): raise timeline scrub debounce above the key-repeat delay
350ms sits below the typical KeyDown-to-first-repeat gap (~400-500ms on
Android/TV), so every hold committed an intermediate seek before repeats
even began. 800ms matches Jellyfin ATV (media3's DefaultTimeBar uses 1s);
key release still flushes synchronously, so taps are unaffected.
2026-07-04 22:57:27 +02:00
edde746 632d66f6ac fix(playback): clear timeline seek dedup state when a gesture finalizes
_lastDispatchedTimelineSeek was set by the drag throttle and never reset, so
with key-seeks now routed through onSeekEnd a coalesced flush targeting the
same position as a stale drag (realistic at the 0/duration clamp boundaries)
skipped the real seek while still reporting completion.
2026-07-04 22:57:00 +02:00
Christian Tismerandedde746 ed843b4b89 fix: coalesce held timeline seeks on direct play
A held fast-forward fired a real seek on every key-repeat for direct/
progressive streams, flooding the source with overlapping range requests and
wedging low-power devices (e.g. Fire TV Stick) in BUFFERING until the player
was restarted. Route direct play through the same preview/debounce path the
transcode case already uses: move only the timeline preview while the key is
held and commit a single seek on release or pause.

close #1424
2026-07-04 22:56:43 +02:00
edde746 27596bb919 fix(windows): enable WinHTTP IPv6 fast fallback
Dual-stack hostnames with unreachable IPv6 stalled past the endpoint
probe budget because WinHTTP tries addresses sequentially. Enable
WINHTTP_OPTION_IPV6_FAST_FALLBACK (Happy Eyeballs) via win_http 0.2.2
so IPv4 is raced after the IPv6 attempt, matching curl/Cronet/NSURLSession.

close #1128
2026-07-04 21:56:41 +02:00
edde746 6b7aac3372 fix(tv): handle remote play/pause at the screen focus level
When focus drifts to the player's screen-level Focus node (after an
overlay sheet closes with the controls hidden), a hardware play/pause
key only revealed the chrome and leaked to Android's MediaSession,
which pauses unreliably when its state is throttled or suspended.
Intercept media play/pause at the screen node on TV-style navigation:
toggle via the same playback-intent path as the Apple TV bridge and
consume the event.

close #1375
2026-07-04 21:33:45 +02:00
edde746 6af4289289 fix(tv): keep sidebar focused when Back returns to the home tab
Backing out to home selected the home tab but let focusActiveTabIfReady
steal real focus into the content while _isSidebarFocused stayed true,
leaving the rail stuck expanded over a shifted content box that clipped
the end of every hub row. Skip the content-focus grab while the sidebar
owns focus, move the sidebar focus ring to the Home item on back-to-home,
and self-heal the flag whenever the content scope actually gains focus.

close #1411
2026-07-04 20:56:04 +02:00
edde746 eb8796fa26 feat(library): indicate active filters in browse view
Badge the mobile Library options icon with a dot while filters are
active, and replace the "This library is empty" state with a
"No items match the active filters" message plus a reset button.

close #1470
2026-07-04 20:36:23 +02:00
edde746 8fe66f6e36 fix(android): keep the activity alive when a BT keyboard connects
close #1455
2026-07-04 19:54:19 +02:00
edde746 837fdf4031 fix(playback): canonicalize base URL scheme case
FFmpeg's protocol lookup is case-sensitive, so a stored "Https://" base
URL reaches mpv verbatim through the direct-play string concat and fails
with "Protocol not found" (API calls survive because Dart's Uri
lowercases the scheme). Canonicalize at Jellyfin URL intake and in the
connection constructor so persisted configs self-heal on load, and
register mpv-escaped (https\://) redaction variants so option-value
logs stop leaking the server host.

close #1465
2026-07-04 19:43:32 +02:00
edde746 dd09e421bf fix(android): force codec re-init on TV surface changes to recover video after screensaver
close #1481
2026-07-04 19:25:56 +02:00
edde746 50261398bf fix(android): serialize mpv writes to restore fallback ordering
close #1482
2026-07-04 19:15:34 +02:00
edde746 7632d4bea7 feat(jellyfin): favorites library filter + heart favorite in the rate sheet
close #1485
2026-07-04 18:33:58 +02:00
edde746 30de8be2cd fix(images): release artwork slots on non-200 responses 2026-07-04 17:31:52 +02:00
edde746 536e8e3d2a fix(playback): keep the Jellyfin shuffle queue across episodes
close #1466
2026-07-03 10:20:13 +02:00
edde746 3f9c25fe5e fix(ui): hide Play Version while the item's server is unreachable
At most one version of an item can be downloaded, and plain Play now
targets it directly, so an offline Play Version picker is a no-op
detour offering versions that cannot play (#1440). Backend
capabilities are static, so the menu gate and the quality picker in
_handlePlayVersion both get a liveness check — a server dropping
between menu open and tap must not offer transcodes either.
2026-07-03 10:19:55 +02:00
edde746 fd4291aafb fix(playback): play the downloaded version when offline close #1440
Plain Play requests the default media version (index 0 or the saved
preference), but the offline resolvers rejected the single downloaded
row when a non-default version was downloaded, then threw "No video
URL available" with no client to fall back to.

Three-part fix sharing one matcher (downloadedVersionMatches):
- getPlaybackData falls back to the downloaded version when there is no
  client to stream from; the result now carries the effective
  mediaIndex/mediaSourceId so cached media info and the committed
  session describe the file actually played.
- navigateToVideoPlayer seeds the selection from the download record
  for isOffline plays with no explicit version, covering the external
  player branch and offline-library plays with a reachable server.
- PlaybackSession.fromContext prefers the result source id over the
  requested one, keeping in-player state in sync after a fallback.

Online pinning is untouched: with a live client an explicitly requested
non-downloaded version still streams from the server.
2026-07-03 10:19:55 +02:00
edde746 8fa91fe444 chore(apple): pin MPVKit 1.0.8
AV1 perf: NEON dav1d (upstream prebuilt shipped C-only) + fused
software-frame upload in the avfoundation VO (patch 0009).
2026-07-03 08:51:19 +02:00
edde746 7972743a2f fix(windows): stop mpv from double-handling hardware media keys 2026-07-02 18:30:20 +02:00
edde746 6d95e35448 feat(tvos): AVPlayer Atmos sink wiring + Atmos output diagnostics
Re-enables Audio Passthrough on Apple TV against the MPVKit EAC3-JOC
AVPlayer sink (pin bump to v1.0.8 follows), adds an AVPlayer test
harness + diagnostics screen for #1300, and makes loudnorm yield while
passthrough is active (fixes a latent spdif conflict on desktop too).
2026-07-02 15:52:10 +02:00
edde746 86abf3e9da fix(watch-together): retry guest media switches until they commit
Guest switch dispatch pre-marked its dedup key and fired-and-forgot, so
any failure (fetch error, reload busy with an auto-advance, navigation
race with the host exiting) silently stranded the guest on the old media.
A CurrentPlaybackDispatcher now marks a key handled only after the sink
reports success against the committed identity, with a serialized
in-flight slot, timeout, and generation reset; the reconciler re-offers
unattached media on every host heartbeat, making the heartbeat the retry
channel. Fetches that outlive their dispatch are re-validated against the
current snapshot so a stale switch can't override the live one.
hostExitedPlayer now rides the controller's ordered message queue with
host authentication instead of racing state handling in the provider.
2026-07-02 12:44:15 +02:00
edde746 0e3c592205 fix(windows): marshal mpv events onto the platform thread
close #1453

Events were delivered to the Flutter event sink directly on the mpv event
thread while method replies were already marshaled; concurrent messenger
use from two threads intermittently crashed guests during the event burst
of an in-place media switch. Also joins the event thread before draining
platform tasks in the plugin destructor (reverse member destruction order
would otherwise let the event thread enqueue into a destroyed queue) and
coalesces the wakeup PostMessage behind a retry-safe flag.
2026-07-02 12:43:10 +02:00
edde746 5f49dddb4d feat(ui): M3E restyle for settings, auth, and profile screens 2026-07-02 11:47:43 +02:00
edde746 074f92d144 fix(tv): bleed the unfocused-rail dim under the side nav
The rail dim (and its top fade band) was clipped to the rail's footprint,
so it terminated in a vertical seam at the nav edge while the backdrop
continued behind the nav. Generalize _RailBackgroundBleed into
_RailBleedPositioned and render the dim through it, full-width like the
background gradient. Row stripes now apply only while the rail itself is
focused — under the full-width dim they'd re-introduce level seams at the
nav edge (and read as noise anyway).
2026-07-02 11:41:25 +02:00
edde746 6274facc3c fix(tv): fade dim-scrim edges instead of hard rect boundaries
Unlike the content opacity it replaced, the dim quad also darkens the
backdrop showing through around the rows, so its rectangle edge read as
a hard line across the spotlight artwork. Ramp the dim in over narrow
top/bottom gradient bands (flat quad interior, non-AA to avoid seams);
band area keeps the gradient-shader cost negligible on weak TV GPUs.
Browse pass on the Mali-G31 box unchanged: draw p50 7.2ms, 2% janky.
2026-07-02 11:41:25 +02:00
edde746 b08b3b846a perf(tv): rasterize axis-aligned gradients into strip textures
Skia's dithered gradient shaders cost ~10ms per full-screen pass on
Mali-class TV GPUs: the two spotlight scrims alone were ~20ms of a 27ms
raster frame, while flat blended quads at the same coverage are ~free.
Bake axis-aligned LinearGradients once into cached 1x1024 premultiplied
strip textures drawn as stretched quads (shader fallback for unsupported
shapes and the first frame). Converted the spotlight, TV detail backdrop,
app-bar scrims, rail bleed, person-card overlay, and the video-controls
scrim, which now also keeps one widget type across hasFrame flips so the
controls subtree survives in-place source switches.

Scripted-browse on a Mali-G31 box: draw p50 27.5ms -> 7.1ms, swap block
20.3ms -> 0.9ms, janky draws 69% -> 2%; screenshots pixel-identical.
2026-07-02 11:41:25 +02:00
edde746 1059658515 refactor(profiles): remove dead registry surface
Delete unused registry members (ProfileConnectionRegistry.insertIfAbsent /
removeAllForProfile, ProfileRegistry.reorder, ProfilesView.countFor,
ConnectionRegistry.getDefault) and their orphan tests, refreshing the stale
docs that named removeAllForProfile as the profile-delete cleanup path.

Repair the "one default per profile" join-row invariant: the connectionId FK
cascade (foreign_keys=ON) silently drops a profile's default row while its
other rows survive, leaving it defaultless. Add promoteMissingDefaults, share
a deterministic re-promotion helper with remove(), and re-promote in
removeAllForConnection.
2026-07-02 11:41:25 +02:00
edde746 d193633a5d fix(remote): live auth-context refresh + lifecycle races
Keep a running companion-remote host's crypto identity in sync with the
active profile: subscribe to PlexHome/connection/join streams and rebuild
auth contexts (restarting the broadcast when they change) so a removed
home user or revoked borrowed connection stops controlling the host.

Serialize host start/stop/crypto-rebuild through a lifecycle lock, clean
up peer subscriptions before re-listening, and guard the replaced-client
onDone against clobbering the new client's session. Drop the context.mounted
guards that aborted an app-level host start, fix the DiscoveryView
init-flash/stuck-on-throw, and delete the dead initialize*Crypto helpers.
2026-07-02 11:41:25 +02:00
edde746 2b7142bdcd fix(downloads): profile-scoped ownership and watch-sync integrity 2026-07-02 11:41:25 +02:00
edde746 44be03d39c refactor(profiles): shared auth/mint flows + screen fixes 2026-07-02 11:41:25 +02:00
edde746 f9123eb40f fix(profiles): binder settle, active-id, and rebind correctness 2026-07-02 11:41:25 +02:00
edde746 2025e1f9fd fix(profiles): clean up orphaned connections on Plex sign-out
close #1423
2026-07-02 11:41:25 +02:00
edde746 6e8320f782 fix(profiles): parse real Plex Home uuids + migrate pref scopes 2026-07-02 11:41:25 +02:00
edde746 bfcd11538e fix(security): redact Plex Home PIN from logs 2026-07-02 11:41:25 +02:00
edde746 72d37f2362 perf(tv): dim action bars once at row level while unfocused
In d-pad mode every unfocused FocusableActionBar button held its own
AnimatedOpacity(0.6) — 4-5 permanent saveLayers (one render pass each
on tiled TV GPUs) on discover and detail alike, every frame. While no
button in the row has focus (the entire time the user browses content)
the whole row now shares a single dim layer; per-button dims apply only
while the row holds focus.
2026-07-02 11:41:25 +02:00
edde746 e8a99c1108 fix(tv): harden spotlight crossfade broken-artwork path
The base image shared the incoming's fade-riding errorBuilder, so a
404'd backdrop flashed transparent on the next swap, could start the
fade before any frame existed, and an errored provider got promoted
into the base (re-resolve loop). Base now uses a static fallback,
error/frame state is tracked per incoming (keyed by provider), and
promotion settles on the fallback color when no frame ever arrived.
2026-07-02 11:41:25 +02:00
edde746 48568fd412 perf(tv): exclude inactive hub rows from semantics
Their cards can't take focus until the row activates (locked-hub
model), and the per-frame semantics pass scales with node count.
2026-07-02 11:41:25 +02:00
edde746 320bde7f33 perf(tv): spotlight backdrop cross-fades by paint alpha
The whole-stack AnimatedSwitcher kept two full-screen saveLayers (each
compositing backdrop + two full-screen gradients) blending on every
focus move — with CachedNetworkImage's own fade nested inside, the
dominant GPU load while browsing. Gradients are identical between items
so they never fade now; the incoming artwork fades in via Image.opacity
over the still-opaque previous one (no placeholder flash), and only the
bounded info block keeps a real cross-fade.
2026-07-02 11:41:25 +02:00
edde746 868a1469a3 perf: slim per-card build cost
Memoize the per-image SHA-1 disk-cache key (ran on the UI thread on
every image build), fade images in via paint alpha instead of an
AnimatedSwitcher saveLayer per in-flight tile, create SettingsBuilder's
merged listenable once instead of per build, and drop the pointer
chrome (InkWell ink machinery, cursor MouseRegions) from cards on TV
where no pointer exists.
2026-07-02 11:41:25 +02:00
edde746 43ab5d3246 perf: shrink semantics tree on media lists
Poster images are decorative (the card exposes one merged node), and
the default per-child AutomaticKeepAlive/_SelectionKeepAlive/
IndexedSemantics wrappers are inert here — no keep-alive clients or
SelectionArea exist. The semantics phase ran ~9ms every frame on TV
devices with an accessibility service; it scales with node count.
2026-07-02 11:41:25 +02:00
edde746 c38f24aee9 perf(tv): isolate rail rebuilds; dim rows via scrims, not opacity
Hub moves, focus flips and item selects now flow through the rail focus
model + ListenableSelectors (two headers/cards repaint instead of every
visible card rebuilding). DiscoverScreen memoizes the hubs list, gates
provider notifies on a render signature and caches the rail widget so
no-op refreshes skip the subtree entirely. The whole-rail 0.6 and
inactive-row 0.7 AnimatedOpacity layers are replaced by AnimatedDimScrim
quads, removing the permanent per-frame saveLayers that kept low-end TV
GPUs raster-bound.
2026-07-02 11:41:25 +02:00
edde746 a5041cb3db perf(tv): opaque detail route + isolate focused-episode updates
Covered routes stop painting/building once the fade settles, and d-pad
episode scrubbing rebuilds only the foreground info panel instead of
the whole screen with its rail.
2026-07-02 11:41:25 +02:00
edde746 7143bb380f fix(tv): skip desktop hover-arrows machinery on TV 2026-07-02 11:41:25 +02:00
edde746 d5df426ab6 build(libass): bump to 0.18.2 2026-07-02 11:41:24 +02:00
edde746 1d2dea214c ci(windows): set up arm64 Flutter 3.44.0 from git tag 2026-07-01 07:10:24 +02:00
edde746 e07f54921c ci(windows): install patched DComp engine for x64 and arm64 2026-07-01 06:37:51 +02:00
edde746 ba112d7aa6 refactor(windows): remove legacy mpv compositing, require DComp engine 2026-07-01 06:37:35 +02:00
edde746 28e6e349b3 fix(android): restore ExoPlayer audio for tunneled decoded PCM 2026-06-30 18:58:08 +02:00
edde746 2d30686857 fix: decouple library grouping from provider context 2026-06-30 06:57:21 +02:00
edde746 ea86ce5a4b fix(android): preserve bitmap subtitle aspect
close #1444
2026-06-30 02:31:18 +02:00
edde746 4cf94683ae fix: send correct streamID for same-language forced subtitles
close #1443
2026-06-29 07:10:25 +02:00
edde746 6c96830033 fix(android): never-drop multi-page subtitle atlas 2026-06-29 02:31:14 +02:00
edde746 ec1473af5e fix(android): tile oversized subtitle images so the atlas never drops them 2026-06-28 21:49:19 +02:00
github-actions[bot] 675886673e chore: update cask to 2.8.0 2026-06-28 08:07:38 +00:00
github-actions[bot] 19806d9b54 chore: bump version to 2.8.0 2026-06-28 07:44:28 +00:00
edde746 79b75483bd style: fix CI formatting 2026-06-27 10:36:21 +02:00
edde746 78090d8bd6 refactor(trackers): unify session and account store across services
Replace the per-tracker json_serializable session classes and account stores with a shared TrackerSession (service-aware persisted validation), a single TrackerAccountStore, a shared TrackerHttpClient, and an AnimeListTrackerBase mixin for MAL/AniList. Scope the per-service rebind guard so a disconnect can't abort a racing profile load. Add migration-safety, MAL refresh, episode-count cache, and content-type tests.
2026-06-27 10:05:03 +02:00
edde746 2fe0fdb975 fix: hide player queue spoilers
close #1426
2026-06-27 07:22:21 +02:00
edde746 930534ee31 fix: avoid duplicate timeline seek
close #1421
2026-06-27 07:05:06 +02:00
edde746 3b611a1e18 fix: avoid early playback completion 2026-06-27 06:46:32 +02:00
edde746 120749e442 fix(android): regenerate libass prebuilt archive 2026-06-27 06:43:37 +02:00
edde746 d333ac2382 fix(apple): pin MPVKit 1.0.6 2026-06-27 06:03:07 +02:00
edde746 c3ca6e4c49 fix: clear subtitle overlays when disabling subtitles
close #1387
2026-06-26 10:09:45 +02:00
edde746 ad6ed04901 style: abbreviate episode date on TV media detail
close #1380
2026-06-26 08:48:30 +02:00
edde746 25e5ea042f fix: server-qualify TvBrowseRail hub keys to avoid duplicate GlobalKey 2026-06-26 08:34:54 +02:00
edde746 4462b44e9b fix: show server name on TV hubs with multiple servers
close #1319
2026-06-26 07:57:21 +02:00
edde746 7df969cb90 style: compact episode rows, align thumbnails to page margin 2026-06-26 07:40:51 +02:00
edde746 719f317b5d feat: show genres on the media detail screen
close #1390
2026-06-26 07:16:39 +02:00
edde746 c32806d987 fix: show server name on all hubs with multiple servers
close #1319
2026-06-26 05:16:41 +02:00
edde746 86637012dc fix: show server name on all libraries with multiple servers
close #1319
2026-06-26 04:54:28 +02:00
edde746 bd7f37a3f6 test: align spoiler progress expectation 2026-06-26 01:30:06 +02:00
edde746 d5c575cbfe fix: keep download toggle label on one line 2026-06-26 01:19:38 +02:00
edde746 f29030c3a0 fix: correct jellyfin trickplay sheet geometry
close #1417
2026-06-26 00:26:26 +02:00
edde746 f04691d321 feat: add "Include Specials" toggle to the show download dialog
The aired-order rework can sweep correctly-placed Specials into "download
next N"; this toggle lets users opt out. Shown only for whole shows
(reusing FocusableSwitchListTile via an optional toggle on the shared
option-picker dialog), remembered across opens via a BoolPref
(default on = unchanged behavior). Filters Specials at the single
collect choke point (_collectPlayable), with a guard so explicitly
downloading the Specials season still queues its episodes.
2026-06-25 23:41:31 +02:00
edde746 dbe804f8db fix: order episodes by air date for offline, Jellyfin, and downloads
Extends the Plex play-queue fix (#1416) to the shared episode comparator
so Specials interleave by air date everywhere, not just Plex streaming:
offline next/prev, the Jellyfin online queue, offline OnDeck, and the
download/sync "next N" selection. Undated episodes fall back to
Specials-last, preserving the #1414 "never front-load the Specials
folder" guarantee. Jellyfin queue now requests PremiereDate.
2026-06-25 23:05:16 +02:00
edde746 37e4153602 fix(plex): interleave Specials in show play queue
close #1416
2026-06-25 19:45:58 +02:00
edde746 b0b14bcd18 fix: hide episode spoilers until marked watched
close #1397
2026-06-25 11:13:57 +02:00
Huzama AhmadandGitHub 7b917462c7 fix(plex): show PGS subtitles when transcoding (#1399)
* fix(plex): show PGS subtitles when transcoding

Bitmap subtitles (PGS/VOBSUB) disappeared from the menu while transcoding on Plex, leaving only "Off". The MKV transcode already supports them, so embed them in the stream like text subs. Now they show up and can be turned on.

* fix(plex): give bitmap subtitle codecs the right sidecar extension

getSubtitleExtension fell back to .srt for vobsub, pgssub and dvb subs. Map them to .sub/.sup so it stays consistent with isImageSubtitleCodec and any sidecar URL or download uses the correct extension.
2026-06-25 10:50:38 +02:00
edde746 791433bceb fix: download and queue episodes in watch order, Specials last
close #1414
2026-06-25 10:47:13 +02:00
edde746 e90835c234 fix(ci): restore sanity checks 2026-06-25 07:21:16 +02:00
edde746 8affbb7af6 fix(tvos): align embedded framework minimum os 2026-06-25 06:19:29 +02:00
edde746 21c4ab430e feat(android): tune frame rate and subtitle rendering 2026-06-24 01:34:03 +02:00
edde746 c9dc15b1d8 fix(android): improve libass frame timing 2026-06-24 01:26:46 +02:00
edde746 b4967ca075 fix: expose offline settings 2026-06-23 05:11:39 +02:00
edde746 cd1978ee1c fix: scope hidden libraries to profiles
close #1388
2026-06-23 00:21:01 +02:00
edde746 a5e422d284 fix(trackers): parse new Fribb imdb_id/themoviedb_id shapes
close #1402
2026-06-22 23:58:17 +02:00
edde746 5a1d378b42 fix(player): stop writing show-wide track defaults 2026-06-21 16:23:54 +02:00
Huzama AhmadandGitHub 19abd7831f fix(plex): report transcode session on the timeline (#1381)
Send the playback X-Plex-Session-Identifier on /:/timeline so the server reports Transcode instead of Direct Play.
2026-06-20 03:32:02 +02:00
edde746 0d78020fbf fix(images): reduce artwork decode pressure 2026-06-18 18:00:23 +02:00
edde746 7e1d5ad4c4 fix: add Jellyfin episode-added sort
close #1274
2026-06-18 16:22:01 +02:00
edde746 94f2daa22e feat: add episode action setting
close #1351
2026-06-18 11:16:38 +02:00
edde746 075e4aeb32 fix(player): restore OSD auto-hide
close #1360
2026-06-18 10:18:57 +02:00
edde746 52d70dd97d fix(libraries): add Plex TV date added sort
close #1369
2026-06-18 09:05:09 +02:00
edde746 d9b03160f0 fix(video-controls): activate skip marker on select when controls hidden
close #1374
2026-06-18 07:59:26 +02:00
edde746 b11c63f557 fix: restore sidebar focus visibility 2026-06-18 04:29:34 +02:00
edde746 a75cf5fd35 fix(player): dismiss prompts on back
close #1373
2026-06-18 03:25:30 +02:00
edde746 6f39a286d3 fix(profiles): remount profile session
close #1371
2026-06-18 00:53:48 +02:00
edde746 66b80a33ba fix(libraries): preserve Jellyfin alpha focus
close #1367
2026-06-17 20:55:26 +02:00
edde746 84b9eac09b fix(ci): restore sanity checks 2026-06-16 22:43:56 +02:00
edde746 39788ab64a fix(android): guard missing HDR capabilities 2026-06-16 22:00:19 +02:00
edde746 4cd289b4b8 fix(profiles): forget removed Jellyfin connections
close #1355
2026-06-16 20:08:47 +02:00
edde746 d49bd20fa0 fix(libraries): restore top-row focus escape
close #1354
2026-06-16 16:03:18 +02:00
edde746 618251b8eb fix(player): attach external subtitles during open 2026-06-15 17:21:08 +02:00
edde746 9437956b83 fix(livetv): keep timeline heartbeat on active endpoint 2026-06-15 14:59:06 +02:00
edde746 f602925896 fix(trakt): persist refreshed auth sessions
close #1347
2026-06-15 14:42:24 +02:00
edde746 1aecb9d2d2 fix(trakt): publish refreshed sessions 2026-06-15 14:42:18 +02:00
edde746 4a5731976a refactor(platform): centralize Apple TV detection 2026-06-15 13:32:54 +02:00
edde746 8198ea9522 fix(android): wire ExoPlayer passthrough control 2026-06-15 13:31:42 +02:00
edde746 e069d30555 fix(android): block direct audio without passthrough 2026-06-15 13:28:54 +02:00
edde746 1aa06ffe90 fix(tv): restore passthrough setting visibility 2026-06-15 13:28:38 +02:00
edde746 1b29cb3ef7 fix(player): apply stored passthrough setting 2026-06-15 13:28:23 +02:00
edde746 ba22dca9e5 fix(platform): gate audio passthrough support 2026-06-15 13:28:10 +02:00
edde746 b5a9f09f12 fix(player): wait for autoplay subtitle tracks
close #1348
2026-06-15 13:09:09 +02:00
edde746 8bf5dbb379 fix(player): resume mpv startup frame after subtitles 2026-06-15 12:06:04 +02:00
edde746 5fc599439e fix(player): wire playback streams before open 2026-06-15 12:05:48 +02:00
edde746 27723e6f29 fix(video): sync first-frame background state 2026-06-15 12:05:29 +02:00
edde746 a4c444435f fix(player): avoid overlapping performance stat fetches 2026-06-15 12:05:15 +02:00
edde746 6292685b5d fix(player): fetch Android mpv stats off main thread 2026-06-15 12:04:58 +02:00
edde746 7195702242 fix(player): repair Plex transcode seeking
close #1341
2026-06-14 23:39:05 +02:00
github-actions[bot] b459c5150c chore: update cask to 2.7.1 2026-06-14 16:57:48 +00:00
github-actions[bot] dba292cbfb chore: bump version to 2.7.1 2026-06-14 16:35:08 +00:00
edde746 01a5d11ef5 fix(jellyfin): use season episode endpoint 2026-06-14 18:34:12 +02:00
edde746 5e2bd4efa8 fix(video): release scrub chrome hold
close #1340
2026-06-14 18:34:12 +02:00
github-actions[bot] b23ba4c839 chore: update cask to 2.7.0 2026-06-14 13:49:45 +00:00
983 changed files with 88472 additions and 21820 deletions
+119 -225
View File
@@ -373,60 +373,26 @@ jobs:
macos-ed-signature.txt
macos-dmg-size.txt
build-windows-x64:
build-windows:
name: Build Windows (${{ matrix.arch }})
if: ${{ inputs.build_windows }}
runs-on: windows-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v4
- name: Setup Flutter
uses: subosito/flutter-action@v2
with:
channel: "stable"
flutter-version: "3.44.0"
cache: true
pub-cache: false
- name: Cache Pub dependencies
uses: actions/cache@v4
with:
path: |
~\AppData\Local\Pub\Cache
key: ${{ runner.os }}-${{ runner.arch }}-pub-v2-${{ hashFiles('pubspec.yaml', 'pubspec.lock') }}
- name: Cache Windows native dependencies
uses: actions/cache@v4
with:
path: build/windows/x64/_deps
key: windows-native-x64-${{ hashFiles('windows/CMakeLists.txt') }}
- name: Install dependencies
run: flutter pub get --enforce-lockfile --no-example
- name: Build Windows x64
run: flutter build windows --release --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} --dart-define=SENTRY_DIST=github-windows-x64 ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/windows-x64
- name: Upload symbols to bugs.plezy.app
if: github.repository == 'edde746/plezy'
shell: pwsh
env:
BUGS_ADMIN_TOKEN: ${{ secrets.BUGS_ADMIN_TOKEN }}
SENTRY_DIST: github-windows-x64
run: .\scripts\upload-symbols.ps1 windows-x64
- name: Upload x64 build
uses: actions/upload-artifact@v4
with:
name: windows-x64-build
path: build/windows/x64/runner/Release/
build-windows-arm64:
if: ${{ inputs.build_windows }}
runs-on: windows-11-arm
runs-on: ${{ matrix.runner }}
permissions:
contents: read
strategy:
fail-fast: false
matrix:
include:
- arch: x64
runner: windows-latest
flutter_setup: action
native_cache_path: build/windows/x64/_deps
- arch: arm64
runner: windows-11-arm
flutter_setup: git
native_cache_path: |
build/windows/arm64/_deps
build/windows/arm64/mpv-dev-arm64
steps:
- uses: actions/checkout@v4
@@ -434,23 +400,37 @@ jobs:
id: windows-native-cache
uses: actions/cache@v4
with:
path: |
build/windows/arm64/_deps
build/windows/arm64/mpv-dev-arm64
key: windows-native-arm64-${{ hashFiles('windows/CMakeLists.txt') }}
path: ${{ matrix.native_cache_path }}
key: windows-native-${{ matrix.arch }}-${{ hashFiles('windows/CMakeLists.txt') }}
- name: Install 7-Zip
if: steps.windows-native-cache.outputs.cache-hit != 'true'
if: matrix.arch == 'arm64' && steps.windows-native-cache.outputs.cache-hit != 'true'
shell: pwsh
run: choco install 7zip -y
- name: Setup Flutter
if: matrix.flutter_setup == 'action'
uses: subosito/flutter-action@v2
with:
channel: "master"
channel: "stable"
flutter-version: "3.44.0"
cache: true
pub-cache: false
- name: Set up Flutter 3.44.0 (git tag)
if: matrix.flutter_setup == 'git'
# Flutter publishes no windows-arm64 SDK archive, so subosito can't
# resolve 3.44.0 for arm64: the stable manifest has no arm64 entry, and
# `channel: master` would git-clone master HEAD (whose engine != our
# patched 3.44.0). Clone the 3.44.0 tag directly to get engine rev
# 4c525dac, which install-patched-engine.ps1 asserts before swapping.
shell: pwsh
run: |
$root = "$env:RUNNER_TEMP\flutter"
git clone --depth 1 --branch 3.44.0 https://github.com/flutter/flutter.git $root
"$root\bin" | Out-File -FilePath $env:GITHUB_PATH -Append -Encoding utf8
& "$root\bin\flutter.bat" --version
- name: Cache Pub dependencies
uses: actions/cache@v4
with:
@@ -459,27 +439,35 @@ jobs:
key: ${{ runner.os }}-${{ runner.arch }}-pub-v2-${{ hashFiles('pubspec.yaml', 'pubspec.lock') }}
- name: Install dependencies
run: flutter pub get --no-example
shell: pwsh
run: flutter pub get --enforce-lockfile --no-example
- name: Build Windows arm64
run: flutter build windows --release --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} --dart-define=SENTRY_DIST=github-windows-arm64 ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/windows-arm64
- name: Install patched Flutter engine (DComp)
shell: pwsh
run: |
flutter precache --windows
.\windows\tool\install-patched-engine.ps1
- name: Build Windows ${{ matrix.arch }}
shell: pwsh
run: flutter build windows --release --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} --dart-define=SENTRY_DIST=github-windows-${{ matrix.arch }} ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/windows-${{ matrix.arch }}
- name: Upload symbols to bugs.plezy.app
if: github.repository == 'edde746/plezy'
shell: pwsh
env:
BUGS_ADMIN_TOKEN: ${{ secrets.BUGS_ADMIN_TOKEN }}
SENTRY_DIST: github-windows-arm64
run: .\scripts\upload-symbols.ps1 windows-arm64
SENTRY_DIST: github-windows-${{ matrix.arch }}
run: .\scripts\upload-symbols.ps1 windows-${{ matrix.arch }}
- name: Upload arm64 build
- name: Upload ${{ matrix.arch }} build
uses: actions/upload-artifact@v4
with:
name: windows-arm64-build
path: build/windows/arm64/runner/Release/
name: windows-${{ matrix.arch }}-build
path: build/windows/${{ matrix.arch }}/runner/Release/
package-windows:
needs: [build-windows-x64, build-windows-arm64]
needs: build-windows
if: ${{ inputs.build_windows }}
runs-on: windows-latest
permissions:
@@ -562,20 +550,33 @@ jobs:
win-ed-signature.txt
win-installer-size.txt
build-linux-x64:
build-linux:
name: Build Linux (${{ matrix.arch }})
if: ${{ inputs.build_linux }}
runs-on: ubuntu-latest
runs-on: ${{ matrix.runner }}
permissions:
id-token: write
attestations: write
contents: read
strategy:
fail-fast: false
matrix:
include:
- arch: x64
runner: ubuntu-latest
flutter_channel: stable
pkg_config_arch: x86_64-linux-gnu
- arch: arm64
runner: ubuntu-24.04-arm
flutter_channel: master
pkg_config_arch: aarch64-linux-gnu
steps:
- uses: actions/checkout@v4
- name: Setup Flutter
uses: subosito/flutter-action@v2
with:
channel: "stable"
channel: ${{ matrix.flutter_channel }}
flutter-version: "3.44.0"
cache: true
pub-cache: false
@@ -594,6 +595,7 @@ jobs:
version: 1.1
- name: Install Linux dependencies
shell: bash
run: |
read -r -a packages <<< "$LINUX_APT_PACKAGES"
@@ -618,182 +620,73 @@ jobs:
- name: Build libmpv
if: steps.libmpv-cache.outputs.cache-hit != 'true'
shell: bash
run: bash linux/packaging/build-libmpv.sh
- name: Install fpm
shell: bash
run: sudo gem install fpm
- name: Install dependencies
shell: bash
run: flutter pub get --enforce-lockfile --no-example
- name: Build Linux x64
run: flutter build linux --release --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} --dart-define=SENTRY_DIST=github-linux-x64 ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/linux-x64
- name: Build Linux ${{ matrix.arch }}
shell: bash
run: flutter build linux --release --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} --dart-define=SENTRY_DIST=github-linux-${{ matrix.arch }} ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/linux-${{ matrix.arch }}
env:
PKG_CONFIG_PATH: ${{ github.workspace }}/libmpv-prefix/lib/pkgconfig:${{ github.workspace }}/libmpv-prefix/lib/x86_64-linux-gnu/pkgconfig
PKG_CONFIG_PATH: ${{ github.workspace }}/libmpv-prefix/lib/pkgconfig:${{ github.workspace }}/libmpv-prefix/lib/${{ matrix.pkg_config_arch }}/pkgconfig
- name: Upload symbols to bugs.plezy.app
if: github.repository == 'edde746/plezy'
shell: bash
env:
BUGS_ADMIN_TOKEN: ${{ secrets.BUGS_ADMIN_TOKEN }}
SENTRY_DIST: github-linux-x64
run: ./scripts/upload-symbols.sh linux-x64
SENTRY_DIST: github-linux-${{ matrix.arch }}
run: ./scripts/upload-symbols.sh linux-${{ matrix.arch }}
- name: Build Linux Packages
run: ARCH_SUFFIX=x64 OUTPUT_DIR=$GITHUB_WORKSPACE python3 linux/packaging/build-packages.py
- name: Copy libmpv into bundle
- name: Resolve bundle directory
shell: bash
run: |
BUNDLE_LIB=build/linux/x64/release/bundle/lib
LIBMPV_DIR=$(dirname "$(find libmpv-prefix -name 'libmpv.so' | head -1)")
cp -a "$LIBMPV_DIR"/libmpv.so* "$BUNDLE_LIB/"
cp -a libmpv-prefix/lib/libshaderc_shared.so* "$BUNDLE_LIB/"
- name: Bundle shared libraries for portable tarball
run: bash linux/packaging/bundle-libs.sh build/linux/x64/release/bundle
- name: Copy wrapper script into bundle
run: cp linux/packaging/plezy.sh build/linux/x64/release/bundle/plezy.sh
- name: Verify no missing dependencies
run: |
cd build/linux/x64/release/bundle
MISSING=$(LD_LIBRARY_PATH=lib ldd ./plezy 2>&1 | grep "not found" || true)
if [[ -n "$MISSING" ]]; then
echo "ERROR: Unresolved dependencies found:" >&2
echo "$MISSING" >&2
if [[ "${{ matrix.arch }}" == "x64" ]]; then
bundle_dir=build/linux/x64/release/bundle
else
bundle_dir=$(find build/linux -path "*/release/bundle" -type d | head -1)
fi
if [[ -z "$bundle_dir" || ! -d "$bundle_dir" ]]; then
echo "ERROR: Linux bundle directory not found" >&2
exit 1
fi
echo "All dependencies resolved."
- name: Create tarball
run: |
cd build/linux/x64/release/bundle
tar -czf $GITHUB_WORKSPACE/plezy-linux-x64.tar.gz *
- name: Attest Linux x64 artifacts
uses: actions/attest-build-provenance@v2
with:
subject-path: |
plezy-linux-x64.tar.gz
plezy-linux-x64.deb
plezy-linux-x64.rpm
plezy-linux-x64.pkg.tar.zst
- name: Upload Linux x64 artifacts
uses: actions/upload-artifact@v4
with:
name: linux-x64
path: |
plezy-linux-x64.tar.gz
plezy-linux-x64.deb
plezy-linux-x64.rpm
plezy-linux-x64.pkg.tar.zst
build-linux-arm64:
if: ${{ inputs.build_linux }}
runs-on: ubuntu-24.04-arm
permissions:
id-token: write
attestations: write
contents: read
steps:
- uses: actions/checkout@v4
- name: Setup Flutter
uses: subosito/flutter-action@v2
with:
channel: "master"
flutter-version: "3.44.0"
cache: true
pub-cache: false
- name: Cache Pub dependencies
uses: actions/cache@v4
with:
path: |
~/.pub-cache
key: ${{ runner.os }}-${{ runner.arch }}-pub-v2-${{ hashFiles('pubspec.yaml', 'pubspec.lock') }}
- name: Cache APT packages
uses: awalsh128/cache-apt-pkgs-action@latest
with:
packages: ${{ env.LINUX_APT_PACKAGES }}
version: 1.1
- name: Install Linux dependencies
run: |
read -r -a packages <<< "$LINUX_APT_PACKAGES"
for attempt in 1 2 3; do
if sudo apt-get update -o Acquire::Retries=3 && sudo apt-get install -y -o Acquire::Retries=3 "${packages[@]}"; then
exit 0
fi
sudo apt-get clean
sudo rm -rf /var/lib/apt/lists/*
sleep $((attempt * 15))
done
exit 1
- name: Cache libmpv build
id: libmpv-cache
uses: actions/cache@v4
with:
path: libmpv-prefix
key: libmpv-${{ runner.arch }}-${{ hashFiles('linux/packaging/build-libmpv.sh') }}
- name: Build libmpv
if: steps.libmpv-cache.outputs.cache-hit != 'true'
run: bash linux/packaging/build-libmpv.sh
- name: Install fpm
run: sudo gem install fpm
- name: Install dependencies
run: flutter pub get --no-example
- name: Build Linux arm64
run: flutter build linux --release --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }} ${{ env.SENTRY_ENV_DART_DEFINE }} --dart-define=SENTRY_DIST=github-linux-arm64 ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/linux-arm64
env:
PKG_CONFIG_PATH: ${{ github.workspace }}/libmpv-prefix/lib/pkgconfig:${{ github.workspace }}/libmpv-prefix/lib/aarch64-linux-gnu/pkgconfig
- name: Upload symbols to bugs.plezy.app
if: github.repository == 'edde746/plezy'
env:
BUGS_ADMIN_TOKEN: ${{ secrets.BUGS_ADMIN_TOKEN }}
SENTRY_DIST: github-linux-arm64
run: ./scripts/upload-symbols.sh linux-arm64
- name: Find bundle directory
id: find-bundle
run: |
BUNDLE_DIR=$(find build/linux -path "*/release/bundle" -type d | head -1)
echo "bundle_dir=$BUNDLE_DIR" >> $GITHUB_OUTPUT
echo "BUNDLE_DIR=$bundle_dir" >> "$GITHUB_ENV"
- name: Build Linux Packages
shell: bash
run: |
BUILD_DIR=${{ steps.find-bundle.outputs.bundle_dir }} \
ARCH_SUFFIX=arm64 \
OUTPUT_DIR=$GITHUB_WORKSPACE \
BUILD_DIR="$BUNDLE_DIR" \
ARCH_SUFFIX=${{ matrix.arch }} \
OUTPUT_DIR="$GITHUB_WORKSPACE" \
python3 linux/packaging/build-packages.py
- name: Copy libmpv into bundle
shell: bash
run: |
BUNDLE_LIB=${{ steps.find-bundle.outputs.bundle_dir }}/lib
BUNDLE_LIB="$BUNDLE_DIR/lib"
LIBMPV_DIR=$(dirname "$(find libmpv-prefix -name 'libmpv.so' | head -1)")
cp -a "$LIBMPV_DIR"/libmpv.so* "$BUNDLE_LIB/"
cp -a libmpv-prefix/lib/libshaderc_shared.so* "$BUNDLE_LIB/"
- name: Bundle shared libraries for portable tarball
run: bash linux/packaging/bundle-libs.sh ${{ steps.find-bundle.outputs.bundle_dir }}
shell: bash
run: bash linux/packaging/bundle-libs.sh "$BUNDLE_DIR"
- name: Copy wrapper script into bundle
run: cp linux/packaging/plezy.sh ${{ steps.find-bundle.outputs.bundle_dir }}/plezy.sh
shell: bash
run: cp linux/packaging/plezy.sh "$BUNDLE_DIR/plezy.sh"
- name: Verify no missing dependencies
shell: bash
run: |
cd ${{ steps.find-bundle.outputs.bundle_dir }}
cd "$BUNDLE_DIR"
MISSING=$(LD_LIBRARY_PATH=lib ldd ./plezy 2>&1 | grep "not found" || true)
if [[ -n "$MISSING" ]]; then
echo "ERROR: Unresolved dependencies found:" >&2
@@ -803,31 +696,32 @@ jobs:
echo "All dependencies resolved."
- name: Create tarball
shell: bash
run: |
cd ${{ steps.find-bundle.outputs.bundle_dir }}
tar -czf $GITHUB_WORKSPACE/plezy-linux-arm64.tar.gz *
cd "$BUNDLE_DIR"
tar -czf "$GITHUB_WORKSPACE/plezy-linux-${{ matrix.arch }}.tar.gz" *
- name: Attest Linux arm64 artifacts
- name: Attest Linux ${{ matrix.arch }} artifacts
uses: actions/attest-build-provenance@v2
with:
subject-path: |
plezy-linux-arm64.tar.gz
plezy-linux-arm64.deb
plezy-linux-arm64.rpm
plezy-linux-arm64.pkg.tar.zst
plezy-linux-${{ matrix.arch }}.tar.gz
plezy-linux-${{ matrix.arch }}.deb
plezy-linux-${{ matrix.arch }}.rpm
plezy-linux-${{ matrix.arch }}.pkg.tar.zst
- name: Upload Linux arm64 artifacts
- name: Upload Linux ${{ matrix.arch }} artifacts
uses: actions/upload-artifact@v4
with:
name: linux-arm64
name: linux-${{ matrix.arch }}
path: |
plezy-linux-arm64.tar.gz
plezy-linux-arm64.deb
plezy-linux-arm64.rpm
plezy-linux-arm64.pkg.tar.zst
plezy-linux-${{ matrix.arch }}.tar.gz
plezy-linux-${{ matrix.arch }}.deb
plezy-linux-${{ matrix.arch }}.rpm
plezy-linux-${{ matrix.arch }}.pkg.tar.zst
create-release:
needs: [build-android, build-ios, build-macos, build-windows-x64, build-windows-arm64, package-windows, build-linux-x64, build-linux-arm64]
needs: [build-android, build-ios, build-macos, build-windows, package-windows, build-linux]
if: ${{ always() && !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && (inputs.build_android || inputs.build_ios || inputs.build_macos || inputs.build_windows || inputs.build_linux) }}
runs-on: ubuntu-latest
permissions:
@@ -1005,7 +899,7 @@ jobs:
} >> "$GITHUB_OUTPUT"
- name: Create Release
uses: softprops/action-gh-release@v1
uses: softprops/action-gh-release@v2
with:
files: ${{ steps.release-files.outputs.files }}
draft: true
+69 -32
View File
@@ -39,44 +39,31 @@ jobs:
flutter pub get
- name: Install saf_util development dependencies
working-directory: packages/saf_util
run: flutter pub get
- name: Verify generated files committed
run: scripts/codegen.sh --check
- name: Verify translation hygiene
run: python3 scripts/clean_translations.py --check --strict
- name: Verify workflow and script guards
run: |
scripts/codegen.sh
if ! git diff --exit-code lib/; then
echo "::error::Generated files (.g.dart / .freezed.dart) are out of date."
echo "Run 'scripts/codegen.sh' and commit the result."
exit 1
fi
python3 scripts/check_build_workflow.py
python3 scripts/check_update_packages_workflow.py
python3 scripts/test_pubspec_version.py
python3 scripts/test_clean_translations.py
- name: Verify formatting
run: |
# Find all Dart files excluding generated files
find lib $([ -d test ] && echo test) -name "*.dart" ! -name "*.g.dart" ! -name "*.freezed.dart" -type f 2>/dev/null | while IFS= read -r file; do
files_found=true
break
done
if [ "$files_found" != "true" ]; then
echo "No Dart files found to format"
exit 0
fi
find lib $([ -d test ] && echo test) -name "*.dart" ! -name "*.g.dart" ! -name "*.freezed.dart" -type f 2>/dev/null -print0 | xargs -0 dart format --output=none --set-exit-if-changed
paths=(lib)
[ ! -d test ] || paths+=(test)
find "${paths[@]}" -name "*.dart" ! -name "*.g.dart" ! -name "*.freezed.dart" -type f -print0 |
xargs -0 -r dart format --output=none --set-exit-if-changed
- name: Analyze code
run: |
# Run flutter analyze
# Fails on errors or warnings only (info messages are allowed)
flutter analyze 2>&1 | tee analyze_output.txt || true
# Check output for errors or warnings
if grep -q "error •" analyze_output.txt; then
echo "❌ Analysis failed with errors"
exit 1
elif grep -q "warning •" analyze_output.txt; then
echo "⚠️ Analysis completed with warnings"
exit 1
else
echo "✅ Analysis passed!"
exit 0
fi
run: dart run scripts/check_analyzer.dart
- name: Check for unused code
run: |
@@ -139,6 +126,56 @@ jobs:
echo "No tests found, skipping test execution"
fi
android-test:
name: Android JVM Unit Tests
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Java
uses: actions/setup-java@v4
with:
distribution: "temurin"
java-version: "17"
- name: Setup Flutter
uses: subosito/flutter-action@v2
with:
channel: "stable"
flutter-version: "3.44.0"
cache: true
pub-cache: false
- name: Cache Pub dependencies
uses: actions/cache@v4
with:
path: |
~/.pub-cache
key: ${{ runner.os }}-pub-v3-${{ hashFiles('**/pubspec.yaml', '**/pubspec.lock') }}
- name: Cache Gradle
uses: actions/cache@v4
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
restore-keys: |
${{ runner.os }}-gradle-
- name: Install dependencies
run: flutter pub get
- name: Configure Android local properties
run: printf 'flutter.sdk=%s\nsdk.dir=%s\n' "$FLUTTER_ROOT" "$ANDROID_HOME" > android/local.properties
- name: Run Android JVM unit tests
working-directory: android
run: ./gradlew :app:testDebugUnitTest :saf_util:testDebugUnitTest :libass:testDebugUnitTest -x :app:compileFlutterBuildDebug --continue
native-format:
name: Native Formatting
runs-on: ubuntu-latest
+3 -5
View File
@@ -32,10 +32,8 @@ jobs:
- name: Extract current build number
id: get_build
run: |
# Extract current build number from pubspec.yaml
CURRENT_VERSION=$(grep '^version:' pubspec.yaml | sed 's/version: //')
CURRENT_BUILD=$(echo "$CURRENT_VERSION" | cut -d'+' -f2)
NEW_BUILD=$((CURRENT_BUILD + 1))
CURRENT_BUILD=$(python3 scripts/pubspec_version.py --build-number pubspec.yaml)
NEW_BUILD=$((10#$CURRENT_BUILD + 1))
echo "current_build=$CURRENT_BUILD" >> $GITHUB_OUTPUT
echo "new_build=$NEW_BUILD" >> $GITHUB_OUTPUT
@@ -71,7 +69,7 @@ jobs:
- name: Trigger build workflow
run: |
curl -L \
curl --fail-with-body -L \
-X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" \
+61 -10
View File
@@ -4,12 +4,61 @@ on:
release:
types: [published]
workflow_dispatch:
inputs:
release_tag:
description: Published release tag to update packages for
required: true
type: string
jobs:
resolve-release:
runs-on: ubuntu-latest
permissions:
contents: read
outputs:
tag: ${{ steps.release.outputs.tag }}
steps:
- name: Resolve published release tag
id: release
env:
EVENT_TAG: ${{ github.event.release.tag_name }}
INPUT_TAG: ${{ inputs.release_tag }}
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
if [ "$GITHUB_EVENT_NAME" = "release" ]; then
REQUESTED_TAG="$EVENT_TAG"
else
REQUESTED_TAG="$INPUT_TAG"
fi
if [ -z "$REQUESTED_TAG" ]; then
echo "A release tag is required." >&2
exit 1
fi
RELEASE=$(gh release view "$REQUESTED_TAG" --repo "$GITHUB_REPOSITORY" \
--json tagName,isDraft,publishedAt)
RESOLVED_TAG=$(jq -r '.tagName' <<< "$RELEASE")
IS_DRAFT=$(jq -r '.isDraft' <<< "$RELEASE")
PUBLISHED_AT=$(jq -r '.publishedAt // empty' <<< "$RELEASE")
if [ "$RESOLVED_TAG" != "$REQUESTED_TAG" ] || \
[ "$IS_DRAFT" != "false" ] || [ -z "$PUBLISHED_AT" ]; then
echo "Tag '$REQUESTED_TAG' is not an exact published release tag." >&2
exit 1
fi
echo "tag=$RESOLVED_TAG" >> "$GITHUB_OUTPUT"
update-homebrew:
needs: resolve-release
runs-on: macos-latest
permissions:
contents: write
env:
RELEASE_TAG: ${{ needs.resolve-release.outputs.tag }}
steps:
- uses: actions/checkout@v4
with:
@@ -19,16 +68,14 @@ jobs:
- name: Download and hash release
id: release
run: |
VERSION="${{ github.event.release.tag_name || github.ref_name }}"
curl -L -o plezy-macos.dmg \
"https://github.com/edde746/plezy/releases/download/$VERSION/plezy-macos.dmg"
curl --fail-with-body -L -o plezy-macos.dmg \
"https://github.com/edde746/plezy/releases/download/$RELEASE_TAG/plezy-macos.dmg"
SHA256=$(shasum -a 256 plezy-macos.dmg | cut -d' ' -f1)
echo "version=$VERSION" >> $GITHUB_OUTPUT
echo "sha256=$SHA256" >> $GITHUB_OUTPUT
echo "sha256=$SHA256" >> "$GITHUB_OUTPUT"
- name: Update cask
run: |
sed -i '' "s/version \".*\"/version \"${{ steps.release.outputs.version }}\"/" Casks/plezy.rb
sed -i '' "s/version \".*\"/version \"$RELEASE_TAG\"/" Casks/plezy.rb
sed -i '' "s/sha256 \".*\"/sha256 \"${{ steps.release.outputs.sha256 }}\"/" Casks/plezy.rb
- name: Commit
@@ -38,41 +85,45 @@ jobs:
git config user.email "github-actions[bot]@users.noreply.github.com"
git add Casks/plezy.rb
if ! git diff --staged --quiet; then
git commit -m "chore: update cask to ${{ steps.release.outputs.version }}"
git commit -m "chore: update cask to $RELEASE_TAG"
git push origin "HEAD:$BRANCH"
else
echo "No cask changes to commit."
fi
update-winget:
needs: resolve-release
runs-on: windows-latest
steps:
- uses: vedantmgoyal9/winget-releaser@v2
with:
identifier: edde746.Plezy
installers-regex: 'plezy-windows-installer\.exe$'
release-tag: ${{ needs.resolve-release.outputs.tag }}
token: ${{ secrets.WINGET_TOKEN }}
update-appcast-branch:
needs: resolve-release
runs-on: ubuntu-latest
permissions:
contents: write
env:
RELEASE_TAG: ${{ needs.resolve-release.outputs.tag }}
steps:
- uses: actions/checkout@v4
- name: Download appcast.xml from release
run: |
gh release download "${{ github.event.release.tag_name }}" \
gh release download "$RELEASE_TAG" \
--pattern "appcast.xml"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Push to appcast branch
run: |
VERSION="${{ github.event.release.tag_name }}"
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
BLOB=$(git hash-object -w appcast.xml)
TREE=$(printf "100644 blob %s\tappcast.xml\n" "$BLOB" | git mktree)
COMMIT=$(git commit-tree "$TREE" -m "Update appcast for $VERSION")
COMMIT=$(git commit-tree "$TREE" -m "Update appcast for $RELEASE_TAG")
git push origin "$COMMIT:refs/heads/appcast" --force
+2 -1
View File
@@ -70,4 +70,5 @@ duplication-report/
**/fastlane/report.xml
maestro/**/*.png
server/deploy.sh
server/deploy.sh
server/Caddyfile
+5 -2
View File
@@ -4,7 +4,7 @@
1. Fork and clone the repository
2. Run `flutter pub get` to install dependencies
3. Run `dart run build_runner build` to generate code
3. Run `scripts/codegen.sh` to generate translations and Dart model code
4. Start developing!
## Development
@@ -30,7 +30,10 @@ The project includes automated CI checks that run on all pull requests:
- Run locally: `flutter analyze`
- Note: CI excludes generated files from analysis (configured in `analysis_options.yaml`)
3. **Tests**: Runs unit and widget tests (when available)
3. **Generated Code**: Ensures generated translations and model files are current
- Run locally: `scripts/codegen.sh --check`
4. **Tests**: Runs unit and widget tests (when available)
- Run locally: `flutter test`
All these checks must pass before your changes can be merged.
+2 -2
View File
@@ -1,6 +1,6 @@
cask "plezy" do
version "2.6.0"
sha256 "e408fe84c07e0ff4a2f1a78e8dcfc418233c66ca98c79028a7b099499307a59e"
version "2.8.0"
sha256 "78df0227fc9a578c259fa7cdda526a2679fe46f5be6620f7a020e18d08f206f5"
url "https://github.com/edde746/plezy/releases/download/#{version}/plezy-macos.dmg"
name "Plezy"
+5 -6
View File
@@ -87,15 +87,15 @@ Package managers:
- Real-time play / pause / seek sync
### <img src="assets/readme_icons/integrations.svg" height="20" alt="" align="center" /> Integrations
- Discord Rich Presence[^7]
- Discord Rich Presence[^6]
- Trakt, MyAnimeList, AniList, and Simkl tracking & rating
- Plezy Remote — control desktop and TV from mobile
- Watch Next row[^6]
- Watch Next row
### <img src="assets/readme_icons/customization.svg" height="20" alt="" align="center" /> Platform & Customization
- Desktop, mobile, and TV — full D-pad, keyboard, and gamepad support
- Customizable keyboard shortcuts[^7]
- Metadata and artwork editing[^2]
- Customizable keyboard shortcuts[^6]
- Metadata and artwork editing
- Settings import/export
- Localized in English plus 14 translations
@@ -104,8 +104,7 @@ Package managers:
[^3]: Not available on iOS or tvOS.
[^4]: Android, iOS, and macOS.
[^5]: Windows, Android, and tvOS.
[^6]: Android TV only.
[^7]: Desktop only.
[^6]: Desktop only.
## Building from Source
+5
View File
@@ -18,6 +18,11 @@ linter:
avoid_print: true
dart_code_linter:
rules-exclude:
- "test/**"
metrics-exclude:
- "test/**"
extends:
- package:dart_code_linter/presets/recommended.yaml
-3
View File
@@ -1,8 +1,5 @@
gradle-wrapper.jar
/.gradle
/captures/
/gradlew
/gradlew.bat
/local.properties
GeneratedPluginRegistrant.java
.cxx/
+12 -24
View File
@@ -152,26 +152,17 @@ android {
packaging {
jniLibs {
// Three copies of libc++_shared.so reach the merge: the libmpv AAR's
// (NDK r29 — exports std::from_chars<float> that libmpv.so needs), the
// :libass module's CMake-contributed copy (NDK 28.2 — lacks it), and
// peerless2012:ass's bundled copy (also old). pickFirst keeps the merge
// from erroring on the duplicates; WHICH copy wins is pinned by the
// sourceSets block below: extractMpvLibcxx unpacks the libmpv AAR's copy
// into an app jniLibs dir, and PROJECT-scope sources beat sub-projects
// and external AARs. libc++ is backward ABI-compatible, so the older-NDK
// consumers (libass.so, libasskt.so, ffmpeg decoder, cronet) run fine
// against the newer copy.
// pickFirst only suppresses the duplicate libc++ merge error; the
// sourceSets rule below makes libmpv's newer runtime win for
// std::from_chars<float>, while older native consumers remain ABI-compatible.
pickFirsts.add("lib/*/libc++_shared.so")
}
}
sourceSets {
getByName("main") {
// libc++_shared.so extracted from the libmpv AAR by extractMpvLibcxx.
// App source-set jniLibs sit in the PROJECT scope, merged ahead of
// subprojects (:libass) and external AARs, so with the pickFirst rule
// above this copy deterministically wins regardless of dependency order.
// PROJECT-scope jniLibs merge ahead of subprojects/AARs, so dependency
// order cannot accidentally select the older libc++ copy.
jniLibs.srcDir(File(mpvDir, "libcxx/jni"))
}
}
@@ -181,17 +172,15 @@ flutter {
source = "../.."
}
// Download libdovi before any CMake/native build task
tasks.matching { it.name.contains("CMake") || it.name.contains("externalNative") }.configureEach {
dependsOn(downloadLibdovi)
}
// Download the libmpv AAR before compilation
tasks.matching { it.name.startsWith("pre") && it.name.endsWith("Build") }.configureEach {
dependsOn(downloadLibmpv, extractMpvLibcxx)
}
// merge{Debug,Profile,Release}JniLibFolders snapshot jniLibs source dirs as inputs;
// Gradle 8 requires an explicit dependency on the producing task.
// Gradle snapshots jniLibs source dirs before task execution; this keeps the
// extracted libmpv libc++ directory present during input discovery.
tasks.matching { it.name.startsWith("merge") && it.name.endsWith("JniLibFolders") }.configureEach {
dependsOn(extractMpvLibcxx)
}
@@ -216,13 +205,12 @@ dependencies {
// FFmpeg audio decoder for unsupported codecs (ALAC, DTS, TrueHD, etc.)
implementation("org.jellyfin.media3:media3-ffmpeg-decoder:1.9.0+1")
// libass ASS/SSA subtitle rendering: optimized native core (libass.so +
// prefab headers) from the edde746/libass-android fork's releases; Kotlin/JNI
// bindings + Media3 glue live in the android/libass module. -PlocalAssCore
// swaps in a mavenLocal()-published core (0.4.0-local) for native A/B tests.
val assCoreVersion = if (project.hasProperty("localAssCore")) "0.4.0-local" else "0.4.1-plezy.1"
implementation("io.github.peerless2012:ass:$assCoreVersion@aar")
// Keeping libass in-project lets its static core share the app's native
// packaging rules.
implementation(project(":libass"))
testImplementation("junit:junit:4.13.2")
// Real android.util.* implementations for tests exercising media3 classes
// (MatroskaExtractor uses SparseArray, which is a no-op stub on plain JVM)
testImplementation("org.robolectric:robolectric:4.15.1")
}
+1 -1
View File
@@ -49,7 +49,7 @@
android:taskAffinity=""
android:theme="@style/LaunchTheme"
android:supportsPictureInPicture="true"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
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
@@ -0,0 +1,46 @@
package com.edde746.plezy
import android.graphics.SurfaceTexture
import android.os.Handler
import android.os.Looper
import android.view.TextureView
internal class DeferredSurfaceTextureListener(
private val delegate: TextureView.SurfaceTextureListener,
private val handler: Handler = Handler(Looper.getMainLooper()),
private val onSurfaceAvailable: () -> Unit = {},
private val isCurrentSurface: (SurfaceTexture) -> Boolean
) : TextureView.SurfaceTextureListener {
private var pendingResize: Runnable? = null
override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {
delegate.onSurfaceTextureAvailable(surface, width, height)
onSurfaceAvailable()
}
override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {
pendingResize?.let(handler::removeCallbacks)
pendingResize = Runnable {
pendingResize = null
if (isCurrentSurface(surface)) {
delegate.onSurfaceTextureSizeChanged(surface, width, height)
}
}
handler.postDelayed(pendingResize!!, RESIZE_DELAY_MILLIS)
}
override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {
delegate.onSurfaceTextureUpdated(surface)
}
override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
pendingResize?.let(handler::removeCallbacks)
pendingResize = null
return delegate.onSurfaceTextureDestroyed(surface)
}
private companion object {
const val RESIZE_DELAY_MILLIS = 100L
}
}
@@ -0,0 +1,194 @@
package com.edde746.plezy
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.core.content.FileProvider
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import java.io.File
internal class ExternalPlayerChannel(private val activity: Activity) {
companion object {
private const val CHANNEL = "com.plezy/external_player"
const val REQUEST_CODE = 7461
private const val API_MX_RETURN_RESULT = "return_result"
private const val API_MX_RESULT_ID = "com.mxtech.intent.result.VIEW"
private const val API_MX_RESULT_POSITION = "position"
private const val API_MX_RESULT_DURATION = "duration"
private const val API_MX_RESULT_END_BY = "end_by"
private const val API_MX_RESULT_END_BY_PLAYBACK_COMPLETION = "playback_completion"
private const val API_MX_TITLE = "title"
private const val API_MX_FILENAME = "filename"
private const val API_MX_SECURE_URI = "secure_uri"
private const val API_VLC_RESULT_POSITION = "extra_position"
private const val API_VLC_RESULT_DURATION = "extra_duration"
private const val API_VIMU_TITLE = "forcename"
private const val API_VIMU_SEEK_POSITION = "startfrom"
private const val API_VIMU_RESUME = "forceresume"
private const val API_VIMU_RESULT_ID = "net.gtvbox.videoplayer.result"
private const val API_VIMU_RESULT_ERROR = 4
private const val API_VIMU_RESULT_PLAYBACK_COMPLETED = 1
private val positionExtras = arrayOf(API_MX_RESULT_POSITION, API_VLC_RESULT_POSITION)
private val durationExtras = arrayOf(API_MX_RESULT_DURATION, API_VLC_RESULT_DURATION)
}
private var pendingResult: MethodChannel.Result? = null
fun attach(messenger: BinaryMessenger) {
MethodChannel(messenger, CHANNEL).setMethodCallHandler(::onMethodCall)
}
fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
if (requestCode != REQUEST_CODE) return false
val result = pendingResult
pendingResult = null
if (result == null) {
android.util.Log.w("ExternalPlayerChannel", "Result received without a pending channel call")
} else {
result.success(buildResult(resultCode, data))
}
return true
}
fun dispose() {
pendingResult?.error("ACTIVITY_DESTROYED", "Activity was destroyed while external player was active", null)
pendingResult = null
}
internal fun buildResult(resultCode: Int, data: Intent?): Map<String, Any?> {
val extras = data?.extras
val endPosition = firstNumberExtra(extras, positionExtras)
val duration = firstNumberExtra(extras, durationExtras)
val action = data?.action
val playbackCompleted = when (action) {
API_MX_RESULT_ID -> extras?.getString(API_MX_RESULT_END_BY) == API_MX_RESULT_END_BY_PLAYBACK_COMPLETION
API_VIMU_RESULT_ID -> resultCode == API_VIMU_RESULT_PLAYBACK_COMPLETED
else -> false
}
val playbackError = action == API_VIMU_RESULT_ID && resultCode == API_VIMU_RESULT_ERROR
return mapOf(
"launched" to true,
"resultCode" to resultCode,
"resultOk" to (resultCode == Activity.RESULT_OK),
"action" to action,
"positionMs" to endPosition,
"durationMs" to duration,
"playbackCompleted" to playbackCompleted,
"playbackError" to playbackError
)
}
private fun firstNumberExtra(extras: Bundle?, keys: Array<String>): Long? {
if (extras == null) return null
for (key in keys) {
@Suppress("DEPRECATION")
val value = extras.get(key)
when (value) {
is Number -> return value.toLong()
is String -> value.toLongOrNull()?.let { return it }
}
}
return null
}
@Suppress("UNCHECKED_CAST")
private fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
if (call.method != "openVideo") {
result.notImplemented()
return
}
val filePath = call.argument<String>("filePath")
val packageNames = call.argument<List<Any?>>("packages")
?.mapNotNull { (it as? String)?.trim()?.takeIf(String::isNotEmpty) }
?: emptyList()
val title = call.argument<String>("title")?.trim()?.takeIf(String::isNotEmpty)
val startPositionMs = call.argument<Number>("startPositionMs")?.toLong() ?: 0L
if (filePath == null) {
result.error("INVALID_ARGUMENT", "filePath is required", null)
return
}
if (pendingResult != null) {
result.error("ALREADY_ACTIVE", "An external player is already active", null)
return
}
try {
val source = resolveSource(filePath)
val targetPackages = if (packageNames.isEmpty()) listOf<String?>(null) else packageNames
for (packageName in targetPackages) {
try {
pendingResult = result
activity.startActivityForResult(
buildIntent(source, packageName, startPositionMs, title),
REQUEST_CODE
)
return
} catch (_: ActivityNotFoundException) {
pendingResult = null
}
}
val message = if (packageNames.isEmpty()) {
"No app found for video"
} else {
"No app found for packages: ${packageNames.joinToString(", ")}"
}
result.error("APP_NOT_FOUND", message, null)
} catch (error: Exception) {
pendingResult = null
result.error("LAUNCH_FAILED", error.message ?: error.javaClass.simpleName, null)
}
}
private data class Source(val uri: Uri, val grantRead: Boolean, val fileName: String?)
private fun resolveSource(filePath: String): Source {
if (filePath.startsWith("http://") || filePath.startsWith("https://")) {
val uri = Uri.parse(filePath)
return Source(uri, grantRead = false, fileName = uri.lastPathSegment)
}
if (filePath.startsWith("content://")) {
val uri = Uri.parse(filePath)
return Source(uri, grantRead = true, fileName = uri.lastPathSegment)
}
val path = if (filePath.startsWith("file://")) filePath.removePrefix("file://") else filePath
val file = File(path)
val uri = FileProvider.getUriForFile(activity, "com.edde746.plezy.fileprovider", file)
return Source(uri, grantRead = true, fileName = file.name)
}
private fun buildIntent(
source: Source,
packageName: String?,
startPositionMs: Long,
title: String?
): Intent = Intent(Intent.ACTION_VIEW).apply {
setDataAndType(source.uri, "video/*")
if (source.grantRead) addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
packageName?.let(::setPackage)
val startPosition = startPositionMs.coerceAtLeast(0).coerceAtMost(Int.MAX_VALUE.toLong()).toInt()
if (startPosition > 0) {
putExtra(API_MX_RESULT_POSITION, startPosition)
putExtra(API_VIMU_SEEK_POSITION, startPosition)
}
putExtra(API_MX_RETURN_RESULT, true)
putExtra(API_MX_SECURE_URI, true)
putExtra(API_VIMU_RESUME, false)
title?.let {
putExtra(API_MX_TITLE, it)
putExtra(API_VIMU_TITLE, it)
}
source.fileName?.let { putExtra(API_MX_FILENAME, it) }
}
}
@@ -1,35 +1,28 @@
package com.edde746.plezy
import android.app.Activity
import android.app.ActivityManager
import android.app.AppOpsManager
import android.app.PictureInPictureParams
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.graphics.SurfaceTexture
import android.media.AudioManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Process
import android.provider.Settings
import android.util.Log
import android.util.Rational
import android.view.InputDevice
import android.view.KeyEvent
import android.view.TextureView
import android.view.ViewGroup
import android.view.WindowInsets
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.FrameLayout
import androidx.core.content.FileProvider
import com.edde746.plezy.exoplayer.ExoPlayerPlugin
import com.edde746.plezy.mpv.MpvAudioPlayerPlugin
import com.edde746.plezy.mpv.MpvPlayerPlugin
import com.edde746.plezy.shared.DeviceQuirks
import com.edde746.plezy.shared.ThemeHelper
@@ -41,7 +34,6 @@ import io.flutter.embedding.android.TransparencyMode
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.FlutterShellArgs
import io.flutter.plugin.common.MethodChannel
import java.io.File
import kotlin.math.roundToInt
class MainActivity : FlutterActivity() {
@@ -49,46 +41,27 @@ class MainActivity : FlutterActivity() {
companion object {
private const val TAG = "MainActivity"
private const val TEXT_INPUT_DIAGNOSTICS_ENABLED = false
private const val EXTERNAL_PLAYER_REQUEST_CODE = 7461
// External player result APIs used by Jellyfin Android TV.
private const val API_MX_RETURN_RESULT = "return_result"
private const val API_MX_RESULT_ID = "com.mxtech.intent.result.VIEW"
private const val API_MX_RESULT_POSITION = "position"
private const val API_MX_RESULT_DURATION = "duration"
private const val API_MX_RESULT_END_BY = "end_by"
private const val API_MX_RESULT_END_BY_PLAYBACK_COMPLETION = "playback_completion"
private const val API_MX_TITLE = "title"
private const val API_MX_FILENAME = "filename"
private const val API_MX_SECURE_URI = "secure_uri"
private const val API_VLC_RESULT_POSITION = "extra_position"
private const val API_VLC_RESULT_DURATION = "extra_duration"
private const val API_VIMU_TITLE = "forcename"
private const val API_VIMU_SEEK_POSITION = "startfrom"
private const val API_VIMU_RESUME = "forceresume"
private const val API_VIMU_RESULT_ID = "net.gtvbox.videoplayer.result"
private const val API_VIMU_RESULT_ERROR = 4
private const val API_VIMU_RESULT_PLAYBACK_COMPLETED = 1
private val externalPlayerPositionExtras = arrayOf(API_MX_RESULT_POSITION, API_VLC_RESULT_POSITION)
private val externalPlayerDurationExtras = arrayOf(API_MX_RESULT_DURATION, API_VLC_RESULT_DURATION)
// Mirrors DevicePerformance._lowMemThresholdBytes (2252 MiB): nominal
// "2GB" devices report totalMem slightly above 2 GiB after carve-outs.
private const val LOW_MEM_THRESHOLD_BYTES = 2252L shl 20
var usingSkia = false
}
private val PIP_CHANNEL = "com.plezy/pip"
private val EXTERNAL_PLAYER_CHANNEL = "com.plezy/external_player"
private val THEME_CHANNEL = "com.plezy/theme"
private val DEVICE_CHANNEL = "com.plezy/device"
private val DEVICE_ADJUSTMENT_CHANNEL = "com.plezy/device_adjustment"
private val TEXT_INPUT_CHANNEL = "com.plezy/text_input"
private val APP_EXIT_CHANNEL = "com.plezy/app_exit"
private val APP_FOREGROUND_CHANNEL = "com.plezy/app_foreground"
private var watchNextPlugin: WatchNextPlugin? = null
private var nativeTextInputFocused = false
private var pendingExternalPlayerResult: MethodChannel.Result? = null
private var originalWindowBrightness: Float? = null
private var flutterTextureView: FlutterTextureView? = null
private var flutterSurfaceReconnectPending = false
private var activityStarted = false
private val externalPlayerChannel = ExternalPlayerChannel(this)
private inline fun logTextInputDiag(message: () -> String) {
if (TEXT_INPUT_DIAGNOSTICS_ENABLED) {
@@ -210,6 +183,18 @@ class MainActivity : FlutterActivity() {
)
}
/**
* Same triple DevicePerformance uses for the reduced tier on the Dart
* side — keep the two in sync. Evaluated here too because engine shell
* args must be decided before Dart runs.
*/
private fun isLowRamClass(): Boolean {
val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val memoryInfo = ActivityManager.MemoryInfo()
activityManager.getMemoryInfo(memoryInfo)
return !Process.is64Bit() || activityManager.isLowRamDevice || memoryInfo.totalMem <= LOW_MEM_THRESHOLD_BYTES
}
/** User-assigned device name (Settings > About > Device name), or null. */
private fun getDeviceName(): String? {
// The name the user gave the device; also used by Cast/Nearby.
@@ -310,63 +295,16 @@ class MainActivity : FlutterActivity() {
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == EXTERNAL_PLAYER_REQUEST_CODE) {
val pendingResult = pendingExternalPlayerResult
pendingExternalPlayerResult = null
if (pendingResult == null) {
Log.w(TAG, "External player result received without a pending channel result")
} else {
pendingResult.success(buildExternalPlayerResult(resultCode, data))
}
return
if (!externalPlayerChannel.onActivityResult(requestCode, resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data)
}
super.onActivityResult(requestCode, resultCode, data)
}
private fun buildExternalPlayerResult(resultCode: Int, data: Intent?): Map<String, Any?> {
val extras = data?.extras
val endPosition = firstNumberExtra(extras, externalPlayerPositionExtras)
val duration = firstNumberExtra(extras, externalPlayerDurationExtras)
val action = data?.action
val playbackCompleted = when (action) {
API_MX_RESULT_ID -> extras?.getString(API_MX_RESULT_END_BY) == API_MX_RESULT_END_BY_PLAYBACK_COMPLETION
API_VIMU_RESULT_ID -> resultCode == API_VIMU_RESULT_PLAYBACK_COMPLETED
else -> false
}
val playbackError = when (action) {
API_VIMU_RESULT_ID -> resultCode == API_VIMU_RESULT_ERROR
else -> false
}
return mapOf(
"launched" to true,
"resultCode" to resultCode,
"resultOk" to (resultCode == Activity.RESULT_OK),
"action" to action,
"positionMs" to endPosition,
"durationMs" to duration,
"playbackCompleted" to playbackCompleted,
"playbackError" to playbackError
)
}
private fun firstNumberExtra(extras: Bundle?, keys: Array<String>): Long? {
if (extras == null) return null
for (key in keys) {
@Suppress("DEPRECATION")
val value = extras.get(key)
when (value) {
is Number -> return value.toLong()
is String -> value.toLongOrNull()?.let { return it }
}
}
return null
}
override fun onDestroy() {
pendingExternalPlayerResult?.error("ACTIVITY_DESTROYED", "Activity was destroyed while external player was active", null)
pendingExternalPlayerResult = null
externalPlayerChannel.dispose()
activityStarted = false
flutterSurfaceReconnectPending = false
flutterTextureView = null
super.onDestroy()
}
@@ -382,12 +320,19 @@ class MainActivity : FlutterActivity() {
val args = super.getFlutterShellArgs()
usingSkia = shouldDisableImpeller()
if (usingSkia) args.add("--enable-impeller=false")
if (isLowRamClass()) {
// Bound the memory pools Dart can't reach: Skia's GPU resource cache
// is sized from the surface area (hundreds of MB on a 4K-composited
// TV) and the Dart old gen defaults to a large fraction of physical
// RAM. Both drive LMK kills on 2GB boxes (#1349).
if (usingSkia) args.add("--resource-cache-max-bytes-threshold=50331648")
args.add("--old-gen-heap-size=256")
Log.i(TAG, "Low-RAM device: capped engine caches (skia=$usingSkia, oldGen=256MB)")
}
return args
}
private fun shouldDisableImpeller(): Boolean {
// Android TV devices — weaker GPUs, less Impeller testing
if (isAndroidTvDevice()) return true
if (DeviceQuirks.isEWaste) return true
// NVIDIA Tegra (Shield TV)
if (Build.MANUFACTURER.equals("NVIDIA", ignoreCase = true)) return true
@@ -397,9 +342,21 @@ class MainActivity : FlutterActivity() {
) {
return true
}
if (isAndroidTvDevice()) return !tvSupportsImpeller()
return false
}
// Impeller froze API 30 Fire TV hardware (#749) and Flutter's Vulkan → GLES
// fallback still miscompiles gradients/SVGs, so only TV devices on Android 12+
// with a Vulkan 1.1 driver leave the Skia path.
private fun tvSupportsImpeller(): Boolean {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return false
// Fire OS reports modern API levels on GPUs whose drivers can't back it up
if (Build.MANUFACTURER.equals("Amazon", ignoreCase = true)) return false
val vulkan11 = 0x401000 // FEATURE_VULKAN_HARDWARE_VERSION encodes 1.1.0 as 0x401000
return packageManager.hasSystemFeature(PackageManager.FEATURE_VULKAN_HARDWARE_VERSION, vulkan11)
}
override fun getRenderMode(): RenderMode {
// Keep Flutter in the normal View hierarchy so video/subtitle SurfaceViews
// remain the only native composition layers. This restores the pre-1.35.0
@@ -413,41 +370,49 @@ class MainActivity : FlutterActivity() {
}
override fun onFlutterTextureViewCreated(flutterTextureView: FlutterTextureView) {
this.flutterTextureView = flutterTextureView
val original = flutterTextureView.surfaceTextureListener ?: return
val handler = Handler(Looper.getMainLooper())
var pendingResize: Runnable? = null
var lastWidth = 0
var lastHeight = 0
flutterTextureView.surfaceTextureListener =
DeferredSurfaceTextureListener(
delegate = original,
onSurfaceAvailable = ::tryReconnectFlutterSurface
) { surface ->
flutterTextureView.isAvailable && flutterTextureView.surfaceTexture === surface
}
}
flutterTextureView.surfaceTextureListener = object : TextureView.SurfaceTextureListener {
override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {
original.onSurfaceTextureAvailable(surface, width, height)
override fun onStop() {
activityStarted = false
if (isAndroidTvDevice()) flutterSurfaceReconnectPending = true
super.onStop()
}
override fun onStart() {
super.onStart()
activityStarted = true
tryReconnectFlutterSurface()
}
private fun tryReconnectFlutterSurface() {
if (!activityStarted || !flutterSurfaceReconnectPending) return
val textureView = flutterTextureView ?: return
textureView.post {
if (!activityStarted ||
!flutterSurfaceReconnectPending ||
textureView !== flutterTextureView ||
!textureView.isAttachedToWindow ||
!textureView.isAvailable
) {
return@post
}
override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {
if (width == lastWidth && height == lastHeight) return
lastWidth = width
lastHeight = height
pendingResize?.let { handler.removeCallbacks(it) }
pendingResize = Runnable {
if (flutterTextureView.isAvailable) {
original.onSurfaceTextureSizeChanged(surface, width, height)
}
}
handler.postDelayed(pendingResize!!, 100)
}
override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {
original.onSurfaceTextureUpdated(surface)
}
override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
pendingResize?.let { handler.removeCallbacks(it) }
pendingResize = null
lastWidth = 0
lastHeight = 0
return original.onSurfaceTextureDestroyed(surface)
}
// Some TV firmware retains an available TextureView while invalidating
// its compositor surface during standby. Force Flutter's supported
// surface-swap path so rendering resumes without restarting the engine.
Log.i(TAG, "Reconnecting Flutter texture surface after Android TV standby")
textureView.pause()
textureView.resume()
flutterSurfaceReconnectPending = false
}
}
@@ -455,6 +420,7 @@ class MainActivity : FlutterActivity() {
super.configureFlutterEngine(flutterEngine)
flutterEngine.plugins.add(MpvPlayerPlugin())
flutterEngine.plugins.add(ExoPlayerPlugin())
flutterEngine.plugins.add(MpvAudioPlayerPlugin())
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, DEVICE_CHANNEL).setMethodCallHandler { call, result ->
when (call.method) {
@@ -495,101 +461,7 @@ class MainActivity : FlutterActivity() {
}
}
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, APP_FOREGROUND_CHANNEL).setMethodCallHandler { call, result ->
when (call.method) {
"requestForeground" -> result.success(requestForeground())
else -> result.notImplemented()
}
}
// External player: open local video files with proper content:// URIs
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, EXTERNAL_PLAYER_CHANNEL).setMethodCallHandler { call, result ->
when (call.method) {
"openVideo" -> {
val filePath = call.argument<String>("filePath")
val packageNames = call.argument<List<Any?>>("packages")
?.mapNotNull { (it as? String)?.trim()?.takeIf { value -> value.isNotEmpty() } }
?: emptyList()
val title = call.argument<String>("title")?.trim()?.takeIf { it.isNotEmpty() }
val startPositionMs = call.argument<Number>("startPositionMs")?.toLong() ?: 0L
if (filePath == null) {
result.error("INVALID_ARGUMENT", "filePath is required", null)
return@setMethodCallHandler
}
if (pendingExternalPlayerResult != null) {
result.error("ALREADY_ACTIVE", "An external player is already active", null)
return@setMethodCallHandler
}
try {
val uri: Uri
val grantRead: Boolean
val fileName: String?
if (filePath.startsWith("http://") || filePath.startsWith("https://")) {
uri = Uri.parse(filePath)
grantRead = false
fileName = uri.lastPathSegment
} else if (filePath.startsWith("content://")) {
uri = Uri.parse(filePath)
grantRead = true
fileName = uri.lastPathSegment
} else {
val path = if (filePath.startsWith("file://")) filePath.removePrefix("file://") else filePath
fileName = File(path).name
uri = FileProvider.getUriForFile(this, "com.edde746.plezy.fileprovider", File(path))
grantRead = true
}
fun buildIntent(packageName: String?): Intent = Intent(Intent.ACTION_VIEW).apply {
setDataAndType(uri, "video/*")
if (grantRead) {
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
packageName?.let { setPackage(it) }
val startPosition = startPositionMs.coerceAtLeast(0).coerceAtMost(Int.MAX_VALUE.toLong()).toInt()
if (startPosition > 0) {
putExtra(API_MX_RESULT_POSITION, startPosition)
putExtra(API_VIMU_SEEK_POSITION, startPosition)
}
putExtra(API_MX_RETURN_RESULT, true)
putExtra(API_MX_SECURE_URI, true)
putExtra(API_VIMU_RESUME, false)
title?.let {
putExtra(API_MX_TITLE, it)
putExtra(API_VIMU_TITLE, it)
}
fileName?.let { putExtra(API_MX_FILENAME, it) }
}
val targetPackages = if (packageNames.isEmpty()) listOf<String?>(null) else packageNames
for (packageName in targetPackages) {
try {
pendingExternalPlayerResult = result
startActivityForResult(buildIntent(packageName), EXTERNAL_PLAYER_REQUEST_CODE)
return@setMethodCallHandler
} catch (e: ActivityNotFoundException) {
pendingExternalPlayerResult = null
}
}
pendingExternalPlayerResult = null
val message = if (packageNames.isEmpty()) {
"No app found for video"
} else {
"No app found for packages: ${packageNames.joinToString(", ")}"
}
result.error("APP_NOT_FOUND", message, null)
} catch (e: Exception) {
pendingExternalPlayerResult = null
result.error("LAUNCH_FAILED", e.message ?: e.javaClass.simpleName, null)
}
}
else -> result.notImplemented()
}
}
externalPlayerChannel.attach(flutterEngine.dartExecutor.binaryMessenger)
// Splash screen theme: persist user's chosen theme for next launch (API 31+)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, THEME_CHANNEL).setMethodCallHandler { call, result ->
@@ -686,31 +558,6 @@ class MainActivity : FlutterActivity() {
}
}
private fun requestForeground(): Boolean = try {
val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
activityManager.moveTaskToFront(taskId, 0)
true
} catch (e: Exception) {
Log.w(TAG, "Failed to move task to foreground", e)
try {
val launchIntent = packageManager.getLaunchIntentForPackage(packageName)?.apply {
addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
if (launchIntent != null) {
startActivity(launchIntent)
true
} else {
false
}
} catch (launchError: Exception) {
Log.w(TAG, "Failed to start foreground activity", launchError)
false
}
}
private fun handleDeviceAdjustmentCall(method: String, arguments: Any?, result: MethodChannel.Result) {
try {
when (method) {
@@ -0,0 +1,24 @@
package com.edde746.plezy
import android.content.Context
import android.content.pm.PackageManager
import android.content.res.Configuration
/**
* Native mirror of MainActivity.getAndroidTvDetection(): any TV signal counts.
* Kept in sync with the Dart-facing detection so native gating matches
* PlatformDetector.isTV().
*/
object TvDetection {
fun isTv(context: Context): Boolean {
val pm = context.packageManager
val uiModeType = context.resources.configuration.uiMode and Configuration.UI_MODE_TYPE_MASK
@Suppress("DEPRECATION")
return uiModeType == Configuration.UI_MODE_TYPE_TELEVISION ||
pm.hasSystemFeature(PackageManager.FEATURE_TELEVISION) ||
pm.hasSystemFeature(PackageManager.FEATURE_LEANBACK) ||
pm.hasSystemFeature("amazon.hardware.fire_tv") ||
!pm.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN)
}
}
@@ -0,0 +1,202 @@
package com.edde746.plezy.exoplayer
import android.os.Build
import android.view.SurfaceControl
import android.view.SurfaceView
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import kotlin.math.abs
import kotlin.math.roundToInt
/**
* Auto-calibrates [ExoPlayerCore]'s subtitle/video layer offset by measuring, per device, how much
* later the codec VIDEO plane reaches the display than the GL subtitle OVERLAY plane — the
* inter-plane latency (a deep video VPP on TV boxes) that otherwise makes subtitles a frame ahead.
*
* Both planes are pinned to the same video-frame target (releaseTimeNs). Measuring BOTH with the
* same mechanism — [SurfaceTxProbe] + the API-34 previous-release fence — the per-SoC buffer-recycle
* bias cancels in the difference, leaving the pure offset:
*
* offsetFrames = round( (median(videoReleaseVsTarget) − median(overlayReleaseVsTarget)) / frameMs )
*
* This is a MEDIAN-of-each-plane model, NOT a per-frame paired difference: every sample is
* self-paired to its own frame's target, and the per-plane release-vs-target is a steady hardware
* constant, so the two medians need not come from the same frames — only from the same (stable)
* device. Both medians use a recent-sample window so they stay roughly contemporaneous, and a
* confidence gate refuses to converge on an ambiguous (~half-frame) result.
*
* Video samples arrive every few frames from the metadata listener (codec thread); overlay samples
* from the libass GL thread's pre-swap hook (sparse — only when subtitles swap). Once both planes
* have enough samples and the result is confident it converges ONCE, applies + persists, and stops
* all probing (zero steady-state overhead). Re-runs each play to re-confirm.
*
* Threads: probeVideo (codec), probeOverlay (libass GL), onResult (probe reader). The lock guards
* only counter/sample state and is NEVER held across the binder/JNI `applyTransactionToFrame` call
* (so the GL swap path is never stalled by it). The native slot ring is allocated atomically.
*/
internal class AssLatencyCalibrator(
private val videoSurface: SurfaceView,
private val overlaySurface: SurfaceView,
private val onCalibrated: (Int) -> Unit,
private val onDone: () -> Unit,
private val log: (String) -> Unit
) {
private val lock = Any()
private val finished = AtomicBoolean(false)
private val applyFail = AtomicInteger(0)
@Volatile private var frameIntervalNs: Long = 0L
@Volatile private var converged = false
@Volatile private var stopped = false
private var videoFrames = 0
private var videoAttempts = 0
private var overlaySwaps = 0
private var overlayAttempts = 0
private val videoRel = ArrayDeque<Double>()
private val overlayRel = ArrayDeque<Double>()
fun start() {
SurfaceTxProbe.sink = { tag, latch, release, count, state, source, cb ->
onResult(tag, latch, release, count, state, source, cb)
}
log("calibration started (API ${Build.VERSION.SDK_INT})")
}
fun probeVideo(releaseTimeNs: Long, fps: Float) {
if (stopped || converged || Build.VERSION.SDK_INT < 34) return
if (fps > 1f) frameIntervalNs = (1_000_000_000.0 / fps).toLong()
var doAttach = false
var giveUp = false
synchronized(lock) {
videoFrames++
if (videoFrames > GIVEUP_FRAMES) {
giveUp = true
} else if (videoAttempts < VIDEO_ATTEMPT_CAP && videoFrames % VIDEO_EVERY == 0) {
videoAttempts++
doAttach = true
}
}
if (giveUp) {
finishIncomplete()
} else if (doAttach) {
attach(videoSurface, releaseTimeNs, SurfaceTxProbe.SOURCE_VIDEO)
}
}
fun probeOverlay(releaseTimeNs: Long) {
if (stopped || converged || Build.VERSION.SDK_INT < 34) return
var doAttach = false
synchronized(lock) {
overlaySwaps++
if (overlayAttempts < OVERLAY_ATTEMPT_CAP && overlaySwaps % OVERLAY_EVERY == 0) {
overlayAttempts++
doAttach = true
}
}
if (doAttach) attach(overlaySurface, releaseTimeNs, SurfaceTxProbe.SOURCE_OVERLAY)
}
/** Never called while holding [lock]: applyTransactionToFrame is a binder call and runs on the
* GL swap path. The native slot allocation is atomic, so concurrent callers are safe. */
private fun attach(surface: SurfaceView, releaseTimeNs: Long, source: Int) {
try {
val tx = SurfaceControl.Transaction()
SurfaceTxProbe.nativeAttach(tx, releaseTimeNs, source)
surface.applyTransactionToFrame(tx)
} catch (t: Throwable) {
if (applyFail.incrementAndGet() == 1) {
log("applyTransactionToFrame failed: ${t.javaClass.simpleName}: ${t.message}")
}
}
}
private fun onResult(
tag: Long,
latchNs: Long,
releaseNs: Long,
surfaceCount: Int,
fenceState: Int,
source: Int,
callbackNs: Long
) {
if (surfaceCount <= 0 || fenceState != FENCE_OK || releaseNs <= 0) return
val relMs = (releaseNs - tag) / 1_000_000.0
var result: Int? = null
synchronized(lock) {
if (converged || stopped) return
val list = if (source == SurfaceTxProbe.SOURCE_OVERLAY) overlayRel else videoRel
val window = if (source == SurfaceTxProbe.SOURCE_OVERLAY) OVERLAY_WINDOW else VIDEO_WINDOW
list.addLast(relMs)
while (list.size > window) list.removeFirst() // keep a recent window so medians stay fresh
result = tryComputeOffset()
}
result?.let {
onCalibrated(it)
finish()
}
}
private fun tryComputeOffset(): Int? {
val frameMs = frameIntervalNs / 1_000_000.0
if (frameMs <= 0.5) return null
if (videoRel.size < VIDEO_MIN || overlayRel.size < OVERLAY_MIN) return null
val medV = median(videoRel)
val medO = median(overlayRel)
val offsetMs = medV - medO
val raw = offsetMs / frameMs
val frames = raw.roundToInt()
// Confidence gate: only trust a measurement that points clearly at an integer frame count.
// An ambiguous ~half-frame result (corruption / drift / wrong fps) keeps collecting instead.
if (abs(raw - frames) > CONFIDENCE_TOL) return null
val clamped = frames.coerceIn(-2, 2)
converged = true
log(
"CALIBRATED offsetFrames=$clamped raw=${"%.2f".format(raw)} " +
"(video=${"%.1f".format(medV)}ms − overlay=${"%.1f".format(medO)}ms = ${"%.1f".format(offsetMs)}ms " +
"/ frameMs=${"%.2f".format(frameMs)}) samples video=${videoRel.size} overlay=${overlayRel.size} " +
"applyFail=${applyFail.get()}"
)
return clamped
}
private fun finishIncomplete() {
if (converged || stopped) return
log(
"calibration incomplete after $videoFrames frames " +
"(video=${videoRel.size} overlay=${overlayRel.size}); keeping seed"
)
finish()
}
fun stop() = finish()
private fun finish() {
if (!finished.compareAndSet(false, true)) return
stopped = true
SurfaceTxProbe.sink = null
onDone()
}
private fun median(xs: Collection<Double>): Double {
val s = xs.sorted()
val n = s.size
return if (n % 2 == 1) s[n / 2] else (s[n / 2 - 1] + s[n / 2]) / 2.0
}
companion object {
private const val FENCE_OK = 3
private const val VIDEO_EVERY = 2
private const val OVERLAY_EVERY = 1 // overlay swaps are already sparse
private const val VIDEO_MIN = 40
private const val OVERLAY_MIN = 12
private const val VIDEO_WINDOW = 60 // recent-sample window for the median
private const val OVERLAY_WINDOW = 40
private const val VIDEO_ATTEMPT_CAP = 200 // ~16s @24fps/2 of video probing, then the window freezes
private const val OVERLAY_ATTEMPT_CAP = 60
private const val CONFIDENCE_TOL = 0.33 // |raw − round(raw)| must be within ⅓ frame to converge
private const val GIVEUP_FRAMES = 1800 // ~75s @24fps without enough confident overlay samples
}
}
@@ -0,0 +1,17 @@
package com.edde746.plezy.exoplayer
import androidx.media3.common.MimeTypes
internal fun isPassthroughAudioMimeType(mimeType: String): Boolean = when (mimeType) {
"audio/ac3",
"audio/eac3",
"audio/eac3-joc",
"audio/ac4",
"audio/vnd.dts",
"audio/vnd.dts.hd",
"audio/vnd.dts.uhd",
MimeTypes.AUDIO_TRUEHD -> true
else -> false
}
internal fun shouldBlockDirectOutputForPassthrough(mimeType: String, audioPassthroughEnabled: Boolean): Boolean = !audioPassthroughEnabled && isPassthroughAudioMimeType(mimeType)
@@ -0,0 +1,95 @@
package com.edde746.plezy.exoplayer
import androidx.media3.common.C
import androidx.media3.common.DataReader
import androidx.media3.common.Format
import androidx.media3.common.util.ParsableByteArray
import androidx.media3.extractor.TrackOutput
import java.io.EOFException
/** Shared whole-sample buffering protocol for TrackOutput transforms. */
abstract class BufferedTransformingTrackOutput(
protected val delegate: TrackOutput,
initialBufferSize: Int,
initialReadBufferSize: Int = initialBufferSize
) : TrackOutput {
protected var inputBuffer = ByteArray(initialBufferSize)
private set
private var inputLength = 0
private var buffering = false
private var readBuffer = ByteArray(initialReadBufferSize)
private val outputParsable = ParsableByteArray()
protected abstract val transformEnabled: Boolean
protected abstract val transformedBuffer: ByteArray
/** Returns transformed length, or a negative value to drop the sample. */
protected abstract fun transformSample(inputLength: Int, flags: Int): Int
open override fun format(format: Format) = delegate.format(format)
override fun sampleData(
input: DataReader,
length: Int,
allowEndOfInput: Boolean,
sampleDataPart: Int
): Int {
if (!transformEnabled) {
return delegate.sampleData(input, length, allowEndOfInput, sampleDataPart)
}
buffering = true
if (readBuffer.size < length) readBuffer = ByteArray(length)
val bytesRead = input.read(readBuffer, 0, length)
if (bytesRead == C.RESULT_END_OF_INPUT && !allowEndOfInput) throw EOFException()
if (bytesRead > 0) appendInput(readBuffer, bytesRead)
return bytesRead
}
override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) {
if (!transformEnabled) {
delegate.sampleData(data, length, sampleDataPart)
return
}
buffering = true
ensureInputCapacity(inputLength + length)
data.readBytes(inputBuffer, inputLength, length)
inputLength += length
}
override fun sampleMetadata(
timeUs: Long,
flags: Int,
size: Int,
offset: Int,
cryptoData: TrackOutput.CryptoData?
) {
if (!transformEnabled || !buffering) {
delegate.sampleMetadata(timeUs, flags, size, offset, cryptoData)
return
}
buffering = false
val sourceLength = inputLength
inputLength = 0
val transformedLength = transformSample(sourceLength, flags)
if (transformedLength < 0) return
outputParsable.reset(transformedBuffer, transformedLength)
delegate.sampleData(outputParsable, transformedLength, TrackOutput.SAMPLE_DATA_PART_MAIN)
delegate.sampleMetadata(timeUs, flags, transformedLength, 0, cryptoData)
}
private fun appendInput(source: ByteArray, length: Int) {
ensureInputCapacity(inputLength + length)
System.arraycopy(source, 0, inputBuffer, inputLength, length)
inputLength += length
}
private fun ensureInputCapacity(needed: Int) {
if (inputBuffer.size < needed) {
inputBuffer = inputBuffer.copyOf(maxOf(needed, inputBuffer.size * 2))
}
}
}
@@ -258,24 +258,40 @@ object DoviBridge {
}
private fun describeDisplayHdrCapabilities(display: Display): String {
val hdrCapabilities = display.hdrCapabilities
val hdrCapabilities = getDisplayHdrCapabilities(display)
val parts = mutableListOf(
"display=${display.displayId}:${display.name}",
"activeMode=${describeDisplayMode(display.mode)}",
"hdrCapabilities=${describeHdrTypes(hdrCapabilities.supportedHdrTypes)}",
"desiredLuminance=max=${formatLuminance(hdrCapabilities.desiredMaxLuminance)}, " +
"activeMode=${describeDisplayMode(display.mode)}"
)
if (hdrCapabilities == null) {
parts += "hdrCapabilities=unavailable"
} else {
@Suppress("DEPRECATION")
parts += "hdrCapabilities=${describeHdrTypes(hdrCapabilities.supportedHdrTypes)}"
parts += "desiredLuminance=max=${formatLuminance(hdrCapabilities.desiredMaxLuminance)}, " +
"maxAvg=${formatLuminance(hdrCapabilities.desiredMaxAverageLuminance)}, " +
"min=${formatLuminance(hdrCapabilities.desiredMinLuminance)}"
)
}
parts += "supportedModes=${display.supportedModes.joinToString(prefix = "[", postfix = "]") { describeDisplayMode(it) }}"
return parts.joinToString(prefix = "{", postfix = "}")
}
private fun getDisplayHdrTypes(display: Display): IntArray = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
display.mode.supportedHdrTypes
} else {
private fun getDisplayHdrCapabilities(display: Display): Display.HdrCapabilities? = runCatching {
display.hdrCapabilities
}.onFailure { Log.w(TAG, "Failed to query display HDR capabilities", it) }.getOrNull()
private fun getDisplayHdrTypes(display: Display): IntArray {
val hdrCapabilities = getDisplayHdrCapabilities(display) ?: return IntArray(0)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
return runCatching { display.mode.supportedHdrTypes }.getOrElse { error ->
Log.w(TAG, "Failed to query mode HDR types; falling back to display HDR capabilities", error)
@Suppress("DEPRECATION")
hdrCapabilities.supportedHdrTypes
}
}
@Suppress("DEPRECATION")
display.hdrCapabilities.supportedHdrTypes
return hdrCapabilities.supportedHdrTypes
}
private fun describeDisplayMode(mode: Display.Mode): String {
@@ -2,10 +2,8 @@ package com.edde746.plezy.exoplayer
import android.util.Log
import androidx.media3.common.C
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.TrackOutput
/**
@@ -28,10 +26,10 @@ import androidx.media3.extractor.TrackOutput
* All buffers are reused across samples to minimize GC pressure on the hot path.
*/
class DoviConvertingTrackOutput(
private val delegate: TrackOutput,
delegate: TrackOutput,
private val dvMode: DvConversionMode = DvConversionMode.HEVC_STRIP,
private val emitLog: ((String, String, String) -> Unit)? = null
) : TrackOutput {
) : BufferedTransformingTrackOutput(delegate, INITIAL_BUFFER_SIZE) {
companion object {
private const val TAG = "DoviConvertTrack"
@@ -65,12 +63,8 @@ class DoviConvertingTrackOutput(
get() = if (sampleCount > 0) totalSampleProcessingTimeUs / sampleCount else 0L
// Reusable buffers — grown as needed, never shrunk
private var sampleBuf = ByteArray(INITIAL_BUFFER_SIZE)
private var sampleLen = 0
private var outputBuf = ByteArray(INITIAL_BUFFER_SIZE)
private var outputLen = 0
private val outputParsable = ParsableByteArray()
private var buffering = false
// Sample counter for periodic logging
private var sampleCount = 0L
@@ -79,6 +73,7 @@ class DoviConvertingTrackOutput(
private var totalSampleProcessingTimeUs = 0L
private var loggedSupplementalWrapper = false
private var loggedEncryptedSupplementalPassthrough = false
private var outputIsProcessed = false
override fun format(format: Format) {
if (!conversionActive) {
@@ -135,55 +130,15 @@ class DoviConvertingTrackOutput(
delegate.format(format)
}
override fun sampleData(
input: DataReader,
length: Int,
allowEndOfInput: Boolean,
sampleDataPart: Int
): Int {
if (!conversionActive) {
return delegate.sampleData(input, length, allowEndOfInput, sampleDataPart)
}
override val transformEnabled: Boolean
get() = conversionActive
buffering = true
ensureSampleCapacity(sampleLen + length)
val bytesRead = input.read(sampleBuf, sampleLen, length)
if (bytesRead > 0) {
sampleLen += bytesRead
}
return bytesRead
}
override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) {
if (!conversionActive) {
delegate.sampleData(data, length, sampleDataPart)
return
}
buffering = true
ensureSampleCapacity(sampleLen + length)
data.readBytes(sampleBuf, sampleLen, length)
sampleLen += length
}
override fun sampleMetadata(
timeUs: Long,
flags: Int,
size: Int,
offset: Int,
cryptoData: TrackOutput.CryptoData?
) {
if (!conversionActive || !buffering) {
delegate.sampleMetadata(timeUs, flags, size, offset, cryptoData)
return
}
buffering = false
val srcLen = sampleLen
sampleLen = 0
override val transformedBuffer: ByteArray
get() = if (outputIsProcessed) outputBuf else inputBuffer
override fun transformSample(inputLength: Int, flags: Int): Int {
val processStartNs = System.nanoTime()
val success = if ((flags and C.BUFFER_FLAG_ENCRYPTED) != 0) {
outputIsProcessed = if ((flags and C.BUFFER_FLAG_ENCRYPTED) != 0) {
if (!loggedEncryptedSupplementalPassthrough && (flags and C.BUFFER_FLAG_HAS_SUPPLEMENTAL_DATA) != 0) {
loggedEncryptedSupplementalPassthrough = true
logWarn("Encrypted supplemental sample encountered, passing raw sample")
@@ -191,25 +146,20 @@ class DoviConvertingTrackOutput(
false
} else {
try {
processSampleData(flags, srcLen)
processSampleData(flags, inputLength)
true
} catch (e: Exception) {
logError("NAL processing failed, passing raw sample", e)
false
}
}
val outLen = if (success) outputLen else srcLen
val outBuf = if (success) outputBuf else sampleBuf
if (success) {
val transformedLength = if (outputIsProcessed) outputLen else inputLength
if (outputIsProcessed) {
recordSampleProcessing((System.nanoTime() - processStartNs) / 1_000L)
}
// Skip empty samples (all NALs were DV layers) — don't confuse the decoder
if (outLen == 0) return
outputParsable.reset(outBuf, outLen)
delegate.sampleData(outputParsable, outLen, TrackOutput.SAMPLE_DATA_PART_MAIN)
delegate.sampleMetadata(timeUs, flags, outLen, 0, cryptoData)
// Skip empty samples (all NALs were DV layers) — don't confuse the decoder.
return if (transformedLength == 0) -1 else transformedLength
}
/**
@@ -231,7 +181,7 @@ class DoviConvertingTrackOutput(
return
}
val mainSampleLen = readInt32BE(sampleBuf, 0)
val mainSampleLen = readInt32BE(inputBuffer, 0)
if (mainSampleLen < 0 || mainSampleLen > dataLen - 4) {
logWarn("Bad supplemental sample: mainLen=$mainSampleLen total=$dataLen")
copyRawSample(dataLen)
@@ -243,7 +193,7 @@ class DoviConvertingTrackOutput(
loggedSupplementalWrapper = true
logDebug(
"Supplemental wrapper detected: total=${dataLen}B, main=${mainSampleLen}B, " +
"supplemental=${supplementalLen}B, innerFirstBytes=${formatBytes(sampleBuf, 4, 8)}"
"supplemental=${supplementalLen}B, innerFirstBytes=${formatBytes(inputBuffer, 4, 8)}"
)
}
@@ -259,7 +209,7 @@ class DoviConvertingTrackOutput(
System.arraycopy(outputBuf, 0, outputBuf, 4, processedMainLen)
writeInt32BE(outputBuf, 0, processedMainLen)
if (supplementalLen > 0) {
System.arraycopy(sampleBuf, 4 + mainSampleLen, outputBuf, 4 + processedMainLen, supplementalLen)
System.arraycopy(inputBuffer, 4 + mainSampleLen, outputBuf, 4 + processedMainLen, supplementalLen)
}
outputLen = 4 + processedMainLen + supplementalLen
@@ -282,7 +232,7 @@ class DoviConvertingTrackOutput(
outputLen = 0
if (dataLen < 4) {
ensureOutputCapacity(dataLen)
System.arraycopy(sampleBuf, dataOffset, outputBuf, 0, dataLen)
System.arraycopy(inputBuffer, dataOffset, outputBuf, 0, dataLen)
outputLen = dataLen
return
}
@@ -290,22 +240,22 @@ class DoviConvertingTrackOutput(
// Auto-detect: Annex B starts with 00 00 00 01 or 00 00 01
val isAnnexB = (
dataLen >= 4 &&
sampleBuf[dataOffset] == 0.toByte() &&
sampleBuf[dataOffset + 1] == 0.toByte() &&
sampleBuf[dataOffset + 2] == 0.toByte() &&
sampleBuf[dataOffset + 3] == 1.toByte()
inputBuffer[dataOffset] == 0.toByte() &&
inputBuffer[dataOffset + 1] == 0.toByte() &&
inputBuffer[dataOffset + 2] == 0.toByte() &&
inputBuffer[dataOffset + 3] == 1.toByte()
) ||
(
dataLen >= 3 &&
sampleBuf[dataOffset] == 0.toByte() &&
sampleBuf[dataOffset + 1] == 0.toByte() &&
sampleBuf[dataOffset + 2] == 1.toByte()
inputBuffer[dataOffset] == 0.toByte() &&
inputBuffer[dataOffset + 1] == 0.toByte() &&
inputBuffer[dataOffset + 2] == 1.toByte()
)
if (sampleCount == 0L) {
logDebug(
"NAL format detected: ${if (isAnnexB) "Annex B" else "length-prefixed"}, " +
"first bytes: ${formatBytes(sampleBuf, dataOffset, 8)}"
"first bytes: ${formatBytes(inputBuffer, dataOffset, 8)}"
)
}
@@ -323,11 +273,11 @@ class DoviConvertingTrackOutput(
var scEnd = -1
var i = dataOffset
while (i < dataEnd - 2) {
if (sampleBuf[i] == 0.toByte() && sampleBuf[i + 1] == 0.toByte()) {
if (i + 3 < dataEnd && sampleBuf[i + 2] == 0.toByte() && sampleBuf[i + 3] == 1.toByte()) {
if (inputBuffer[i] == 0.toByte() && inputBuffer[i + 1] == 0.toByte()) {
if (i + 3 < dataEnd && inputBuffer[i + 2] == 0.toByte() && inputBuffer[i + 3] == 1.toByte()) {
scEnd = i + 4
break
} else if (sampleBuf[i + 2] == 1.toByte()) {
} else if (inputBuffer[i + 2] == 1.toByte()) {
scEnd = i + 3
break
}
@@ -337,7 +287,7 @@ class DoviConvertingTrackOutput(
if (scEnd < 0) {
// No start codes found — pass through
System.arraycopy(sampleBuf, dataOffset, outputBuf, 0, dataLen)
System.arraycopy(inputBuffer, dataOffset, outputBuf, 0, dataLen)
outputLen = dataLen
sampleCount++
return
@@ -350,11 +300,11 @@ class DoviConvertingTrackOutput(
var nalEnd = dataEnd
i = nalStart
while (i < dataEnd - 2) {
if (sampleBuf[i] == 0.toByte() && sampleBuf[i + 1] == 0.toByte()) {
if (i + 3 < dataEnd && sampleBuf[i + 2] == 0.toByte() && sampleBuf[i + 3] == 1.toByte()) {
if (inputBuffer[i] == 0.toByte() && inputBuffer[i + 1] == 0.toByte()) {
if (i + 3 < dataEnd && inputBuffer[i + 2] == 0.toByte() && inputBuffer[i + 3] == 1.toByte()) {
nalEnd = i
break
} else if (sampleBuf[i + 2] == 1.toByte()) {
} else if (inputBuffer[i + 2] == 1.toByte()) {
nalEnd = i
break
}
@@ -369,7 +319,7 @@ class DoviConvertingTrackOutput(
ensureOutputCapacity(outputLen + 4 + nalLen)
System.arraycopy(ANNEX_B_START_CODE, 0, outputBuf, outputLen, 4)
outputLen += 4
System.arraycopy(sampleBuf, nalStart, outputBuf, outputLen, nalLen)
System.arraycopy(inputBuffer, nalStart, outputBuf, outputLen, nalLen)
outputLen += nalLen
kept++
} else if (action == NalAction.CONVERT) {
@@ -392,7 +342,7 @@ class DoviConvertingTrackOutput(
// Advance past the next start code
if (nalEnd >= dataEnd) break
nalStart = if (nalEnd + 3 < dataEnd && sampleBuf[nalEnd + 2] == 0.toByte() && sampleBuf[nalEnd + 3] == 1.toByte()) {
nalStart = if (nalEnd + 3 < dataEnd && inputBuffer[nalEnd + 2] == 0.toByte() && inputBuffer[nalEnd + 3] == 1.toByte()) {
nalEnd + 4
} else {
nalEnd + 3
@@ -417,10 +367,10 @@ class DoviConvertingTrackOutput(
var stripped = 0
while (pos + 4 <= dataEnd) {
val nalLen = ((sampleBuf[pos].toInt() and 0xFF) shl 24) or
((sampleBuf[pos + 1].toInt() and 0xFF) shl 16) or
((sampleBuf[pos + 2].toInt() and 0xFF) shl 8) or
(sampleBuf[pos + 3].toInt() and 0xFF)
val nalLen = ((inputBuffer[pos].toInt() and 0xFF) shl 24) or
((inputBuffer[pos + 1].toInt() and 0xFF) shl 16) or
((inputBuffer[pos + 2].toInt() and 0xFF) shl 8) or
(inputBuffer[pos + 3].toInt() and 0xFF)
if (nalLen <= 0 || pos + 4 + nalLen > dataEnd) {
if (sampleCount < 5) {
@@ -435,7 +385,7 @@ class DoviConvertingTrackOutput(
ensureOutputCapacity(outputLen + 4 + nalLen)
writeInt32BE(outputBuf, outputLen, nalLen)
outputLen += 4
System.arraycopy(sampleBuf, nalStart, outputBuf, outputLen, nalLen)
System.arraycopy(inputBuffer, nalStart, outputBuf, outputLen, nalLen)
outputLen += nalLen
kept++
} else if (action == NalAction.CONVERT) {
@@ -486,7 +436,7 @@ class DoviConvertingTrackOutput(
while (true) {
val startNs = System.nanoTime()
val written = DoviBridge.convertRpuNalu(
payload = sampleBuf,
payload = inputBuffer,
payloadOffset = nalStart,
payloadLength = nalLen,
output = outputBuf,
@@ -630,7 +580,7 @@ class DoviConvertingTrackOutput(
}
/** Classify a NAL at sampleBuf[offset..offset+len) without copying. */
private fun processNalInline(offset: Int, len: Int): NalAction = classifyNal(sampleBuf, offset, len, convertRpu = dvMode == DvConversionMode.DV81)
private fun processNalInline(offset: Int, len: Int): NalAction = classifyNal(inputBuffer, offset, len, convertRpu = dvMode == DvConversionMode.DV81)
private fun isDvProfile7Codec(codecs: String?): Boolean {
val normalized = codecs?.lowercase() ?: return false
@@ -662,7 +612,7 @@ class DoviConvertingTrackOutput(
private fun copyRawSample(dataLen: Int) {
ensureOutputCapacity(dataLen)
System.arraycopy(sampleBuf, 0, outputBuf, 0, dataLen)
System.arraycopy(inputBuffer, 0, outputBuf, 0, dataLen)
outputLen = dataLen
}
@@ -672,12 +622,6 @@ class DoviConvertingTrackOutput(
return (offset until end).joinToString(" ") { "%02X".format(data[it]) }
}
private fun ensureSampleCapacity(needed: Int) {
if (sampleBuf.size < needed) {
sampleBuf = sampleBuf.copyOf(maxOf(needed, sampleBuf.size * 2))
}
}
private fun ensureOutputCapacity(needed: Int) {
if (outputBuf.size < needed) {
outputBuf = outputBuf.copyOf(maxOf(needed, outputBuf.size * 2))
@@ -0,0 +1,74 @@
package com.edde746.plezy.exoplayer
import kotlin.math.pow
/**
* Stereo downmix coefficient builder (Kodi-style center boost).
*
* Channel-order assumptions per input count follow the Android channel-mask
* bit order that MediaCodec / the FFmpeg extension emit:
* 3 = FL FR FC, 4 = FL FR BL BR, 5 = FL FR FC BL BR, 6 = FL FR FC LFE BL BR,
* 7 = 6.1 (5.1 + BC), 8 = 7.1 (5.1 + SL SR). LFE is dropped, matching
* ffmpeg's default lfe_mix_level=0 (and what the mpv backends produce).
*
* All coefficients must stay >= 0: ChannelMixingMatrix throws on negatives.
*/
object DownmixMatrices {
const val MIN_DOWNMIX_INPUT_CHANNELS = 3
const val MAX_DOWNMIX_INPUT_CHANNELS = 8
const val MAX_CENTER_BOOST_DB = 12
const val SURROUND_GAIN = 0.70710678f // -3 dB
private const val BACK_CENTER_GAIN = 0.5f // SURROUND_GAIN split across both outputs
/** Kodi's mechanism: center coefficient = 10^((-3 + boostDb) / 20); boost 0 is the standard -3 dB. */
fun centerGain(centerBoostDb: Int): Float = 10f.pow((-3f + centerBoostDb.coerceIn(0, MAX_CENTER_BOOST_DB)) / 20f)
/**
* Row-major stereo coefficients ([inputChannel * 2 + outputChannel]), or null
* when [inputChannels] is not downmixed (mono/stereo pass through; >8ch
* unsupported, the caller keeps an identity matrix).
*
* [normalize] scales the matrix so the loudest output sum is <= 1 (cannot
* clip); disabled keeps the original level like Kodi's "maintain original
* volume" (the 16-bit mix saturates on clip).
*/
fun stereoCoefficients(inputChannels: Int, centerBoostDb: Int, normalize: Boolean): FloatArray? {
val c = centerGain(centerBoostDb)
val s = SURROUND_GAIN
val rows: List<FloatArray> = when (inputChannels) {
3 -> listOf(fl(), fr(), both(c))
4 -> listOf(fl(), fr(), left(s), right(s))
5 -> listOf(fl(), fr(), both(c), left(s), right(s))
6 -> listOf(fl(), fr(), both(c), lfe(), left(s), right(s))
7 -> listOf(fl(), fr(), both(c), lfe(), left(s), right(s), both(BACK_CENTER_GAIN))
8 -> listOf(fl(), fr(), both(c), lfe(), left(s), right(s), left(s), right(s))
else -> return null
}
val flat = FloatArray(rows.size * 2)
rows.forEachIndexed { i, row ->
flat[i * 2] = row[0]
flat[i * 2 + 1] = row[1]
}
if (normalize) {
var sumL = 0f
var sumR = 0f
for (i in rows.indices) {
sumL += flat[i * 2]
sumR += flat[i * 2 + 1]
}
val peak = maxOf(sumL, sumR, 1f)
if (peak > 1f) {
for (i in flat.indices) flat[i] /= peak
}
}
return flat
}
private fun fl() = floatArrayOf(1f, 0f)
private fun fr() = floatArrayOf(0f, 1f)
private fun left(gain: Float) = floatArrayOf(gain, 0f)
private fun right(gain: Float) = floatArrayOf(0f, gain)
private fun both(gain: Float) = floatArrayOf(gain, gain)
private fun lfe() = floatArrayOf(0f, 0f)
}
File diff suppressed because it is too large Load Diff
@@ -2,13 +2,12 @@ package com.edde746.plezy.exoplayer
import android.app.Activity
import android.app.ActivityManager
import android.content.ContentResolver
import android.content.Context
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.util.Log
import com.edde746.plezy.libass.media.AssHandler
import com.edde746.plezy.mpv.MpvPlayerCore
import com.edde746.plezy.shared.MpvContentUriResolver
import com.edde746.plezy.shared.PlayerChannelBinding
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
@@ -26,18 +25,14 @@ class ExoPlayerPlugin :
companion object {
private const val TAG = "ExoPlayerPlugin"
private const val METHOD_CHANNEL = "com.plezy/exo_player"
private const val EVENT_CHANNEL = "com.plezy/exo_player/events"
private const val MPV_FALLBACK_SWITCH_TIMEOUT_MS = 15_000L
}
private lateinit var methodChannel: MethodChannel
private lateinit var eventChannel: EventChannel
private var eventSink: EventChannel.EventSink? = null
private val channels = PlayerChannelBinding(METHOD_CHANNEL, this, this, TAG)
private val mainHandler get() = channels.mainHandler
private var playerCore: ExoPlayerCore? = null
private var mpvCore: MpvPlayerCore? = null // MPV fallback player
private var usingMpvFallback: Boolean = false
private var fallbackInProgress: Boolean = false
private var pendingMpvFallbackSwitchGeneration: Int? = null
private var activity: Activity? = null
private var activityBinding: ActivityPluginBinding? = null
@@ -47,7 +42,6 @@ class ExoPlayerPlugin :
private data class ObservedProperty(val id: Int, val format: String)
private val observedProperties = LinkedHashMap<String, ObservedProperty>()
private val mainHandler = Handler(Looper.getMainLooper())
private var configuredBufferSizeBytes: Int? = null
private var sessionGeneration = 0
@@ -60,23 +54,16 @@ class ExoPlayerPlugin :
// fallback is already active) so one playback's properties never leak into
// the next session's fallback.
private val pendingMpvProperties = LinkedHashMap<String, String>()
private var currentExternalSubtitles: List<Map<String, Any?>>? = null
// FlutterPlugin
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
methodChannel = MethodChannel(binding.binaryMessenger, METHOD_CHANNEL)
methodChannel.setMethodCallHandler(this)
eventChannel = EventChannel(binding.binaryMessenger, EVENT_CHANNEL)
eventChannel.setStreamHandler(this)
Log.d(TAG, "Attached to engine")
channels.attach(binding)
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
methodChannel.setMethodCallHandler(null)
eventChannel.setStreamHandler(null)
Log.d(TAG, "Detached from engine")
channels.detach()
}
// ActivityAware
@@ -95,7 +82,7 @@ class ExoPlayerPlugin :
mpvCore = null
usingMpvFallback = false
fallbackInProgress = false
clearPendingMpvFallbackSwitch()
currentExternalSubtitles = null
pendingMpvProperties.clear()
activity = null
activityBinding = null
@@ -111,7 +98,6 @@ class ExoPlayerPlugin :
override fun onDetachedFromActivityForConfigChanges() {
sessionGeneration++
fallbackInProgress = false
clearPendingMpvFallbackSwitch()
activity = null
activityBinding = null
Log.d(TAG, "Detached from activity for config changes")
@@ -120,13 +106,11 @@ class ExoPlayerPlugin :
// EventChannel.StreamHandler
override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
eventSink = events
Log.d(TAG, "Event stream connected")
channels.listen(events)
}
override fun onCancel(arguments: Any?) {
eventSink = null
Log.d(TAG, "Event stream disconnected")
channels.cancel()
}
// MethodChannel.MethodCallHandler
@@ -169,6 +153,8 @@ class ExoPlayerPlugin :
"setVideoZoom" -> handleSetVideoZoom(call, result)
"setDvConversionMode" -> handleSetDvConversionMode(call, result)
"setAudioNormalization" -> handleSetAudioNormalization(call, result)
"setAudioPassthrough" -> handleSetAudioPassthrough(call, result)
"setAudioDownmix" -> handleSetAudioDownmix(call, result)
"observeProperty" -> handleObserveProperty(call, result)
"setMpvProperty" -> handleSetMpvProperty(call, result)
"setLogLevel" -> {
@@ -201,7 +187,13 @@ class ExoPlayerPlugin :
val bufferSizeBytes = call.argument<Int>("bufferSizeBytes")
val tunnelingEnabled = call.argument<Boolean>("tunnelingEnabled") ?: true
val dvConversionMode = call.argument<String>("dvConversionMode") ?: "auto"
val audioPassthroughEnabled = call.argument<Boolean>("audioPassthroughEnabled") ?: false
val assVideoLatencyFrames = call.argument<Int>("assVideoLatencyFrames") ?: 0
val subtitleRenderScale = call.argument<Double>("subtitleRenderScale")?.toFloat() ?: 1.0f
configuredBufferSizeBytes = bufferSizeBytes
// Global libass overlay render scale — set before the player/handler is built below so the
// first frame-size apply already uses it.
AssHandler.setRenderScale(subtitleRenderScale)
currentActivity.runOnUiThread {
sessionGeneration++
@@ -214,29 +206,37 @@ class ExoPlayerPlugin :
mpvCore = null
usingMpvFallback = false
fallbackInProgress = false
clearPendingMpvFallbackSwitch()
}
try {
playerCore = ExoPlayerCore(currentActivity).apply {
val core = ExoPlayerCore(currentActivity).apply {
delegate = this@ExoPlayerPlugin
this.debugLoggingEnabled = this@ExoPlayerPlugin.debugLoggingEnabled
}
val success = playerCore?.initialize(
playerCore = core
val success = core.initialize(
bufferSizeBytes = bufferSizeBytes,
tunnelingEnabled = tunnelingEnabled
) ?: false
if (success && playerCore?.setDebugDvConversionMode(dvConversionMode) != true) {
tunnelingEnabled = tunnelingEnabled,
audioPassthroughEnabled = audioPassthroughEnabled
)
if (!success) {
if (playerCore === core) playerCore = null
result.success(false)
return@runOnUiThread
}
if (core.setDebugDvConversionMode(dvConversionMode) != true) {
Log.w(TAG, "Invalid DV conversion mode during initialize: $dvConversionMode")
}
// Seed from this device's persisted calibration, falling back to the Dart perf-tier proxy.
core.seedAssVideoLatencyFrames(assVideoLatencyFrames)
core.setVisible(false)
// Start hidden
playerCore?.setVisible(false)
Log.d(TAG, "Initialized: $success")
result.success(success)
Log.d(TAG, "Initialized: true")
result.success(true)
} catch (e: Exception) {
Log.e(TAG, "Failed to initialize: ${e.message}", e)
playerCore?.dispose()
playerCore = null
result.error("INIT_FAILED", e.message, null)
}
}
@@ -251,7 +251,7 @@ class ExoPlayerPlugin :
mpvCore = null
usingMpvFallback = false
fallbackInProgress = false
clearPendingMpvFallbackSwitch()
currentExternalSubtitles = null
pendingMpvProperties.clear()
Log.d(TAG, "Disposed")
result.success(null)
@@ -263,6 +263,7 @@ class ExoPlayerPlugin :
val uri = call.argument<String>("uri")
val headers = call.argument<Map<String, String>>("headers")
val startPositionMs = call.argument<Number>("startPositionMs")?.toLong() ?: 0L
val hasStartPosition = call.argument<Boolean>("hasStartPosition") ?: (startPositionMs > 0L)
val autoPlay = call.argument<Boolean>("autoPlay") ?: true
val isLive = call.argument<Boolean>("isLive") ?: false
val externalSubtitles = call.argument<List<Map<String, Any?>>>("externalSubtitles")
@@ -271,37 +272,68 @@ class ExoPlayerPlugin :
result.error("INVALID_ARGS", "Missing 'uri'", null)
return
}
val currentActivity = activity
if (currentActivity == null) {
result.error("NO_ACTIVITY", "Activity not available", null)
return
}
val externalSubtitleSnapshot = externalSubtitles?.map { it.toMap() }
currentExternalSubtitles = externalSubtitleSnapshot
// Only clear pending MPV state when MPV is the active backend. A same-core
// MPV reload must not inherit a fallback switch that was armed for the
// previous load. When ExoPlayer is active, keep queued properties for a
// potential ExoPlayer→MPV fallback.
if (usingMpvFallback) {
clearPendingMpvFallbackSwitch()
pendingMpvProperties.clear()
val generation = sessionGeneration
MpvContentUriResolver.resolve(uri, currentActivity.contentResolver, mainHandler) { source ->
if (generation != sessionGeneration || activity !== currentActivity || !usingMpvFallback) {
source.closeIfUnused()
result.success(null)
return@resolve
}
loadMpvMedia(
source.value,
headers,
startPositionMs,
hasStartPosition,
autoPlay,
externalSubtitleSnapshot
)
result.success(null)
}
return
}
activity?.runOnUiThread {
if (usingMpvFallback) {
// MPV: Build loadfile command with options
val startSeconds = startPositionMs / 1000.0
val options = mutableListOf<String>()
options.add("start=$startSeconds")
if (!autoPlay) options.add("pause=yes")
options.add("sid=no")
options.add("secondary-sid=no")
headers?.forEach { (key, value) ->
options.add("http-header-fields-append=$key: $value")
}
val optionsStr = options.joinToString(",")
// Convert content:// URIs to fdclose:// for MPV (SAF SD card downloads)
val mpvUri = openContentFd(uri)?.let { "fdclose://$it" } ?: uri
mpvCore?.command(arrayOf("loadfile", mpvUri, "replace", "-1", optionsStr))
} else {
playerCore?.open(uri, headers, startPositionMs, autoPlay, isLive, externalSubtitles)
}
currentActivity.runOnUiThread {
playerCore?.open(uri, headers, startPositionMs, autoPlay, isLive, externalSubtitleSnapshot)
result.success(null)
} ?: result.error("NO_ACTIVITY", "Activity not available", null)
}
}
private fun loadMpvMedia(
uri: String,
headers: Map<String, String>?,
startPositionMs: Long,
hasStartPosition: Boolean,
autoPlay: Boolean,
externalSubtitles: List<Map<String, Any?>>?
) {
val startSeconds = startPositionMs / 1000.0
val options = mutableListOf<String>()
options.add(if (hasStartPosition && startPositionMs > 0L) "start=$startSeconds" else "start=none")
if (!autoPlay) options.add("pause=yes")
options.add("sid=no")
options.add("secondary-sid=no")
appendExternalSubtitleOptions(options, externalSubtitles)
appendHttpHeaderOptions(options, headers)
val optionsStr = options.joinToString(",")
mpvCore?.command(arrayOf("loadfile", uri, "replace", "-1", optionsStr)) { success ->
if (success && autoPlay) {
mpvCore?.setProperty("pause", "no")
}
}
}
private fun handlePlay(result: MethodChannel.Result) {
@@ -441,11 +473,18 @@ class ExoPlayerPlugin :
activity?.runOnUiThread {
if (usingMpvFallback) {
val selectFlag = if (select) "select" else "auto"
mpvCore?.command(arrayOf("sub-add", uri, selectFlag, title ?: "External"))
val core = mpvCore
if (core == null) {
result.success(null)
} else {
core.command(arrayOf("sub-add", uri, selectFlag, title ?: "External")) {
result.success(null)
}
}
} else {
playerCore?.addSubtitleTrack(uri, title, language, mimeType, select)
result.success(null)
}
result.success(null)
} ?: result.success(null)
}
@@ -478,22 +517,24 @@ class ExoPlayerPlugin :
val fps = call.argument<Double>("fps")?.toFloat() ?: 0f
val duration = call.argument<Number>("duration")?.toLong() ?: 0L
val extraDelayMs = call.argument<Number>("extraDelayMs")?.toLong() ?: 0L
val videoWidth = call.argument<Number>("videoWidth")?.toInt() ?: 0
val videoHeight = call.argument<Number>("videoHeight")?.toInt() ?: 0
Log.d(TAG, "setVideoFrameRate: fps=$fps, duration=$duration, extraDelayMs=$extraDelayMs")
Log.d(TAG, "setVideoFrameRate: fps=$fps, duration=$duration, extraDelayMs=$extraDelayMs, video=${videoWidth}x$videoHeight")
val onComplete: (Boolean) -> Unit = { switched -> result.success(switched) }
if (usingMpvFallback) {
val core = mpvCore
if (core == null) {
result.success(false)
} else {
core.setVideoFrameRate(fps, duration, extraDelayMs, onComplete)
core.setVideoFrameRate(fps, duration, extraDelayMs, videoWidth, videoHeight, onComplete)
}
} else {
val core = playerCore
if (core == null) {
result.success(false)
} else {
core.setVideoFrameRate(fps, duration, extraDelayMs, onComplete)
core.setVideoFrameRate(fps, duration, extraDelayMs, videoWidth, videoHeight, onComplete)
}
}
}
@@ -635,6 +676,45 @@ class ExoPlayerPlugin :
} ?: result.error("NO_ACTIVITY", "Activity not available", null)
}
private fun handleSetAudioDownmix(call: MethodCall, result: MethodChannel.Result) {
val enabled = call.argument<Boolean>("enabled")
if (enabled == null) {
result.error("INVALID_ARGS", "Missing 'enabled'", null)
return
}
val centerBoostDb = call.argument<Int>("centerBoostDb") ?: 0
val normalize = call.argument<Boolean>("normalize") ?: true
if (usingMpvFallback) {
// mpv applies downmix via the audio-channels/audio-swresample-o
// properties the Dart layer also sends through setMpvProperty.
result.success(true)
return
}
activity?.runOnUiThread {
playerCore?.setAudioDownmix(enabled, centerBoostDb, normalize)
result.success(true)
} ?: result.error("NO_ACTIVITY", "Activity not available", null)
}
private fun handleSetAudioPassthrough(call: MethodCall, result: MethodChannel.Result) {
val enabled = call.argument<Boolean>("enabled")
if (enabled == null) {
result.error("INVALID_ARGS", "Missing 'enabled'", null)
return
}
val audioSpdif = if (enabled) "ac3,eac3,dts,dts-hd,truehd" else ""
pendingMpvProperties["audio-spdif"] = audioSpdif
if (usingMpvFallback) {
mpvCore?.setProperty("audio-spdif", audioSpdif)
result.success(true)
return
}
activity?.runOnUiThread {
playerCore?.setAudioPassthrough(enabled)
result.success(true)
} ?: result.error("NO_ACTIVITY", "Activity not available", null)
}
private fun handleSetMpvProperty(call: MethodCall, result: MethodChannel.Result) {
val name = call.argument<String>("name")
val value = call.argument<String>("value")
@@ -652,6 +732,7 @@ class ExoPlayerPlugin :
// mpv semantics mirrored on the libass overlay: anchor non-positioned ASS
// events to the visible screen (Dart sets 'yes' for cover mode / zoom > 1)
"sub-ass-force-margins" -> playerCore?.setAssForceMargins(value == "yes")
"force-seekable" -> playerCore?.setForceSeekable(value == "yes")
}
}
@@ -667,8 +748,15 @@ class ExoPlayerPlugin :
private fun handleGetStats(result: MethodChannel.Result) {
if (usingMpvFallback) {
Thread {
val stats = getMpvStats()
activity?.runOnUiThread { result.success(stats) }
val stats = try {
getMpvStats()
} catch (error: Throwable) {
Log.w(TAG, "Failed to collect mpv fallback stats", error)
mapOf("playerType" to "mpv")
}
// Platform-channel replies must return to Android's platform thread.
// Do not depend on an Activity: it may detach while this work runs.
mainHandler.post { result.success(stats) }
}.start()
} else {
activity?.runOnUiThread {
@@ -683,59 +771,7 @@ class ExoPlayerPlugin :
* Queries relevant MPV properties and returns them in a map format
* compatible with the performance overlay.
*/
private fun getMpvStats(): Map<String, Any?> {
val mpv = mpvCore ?: return mapOf("playerType" to "mpv")
val hasVideo = mpv.getProperty("video-params/w") != null
val stats = mutableMapOf<String, Any?>(
"playerType" to "mpv",
// Video metrics
"video-codec" to mpv.getProperty("video-codec"),
"video-params/w" to mpv.getProperty("video-params/w"),
"video-params/h" to mpv.getProperty("video-params/h"),
"videoWidth" to mpv.getProperty("dwidth"),
"videoHeight" to mpv.getProperty("dheight"),
"container-fps" to mpv.getProperty("container-fps"),
"estimated-vf-fps" to mpv.getProperty("estimated-vf-fps"),
"video-bitrate" to mpv.getProperty("video-bitrate"),
"hwdec-current" to mpv.getProperty("hwdec-current"),
// Audio metrics
"audio-codec-name" to mpv.getProperty("audio-codec-name"),
"audio-params/samplerate" to mpv.getProperty("audio-params/samplerate"),
"audio-params/hr-channels" to mpv.getProperty("audio-params/hr-channels"),
"audio-bitrate" to mpv.getProperty("audio-bitrate"),
// Performance metrics
"total-avsync-change" to mpv.getProperty("total-avsync-change"),
"cache-used" to mpv.getProperty("cache-used"),
"demuxer-max-bytes" to mpv.getProperty("demuxer-max-bytes"),
"cache-speed" to mpv.getProperty("cache-speed"),
"frame-drop-count" to mpv.getProperty("frame-drop-count"),
"decoder-frame-drop-count" to mpv.getProperty("decoder-frame-drop-count"),
"demuxer-cache-duration" to mpv.getProperty("demuxer-cache-duration")
)
// Only query properties that require an active video track
if (hasVideo) {
stats["display-fps"] = mpv.getProperty("display-fps")
// Color/Format properties
stats["video-params/pixelformat"] = mpv.getProperty("video-params/pixelformat")
stats["video-params/hw-pixelformat"] = mpv.getProperty("video-params/hw-pixelformat")
stats["video-params/colormatrix"] = mpv.getProperty("video-params/colormatrix")
stats["video-params/primaries"] = mpv.getProperty("video-params/primaries")
stats["video-params/gamma"] = mpv.getProperty("video-params/gamma")
// HDR metadata
stats["video-params/max-luma"] = mpv.getProperty("video-params/max-luma")
stats["video-params/min-luma"] = mpv.getProperty("video-params/min-luma")
stats["video-params/max-cll"] = mpv.getProperty("video-params/max-cll")
stats["video-params/max-fall"] = mpv.getProperty("video-params/max-fall")
// Other
stats["video-params/aspect-name"] = mpv.getProperty("video-params/aspect-name")
stats["video-params/rotate"] = mpv.getProperty("video-params/rotate")
}
return stats
}
private fun getMpvStats(): Map<String, Any?> = mpvCore?.getStats() ?: mapOf("playerType" to "mpv")
// PiP Mode handling
@@ -753,68 +789,42 @@ class ExoPlayerPlugin :
override fun onPropertyChange(name: String, value: Any?) {
val propId = observedProperties[name]?.id ?: return
mainHandler.post { eventSink?.success(listOf(propId, value)) }
}
private fun eventPayload(name: String, data: Map<String, Any>? = null): Map<String, Any> {
val event = mutableMapOf<String, Any>(
"type" to "event",
"name" to name
)
data?.let { event["data"] = it }
return event
channels.emitProperty(propId, value)
}
override fun onEvent(name: String, data: Map<String, Any>?) {
val pendingFallbackSwitch =
name == "file-loaded" && pendingMpvFallbackSwitchGeneration == sessionGeneration && usingMpvFallback
if (pendingFallbackSwitch) {
clearPendingMpvFallbackSwitch()
}
val event = eventPayload(name, data)
mainHandler.post {
eventSink?.success(event)
if (pendingFallbackSwitch) {
eventSink?.success(eventPayload("backend-switched"))
}
}
channels.emitEvent(name, data)
}
private fun armPendingMpvFallbackSwitch(generation: Int) {
pendingMpvFallbackSwitchGeneration = generation
mainHandler.postDelayed({
if (pendingMpvFallbackSwitchGeneration == generation && sessionGeneration == generation && usingMpvFallback) {
Log.w(TAG, "Timed out waiting for MPV fallback file-loaded before backend-switched")
clearPendingMpvFallbackSwitch()
onEvent("backend-switched", null)
}
}, MPV_FALLBACK_SWITCH_TIMEOUT_MS)
private fun notifyBackendSwitched() {
channels.emitEvent("backend-switched")
}
private fun clearPendingMpvFallbackSwitch() {
pendingMpvFallbackSwitchGeneration = null
private fun appendExternalSubtitleOptions(
options: MutableList<String>,
externalSubtitles: List<Map<String, Any?>>?
) {
val escapedUris = externalSubtitles.orEmpty()
.mapNotNull { it["uri"] as? String }
.filter { it.isNotEmpty() }
.map(::escapeMpvPathListEntry)
.toList()
if (escapedUris.isEmpty()) return
val pathList = escapedUris.joinToString(":")
options.add("sub-files=%${pathList.toByteArray(Charsets.UTF_8).size}%$pathList")
}
/**
* Opens a content:// URI via ContentResolver and returns the raw FD number,
* or null if the URI is not a content:// scheme or opening fails.
* The returned FD is detached so MPV can own and close it via fdclose://.
*/
private fun openContentFd(
uriString: String,
resolver: ContentResolver? = activity?.contentResolver
): Int? {
if (!uriString.startsWith("content://")) return null
return try {
val uri = Uri.parse(uriString)
val pfd = resolver?.openFileDescriptor(uri, "r") ?: return null
val fd = pfd.detachFd()
Log.d(TAG, "Opened content FD $fd for $uriString")
fd
} catch (e: Exception) {
Log.e(TAG, "Failed to open content FD: ${e.message}", e)
null
private fun escapeMpvPathListEntry(value: String): String = value.replace("\\", "\\\\").replace(":", "\\:")
private fun appendHttpHeaderOptions(options: MutableList<String>, headers: Map<String, String>?) {
if (headers.isNullOrEmpty()) return
options.add("http-header-fields-clr=")
headers.forEach { (key, value) ->
val header = "$key: $value"
options.add("http-header-fields-append=%${header.toByteArray(Charsets.UTF_8).size}%$header")
}
}
@@ -829,84 +839,80 @@ class ExoPlayerPlugin :
act: Activity,
uri: String,
headers: Map<String, String>?,
positionMs: Long
positionMs: Long,
externalSubtitles: List<Map<String, Any?>>?,
playWhenReady: Boolean,
generation: Int
) {
// Snapshot Dart-registered state on main thread before clearing
// Snapshot Dart-registered state on main thread before clearing.
val pendingProps = pendingMpvProperties.toList()
pendingMpvProperties.clear()
val observedProps = observedProperties.toList()
// Compute content FD on main thread (needs contentResolver)
val mpvUri = openContentFd(uri, act.contentResolver)
?.let { "fdclose://$it" } ?: uri
// Buffer size for closure
val bufferSize = configuredBufferSizeBytes
if (mpvCore !== core) {
core.dispose()
fallbackInProgress = false
clearPendingMpvFallbackSwitch()
return
}
// Configure basic MPV properties for Plex playback
core.setProperty("hwdec", "mediacodec,mediacodec-copy")
core.setProperty("vo", "gpu")
core.setProperty("ao", "audiotrack")
// Forward user's buffer config to MPV fallback
if (bufferSize != null && bufferSize > 0) {
core.setProperty("demuxer-max-bytes", bufferSize.toString())
}
// Apply pending MPV properties from Dart
for ((propName, propValue) in pendingProps) {
core.setProperty(propName, propValue)
}
// Re-observe exactly what Dart registered via observeProperty, so the
// event stream keeps flowing for every property the Dart side consumes.
for ((propName, observed) in observedProps) {
core.observeProperty(propName, observed.format)
}
// Show the MPV surface (internally posts to UI)
core.setVisible(true)
// Load media at the same position
val startSeconds = positionMs / 1000.0
val options = mutableListOf<String>()
options.add("start=$startSeconds")
headers?.forEach { (key, value) ->
options.add("http-header-fields-append=$key: $value")
}
val optionsStr = options.joinToString(",")
armPendingMpvFallbackSwitch(sessionGeneration)
core.command(arrayOf("loadfile", mpvUri, "replace", "-1", optionsStr))
// On GPUs without compute shaders, MPV can't do dynamic peak detection
// and spline tone-mapping produces dim/washed-out results with extreme
// static HDR peak metadata. Use reinhard which handles this better.
Thread {
val peakDetection = core.getProperty("hdr-compute-peak")
if (peakDetection == "no") {
Log.i(TAG, "No compute shaders — overriding tone-mapping to reinhard")
core.setProperty("tone-mapping", "reinhard")
core.setProperty("tone-mapping-param", "0.7")
core.setProperty("tone-mapping-mode", "luma")
MpvContentUriResolver.resolve(uri, act.contentResolver, mainHandler) { source ->
if (generation != sessionGeneration || mpvCore !== core || activity !== act || !usingMpvFallback) {
source.closeIfUnused()
core.dispose()
return@resolve
}
}.start()
// Request audio focus
core.requestAudioFocus()
// Configure basic MPV properties for Plex playback.
core.setProperty("hwdec", "mediacodec,mediacodec-copy")
core.setProperty("vo", "gpu")
core.setProperty("ao", "audiotrack")
Log.i(TAG, "Successfully switched to MPV fallback")
if (bufferSize != null && bufferSize > 0) {
core.setProperty("demuxer-max-bytes", bufferSize.toString())
}
for ((propName, propValue) in pendingProps) {
core.setProperty(propName, propValue)
}
// Re-observe exactly what Dart registered via observeProperty, so the
// event stream keeps flowing for every property the Dart side consumes.
for ((propName, observed) in observedProps) {
core.observeProperty(propName, observed.format)
}
core.setVisible(true)
val startSeconds = positionMs / 1000.0
val options = mutableListOf<String>()
options.add(if (positionMs > 0L) "start=$startSeconds" else "start=none")
if (!playWhenReady) options.add("pause=yes")
options.add("sid=no")
options.add("secondary-sid=no")
appendExternalSubtitleOptions(options, externalSubtitles)
appendHttpHeaderOptions(options, headers)
val optionsStr = options.joinToString(",")
notifyBackendSwitched()
core.command(arrayOf("loadfile", source.value, "replace", "-1", optionsStr))
// On GPUs without compute shaders, MPV can't do dynamic peak detection
// and spline tone-mapping produces dim/washed-out results with extreme
// static HDR peak metadata. Use reinhard which handles this better.
Thread {
val peakDetection = core.getProperty("hdr-compute-peak")
if (peakDetection == "no") {
Log.i(TAG, "No compute shaders — overriding tone-mapping to reinhard")
core.setProperty("tone-mapping", "reinhard")
core.setProperty("tone-mapping-param", "0.7")
core.setProperty("tone-mapping-mode", "luma")
}
}.start()
core.requestAudioFocus()
Log.i(TAG, "Successfully switched to MPV fallback")
}
}
override fun onFormatUnsupported(
uri: String,
headers: Map<String, String>?,
positionMs: Long,
playWhenReady: Boolean,
errorMessage: String
): Boolean {
if (usingMpvFallback || fallbackInProgress) {
@@ -915,6 +921,7 @@ class ExoPlayerPlugin :
}
val currentActivity = activity ?: return false
val fallbackExternalSubtitles = currentExternalSubtitles?.map { it.toMap() }
fallbackInProgress = true
Log.i(TAG, "ExoPlayer error, switching to MPV fallback at ${positionMs}ms: $errorMessage")
@@ -937,20 +944,17 @@ class ExoPlayerPlugin :
mpvCore?.dispose()
mpvCore = null
usingMpvFallback = false // Clear before handoff
clearPendingMpvFallbackSwitch()
val generation = sessionGeneration
Handler(Looper.getMainLooper()).post {
mainHandler.post {
if (generation != sessionGeneration) {
fallbackInProgress = false
clearPendingMpvFallbackSwitch()
return@post
}
val act = activity
if (act == null) {
fallbackInProgress = false
clearPendingMpvFallbackSwitch()
return@post
}
@@ -967,7 +971,6 @@ class ExoPlayerPlugin :
mpvCore = null
}
fallbackInProgress = false
clearPendingMpvFallbackSwitch()
return@initialize
}
if (!success) {
@@ -976,7 +979,6 @@ class ExoPlayerPlugin :
mpvCore = null
}
fallbackInProgress = false
clearPendingMpvFallbackSwitch()
Log.e(TAG, "Failed to initialize MPV fallback")
onEvent("end-file", mapOf("reason" to "error", "message" to "Fallback failed: $errorMessage"))
return@initialize
@@ -985,18 +987,16 @@ class ExoPlayerPlugin :
usingMpvFallback = true
fallbackInProgress = false
setupMpvFallback(core, act, uri, headers, positionMs)
setupMpvFallback(core, act, uri, headers, positionMs, fallbackExternalSubtitles, playWhenReady, generation)
}
} catch (e: Exception) {
fallbackInProgress = false
clearPendingMpvFallbackSwitch()
Log.e(TAG, "Failed to switch to MPV fallback", e)
onEvent("end-file", mapOf("reason" to "error", "message" to "Fallback failed: ${e.message}"))
}
}
} catch (e: Exception) {
fallbackInProgress = false
clearPendingMpvFallbackSwitch()
Log.e(TAG, "Failed to switch to MPV fallback", e)
onEvent("end-file", mapOf("reason" to "error", "message" to "Fallback failed: ${e.message}"))
}
@@ -0,0 +1,112 @@
package com.edde746.plezy.exoplayer
import android.util.Log
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 (and
* therefore Plex'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)
}
/**
* MatroskaExtractor with LOAS/LATM AAC support, used for Plex Live TV MKV
* streams (which bypass the ASS/DV extractor chain). VOD playback gets the
* same LATM handling via ZlibMatroskaExtractor.
*/
class LatmMatroskaExtractor(flags: Int) : MatroskaExtractor(flags) {
companion object {
private const val TAG = "LatmMkvExtractor"
private const val ID_SEGMENT = 0x18538067
private const val ID_TRACK_ENTRY = 0xAE
}
private var latmWrapper: LatmExtractorOutputWrapper? = null
override fun startMasterElement(id: Int, contentPosition: Long, contentSize: Long) {
super.startMasterElement(id, contentPosition, contentSize)
// init() is final, so install the wrapping output when the Segment starts —
// before any TrackEntry can create a track through it.
if (id == ID_SEGMENT && latmWrapper == null) {
val currentOutput = matroskaExtractorOutputField.get(this) as ExtractorOutput
val wrapper = LatmExtractorOutputWrapper(currentOutput)
latmWrapper = wrapper
matroskaExtractorOutputField.set(this, wrapper)
}
}
override fun endMasterElement(id: Int) {
if (id == ID_TRACK_ENTRY) {
val track = getCurrentTrack(id)
if (isLoasAcmTrack(track.codecId, track.codecPrivate)) {
Log.i(TAG, "Track ${track.number} is LOAS/LATM AAC, unwrapping to raw AAC")
latmWrapper?.markNextTrackLatm()
}
}
super.endMasterElement(id)
}
override fun seek(position: Long, timeUs: Long) {
latmWrapper?.resetTracks()
super.seek(position, timeUs)
}
}
@@ -0,0 +1,156 @@
package com.edde746.plezy.exoplayer
import android.util.Log
import androidx.media3.common.C
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.ExtractorOutput
import androidx.media3.extractor.SeekMap
import androidx.media3.extractor.TrackOutput
import androidx.media3.extractor.ts.LatmReader
import androidx.media3.extractor.ts.TsPayloadReader
import java.io.EOFException
/**
* TrackOutput wrapper that unwraps LOAS/LATM-framed AAC (MKV A_MS/ACM with
* WAVEFORMATEX tag 0x1602) into raw AAC access units MediaCodec can decode.
*
* Each MKV block payload is one or more complete LOAS AudioSyncStream frames.
* Blocks are buffered between sampleData() and sampleMetadata(), then fed to
* media3's LatmReader, which parses the StreamMuxConfig (emitting a proper AAC
* Format with AudioSpecificConfig) and outputs byte-aligned raw AAC samples.
*
* The parent extractor's audio/x-unknown Format is swallowed; its track-selection
* metadata (id, label, language, selection flags) is merged onto the Format
* LatmReader derives from the stream.
*/
class LatmTrackOutput(
private val delegate: TrackOutput,
private val trackId: Int
) : TrackOutput {
companion object {
private const val TAG = "LatmTrackOutput"
private const val INITIAL_BUFFER_SIZE = 4 * 1024
private const val MAX_LOGGED_ERRORS = 3
}
private var latmReader: LatmReader? = null
private var originalFormat: Format? = null
private val parsable = ParsableByteArray()
// Reusable block buffer — grown as needed, never shrunk
private var buf = ByteArray(INITIAL_BUFFER_SIZE)
private var bufLen = 0
private var readBuf = ByteArray(INITIAL_BUFFER_SIZE)
private var errorCount = 0
/** Forwards LatmReader's decoded Format merged with the original track metadata. */
private val mergeProxy = object : TrackOutput {
override fun format(format: Format) {
val original = originalFormat
val merged = if (original == null) {
format
} else {
format.buildUpon()
.setId(original.id)
.setLabel(original.label)
.setLanguage(original.language ?: format.language)
.setSelectionFlags(original.selectionFlags)
.build()
}
delegate.format(merged)
}
override fun sampleData(input: DataReader, length: Int, allowEndOfInput: Boolean, sampleDataPart: Int): Int = delegate.sampleData(input, length, allowEndOfInput, sampleDataPart)
override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) = delegate.sampleData(data, length, sampleDataPart)
override fun sampleMetadata(timeUs: Long, flags: Int, size: Int, offset: Int, cryptoData: TrackOutput.CryptoData?) = delegate.sampleMetadata(timeUs, flags, size, offset, cryptoData)
}
private val readerExtractorOutput = object : ExtractorOutput {
override fun track(id: Int, type: Int): TrackOutput = mergeProxy
override fun endTracks() {}
override fun seekMap(seekMap: SeekMap) {}
}
override fun format(format: Format) {
originalFormat = format
if (latmReader == null) {
latmReader = LatmReader(format.language, format.roleFlags, MimeTypes.VIDEO_MATROSKA).also {
it.createTracks(readerExtractorOutput, TsPayloadReader.TrackIdGenerator(trackId, 1))
}
}
// Swallow the parent's audio/x-unknown Format; LatmReader emits the real
// AAC Format (with AudioSpecificConfig) from the first StreamMuxConfig.
}
override fun sampleData(
input: DataReader,
length: Int,
allowEndOfInput: Boolean,
sampleDataPart: Int
): Int {
if (readBuf.size < length) readBuf = ByteArray(length)
val bytesRead = input.read(readBuf, 0, length)
if (bytesRead == C.RESULT_END_OF_INPUT && !allowEndOfInput) throw EOFException()
if (bytesRead > 0) append(readBuf, bytesRead)
return bytesRead
}
override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) {
ensureCapacity(bufLen + length)
data.readBytes(buf, bufLen, length)
bufLen += length
}
override fun sampleMetadata(
timeUs: Long,
flags: Int,
size: Int,
offset: Int,
cryptoData: TrackOutput.CryptoData?
) {
// offset counts down to 0 across a laced BlockGroup; the buffer holds the
// whole block's data, so slice this sample out and clear at the last one.
val start = bufLen - offset - size
val reader = latmReader
if (reader == null || start < 0) {
if (errorCount++ < MAX_LOGGED_ERRORS) {
Log.e(TAG, "Dropping sample (reader=${reader != null}, start=$start, size=$size, offset=$offset)")
}
if (offset == 0) bufLen = 0
return
}
try {
reader.packetStarted(timeUs, 0)
parsable.reset(buf, start + size)
parsable.position = start
reader.consume(parsable)
} catch (e: Exception) {
if (errorCount++ < MAX_LOGGED_ERRORS) {
Log.e(TAG, "LATM parse failed (${size}B), dropping sample", e)
}
reader.seek() // resync on the next LOAS syncword
}
if (offset == 0) bufLen = 0
}
/** Drops buffered MKV data while retaining the LATM StreamMuxConfig. */
fun reset() {
bufLen = 0
}
private fun append(src: ByteArray, length: Int) {
ensureCapacity(bufLen + length)
System.arraycopy(src, 0, buf, bufLen, length)
bufLen += length
}
private fun ensureCapacity(needed: Int) {
if (buf.size < needed) buf = buf.copyOf(maxOf(needed, buf.size * 2))
}
}
@@ -8,6 +8,8 @@ import androidx.annotation.OptIn
import androidx.media3.common.Format
import androidx.media3.common.MimeTypes
import androidx.media3.common.PlaybackParameters
import androidx.media3.common.audio.ChannelMixingAudioProcessor
import androidx.media3.common.audio.ChannelMixingMatrix
import androidx.media3.common.util.Clock
import androidx.media3.common.util.UnstableApi
import androidx.media3.decoder.DecoderInputBuffer
@@ -25,6 +27,7 @@ import androidx.media3.exoplayer.mediacodec.MediaCodecAdapter
import androidx.media3.exoplayer.mediacodec.MediaCodecSelector
import androidx.media3.exoplayer.video.MediaCodecVideoRenderer
import androidx.media3.exoplayer.video.VideoRendererEventListener
import com.edde746.plezy.TvDetection
import java.nio.ByteBuffer
import java.util.concurrent.atomic.AtomicLong
import kotlin.math.abs
@@ -32,9 +35,26 @@ import kotlin.math.abs
@OptIn(UnstableApi::class)
class PlezyRenderersFactory(context: Context) : DefaultRenderersFactory(context) {
/**
* Android TV: MediaCodec.setOutputSurface is broken on many TV SoCs (Sony Bravia
* MediaTek etc., ExoPlayer #5119/#8329) — force full codec re-init on surface
* changes instead (#1481). TV-only: phones keep the fast path for PiP churn.
*/
private val forceSetOutputSurfaceWorkaround: Boolean = TvDetection.isTv(context)
/** Audio delay in microseconds. Shared with PositionFixAudioSink for live updates. */
val audioDelayUs = AtomicLong(0L)
/**
* Stereo-downmix processor; inactive while every registered matrix is identity.
* Pre-populated for counts 1..12 so sink configure can never hit
* "No mixing matrix for input channel count". ExoPlayerCore swaps in
* downmix matrices via [DownmixMatrices] when the setting is enabled.
*/
val channelMixProcessor = ChannelMixingAudioProcessor().apply {
for (count in 1..12) putChannelMixingMatrix(ChannelMixingMatrix.create(count, count))
}
/** Returns whether direct encoded output should be hidden so decoded PCM output can be selected. */
var shouldBlockDirectAudioOutput: ((Format) -> Boolean)? = null
@@ -79,6 +99,7 @@ class PlezyRenderersFactory(context: Context) : DefaultRenderersFactory(context)
.setEventHandler(eventHandler)
.setEventListener(eventListener)
.setMaxDroppedFramesToNotify(MAX_DROPPED_VIDEO_FRAME_COUNT_TO_NOTIFY),
forceSetOutputSurfaceWorkaround,
videoDiagnosticsLogger
)
}
@@ -107,6 +128,9 @@ class PlezyRenderersFactory(context: Context) : DefaultRenderersFactory(context)
val defaultSink = DefaultAudioSink.Builder(context)
.setEnableFloatOutput(enableFloatOutput)
.setEnableAudioOutputPlaybackParameters(enableAudioOutputPlaybackParams)
// Wraps in DefaultAudioProcessorChain, keeping stock silence-skip +
// Sonic; the downmix runs first and only in the decoded-PCM path.
.setAudioProcessors(arrayOf(channelMixProcessor))
.setAudioOutputProvider(RawPositionOutputProvider(realProvider, rawPositionUs, audioDiagnosticsLogger))
.build()
@@ -341,6 +365,7 @@ internal class SubtitleDelayRenderer(
@OptIn(UnstableApi::class)
internal class DvSanitizingVideoRenderer(
builder: Builder,
private val forceSetOutputSurfaceWorkaround: Boolean,
private val log: ((String, String, String) -> Unit)?
) : MediaCodecVideoRenderer(builder) {
@@ -348,6 +373,26 @@ internal class DvSanitizingVideoRenderer(
private var stripHdr10PlusSei = false
private var stripDvRpu = false
private var loggedSurfaceWorkaround = false
// On TV SoCs MediaCodec.setOutputSurface() silently yields a black picture after
// the screensaver/background destroys and recreates the surface (#1481). Returning
// true makes media3 release + re-init the codec instead. media3's built-in device
// list doesn't cover 2019+ Bravias; consulted once per codec init.
override fun codecNeedsSetOutputSurfaceWorkaround(name: String): Boolean {
if (forceSetOutputSurfaceWorkaround) {
if (!loggedSurfaceWorkaround) {
loggedSurfaceWorkaround = true
log?.invoke(
"info",
"video",
"TV setOutputSurface workaround active: codec will fully re-init on surface changes (codec=$name)"
)
}
return true
}
return super.codecNeedsSetOutputSurfaceWorkaround(name)
}
// Sanitize diagnostics — playback-thread only, cumulative for the renderer's lifetime.
private var sanitizedSampleCount = 0L
@@ -0,0 +1,59 @@
package com.edde746.plezy.exoplayer
import androidx.media3.common.C
/**
* Decision logic for the post-resume video stall watchdog (#1454).
*
* Some TV SoCs (the Amlogic Mi Box class) stall the MediaCodec output path after a
* pause -> resume: the playback clock and audio keep advancing but no new video
* frame reaches the screen until the codec is flushed by a seek. The watchdog
* snapshots the rendered-frame counter when playback resumes and evaluates it one
* check window later; a confirmed stall is recovered with a small backward seek
* (ExoPlayer short-circuits a same-position seek without resetting renderers, so
* the recovery must move by a nonzero delta to force the codec flush).
*/
internal object ResumeStallPolicy {
/** Floor for the check window; frame-interval scaling only ever raises it. */
const val DEFAULT_CHECK_WINDOW_MS = 1000L
/** Frames that must have been due within the window before calling it a stall. */
const val MIN_FRAME_INTERVALS = 4
/** Assumed fps when neither the format nor timestamp detection knows it. */
const val FALLBACK_FPS = 24f
/** Recovery seek delta. Must stay under the 350ms watch-together drift deadband. */
const val SEEK_BACK_MS = 250L
/** Re-checks allowed while the clock itself is not advancing (generic stall, not this bug). */
const val MAX_RECHECKS = 2
/** Recovery cap per media session; a pathological stream stops arming after this. */
const val MAX_RECOVERIES_PER_SESSION = 5
enum class Verdict { HEALTHY, RECHECK, SKIP_NEAR_EOF, STALLED }
/** Window sized so even low-fps or slowed-down content has had several frames due. */
fun checkWindowMs(formatFps: Float?, detectedFps: Float?, speed: Float): Long {
val fps = formatFps?.takeIf { it > 1f } ?: detectedFps?.takeIf { it > 1f } ?: FALLBACK_FPS
val frameIntervalMs = (1000f / fps / speed.coerceAtLeast(0.25f)).toLong()
return maxOf(DEFAULT_CHECK_WINDOW_MS, MIN_FRAME_INTERVALS * frameIntervalMs)
}
fun evaluate(
baselineFrames: Int,
currentFrames: Int,
baselinePositionMs: Long,
currentPositionMs: Long,
durationMs: Long,
windowMs: Long
): Verdict = when {
// Any counter movement counts as healthy, including a renderer re-enable
// resetting DecoderCounters below the baseline.
currentFrames != baselineFrames -> Verdict.HEALTHY
currentPositionMs - baselinePositionMs < windowMs / 2 -> Verdict.RECHECK
durationMs != C.TIME_UNSET && durationMs - currentPositionMs < 2 * windowMs -> Verdict.SKIP_NEAR_EOF
else -> Verdict.STALLED
}
}
@@ -0,0 +1,77 @@
package com.edde746.plezy.exoplayer
import androidx.annotation.OptIn
import androidx.media3.common.text.Cue
import androidx.media3.common.util.UnstableApi
@OptIn(UnstableApi::class)
internal object SubtitleCueLayout {
fun layout(cues: List<Cue>, positionPercent: Int, fontSize: Float): List<Cue> = applyPosition(stackUnpositioned(cues), positionPercent, fontSize)
// SRT carries no per-cue positioning, so SubripParser emits cues with
// lineType = TYPE_UNSET. SubtitlePainter then renders every such cue at the
// same default bottom-anchored position, causing visible overlap when more
// than one is active. Reassign line numbers from the bottom up so concurrent
// unpositioned cues stack instead. Workaround for
// https://github.com/androidx/media/issues/2237; can be removed once
// https://github.com/androidx/media/pull/3151 lands and we upgrade Media3.
private fun stackUnpositioned(cues: List<Cue>): List<Cue> {
if (cues.size < 2) return cues
val toStack = cues.indices.filter {
cues[it].lineType == Cue.TYPE_UNSET && cues[it].text != null
}
if (toStack.size < 2) return cues
val rebuilt = cues.toMutableList()
var nextRow = -1
// Reverse so the last cue in the group lands on row -1 (bottom).
for (idx in toStack.reversed()) {
val cue = cues[idx]
rebuilt[idx] = cue.buildUpon()
.setLine(nextRow.toFloat(), Cue.LINE_TYPE_NUMBER)
.setLineAnchor(Cue.ANCHOR_TYPE_END)
.build()
val rowsConsumed = (cue.text?.toString()?.count { it == '\n' } ?: 0) + 1
nextRow -= rowsConsumed
}
return rebuilt
}
private fun applyPosition(cues: List<Cue>, positionPercent: Int, fontSize: Float): List<Cue> {
val clampedPosition = positionPercent.coerceIn(0, 100)
if (clampedPosition == 100 || cues.isEmpty()) return cues
val baseLine = clampedPosition / 100f
val rowHeight = (fontSize / 720f * 1.2f).coerceAtLeast(0.01f)
var changed = false
val rebuilt = cues.map { cue ->
if (!usesDefaultVerticalPlacement(cue)) return@map cue
val rowOffset = if (cue.lineType == Cue.LINE_TYPE_NUMBER && cue.line < 0f) {
(-cue.line - 1f).coerceAtLeast(0f)
} else {
0f
}
val line = if (clampedPosition == 0) {
(rowOffset * rowHeight).coerceAtMost(1f)
} else {
(baseLine - rowOffset * rowHeight).coerceIn(0f, 1f)
}
val lineAnchor = if (clampedPosition == 0) Cue.ANCHOR_TYPE_START else Cue.ANCHOR_TYPE_END
changed = true
cue.buildUpon()
.setLine(line, Cue.LINE_TYPE_FRACTION)
.setLineAnchor(lineAnchor)
.build()
}
return if (changed) rebuilt else cues
}
private fun usesDefaultVerticalPlacement(cue: Cue): Boolean {
if (cue.text == null || cue.bitmap != null || cue.verticalType != Cue.TYPE_UNSET) return false
return cue.line == Cue.DIMEN_UNSET || (cue.lineType == Cue.LINE_TYPE_NUMBER && cue.line < 0f)
}
}
@@ -0,0 +1,85 @@
package com.edde746.plezy.exoplayer
import androidx.media3.ui.AspectRatioFrameLayout
import kotlin.math.roundToInt
internal data class SubtitleViewDimensions(val width: Int, val height: Int)
internal object SubtitleViewLayout {
fun textDimensions(
containerWidth: Int,
containerHeight: Int,
videoWidth: Int,
videoHeight: Int,
pixelRatio: Float,
resizeMode: Int,
zoomScale: Float
): SubtitleViewDimensions? {
val videoAspect = videoAspect(videoWidth, videoHeight, pixelRatio) ?: return null
if (containerWidth <= 0 || containerHeight <= 0) return null
if (resizeMode != AspectRatioFrameLayout.RESIZE_MODE_FIT) {
return SubtitleViewDimensions(containerWidth, containerHeight)
}
val base = fit(containerWidth, containerHeight, videoAspect)
return when {
zoomScale < 0.999f -> scale(base, zoomScale)
zoomScale > 1.001f -> SubtitleViewDimensions(containerWidth, containerHeight)
else -> base
}
}
fun bitmapDimensions(
containerWidth: Int,
containerHeight: Int,
videoWidth: Int,
videoHeight: Int,
pixelRatio: Float,
resizeMode: Int,
zoomScale: Float
): SubtitleViewDimensions? {
val videoAspect = videoAspect(videoWidth, videoHeight, pixelRatio) ?: return null
if (containerWidth <= 0 || containerHeight <= 0) return null
// 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)
}
private fun videoAspect(videoWidth: Int, videoHeight: Int, pixelRatio: Float): Float? {
if (videoWidth <= 0 || videoHeight <= 0 || pixelRatio <= 0f) return null
val aspect = (videoWidth * pixelRatio) / videoHeight
return if (aspect.isFinite() && aspect > 0f) aspect else null
}
// Largest [videoAspect] rectangle that fits inside the container, as (width, height)
// in float pixels. Shared by the SubtitleView sizing (rounded to ints in [fit]) and
// the libass FIT-mode margins in updateAssMargins() (kept as floats for the zoom
// multiply) so both agree on the video dst rect.
fun letterbox(containerWidth: Int, containerHeight: Int, videoAspect: Float): Pair<Float, Float> {
val containerAspect = containerWidth.toFloat() / containerHeight
return if (videoAspect > containerAspect) {
containerWidth.toFloat() to containerWidth / videoAspect
} else {
containerHeight * videoAspect to containerHeight.toFloat()
}
}
private fun fit(containerWidth: Int, containerHeight: Int, videoAspect: Float): SubtitleViewDimensions {
val (width, height) = letterbox(containerWidth, containerHeight, videoAspect)
return SubtitleViewDimensions(
width.roundToInt().coerceAtLeast(1),
height.roundToInt().coerceAtLeast(1)
)
}
private fun scale(dimensions: SubtitleViewDimensions, scale: Float): SubtitleViewDimensions {
val safeScale = scale.coerceAtLeast(0.001f)
return SubtitleViewDimensions(
(dimensions.width * safeScale).roundToInt().coerceAtLeast(1),
(dimensions.height * safeScale).roundToInt().coerceAtLeast(1)
)
}
}
@@ -0,0 +1,44 @@
package com.edde746.plezy.exoplayer
import android.view.SurfaceControl
import androidx.annotation.Keep
/**
* EXPERIMENTAL SPIKE: the API-34 transaction callback path is the only in-app signal we have
* for comparing the codec video plane and the libass overlay plane with the same clock.
*/
// R8 cannot see the JNI-by-name callback edge, and class-level @Keep is not enough for members.
@Keep
object SurfaceTxProbe {
init {
System.loadLibrary("asskt")
}
const val SOURCE_VIDEO = 0
const val SOURCE_OVERLAY = 1
// CLOCK_MONOTONIC keeps native callback times comparable with ExoPlayer release targets.
@Volatile
@JvmStatic
var sink: ((Long, Long, Long, Int, Int, Int, Long) -> Unit)? = null
// The same transaction must be applied to the frame so the callback follows that buffer.
@JvmStatic
external fun nativeAttach(transaction: SurfaceControl.Transaction, tag: Long, source: Int)
// JNI calls this by name after shrink.
@Keep
@JvmStatic
fun onResult(
tag: Long,
latchNs: Long,
releaseNs: Long,
surfaceCount: Int,
fenceState: Int,
source: Int,
callbackNs: Long
) {
val s = sink ?: return
s.invoke(tag, latchNs, releaseNs, surfaceCount, fenceState, source, callbackNs)
}
}
@@ -1,9 +1,6 @@
package com.edde746.plezy.exoplayer
import android.util.Log
import androidx.media3.common.DataReader
import androidx.media3.common.Format
import androidx.media3.common.util.ParsableByteArray
import androidx.media3.extractor.TrackOutput
import java.util.zip.DataFormatException
import java.util.zip.Inflater
@@ -16,8 +13,8 @@ import java.util.zip.Inflater
* All buffers are reused across samples to minimize GC pressure on the hot path.
*/
class ZlibInflatingTrackOutput(
private val delegate: TrackOutput
) : TrackOutput {
delegate: TrackOutput
) : BufferedTransformingTrackOutput(delegate, INITIAL_BUFFER_SIZE, INFLATE_CHUNK) {
companion object {
private const val TAG = "ZlibTrackOutput"
@@ -28,94 +25,30 @@ class ZlibInflatingTrackOutput(
var active = false
private val inflater = Inflater()
// Reusable buffers — grown as needed, never shrunk
private var compressedBuf = ByteArray(INITIAL_BUFFER_SIZE)
private var compressedLen = 0
private var inflateBuf = ByteArray(INITIAL_BUFFER_SIZE)
private var readBuf = ByteArray(INFLATE_CHUNK)
private val outputParsable = ParsableByteArray()
private var buffering = false
override fun format(format: Format) = delegate.format(format)
override val transformEnabled: Boolean
get() = active
override fun sampleData(
input: DataReader,
length: Int,
allowEndOfInput: Boolean,
sampleDataPart: Int
): Int {
if (!active) return delegate.sampleData(input, length, allowEndOfInput, sampleDataPart)
override val transformedBuffer: ByteArray
get() = inflateBuf
buffering = true
if (readBuf.size < length) readBuf = ByteArray(length)
val bytesRead = input.read(readBuf, 0, length)
if (bytesRead > 0) appendCompressed(readBuf, 0, bytesRead)
return bytesRead
}
override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) {
if (!active) {
delegate.sampleData(data, length, sampleDataPart)
return
}
buffering = true
ensureCompressedCapacity(compressedLen + length)
data.readBytes(compressedBuf, compressedLen, length)
compressedLen += length
}
override fun sampleMetadata(
timeUs: Long,
flags: Int,
size: Int,
offset: Int,
cryptoData: TrackOutput.CryptoData?
) {
if (!active || !buffering) {
delegate.sampleMetadata(timeUs, flags, size, offset, cryptoData)
return
}
buffering = false
val srcLen = compressedLen
compressedLen = 0
val inflatedLen = try {
inflater.reset()
inflater.setInput(compressedBuf, 0, srcLen)
var written = 0
while (!inflater.finished()) {
if (written == inflateBuf.size) growInflateBuf()
val count = inflater.inflate(inflateBuf, written, inflateBuf.size - written)
if (count == 0 && !inflater.finished()) break
written += count
}
written
} catch (e: DataFormatException) {
Log.e(TAG, "Zlib inflate failed (${srcLen}B), passing raw", e)
// Fall back to raw compressed data
ensureInflateCapacity(srcLen)
System.arraycopy(compressedBuf, 0, inflateBuf, 0, srcLen)
srcLen
}
outputParsable.reset(inflateBuf, inflatedLen)
delegate.sampleData(outputParsable, inflatedLen, TrackOutput.SAMPLE_DATA_PART_MAIN)
delegate.sampleMetadata(timeUs, flags, inflatedLen, 0, cryptoData)
}
private fun appendCompressed(src: ByteArray, offset: Int, length: Int) {
ensureCompressedCapacity(compressedLen + length)
System.arraycopy(src, offset, compressedBuf, compressedLen, length)
compressedLen += length
}
private fun ensureCompressedCapacity(needed: Int) {
if (compressedBuf.size < needed) {
compressedBuf = compressedBuf.copyOf(maxOf(needed, compressedBuf.size * 2))
override fun transformSample(inputLength: Int, flags: Int): Int = try {
inflater.reset()
inflater.setInput(inputBuffer, 0, inputLength)
var written = 0
while (!inflater.finished()) {
if (written == inflateBuf.size) growInflateBuf()
val count = inflater.inflate(inflateBuf, written, inflateBuf.size - written)
if (count == 0 && !inflater.finished()) break
written += count
}
written
} catch (e: DataFormatException) {
Log.e(TAG, "Zlib inflate failed (${inputLength}B), passing raw", e)
ensureInflateCapacity(inputLength)
System.arraycopy(inputBuffer, 0, inflateBuf, 0, inputLength)
inputLength
}
private fun ensureInflateCapacity(needed: Int) {
@@ -5,19 +5,24 @@ import androidx.media3.extractor.ExtractorInput
import androidx.media3.extractor.ExtractorOutput
import androidx.media3.extractor.SeekMap
import androidx.media3.extractor.TrackOutput
import androidx.media3.extractor.mkv.MatroskaExtractor
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 ContentCompAlgo 0 (zlib).
* Extends AssMatroskaExtractor to add support for MKV quirks media3 rejects:
*
* Media3's MatroskaExtractor only supports ContentCompAlgo 3 (header stripping).
* This subclass intercepts the compression algorithm during track header parsing:
* 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 (see LatmMatroskaExtractor for the
* Live TV counterpart).
*/
class ZlibMatroskaExtractor(
subtitleParserFactory: SubtitleParser.Factory,
@@ -32,27 +37,25 @@ class ZlibMatroskaExtractor(
private const val ID_TRACK_ENTRY = 0xAE
private const val ID_CONTENT_COMPRESSION_ALGORITHM = 0x4254
private const val ID_CONTENT_COMPRESSION_SETTINGS = 0x4255
private val extractorOutputField by lazy {
MatroskaExtractor::class.java.getDeclaredField("extractorOutput").apply {
isAccessible = true
}
}
}
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 layer
// 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 = extractorOutputField.get(this) as ExtractorOutput
val wrapper = ZlibExtractorOutputWrapper(currentOutput)
val currentOutput = matroskaExtractorOutputField.get(this) as ExtractorOutput
val latmWrapper = LatmExtractorOutputWrapper(currentOutput)
latmOutput = latmWrapper
val wrapper = ZlibExtractorOutputWrapper(latmWrapper)
zlibOutput = wrapper
extractorOutputField.set(this, wrapper)
Log.d(TAG, "Installed zlib ExtractorOutput wrapper")
matroskaExtractorOutputField.set(this, wrapper)
Log.d(TAG, "Installed zlib+LATM ExtractorOutput wrapper")
}
}
@@ -78,6 +81,16 @@ class ZlibMatroskaExtractor(
}
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)
@@ -88,6 +101,11 @@ class ZlibMatroskaExtractor(
}
}
override fun seek(position: Long, timeUs: Long) {
latmOutput?.resetTracks()
super.seek(position, timeUs)
}
/**
* ExtractorOutput wrapper that wraps all TrackOutputs with ZlibInflatingTrackOutput.
* Tracks are created inactive; activateLast() enables inflation for the most recently
@@ -0,0 +1,35 @@
package com.edde746.plezy.mpv
import dev.jdtech.mpv.EndFileReason
import dev.jdtech.mpv.LogLevel
import dev.jdtech.mpv.LogMessage
import dev.jdtech.mpv.MpvEvent
/** Adds the native diagnostic that libmpv-android exposes separately via logFlow. */
internal class MpvEndFileDiagnostics {
private var errorMessage: String? = null
fun onStartFile() {
errorMessage = null
}
fun onLogMessage(message: LogMessage) {
if (message.level == LogLevel.Fatal || message.level == LogLevel.Error) {
errorMessage = message.text.takeIf { it.isNotBlank() }
}
}
fun onEndFile(event: MpvEvent.EndFile): Map<String, Any>? {
val reason = event.reason
if (reason == null) {
errorMessage = null
return null
}
val data = mutableMapOf<String, Any>("reason" to reason.id)
if (reason == EndFileReason.Error) {
errorMessage?.let { data["message"] = it }
}
errorMessage = null
return data
}
}
@@ -1,8 +1,9 @@
package com.edde746.plezy.mpv
import android.app.Activity
import android.graphics.Color
import android.content.Context
import android.graphics.PixelFormat
import android.media.AudioAttributes
import android.media.ImageReader
import android.os.Handler
import android.os.Looper
@@ -14,20 +15,39 @@ import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import com.edde746.plezy.shared.AudioFocusManager
import com.edde746.plezy.shared.FlutterOverlayHelper
import com.edde746.plezy.shared.FrameRateManager
import com.edde746.plezy.shared.PlayerDelegate
import com.edde746.plezy.shared.PlayerSurfaceHost
import dev.jdtech.mpv.*
import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
/**
* mpv playback core. Two modes:
* - Video (default): [context] is the host Activity, which is needed for the
* SurfaceView/window hierarchy, display refresh-rate reads and frame-rate
* matching.
* - Audio-only ([audioOnly]): the music core. Built on the application
* context (no Activity dependency, so it survives activity teardown);
* never creates a surface, view, or frame-rate manager, and mpv is
* configured before init to never open a video output (`vid=no`,
* `force-window=no`, `audio-display=no`, plus `gapless-audio=weak`).
*/
class MpvPlayerCore(
private val context: Context,
private val audioOnly: Boolean = false
) : SurfaceHolder.Callback {
companion object {
private const val TAG = "MpvPlayerCore"
}
/** Video-only paths. The plugin always constructs video cores with the
* host Activity, and audio-only mode never touches these paths. */
private val activity: Activity
get() = context as Activity
private var surfaceView: SurfaceView? = null
private var surfaceContainer: android.widget.FrameLayout? = null
private var overlayLayoutListener: ViewTreeObserver.OnGlobalLayoutListener? = null
@@ -52,11 +72,28 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
@Volatile private var player: MpvPlayer? = null
private var scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
private val endFileDiagnostics = MpvEndFileDiagnostics()
// mpv writes must stay off the main thread but run in submission order:
// setupMpvFallback sets vo/ao/hwdec immediately before the loadfile command,
// and an unordered pool can run loadfile first, leaving mpv with no video
// output (#1482).
private val mpvWriteDispatcher = Dispatchers.IO.limitedParallelism(1)
// Frame rate matching
private var frameRateManager: FrameRateManager? = null
private val handler = Handler(Looper.getMainLooper())
// Result-callback marshaling. Separate from [handler], whose queued
// messages dispose() clears — pending method-channel results must still
// complete after dispose.
private val mainHandler = Handler(Looper.getMainLooper())
/** Same semantics as Activity.runOnUiThread, without needing an Activity. */
private fun runOnMain(block: () -> Unit) {
if (Looper.myLooper() == Looper.getMainLooper()) block() else mainHandler.post(block)
}
// Audio focus
private var audioFocusManager: AudioFocusManager? = null
@@ -82,18 +119,11 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
private var flutterOverlayApplied = false
private fun ensureFlutterOverlayOnTop() {
if (disposing || flutterOverlayApplied) return
if (audioOnly || disposing || flutterOverlayApplied) return
val contentView = activity.findViewById<ViewGroup>(android.R.id.content)
contentView.post {
if (disposing || !isInitialized) return@post
val container = FlutterOverlayHelper.findFlutterContainer(contentView, surfaceContainer)
?: return@post
if (contentView.getChildAt(contentView.childCount - 1) == container) {
flutterOverlayApplied = true
return@post
}
FlutterOverlayHelper.configureFlutterZOrder(contentView, container, compositionOrder = 1)
flutterOverlayApplied = true
flutterOverlayApplied = PlayerSurfaceHost.ensureFlutterOverlayOnTop(contentView, surfaceContainer)
}
}
@@ -106,25 +136,35 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
}
private fun currentDisplayFpsOverride(): String? {
if (audioOnly) return null
val refreshRate = activity.display?.mode?.refreshRate ?: return null
if (refreshRate <= 0f) return null
return refreshRate.toString()
}
private fun updateDisplayFpsOverride(p: MpvPlayer, reason: String) {
private fun updateDisplayFpsOverride(p: MpvPlayer, reason: String, onComplete: () -> Unit = {}) {
val fps = currentDisplayFpsOverride()
if (fps == null) {
Log.d(TAG, "Skipping display-fps-override update ($reason): no display rate")
onComplete()
return
}
if (!scope.isActive) {
onComplete()
return
}
try {
runBlocking(Dispatchers.IO) {
scope.launch(mpvWriteDispatcher) {
try {
p.setProperty("display-fps-override", fps)
Log.d(TAG, "Updated display-fps-override=$fps ($reason)")
} catch (e: Exception) {
Log.w(TAG, "Failed to update display-fps-override ($reason)", e)
} finally {
withContext(NonCancellable + Dispatchers.Main) {
onComplete()
}
}
Log.d(TAG, "Updated display-fps-override=$fps ($reason)")
} catch (e: Exception) {
Log.w(TAG, "Failed to update display-fps-override ($reason)", e)
}
}
@@ -137,6 +177,7 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
try {
disposing = false
endFileDiagnostics.onStartFile()
cachedPaused = true
pausedForSurfaceLoss = false
pendingSurface = null
@@ -152,12 +193,15 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
lastAppliedSurfaceSize = null
lastKnownSurfaceWidth = 0
lastKnownSurfaceHeight = 0
ensurePlaceholderSurface()
if (!audioOnly) ensurePlaceholderSurface()
// Initialize audio focus handling
// Initialize audio focus handling. mpv has none built in, so both modes
// use the shared manager: pause on (transient) loss, auto-resume on
// regain when the loss interrupted active playback.
audioFocusManager = AudioFocusManager(
context = activity,
context = context,
handler = handler,
contentType = if (audioOnly) AudioAttributes.CONTENT_TYPE_MUSIC else AudioAttributes.CONTENT_TYPE_MOVIE,
onPause = {
scope.launch {
try {
@@ -172,57 +216,29 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
},
isPaused = { cachedPaused }
)
frameRateManager = FrameRateManager(
activity = activity,
handler = handler,
log = { emitLog("info", "framerate", it) }
)
// Create FrameLayout container for video
surfaceContainer = android.widget.FrameLayout(activity).apply {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
if (!audioOnly) {
frameRateManager = FrameRateManager(
activity = activity,
handler = handler,
log = { emitLog("info", "framerate", it) }
)
setBackgroundColor(Color.BLACK)
}
// Create SurfaceView for video rendering
surfaceView = SurfaceView(activity).apply {
layoutParams = android.widget.FrameLayout.LayoutParams(
android.widget.FrameLayout.LayoutParams.MATCH_PARENT,
android.widget.FrameLayout.LayoutParams.MATCH_PARENT
)
holder.addCallback(this@MpvPlayerCore)
setZOrderOnTop(false)
setZOrderMediaOverlay(false)
FlutterOverlayHelper.applyCompositionOrder(this, -2)
}
surfaceContainer = PlayerSurfaceHost.createContainer(activity)
surfaceView = PlayerSurfaceHost.createVideoSurface(activity, this@MpvPlayerCore)
surfaceContainer!!.addView(surfaceView)
// Add SurfaceView to container
surfaceContainer!!.addView(surfaceView)
// Insert container at bottom of view hierarchy (behind Flutter)
val contentView = activity.findViewById<ViewGroup>(android.R.id.content)
contentView.addView(surfaceContainer, 0)
// Find FlutterView and set it on top of our video surface.
// compositionOrder maps directly to SurfaceView mSubLayer on API 36+:
// negative is hole-punched behind the parent canvas, non-negative is above.
// Stack (back → front): video (-2, hole-punched) → parent canvas → Flutter UI (+1).
FlutterOverlayHelper.findFlutterContainer(contentView, surfaceContainer)?.let { container ->
FlutterOverlayHelper.configureFlutterZOrder(contentView, container, compositionOrder = 1)
flutterOverlayApplied = true
}
ensureFlutterOverlayOnTop()
overlayLayoutListener = ViewTreeObserver.OnGlobalLayoutListener {
val contentView = PlayerSurfaceHost.attachToContent(activity, surfaceContainer!!)
flutterOverlayApplied = PlayerSurfaceHost.ensureFlutterOverlayOnTop(contentView, surfaceContainer)
ensureFlutterOverlayOnTop()
val sv = surfaceView
if (sv != null) applySurfaceSize(sv.width, sv.height)
}
contentView.viewTreeObserver.addOnGlobalLayoutListener(overlayLayoutListener)
overlayLayoutListener = ViewTreeObserver.OnGlobalLayoutListener {
ensureFlutterOverlayOnTop()
val sv = surfaceView
if (sv != null) applySurfaceSize(sv.width, sv.height)
}
contentView.viewTreeObserver.addOnGlobalLayoutListener(overlayLayoutListener)
Log.d(TAG, "SurfaceView added to content view")
Log.d(TAG, "SurfaceView added to content view")
}
// Create MpvPlayer on background thread via coroutine
scope.launch {
@@ -232,18 +248,31 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
return@launch
}
val displayFpsOverride = currentDisplayFpsOverride()
val p = MpvPlayer.create(activity.applicationContext) {
setOption("vo", "gpu")
setOption("gpu-context", "android")
setOption("opengl-es", "yes")
setOption("vd-lavc-film-grain", "cpu")
val p = MpvPlayer.create(context.applicationContext) {
if (audioOnly) {
// Pure audio core (all set before mpv_initialize, mirroring the
// Windows/Linux audio instances): vid=no keeps embedded cover
// art from ever becoming a video track, force-window and
// audio-display make sure mpv never opens a video output for
// it, and gapless-audio splices the pre-armed next playlist
// entry into the running audio stream.
setOption("vid", "no")
setOption("force-window", "no")
setOption("audio-display", "no")
setOption("gapless-audio", "weak")
} else {
setOption("vo", "gpu")
setOption("gpu-context", "android")
setOption("opengl-es", "yes")
setOption("vd-lavc-film-grain", "cpu")
if (displayFpsOverride != null) {
setOption("display-fps-override", displayFpsOverride)
}
}
setOption("ao", "audiotrack,opensles")
// Pause on the last frame at EOF instead of unloading the file, so a
// seek after the video ends still works (matches Linux/Windows).
setOption("keep-open", "yes")
if (displayFpsOverride != null) {
setOption("display-fps-override", displayFpsOverride)
}
}
if (displayFpsOverride != null) {
Log.d(TAG, "Initial display-fps-override=$displayFpsOverride")
@@ -258,7 +287,7 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
player = p
isInitialized = true
refreshVideoOutput("initialize")
if (!audioOnly) refreshVideoOutput("initialize")
// Start collecting events/properties/logs
collectEvents(p)
@@ -296,9 +325,9 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
p.eventFlow.collect { event ->
when (event) {
is MpvEvent.EndFile -> {
val data = event.reason?.let { mapOf("reason" to it.id) }
delegate?.onEvent("end-file", data)
delegate?.onEvent("end-file", endFileDiagnostics.onEndFile(event))
}
is MpvEvent.StartFile -> endFileDiagnostics.onStartFile()
is MpvEvent.FileLoaded -> delegate?.onEvent("file-loaded", null)
is MpvEvent.PlaybackRestart -> delegate?.onEvent("playback-restart", null)
else -> {}
@@ -332,6 +361,7 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
private fun collectLogMessages(p: MpvPlayer) {
scope.launch(start = CoroutineStart.UNDISPATCHED) {
p.logFlow.collect { msg ->
endFileDiagnostics.onLogMessage(msg)
emitLog(msg.level.name.lowercase(), msg.prefix, msg.text)
}
}
@@ -393,7 +423,9 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
private fun hasAttachedRealSurface(): Boolean = hasAttachedSurface && !attachedToPlaceholder && (attachedSurface?.isValid == true)
private fun hasReadyVideoOutput(): Boolean = hasAttachedRealSurface() && !videoOutputRestoring
// Audio-only mode has no video output to wait for — playback and resume
// paths gated on output readiness must always proceed there.
private fun hasReadyVideoOutput(): Boolean = audioOnly || (hasAttachedRealSurface() && !videoOutputRestoring)
private fun isCurrentVideoOutputEpoch(epoch: Long): Boolean = !disposing && epoch == videoOutputEpoch
@@ -404,7 +436,7 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
}
private fun refreshVideoOutput(reason: String) {
if (disposing) return
if (audioOnly || disposing) return
rememberCurrentSurfaceSize()
val p = player
@@ -649,8 +681,11 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
// Public API
fun setProperty(name: String, value: String) {
if (!isInitialized || disposing) return
fun setProperty(name: String, value: String, onComplete: ((Boolean) -> Unit)? = null) {
if (!isInitialized || disposing || !scope.isActive) {
onComplete?.invoke(false)
return
}
if (name == "pause") {
val paused = normalizePauseValue(value)
if (paused == true) {
@@ -664,6 +699,7 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
if (!hasReadyVideoOutput()) {
deferredResumeRequested = true
Log.d(TAG, "Deferring public resume until video output is ready")
onComplete?.invoke(true)
return
}
cachedPaused = false
@@ -671,16 +707,30 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
Log.d(TAG, "Public pause state updated: paused=false")
}
}
scope.launch {
scope.launch(mpvWriteDispatcher) {
var success = false
try {
player?.setProperty(name, value)
success = true
} catch (e: Exception) {
Log.w(TAG, "setProperty($name) failed", e)
} finally {
withContext(NonCancellable + Dispatchers.Main) {
onComplete?.invoke(success)
}
}
}
}
fun getProperty(name: String): String? {
if (Looper.myLooper() == Looper.getMainLooper()) {
Log.w(TAG, "Refusing synchronous getProperty($name) on the main thread")
return null
}
return getPropertyBlocking(name)
}
private fun getPropertyBlocking(name: String): String? {
if (!isInitialized || disposing) return null
return try {
runBlocking(Dispatchers.IO) { player?.getString(name) }
@@ -689,6 +739,75 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
}
}
fun getPropertyAsync(name: String, onResult: (String?) -> Unit) {
if (!isInitialized || disposing) {
onResult(null)
return
}
Thread {
val value = getPropertyBlocking(name)
runOnMain {
onResult(if (!disposing && isInitialized) value else null)
}
}.start()
}
/**
* Returns MPV stats in the same key format used by the performance overlay.
* This method performs synchronous native property reads and must not be
* called on Android's main thread.
*/
fun getStats(): Map<String, Any?> {
if (Looper.myLooper() == Looper.getMainLooper()) {
Log.w(TAG, "Refusing synchronous getStats() on the main thread")
return mapOf("playerType" to "mpv")
}
val hasVideo = getProperty("video-params/w") != null
val stats = mutableMapOf<String, Any?>(
"playerType" to "mpv",
"video-codec" to getProperty("video-codec"),
"video-params/w" to getProperty("video-params/w"),
"video-params/h" to getProperty("video-params/h"),
"videoWidth" to getProperty("dwidth"),
"videoHeight" to getProperty("dheight"),
"container-fps" to getProperty("container-fps"),
"estimated-vf-fps" to getProperty("estimated-vf-fps"),
"video-bitrate" to getProperty("video-bitrate"),
"hwdec-current" to getProperty("hwdec-current"),
"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-bitrate" to getProperty("audio-bitrate"),
"total-avsync-change" to getProperty("total-avsync-change"),
"cache-used" to getProperty("cache-used"),
"demuxer-max-bytes" to getProperty("demuxer-max-bytes"),
"cache-speed" to getProperty("cache-speed"),
"frame-drop-count" to getProperty("frame-drop-count"),
"decoder-frame-drop-count" to getProperty("decoder-frame-drop-count"),
"demuxer-cache-duration" to getProperty("demuxer-cache-duration")
)
if (hasVideo) {
stats["display-fps"] = getProperty("display-fps")
stats["video-params/pixelformat"] = getProperty("video-params/pixelformat")
stats["video-params/hw-pixelformat"] = getProperty("video-params/hw-pixelformat")
stats["video-params/colormatrix"] = getProperty("video-params/colormatrix")
stats["video-params/primaries"] = getProperty("video-params/primaries")
stats["video-params/gamma"] = getProperty("video-params/gamma")
stats["video-params/max-luma"] = getProperty("video-params/max-luma")
stats["video-params/min-luma"] = getProperty("video-params/min-luma")
stats["video-params/max-cll"] = getProperty("video-params/max-cll")
stats["video-params/max-fall"] = getProperty("video-params/max-fall")
stats["video-params/aspect-name"] = getProperty("video-params/aspect-name")
stats["video-params/rotate"] = getProperty("video-params/rotate")
}
return stats
}
fun observeProperty(name: String, format: String) {
val p = player ?: return
if (!isInitialized) return
@@ -706,7 +825,7 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
onComplete?.invoke(false)
return
}
scope.launch {
scope.launch(mpvWriteDispatcher) {
var success = false
try {
player?.command(*args)
@@ -714,15 +833,18 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
} catch (e: Exception) {
Log.w(TAG, "command failed", e)
} finally {
onComplete?.invoke(success)
withContext(NonCancellable + Dispatchers.Main) {
onComplete?.invoke(success)
}
}
}
}
fun setVisible(visible: Boolean) {
if (disposing) return
activity.runOnUiThread {
if (disposing) return@runOnUiThread
// Audio-only: no render layer to show or hide — tolerated no-op.
if (audioOnly || disposing) return
runOnMain {
if (disposing) return@runOnMain
surfaceContainer?.visibility = if (visible) View.VISIBLE else View.INVISIBLE
if (visible) {
flutterOverlayApplied = false
@@ -748,16 +870,17 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
}
fun updateFrame() {
if (disposing) return
activity.runOnUiThread {
if (disposing) return@runOnUiThread
// Audio-only: no surface to refresh — tolerated no-op.
if (audioOnly || disposing) return
runOnMain {
if (disposing) return@runOnMain
flutterOverlayApplied = false
ensureFlutterOverlayOnTop()
rememberCurrentSurfaceSize()
val p = player
if (p == null) {
Log.d(TAG, "updateFrame(): skipping Android MPV surface refresh because player is not ready")
return@runOnUiThread
return@runOnMain
}
if (!hasReadyVideoOutput()) {
val surface = currentCandidateSurface()
@@ -767,7 +890,7 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
} else {
Log.d(TAG, "updateFrame(): skipping Android MPV surface refresh because no surface is attached")
}
return@runOnUiThread
return@runOnMain
}
scope.launch {
try {
@@ -785,6 +908,8 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
fps: Float,
videoDurationMs: Long,
extraDelayMs: Long,
videoWidth: Int,
videoHeight: Int,
onComplete: (switched: Boolean) -> Unit
) {
val mgr = frameRateManager
@@ -792,9 +917,12 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
onComplete(false)
return
}
mgr.setVideoFrameRate(fps, videoDurationMs, extraDelayMs) { switched ->
player?.let { updateDisplayFpsOverride(it, "frame rate switch, switched=$switched") }
onComplete(switched)
mgr.setVideoFrameRate(fps, videoDurationMs, extraDelayMs, videoWidth, videoHeight) { switched ->
player?.let {
updateDisplayFpsOverride(it, "frame rate switch, switched=$switched") {
onComplete(switched)
}
} ?: onComplete(switched)
}
}
@@ -848,17 +976,17 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
videoOutputEpoch += 1L
}
// Capture locals for deferred cleanup
// Capture locals for deferred cleanup (audio-only has no views)
val sv = surfaceView
val container = surfaceContainer
val contentView = activity.findViewById<ViewGroup>(android.R.id.content)
val contentView = if (audioOnly) null else activity.findViewById<ViewGroup>(android.R.id.content)
surfaceContainer = null
surfaceView = null
// Remove layout listener synchronously
overlayLayoutListener?.let { listener ->
contentView.viewTreeObserver.removeOnGlobalLayoutListener(listener)
contentView?.viewTreeObserver?.removeOnGlobalLayoutListener(listener)
}
overlayLayoutListener = null
@@ -880,15 +1008,18 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
if (p != null) {
Thread {
try {
// Detach surface BEFORE close to prevent GPU mutex contention with view removal
try {
runBlocking {
p.setProperty("force-window", "no")
p.setProperty("vo", "null")
// Detach surface BEFORE close to prevent GPU mutex contention with
// view removal (audio-only never attached one)
if (!audioOnly) {
try {
runBlocking {
p.setProperty("force-window", "no")
p.setProperty("vo", "null")
}
p.detachSurface()
} catch (e: Exception) {
Log.w(TAG, "Failed to detach surface during dispose", e)
}
p.detachSurface()
} catch (e: Exception) {
Log.w(TAG, "Failed to detach surface during dispose", e)
}
p.close()
} catch (e: Exception) {
@@ -899,7 +1030,7 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
Handler(Looper.getMainLooper()).post {
sv?.holder?.removeCallback(this)
if (container?.parent != null) {
contentView.removeView(container)
contentView?.removeView(container)
}
onComplete?.invoke()
}
@@ -909,7 +1040,7 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
Handler(Looper.getMainLooper()).postAtFrontOfQueue {
sv?.holder?.removeCallback(this)
if (container?.parent != null) {
contentView.removeView(container)
contentView?.removeView(container)
}
}
onComplete?.invoke()
@@ -1,8 +1,11 @@
package com.edde746.plezy.mpv
import android.app.Activity
import android.content.Context
import android.net.Uri
import android.os.ParcelFileDescriptor
import android.util.Log
import com.edde746.plezy.shared.PlayerChannelBinding
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
@@ -10,28 +13,39 @@ import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
class MpvPlayerPlugin :
FlutterPlugin,
/**
* Channel plumbing for [MpvPlayerCore]. The default instance is the video
* player; the [audioOnly] instance (see [MpvAudioPlayerPlugin]) drives the
* dedicated music core on its own channel pair with two lifecycle
* differences:
* - the core is built on the application context, not the Activity, so
* background music playback survives activity teardown — it is only
* disposed on explicit Dart `dispose` or engine detach, never in
* [onDetachedFromActivity];
* - all video-only surface work is skipped inside the core.
*/
open class MpvPlayerPlugin(
private val channelBase: String = "com.plezy/mpv_player",
private val audioOnly: Boolean = false
) : FlutterPlugin,
MethodChannel.MethodCallHandler,
EventChannel.StreamHandler,
ActivityAware,
com.edde746.plezy.shared.PlayerDelegate {
companion object {
private const val TAG = "MpvPlayerPlugin"
private const val METHOD_CHANNEL = "com.plezy/mpv_player"
private const val EVENT_CHANNEL = "com.plezy/mpv_player/events"
}
private val tag = if (audioOnly) "MpvAudioPlayerPlugin" else "MpvPlayerPlugin"
private lateinit var methodChannel: MethodChannel
private lateinit var eventChannel: EventChannel
private var eventSink: EventChannel.EventSink? = null
private val channels = PlayerChannelBinding(channelBase, this, this, tag)
private var playerCore: MpvPlayerCore? = null
private var activity: Activity? = null
private var activityBinding: ActivityPluginBinding? = null
private var applicationContext: Context? = null
private val nameToId = mutableMapOf<String, Int>()
private var sessionGeneration = 0
/** Same semantics as Activity.runOnUiThread, without needing an Activity. */
private fun runOnMain(block: () -> Unit) = channels.runOnMain(block)
// Pending `MethodChannel.Result`s for an init that is currently in flight.
// Concurrent `invoke('initialize')` calls share the same outcome instead
// of each tearing down the in-flight core and starting their own — which
@@ -43,19 +57,27 @@ class MpvPlayerPlugin :
// FlutterPlugin
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
methodChannel = MethodChannel(binding.binaryMessenger, METHOD_CHANNEL)
methodChannel.setMethodCallHandler(this)
eventChannel = EventChannel(binding.binaryMessenger, EVENT_CHANNEL)
eventChannel.setStreamHandler(this)
Log.d(TAG, "Attached to engine")
applicationContext = binding.applicationContext
channels.attach(binding)
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
methodChannel.setMethodCallHandler(null)
eventChannel.setStreamHandler(null)
Log.d(TAG, "Detached from engine")
channels.detach()
if (audioOnly) {
// The audio core is not activity-bound; engine detach is its terminal
// native lifecycle event (mirrors the video core's activity detach).
disposeCoreForTeardown()
}
applicationContext = null
}
private fun disposeCoreForTeardown() {
++sessionGeneration
playerCore?.dispose()
playerCore = null
// Any in-flight init callback would never fire (its scope is cancelled
// by dispose), so close out queued callers explicitly.
completePendingInits(success = false)
}
// ActivityAware
@@ -63,43 +85,40 @@ class MpvPlayerPlugin :
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
activity = binding.activity
activityBinding = binding
Log.d(TAG, "Attached to activity")
Log.d(tag, "Attached to activity")
}
override fun onDetachedFromActivity() {
++sessionGeneration
playerCore?.dispose()
playerCore = null
// Any in-flight init callback would never fire (its scope is cancelled
// by dispose), so close out queued callers explicitly.
completePendingInits(success = false)
// The audio-only core deliberately outlives the activity (background
// music); it is torn down on engine detach / Dart dispose instead.
if (!audioOnly) {
disposeCoreForTeardown()
}
activity = null
activityBinding = null
Log.d(TAG, "Detached from activity")
Log.d(tag, "Detached from activity")
}
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
activity = binding.activity
activityBinding = binding
Log.d(TAG, "Reattached to activity for config changes")
Log.d(tag, "Reattached to activity for config changes")
}
override fun onDetachedFromActivityForConfigChanges() {
activity = null
activityBinding = null
Log.d(TAG, "Detached from activity for config changes")
Log.d(tag, "Detached from activity for config changes")
}
// EventChannel.StreamHandler
override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
eventSink = events
Log.d(TAG, "Event stream connected")
channels.listen(events)
}
override fun onCancel(arguments: Any?) {
eventSink = null
Log.d(TAG, "Event stream disconnected")
channels.cancel()
}
// MethodChannel.MethodCallHandler
@@ -110,6 +129,7 @@ class MpvPlayerPlugin :
"dispose" -> handleDispose(result)
"setProperty" -> handleSetProperty(call, result)
"getProperty" -> handleGetProperty(call, result)
"getStats" -> handleGetStats(result)
"observeProperty" -> handleObserveProperty(call, result)
"command" -> handleCommand(call, result)
"setVisible" -> handleSetVisible(call, result)
@@ -119,21 +139,28 @@ class MpvPlayerPlugin :
"requestAudioFocus" -> handleRequestAudioFocus(result)
"abandonAudioFocus" -> handleAbandonAudioFocus(result)
"openContentFd" -> handleOpenContentFd(call, result)
"closeContentFd" -> handleCloseContentFd(call, result)
"isInitialized" -> result.success(playerCore?.isInitialized ?: false)
"setLogLevel" -> result.success(null)
"setLogLevel" -> handleSetLogLevel(call, result)
else -> result.notImplemented()
}
}
private fun handleInitialize(result: MethodChannel.Result) {
val currentActivity = activity
if (currentActivity == null) {
result.error("NO_ACTIVITY", "Activity not available", null)
// 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
if (coreContext == null) {
if (audioOnly) {
result.error("NO_CONTEXT", "Application context not available", null)
} else {
result.error("NO_ACTIVITY", "Activity not available", null)
}
return
}
if (playerCore?.isInitialized == true) {
Log.d(TAG, "Already initialized")
Log.d(tag, "Already initialized")
result.success(true)
return
}
@@ -145,13 +172,13 @@ class MpvPlayerPlugin :
synchronized(pendingInitResults) {
pendingInitResults += result
if (isInitializing) {
Log.d(TAG, "Init already in flight, queuing caller")
Log.d(tag, "Init already in flight, queuing caller")
return
}
isInitializing = true
}
currentActivity.runOnUiThread {
runOnMain {
val gen: Int
val core: MpvPlayerCore
try {
@@ -159,31 +186,32 @@ class MpvPlayerPlugin :
// OR `playerCore?.isInitialized == true` and we early-exited
// above. We never tear down a core that's mid-initialization.
if (playerCore != null && playerCore?.isInitialized != true) {
Log.w(TAG, "Discarding stale uninitialized core before re-init")
Log.w(tag, "Discarding stale uninitialized core before re-init")
playerCore?.dispose()
playerCore = null
}
gen = ++sessionGeneration
core = MpvPlayerCore(currentActivity).apply {
core = MpvPlayerCore(coreContext, audioOnly).apply {
delegate = this@MpvPlayerPlugin
}
playerCore = core
} catch (e: Exception) {
Log.e(TAG, "Failed to initialize: ${e.message}", e)
Log.e(tag, "Failed to initialize: ${e.message}", e)
completePendingInits(success = false, errorMessage = e.message)
return@runOnUiThread
return@runOnMain
}
core.initialize { success ->
val stale = gen != sessionGeneration || playerCore !== core
if (stale) {
Log.d(TAG, "Stale init callback (gen=$gen, current=$sessionGeneration)")
Log.d(tag, "Stale init callback (gen=$gen, current=$sessionGeneration)")
} else {
// Start hidden - now safe because setVisible operates on the container,
// not the SurfaceView directly (matching ExoPlayer's approach)
// not the SurfaceView directly (matching ExoPlayer's approach).
// No-op on the audio-only core, which has no render layer.
core.setVisible(false)
Log.d(TAG, "Initialized: $success")
Log.d(tag, "Initialized: $success")
}
completePendingInits(success = !stale && success)
}
@@ -207,7 +235,7 @@ class MpvPlayerPlugin :
}
private fun handleDispose(result: MethodChannel.Result) {
activity?.runOnUiThread {
runOnMain {
val core = playerCore
++sessionGeneration
playerCore = null
@@ -217,10 +245,10 @@ class MpvPlayerPlugin :
completePendingInits(success = false)
core?.dispose {
Log.d(TAG, "Disposed")
Log.d(tag, "Disposed")
result.success(null)
} ?: result.success(null)
} ?: result.success(null)
}
}
private fun handleSetProperty(call: MethodCall, result: MethodChannel.Result) {
@@ -232,8 +260,15 @@ class MpvPlayerPlugin :
return
}
playerCore?.setProperty(name, value)
result.success(null)
val core = playerCore
if (core == null) {
result.success(null)
return
}
core.setProperty(name, value) {
result.success(null)
}
}
private fun handleGetProperty(call: MethodCall, result: MethodChannel.Result) {
@@ -244,8 +279,40 @@ class MpvPlayerPlugin :
return
}
val value = playerCore?.getProperty(name)
result.success(value)
val core = playerCore
if (core == null) {
result.success(null)
return
}
val gen = sessionGeneration
core.getPropertyAsync(name) { value ->
if (gen != sessionGeneration || playerCore !== core) {
result.success(null)
} else {
result.success(value)
}
}
}
private fun handleGetStats(result: MethodChannel.Result) {
val core = playerCore
if (core == null) {
result.success(mapOf("playerType" to "mpv"))
return
}
val gen = sessionGeneration
Thread {
val stats = core.getStats()
runOnMain {
if (gen != sessionGeneration || playerCore !== core) {
result.success(mapOf("playerType" to "mpv"))
} else {
result.success(stats)
}
}
}.start()
}
private fun handleObserveProperty(call: MethodCall, result: MethodChannel.Result) {
@@ -273,14 +340,30 @@ class MpvPlayerPlugin :
val core = playerCore
if (core == null) {
result.success(null)
result.error("NOT_INITIALIZED", "Player not initialized", null)
return
}
core.command(args.toTypedArray()) {
result.success(null)
core.command(args.toTypedArray()) { success ->
if (success) {
result.success(null)
} else {
result.error("COMMAND_FAILED", "mpv command failed", args)
}
}
}
private fun handleSetLogLevel(call: MethodCall, result: MethodChannel.Result) {
if (call.argument<String>("level") == null) {
result.error("INVALID_ARGS", "Missing 'level'", null)
return
}
result.error(
"UNSUPPORTED",
"Runtime mpv log level changes are not supported on Android",
null
)
}
private fun handleSetVisible(call: MethodCall, result: MethodChannel.Result) {
val visible = call.argument<Boolean>("visible")
@@ -302,32 +385,34 @@ class MpvPlayerPlugin :
val fps = call.argument<Double>("fps")?.toFloat() ?: 0f
val duration = call.argument<Number>("duration")?.toLong() ?: 0L
val extraDelayMs = call.argument<Number>("extraDelayMs")?.toLong() ?: 0L
val videoWidth = call.argument<Number>("videoWidth")?.toInt() ?: 0
val videoHeight = call.argument<Number>("videoHeight")?.toInt() ?: 0
Log.d(TAG, "setVideoFrameRate: fps=$fps, duration=$duration, extraDelayMs=$extraDelayMs")
Log.d(tag, "setVideoFrameRate: fps=$fps, duration=$duration, extraDelayMs=$extraDelayMs, video=${videoWidth}x$videoHeight")
val core = playerCore
if (core == null) {
result.success(false)
return
}
core.setVideoFrameRate(fps, duration, extraDelayMs) { switched ->
core.setVideoFrameRate(fps, duration, extraDelayMs, videoWidth, videoHeight) { switched ->
result.success(switched)
}
}
private fun handleClearVideoFrameRate(result: MethodChannel.Result) {
Log.d(TAG, "clearVideoFrameRate")
Log.d(tag, "clearVideoFrameRate")
playerCore?.clearVideoFrameRate()
result.success(null)
}
private fun handleRequestAudioFocus(result: MethodChannel.Result) {
Log.d(TAG, "requestAudioFocus")
Log.d(tag, "requestAudioFocus")
val granted = playerCore?.requestAudioFocus() ?: false
result.success(granted)
}
private fun handleAbandonAudioFocus(result: MethodChannel.Result) {
Log.d(TAG, "abandonAudioFocus")
Log.d(tag, "abandonAudioFocus")
playerCore?.abandonAudioFocus()
result.success(null)
}
@@ -339,9 +424,11 @@ class MpvPlayerPlugin :
return
}
val contentResolver = activity?.contentResolver
// The audio instance may run without an Activity (background music), so
// resolve SAF content URIs through the application context there.
val contentResolver = (if (audioOnly) applicationContext else activity)?.contentResolver
if (contentResolver == null) {
result.error("NO_ACTIVITY", "Activity not available", null)
result.error(if (audioOnly) "NO_CONTEXT" else "NO_ACTIVITY", "Context not available", null)
return
}
@@ -351,35 +438,58 @@ class MpvPlayerPlugin :
val uri = Uri.parse(uriString)
val pfd = contentResolver.openFileDescriptor(uri, "r")
if (pfd == null) {
activity?.runOnUiThread {
runOnMain {
result.error("OPEN_FAILED", "Failed to open file descriptor for $uriString", null)
}
return@Thread
}
val fd = pfd.detachFd()
Log.d(TAG, "Opened content FD $fd for $uriString")
activity?.runOnUiThread { result.success(fd) }
Log.d(tag, "Opened content FD $fd for $uriString")
runOnMain { result.success(fd) }
} catch (e: Exception) {
Log.e(TAG, "Failed to open content FD: ${e.message}", e)
activity?.runOnUiThread { result.error("OPEN_FAILED", e.message, null) }
Log.e(tag, "Failed to open content FD: ${e.message}", e)
runOnMain { result.error("OPEN_FAILED", e.message, null) }
}
}.start()
}
// Reclaims a detached fd from handleOpenContentFd that mpv will never
// consume (a gapless-armed entry dropped before mpv opened it). The Dart
// side guarantees single-close and only calls this when the entry provably
// never played.
private fun handleCloseContentFd(call: MethodCall, result: MethodChannel.Result) {
val fd = call.argument<Int>("fd")
if (fd == null || fd < 0) {
result.error("INVALID_ARGS", "Missing 'fd'", null)
return
}
try {
ParcelFileDescriptor.adoptFd(fd).close()
Log.d(tag, "Closed content FD $fd")
result.success(null)
} catch (e: Exception) {
Log.e(tag, "Failed to close content FD $fd: ${e.message}", e)
result.error("CLOSE_FAILED", e.message, null)
}
}
// PlayerDelegate
override fun onPropertyChange(name: String, value: Any?) {
val propId = nameToId[name] ?: return
eventSink?.success(listOf(propId, value))
channels.emitProperty(propId, value)
}
override fun onEvent(name: String, data: Map<String, Any>?) {
val event = mutableMapOf<String, Any>(
"type" to "event",
"name" to name
)
data?.let { event["data"] = it }
eventSink?.success(event)
channels.emitEvent(name, data)
}
}
/**
* The audio-only music instance on `com.plezy/mpv_audio_player[/events]`.
* A distinct class (not just a configured [MpvPlayerPlugin]) because
* FlutterEngine's plugin registry keys plugins by class and would silently
* drop a second [MpvPlayerPlugin] registration.
*/
class MpvAudioPlayerPlugin : MpvPlayerPlugin(channelBase = "com.plezy/mpv_audio_player", audioOnly = true)
@@ -14,7 +14,8 @@ class AudioFocusManager(
private val onPause: () -> Unit,
private val onResume: () -> Unit,
private val isPaused: () -> Boolean,
private val log: (String) -> Unit = { Log.d(TAG, it) }
private val log: (String) -> Unit = { Log.d(TAG, it) },
private val contentType: Int = AudioAttributes.CONTENT_TYPE_MOVIE
) {
companion object {
private const val TAG = "AudioFocusManager"
@@ -62,7 +63,7 @@ class AudioFocusManager(
.setAudioAttributes(
AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MOVIE)
.setContentType(contentType)
.build()
)
.setOnAudioFocusChangeListener(audioFocusChangeListener, handler)
@@ -37,6 +37,8 @@ class FrameRateManager(
)
private var currentVideoFps: Float = 0f
private var currentVideoWidth: Int = 0
private var currentVideoHeight: Int = 0
private var displayListener: DisplayManager.DisplayListener? = null
private var pendingSettleRunnable: Runnable? = null
private var watchdogRunnable: Runnable? = null
@@ -57,9 +59,13 @@ class FrameRateManager(
fps: Float,
videoDurationMs: Long,
extraDelayMs: Long,
videoWidth: Int = 0,
videoHeight: Int = 0,
onComplete: (switched: Boolean) -> Unit
) {
currentVideoFps = fps
currentVideoWidth = videoWidth
currentVideoHeight = videoHeight
if (fps <= 0f) {
Log.d(TAG, "setVideoFrameRate: Invalid fps ($fps), skipping")
onComplete(false)
@@ -68,7 +74,7 @@ class FrameRateManager(
log(
"request fps=$fps, duration=${videoDurationMs}ms, extraDelayMs=$extraDelayMs, " +
"API=${Build.VERSION.SDK_INT}, currentMode=${currentModeDescription()}"
"video=${videoWidth}x$videoHeight, API=${Build.VERSION.SDK_INT}, currentMode=${currentModeDescription()}"
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
@@ -208,17 +214,42 @@ 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>): DisplayModeCandidate? = supportedModes.asSequence()
.filter { mode ->
mode.physicalHeight == currentMode.physicalHeight &&
mode.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) }
)
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 }
)
}
@RequiresApi(Build.VERSION_CODES.M)
private fun setDisplayMode(fps: Float, extraDelayMs: Long, onComplete: (switched: Boolean) -> Unit) {
@@ -239,9 +270,12 @@ class FrameRateManager(
val currentMode = display.mode
log("supported modes=${describeSupportedModes(supportedModes)}")
val modeMatch = findBestModeMatch(fps, currentMode, supportedModes)
val modeMatch = findBestModeMatch(fps, currentMode, supportedModes, currentVideoWidth, currentVideoHeight)
if (modeMatch == null) {
log("no matching display mode for ${fps}fps at ${currentMode.physicalWidth}x${currentMode.physicalHeight}")
log(
"no matching display mode for ${fps}fps at ${currentMode.physicalWidth}x${currentMode.physicalHeight} " +
"(video=${currentVideoWidth}x$currentVideoHeight)"
)
onComplete(false)
return
}
@@ -0,0 +1,52 @@
package com.edde746.plezy.shared
import android.media.MediaCodecInfo
import android.media.MediaCodecList
import android.os.Build
import java.util.Locale
/** Canonical decoder lookup and hardware classification for native playback. */
internal object MediaCodecQuery {
fun findHardwareDecoder(
mimeType: String,
codecKind: Int = MediaCodecList.REGULAR_CODECS,
predicate: (MediaCodecInfo, String) -> Boolean = { _, _ -> true }
): MediaCodecInfo? {
for (info in MediaCodecList(codecKind).codecInfos) {
if (info.isEncoder || !isHardwareAccelerated(info)) continue
for (type in info.supportedTypes) {
if (type.equals(mimeType, ignoreCase = true) && predicate(info, type)) {
return info
}
}
}
return null
}
fun isHardwareAccelerated(info: MediaCodecInfo): Boolean = isHardwareAccelerated(Build.VERSION.SDK_INT, info.isHardwareAccelerated, info.name)
internal fun isHardwareAccelerated(
sdkInt: Int,
platformReportsHardware: Boolean,
name: String
): Boolean {
// API 29 added manufacturer-provided classification, but some Codec2
// builders still flag known software components as hardware. Require both
// signals there; older releases expose only component names.
return if (sdkInt >= Build.VERSION_CODES.Q) {
platformReportsHardware && !isSoftwareCodecName(name)
} else {
!isSoftwareCodecName(name)
}
}
internal fun isSoftwareCodecName(name: String): Boolean {
val normalized = name.lowercase(Locale.ROOT)
return normalized.startsWith("omx.google.") ||
normalized.startsWith("omx.ffmpeg.") ||
normalized.startsWith("c2.android.") ||
normalized.startsWith("c2.google.") ||
normalized.startsWith("c2.ffmpeg.") ||
normalized.contains(".sw.")
}
}
@@ -0,0 +1,69 @@
package com.edde746.plezy.shared
import android.content.ContentResolver
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.os.ParcelFileDescriptor
import android.util.Log
internal data class ResolvedMpvUri(
val value: String,
private val ownedFd: Int? = null
) {
fun closeIfUnused() {
val fd = ownedFd ?: return
try {
ParcelFileDescriptor.adoptFd(fd).close()
} catch (error: Exception) {
Log.w("MpvContentUriResolver", "Failed to close unused content FD $fd", error)
}
}
}
internal object MpvContentUriResolver {
private const val TAG = "MpvContentUriResolver"
fun resolve(
uriString: String,
resolver: ContentResolver,
mainHandler: Handler,
onResolved: (ResolvedMpvUri) -> Unit
) {
resolve(uriString, mainHandler, opener = {
val descriptor = resolver.openFileDescriptor(Uri.parse(uriString), "r") ?: return@resolve null
descriptor.detachFd()
}, onResolved = onResolved)
}
internal fun resolve(
uriString: String,
mainHandler: Handler,
opener: () -> Int?,
onResolved: (ResolvedMpvUri) -> Unit
) {
if (!uriString.startsWith("content://")) {
onResolved(ResolvedMpvUri(uriString))
return
}
Thread {
check(Looper.myLooper() != Looper.getMainLooper()) {
"Content file descriptors must not be opened on the main thread"
}
val fd = try {
opener()
} catch (error: Exception) {
Log.e(TAG, "Failed to open content FD for $uriString", error)
null
}
val resolved = if (fd == null) {
ResolvedMpvUri(uriString)
} else {
Log.d(TAG, "Opened content FD $fd for $uriString")
ResolvedMpvUri("fdclose://$fd", fd)
}
mainHandler.post { onResolved(resolved) }
}.start()
}
}
@@ -0,0 +1,70 @@
package com.edde746.plezy.shared
import android.os.Handler
import android.os.Looper
import android.util.Log
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodChannel
/** Owns the identical MethodChannel/EventChannel lifecycle for native players. */
internal class PlayerChannelBinding(
private val channelBase: String,
private val methodCallHandler: MethodChannel.MethodCallHandler,
private val streamHandler: EventChannel.StreamHandler,
private val logTag: String
) {
private lateinit var methodChannel: MethodChannel
private lateinit var eventChannel: EventChannel
private var eventSink: EventChannel.EventSink? = null
val mainHandler = Handler(Looper.getMainLooper())
fun attach(binding: FlutterPlugin.FlutterPluginBinding) {
methodChannel = MethodChannel(binding.binaryMessenger, channelBase)
methodChannel.setMethodCallHandler(methodCallHandler)
eventChannel = EventChannel(binding.binaryMessenger, "$channelBase/events")
eventChannel.setStreamHandler(streamHandler)
Log.d(logTag, "Attached to engine")
}
fun detach() {
methodChannel.setMethodCallHandler(null)
eventChannel.setStreamHandler(null)
eventSink = null
Log.d(logTag, "Detached from engine")
}
fun listen(events: EventChannel.EventSink?) {
eventSink = events
Log.d(logTag, "Event stream connected")
}
fun cancel() {
eventSink = null
Log.d(logTag, "Event stream disconnected")
}
fun runOnMain(block: () -> Unit) {
if (Looper.myLooper() == Looper.getMainLooper()) {
block()
} else {
mainHandler.post(block)
}
}
fun emitProperty(id: Int, value: Any?) {
runOnMain { eventSink?.success(listOf(id, value)) }
}
fun emitEvent(name: String, data: Map<String, Any>? = null) {
val event = mutableMapOf<String, Any>(
"type" to "event",
"name" to name
)
data?.let { event["data"] = it }
runOnMain { eventSink?.success(event) }
}
}
@@ -0,0 +1,47 @@
package com.edde746.plezy.shared
import android.app.Activity
import android.graphics.Color
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.ViewGroup
import android.widget.FrameLayout
/** Shared Android view scaffold beneath the ExoPlayer and mpv cores. */
internal object PlayerSurfaceHost {
fun createContainer(activity: Activity, clipChildren: Boolean = false): FrameLayout = FrameLayout(activity).apply {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
setBackgroundColor(Color.BLACK)
this.clipChildren = clipChildren
}
fun createVideoSurface(activity: Activity, callback: SurfaceHolder.Callback): SurfaceView = SurfaceView(activity).apply {
layoutParams = FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT
)
holder.addCallback(callback)
setZOrderOnTop(false)
setZOrderMediaOverlay(false)
FlutterOverlayHelper.applyCompositionOrder(this, -2)
}
fun attachToContent(activity: Activity, container: FrameLayout): ViewGroup {
val contentView = activity.findViewById<ViewGroup>(android.R.id.content)
contentView.addView(container, 0)
ensureFlutterOverlayOnTop(contentView, container)
return contentView
}
fun ensureFlutterOverlayOnTop(contentView: ViewGroup, surfaceContainer: ViewGroup?): Boolean {
val flutterContainer = FlutterOverlayHelper.findFlutterContainer(contentView, surfaceContainer)
?: return false
if (contentView.getChildAt(contentView.childCount - 1) !== flutterContainer) {
FlutterOverlayHelper.configureFlutterZOrder(contentView, flutterContainer, compositionOrder = 1)
}
return true
}
}
@@ -0,0 +1,102 @@
package com.edde746.plezy
import android.graphics.SurfaceTexture
import android.os.Looper
import android.view.TextureView
import java.time.Duration
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.LooperMode
@RunWith(RobolectricTestRunner::class)
@LooperMode(LooperMode.Mode.PAUSED)
class DeferredSurfaceTextureListenerTest {
private lateinit var surface: SurfaceTexture
private lateinit var delegate: RecordingListener
private lateinit var listener: DeferredSurfaceTextureListener
private var currentSurface: SurfaceTexture? = null
@Before
fun setUp() {
surface = SurfaceTexture(0)
currentSurface = surface
delegate = RecordingListener()
listener = DeferredSurfaceTextureListener(delegate) { candidate -> candidate === currentSurface }
}
@After
fun tearDown() {
surface.release()
}
@Test
fun forwardsRepeatedSameSizeCallbacks() {
listener.onSurfaceTextureSizeChanged(surface, 1920, 1080)
idlePastResizeDelay()
listener.onSurfaceTextureSizeChanged(surface, 1920, 1080)
idlePastResizeDelay()
assertEquals(listOf(1920 to 1080, 1920 to 1080), delegate.sizes)
}
@Test
fun coalescesPendingCallbacksToLatestSize() {
listener.onSurfaceTextureSizeChanged(surface, 1280, 720)
listener.onSurfaceTextureSizeChanged(surface, 1920, 1080)
idlePastResizeDelay()
assertEquals(listOf(1920 to 1080), delegate.sizes)
}
@Test
fun ignoresCallbackForObsoleteSurface() {
val replacement = SurfaceTexture(0)
try {
listener.onSurfaceTextureSizeChanged(surface, 1920, 1080)
currentSurface = replacement
idlePastResizeDelay()
assertEquals(emptyList<Pair<Int, Int>>(), delegate.sizes)
} finally {
replacement.release()
}
}
@Test
fun destroyingSurfaceCancelsPendingCallback() {
listener.onSurfaceTextureSizeChanged(surface, 1920, 1080)
listener.onSurfaceTextureDestroyed(surface)
idlePastResizeDelay()
assertEquals(emptyList<Pair<Int, Int>>(), delegate.sizes)
assertEquals(1, delegate.destroyedCount)
}
private fun idlePastResizeDelay() {
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(101))
}
private class RecordingListener : TextureView.SurfaceTextureListener {
val sizes = mutableListOf<Pair<Int, Int>>()
var destroyedCount = 0
override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) = Unit
override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {
sizes += width to height
}
override fun onSurfaceTextureUpdated(surface: SurfaceTexture) = Unit
override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean {
destroyedCount++
return true
}
}
}
@@ -0,0 +1,66 @@
package com.edde746.plezy
import android.app.Activity
import android.content.Intent
import io.flutter.plugin.common.MethodChannel
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class ExternalPlayerChannelTest {
@Test
fun mxPlayerResultPreservesPositionDurationAndCompletion() {
val activity = Robolectric.buildActivity(Activity::class.java).get()
val channel = ExternalPlayerChannel(activity)
val data = Intent("com.mxtech.intent.result.VIEW")
.putExtra("position", 123)
.putExtra("duration", "456")
.putExtra("end_by", "playback_completion")
val result = channel.buildResult(Activity.RESULT_OK, data)
assertEquals(123L, result["positionMs"])
assertEquals(456L, result["durationMs"])
assertEquals(true, result["playbackCompleted"])
assertEquals(false, result["playbackError"])
}
@Test
fun activityDestroyCompletesPendingChannelCall() {
val activity = Robolectric.buildActivity(Activity::class.java).get()
val channel = ExternalPlayerChannel(activity)
val result = RecordingResult()
channel.javaClass.getDeclaredField("pendingResult").apply {
isAccessible = true
set(channel, result)
}
channel.dispose()
assertTrue(result.completed)
assertEquals("ACTIVITY_DESTROYED", result.errorCode)
}
private class RecordingResult : MethodChannel.Result {
var completed = false
var errorCode: String? = null
override fun success(result: Any?) {
completed = true
}
override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) {
completed = true
this.errorCode = errorCode
}
override fun notImplemented() {
completed = true
}
}
}
@@ -0,0 +1,47 @@
package com.edde746.plezy.exoplayer
import androidx.media3.common.MimeTypes
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class AudioOutputPolicyTest {
@Test
fun passthroughDisabledBlocksBitstreamFormats() {
val bitstreamFormats = listOf(
"audio/ac3",
"audio/eac3",
"audio/eac3-joc",
"audio/ac4",
"audio/vnd.dts",
"audio/vnd.dts.hd",
"audio/vnd.dts.uhd",
MimeTypes.AUDIO_TRUEHD
)
for (mimeType in bitstreamFormats) {
assertTrue(mimeType, shouldBlockDirectOutputForPassthrough(mimeType, audioPassthroughEnabled = false))
}
}
@Test
fun passthroughEnabledAllowsBitstreamFormats() {
assertFalse(shouldBlockDirectOutputForPassthrough("audio/ac3", audioPassthroughEnabled = true))
assertFalse(shouldBlockDirectOutputForPassthrough(MimeTypes.AUDIO_TRUEHD, audioPassthroughEnabled = true))
}
@Test
fun passthroughDisabledLeavesDecodedFormatsAvailable() {
val decodedFormats = listOf(
MimeTypes.AUDIO_AAC,
MimeTypes.AUDIO_OPUS,
MimeTypes.AUDIO_RAW,
MimeTypes.AUDIO_FLAC
)
for (mimeType in decodedFormats) {
assertFalse(mimeType, shouldBlockDirectOutputForPassthrough(mimeType, audioPassthroughEnabled = false))
}
}
}
@@ -0,0 +1,100 @@
package com.edde746.plezy.exoplayer
import androidx.media3.common.C
import androidx.media3.common.DataReader
import androidx.media3.common.Format
import androidx.media3.common.util.ParsableByteArray
import androidx.media3.extractor.TrackOutput
import java.io.ByteArrayOutputStream
import java.io.EOFException
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertThrows
import org.junit.Test
class BufferedTransformingTrackOutputTest {
@Test
fun activeTransformBuffersChunksAndEmitsOneNormalizedSample() {
val delegate = RecordingTrackOutput()
val output = IncrementingTrackOutput(delegate)
output.sampleData(ParsableByteArray(byteArrayOf(1, 2)), 2, TrackOutput.SAMPLE_DATA_PART_MAIN)
output.sampleData(ParsableByteArray(byteArrayOf(3)), 1, TrackOutput.SAMPLE_DATA_PART_MAIN)
output.sampleMetadata(42, C.BUFFER_FLAG_KEY_FRAME, 3, 7, null)
assertArrayEquals(byteArrayOf(2, 3, 4), delegate.bytes.toByteArray())
assertEquals(42, delegate.timeUs)
assertEquals(3, delegate.sampleSize)
assertEquals(0, delegate.sampleOffset)
}
@Test
fun activeTransformHonorsDataReaderEndOfInputContract() {
val output = IncrementingTrackOutput(RecordingTrackOutput())
val exhausted = DataReader { _, _, _ -> C.RESULT_END_OF_INPUT }
assertThrows(EOFException::class.java) {
output.sampleData(exhausted, 1, false, TrackOutput.SAMPLE_DATA_PART_MAIN)
}
assertEquals(
C.RESULT_END_OF_INPUT,
output.sampleData(exhausted, 1, true, TrackOutput.SAMPLE_DATA_PART_MAIN)
)
}
private class IncrementingTrackOutput(delegate: TrackOutput) : BufferedTransformingTrackOutput(delegate, initialBufferSize = 2) {
private var transformed = ByteArray(2)
override val transformEnabled = true
override val transformedBuffer: ByteArray
get() = transformed
override fun transformSample(inputLength: Int, flags: Int): Int {
if (transformed.size < inputLength) transformed = ByteArray(inputLength)
for (index in 0 until inputLength) {
transformed[index] = (inputBuffer[index] + 1).toByte()
}
return inputLength
}
}
private class RecordingTrackOutput : TrackOutput {
val bytes = ByteArrayOutputStream()
var timeUs = C.TIME_UNSET
var sampleSize = -1
var sampleOffset = -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) bytes.write(buffer, 0, read)
return read
}
override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) {
val buffer = ByteArray(length)
data.readBytes(buffer, 0, length)
bytes.write(buffer)
}
override fun sampleMetadata(
timeUs: Long,
flags: Int,
size: Int,
offset: Int,
cryptoData: TrackOutput.CryptoData?
) {
this.timeUs = timeUs
sampleSize = size
sampleOffset = offset
}
}
}
@@ -0,0 +1,117 @@
package com.edde746.plezy.exoplayer
import kotlin.math.pow
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class DownmixMatricesTest {
private fun coeff(matrix: FloatArray, input: Int, output: Int) = matrix[input * 2 + output]
private fun columnSum(matrix: FloatArray, output: Int): Float {
var sum = 0f
for (input in 0 until matrix.size / 2) sum += coeff(matrix, input, output)
return sum
}
@Test
fun centerGainMatchesKodiFormula() {
// Kodi: center_mix_level = 10^((-3 + boost) / 20)
assertEquals(0.70795f, DownmixMatrices.centerGain(0), 1e-3f)
assertEquals(1.0f, DownmixMatrices.centerGain(3), 1e-3f)
assertEquals(2.81838f, DownmixMatrices.centerGain(12), 1e-3f)
}
@Test
fun centerGainClampsBoost() {
assertEquals(DownmixMatrices.centerGain(12), DownmixMatrices.centerGain(20), 0f)
assertEquals(DownmixMatrices.centerGain(0), DownmixMatrices.centerGain(-5), 0f)
}
@Test
fun fivePointOneLayoutUnnormalized() {
val m = DownmixMatrices.stereoCoefficients(6, centerBoostDb = 0, normalize = false)!!
val c = DownmixMatrices.centerGain(0)
val s = DownmixMatrices.SURROUND_GAIN
// FL FR FC LFE BL BR
assertEquals(1f, coeff(m, 0, 0), 0f)
assertEquals(0f, coeff(m, 0, 1), 0f)
assertEquals(0f, coeff(m, 1, 0), 0f)
assertEquals(1f, coeff(m, 1, 1), 0f)
assertEquals(c, coeff(m, 2, 0), 0f)
assertEquals(c, coeff(m, 2, 1), 0f)
assertEquals(0f, coeff(m, 3, 0), 0f) // LFE dropped
assertEquals(0f, coeff(m, 3, 1), 0f)
assertEquals(s, coeff(m, 4, 0), 0f)
assertEquals(0f, coeff(m, 4, 1), 0f)
assertEquals(0f, coeff(m, 5, 0), 0f)
assertEquals(s, coeff(m, 5, 1), 0f)
}
@Test
fun sixPointOneBackCenterMixesHalfToEachSide() {
val m = DownmixMatrices.stereoCoefficients(7, centerBoostDb = 0, normalize = false)!!
assertEquals(0.5f, coeff(m, 6, 0), 0f)
assertEquals(0.5f, coeff(m, 6, 1), 0f)
}
@Test
fun normalizeScalesMaxColumnSumToOne() {
for (channels in intArrayOf(6, 8)) {
val m = DownmixMatrices.stereoCoefficients(channels, centerBoostDb = 6, normalize = true)!!
assertEquals("channels=$channels L", 1f, columnSum(m, 0), 1e-4f)
assertEquals("channels=$channels R", 1f, columnSum(m, 1), 1e-4f)
// Relative balance is preserved: FC/FL ratio equals the raw center gain.
assertEquals(DownmixMatrices.centerGain(6), coeff(m, 2, 0) / coeff(m, 0, 0), 1e-4f)
}
}
@Test
fun normalizeNeverAmplifies() {
for (channels in DownmixMatrices.MIN_DOWNMIX_INPUT_CHANNELS..DownmixMatrices.MAX_DOWNMIX_INPUT_CHANNELS) {
val raw = DownmixMatrices.stereoCoefficients(channels, centerBoostDb = 6, normalize = false)!!
val normalized = DownmixMatrices.stereoCoefficients(channels, centerBoostDb = 6, normalize = true)!!
for (i in raw.indices) {
assertTrue("channels=$channels i=$i", normalized[i] <= raw[i] + 1e-6f)
}
}
}
@Test
fun boostRaisesOnlyTheCenterChannel() {
val base = DownmixMatrices.stereoCoefficients(6, centerBoostDb = 0, normalize = false)!!
val boosted = DownmixMatrices.stereoCoefficients(6, centerBoostDb = 6, normalize = false)!!
val expectedRatio = 10f.pow(6f / 20f)
assertEquals(expectedRatio, coeff(boosted, 2, 0) / coeff(base, 2, 0), 1e-4f)
for (input in intArrayOf(0, 1, 3, 4, 5)) {
assertEquals("input=$input L", coeff(base, input, 0), coeff(boosted, input, 0), 0f)
assertEquals("input=$input R", coeff(base, input, 1), coeff(boosted, input, 1), 0f)
}
}
@Test
fun passThroughCountsReturnNull() {
for (channels in intArrayOf(1, 2, 9, 12)) {
assertNull("channels=$channels", DownmixMatrices.stereoCoefficients(channels, 0, true))
}
}
@Test
fun allCoefficientsNonNegative() {
// ChannelMixingMatrix throws on negative coefficients; guard every combination.
for (channels in DownmixMatrices.MIN_DOWNMIX_INPUT_CHANNELS..DownmixMatrices.MAX_DOWNMIX_INPUT_CHANNELS) {
for (boost in intArrayOf(0, 6, 12)) {
for (normalize in booleanArrayOf(true, false)) {
val m = DownmixMatrices.stereoCoefficients(channels, boost, normalize)
assertNotNull(m)
for (value in m!!) {
assertTrue("channels=$channels boost=$boost normalize=$normalize", value >= 0f)
}
}
}
}
}
}
@@ -0,0 +1,51 @@
package com.edde746.plezy.exoplayer
import android.app.Activity
import android.os.Looper
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.widget.FrameLayout
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
@RunWith(RobolectricTestRunner::class)
class ExoPlayerInitializationCleanupTest {
@Test
fun disposeRemovesPartiallyAttachedViewAndLayoutListener() {
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
activity.setContentView(FrameLayout(activity))
val content = activity.findViewById<ViewGroup>(android.R.id.content)
val container = FrameLayout(activity)
content.addView(container)
var layoutCallbacks = 0
val listener = ViewTreeObserver.OnGlobalLayoutListener { layoutCallbacks++ }
content.viewTreeObserver.addOnGlobalLayoutListener(listener)
val core = ExoPlayerCore(activity)
core.setPrivateField("surfaceContainer", container)
core.setPrivateField("overlayLayoutListener", listener)
core.dispose()
content.viewTreeObserver.dispatchOnGlobalLayout()
shadowOf(Looper.getMainLooper()).idle()
assertEquals(0, layoutCallbacks)
assertNull(container.parent)
assertNull(core.getPrivateField("overlayLayoutListener"))
}
private fun Any.setPrivateField(name: String, value: Any?) {
javaClass.getDeclaredField(name).apply {
isAccessible = true
set(this@setPrivateField, value)
}
}
private fun Any.getPrivateField(name: String): Any? = javaClass.getDeclaredField(name).apply { isAccessible = true }.get(this)
}
@@ -0,0 +1,90 @@
package com.edde746.plezy.exoplayer
import android.os.Looper
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
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.Shadows.shadowOf
@RunWith(RobolectricTestRunner::class)
class ExoPlayerPluginTest {
@Test
fun fallbackGetStatsCompletesAfterActivityDetach() {
val plugin = ExoPlayerPlugin()
plugin.javaClass.getDeclaredField("usingMpvFallback").apply {
isAccessible = true
setBoolean(plugin, true)
}
val result = RecordingResult()
plugin.onMethodCall(MethodCall("getStats", null), result)
var completed = false
repeat(100) {
shadowOf(Looper.getMainLooper()).idle()
if (result.completed.await(10, TimeUnit.MILLISECONDS)) {
completed = true
return@repeat
}
}
assertTrue("fallback getStats never completed", completed)
assertEquals(mapOf("playerType" to "mpv"), result.successValue)
}
@Test
fun eventCallbacksKeepTheSharedPlayerEnvelope() {
val plugin = ExoPlayerPlugin()
val sink = RecordingEventSink()
plugin.onListen(null, sink)
plugin.onEvent("ready", mapOf("position" to 42))
assertEquals(
mapOf(
"type" to "event",
"name" to "ready",
"data" to mapOf("position" to 42)
),
sink.successValue
)
}
private class RecordingResult : 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()
}
}
private class RecordingEventSink : EventChannel.EventSink {
var successValue: Any? = null
override fun success(event: Any?) {
successValue = event
}
override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) = Unit
override fun endOfStream() = Unit
}
}
@@ -0,0 +1,241 @@
package com.edde746.plezy.exoplayer
import androidx.media3.common.C
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 androidx.media3.extractor.mkv.MatroskaExtractor
import java.io.EOFException
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
/**
* Extracts the committed fixture (1s 440Hz sine, AAC-LC 48kHz stereo, LATM/LOAS
* muxed into MKV as A_MS/ACM tag 0x1602 — the layout Plex produces when
* Direct-Streaming HDHomeRun aac_latm audio) and verifies LOAS frames are
* unwrapped to raw AAC with a synthesized AudioSpecificConfig.
*
* Robolectric provides real android.util.* implementations — MatroskaExtractor
* stores tracks in a SparseArray, which is a no-op stub on plain JVM.
*/
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
class LatmMatroskaExtractorTest {
private class CapturedSample(val timeUs: Long, val flags: Int, val data: ByteArray)
private class FakeTrackOutput : TrackOutput {
val formats = mutableListOf<Format>()
val samples = mutableListOf<CapturedSample>()
private var buf = ByteArray(64 * 1024)
private var bufLen = 0
override fun format(format: Format) {
formats.add(format)
}
override fun sampleData(input: DataReader, length: Int, allowEndOfInput: Boolean, sampleDataPart: Int): Int {
ensureCapacity(bufLen + length)
val read = input.read(buf, bufLen, length)
if (read > 0) bufLen += read
return read
}
override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) {
ensureCapacity(bufLen + length)
data.readBytes(buf, bufLen, length)
bufLen += length
}
override fun sampleMetadata(timeUs: Long, flags: Int, size: Int, offset: Int, cryptoData: TrackOutput.CryptoData?) {
val start = bufLen - offset - size
samples.add(CapturedSample(timeUs, flags, buf.copyOfRange(start, start + size)))
if (offset == 0) bufLen = 0
}
private fun ensureCapacity(needed: Int) {
if (buf.size < needed) buf = buf.copyOf(maxOf(needed, buf.size * 2))
}
}
private class FakeExtractorOutput : ExtractorOutput {
val tracks = mutableMapOf<Int, FakeTrackOutput>()
override fun track(id: Int, type: Int): TrackOutput = tracks.getOrPut(id) { FakeTrackOutput() }
override fun endTracks() {}
override fun seekMap(seekMap: SeekMap) {}
}
private class ByteArrayDataReader(private val data: ByteArray) : DataReader {
var position = 0L
override fun read(buffer: ByteArray, offset: Int, length: Int): Int {
if (position >= data.size) return C.RESULT_END_OF_INPUT
val toRead = minOf(length, data.size - position.toInt())
System.arraycopy(data, position.toInt(), buffer, offset, toRead)
position += toRead
return toRead
}
}
private fun fixtureData(): ByteArray = checkNotNull(javaClass.getResourceAsStream("/latm_loas.mkv")) {
"fixture latm_loas.mkv missing from test resources"
}.use { it.readBytes() }
private fun loasFrames(count: Int): List<ByteArray> {
val data = fixtureData()
val frames = mutableListOf<ByteArray>()
var position = 0
while (position <= data.size - 3 && frames.size < count) {
val isSyncWord = (data[position].toInt() and 0xFF) == 0x56 &&
(data[position + 1].toInt() and 0xE0) == 0xE0
if (isSyncWord) {
val payloadSize = ((data[position + 1].toInt() and 0x1F) shl 8) or
(data[position + 2].toInt() and 0xFF)
val end = position + 3 + payloadSize
if (payloadSize > 0 && end <= data.size) {
frames.add(data.copyOfRange(position, end))
position = end
continue
}
}
position++
}
check(frames.size == count) { "expected $count LOAS frames, found ${frames.size}" }
return frames
}
private fun extractFixture(): FakeExtractorOutput {
val data = fixtureData()
val extractor = LatmMatroskaExtractor(MatroskaExtractor.FLAG_DISABLE_SEEK_FOR_CUES)
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 -> {}
}
}
}
@Test
fun unwrapsLoasAcmTrackToRawAac() {
val output = extractFixture()
assertEquals(1, output.tracks.size)
val track = output.tracks.values.first()
// 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()
assertEquals(MimeTypes.AUDIO_AAC, format.sampleMimeType)
assertEquals(48000, format.sampleRate)
assertEquals(2, format.channelCount)
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(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
fun formatIsEmittedBeforeFirstSample() {
val output = extractFixture()
val track = output.tracks.values.first()
assertNotNull(track.formats.firstOrNull())
// LatmReader emits the format from the first StreamMuxConfig, which arrives
// with the first LOAS frame — before any sample metadata is committed.
assertTrue(track.samples.isNotEmpty())
}
@Test
fun rejectsUnexpectedEndOfInput() {
val output = LatmTrackOutput(FakeTrackOutput(), 1)
val reader = ByteArrayDataReader(ByteArray(0))
assertThrows(EOFException::class.java) {
output.sampleData(reader, 1, false, TrackOutput.SAMPLE_DATA_PART_MAIN)
}
assertEquals(
C.RESULT_END_OF_INPUT,
output.sampleData(reader, 1, true, TrackOutput.SAMPLE_DATA_PART_MAIN)
)
}
@Test
fun preservesStreamMuxConfigAcrossExtractorSeek() {
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.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)
assertEquals(1, delegate.samples.size)
output.reset()
output.sampleData(ParsableByteArray(frames[1]), frames[1].size, TrackOutput.SAMPLE_DATA_PART_MAIN)
output.sampleMetadata(21_000, C.BUFFER_FLAG_KEY_FRAME, frames[1].size, 0, null)
assertEquals(2, delegate.samples.size)
}
}
@@ -0,0 +1,138 @@
package com.edde746.plezy.exoplayer
import androidx.media3.common.C
import com.edde746.plezy.exoplayer.ResumeStallPolicy.Verdict
import org.junit.Assert.assertEquals
import org.junit.Test
class ResumeStallPolicyTest {
// checkWindowMs
@Test
fun windowFloorsAtDefaultForNormalFrameRates() {
// 24fps → 4 × 42ms = 168ms, floored to 1000ms
assertEquals(1000L, ResumeStallPolicy.checkWindowMs(formatFps = 24f, detectedFps = -1f, speed = 1f))
assertEquals(1000L, ResumeStallPolicy.checkWindowMs(formatFps = 60f, detectedFps = -1f, speed = 1f))
}
@Test
fun windowScalesUpForLowFrameRates() {
// 2fps → 4 × 500ms = 2000ms
assertEquals(2000L, ResumeStallPolicy.checkWindowMs(formatFps = 2f, detectedFps = -1f, speed = 1f))
}
@Test
fun windowScalesUpForSlowedPlayback() {
// 8fps at 0.25× speed → effective 2fps → 2000ms
assertEquals(2000L, ResumeStallPolicy.checkWindowMs(formatFps = 8f, detectedFps = -1f, speed = 0.25f))
// fast playback shrinks the interval; still floored
assertEquals(1000L, ResumeStallPolicy.checkWindowMs(formatFps = 24f, detectedFps = -1f, speed = 2f))
}
@Test
fun windowFallsBackThroughDetectedFpsToDefault() {
// Format fps unknown (NO_VALUE = -1) → detected fps wins
assertEquals(2000L, ResumeStallPolicy.checkWindowMs(formatFps = -1f, detectedFps = 2f, speed = 1f))
// Neither known → 24fps assumption → floor
assertEquals(1000L, ResumeStallPolicy.checkWindowMs(formatFps = -1f, detectedFps = -1f, speed = 1f))
assertEquals(1000L, ResumeStallPolicy.checkWindowMs(formatFps = null, detectedFps = null, speed = 1f))
}
// evaluate
@Test
fun advancingFramesAreHealthy() {
assertEquals(
Verdict.HEALTHY,
ResumeStallPolicy.evaluate(
baselineFrames = 100,
currentFrames = 124,
baselinePositionMs = 60_000,
currentPositionMs = 61_000,
durationMs = 3_600_000,
windowMs = 1000
)
)
}
@Test
fun counterResetCountsAsHealthy() {
// Renderer re-enable resets DecoderCounters below the baseline — not a stall.
assertEquals(
Verdict.HEALTHY,
ResumeStallPolicy.evaluate(
baselineFrames = 100,
currentFrames = 3,
baselinePositionMs = 60_000,
currentPositionMs = 61_000,
durationMs = 3_600_000,
windowMs = 1000
)
)
}
@Test
fun stalledClockRequestsRecheck() {
// Frames frozen but the position isn't advancing either: generic buffering
// stall, not the decoder freeze this watchdog targets.
assertEquals(
Verdict.RECHECK,
ResumeStallPolicy.evaluate(
baselineFrames = 100,
currentFrames = 100,
baselinePositionMs = 60_000,
currentPositionMs = 60_200,
durationMs = 3_600_000,
windowMs = 1000
)
)
}
@Test
fun nearEndOfStreamIsSkipped() {
// Video track ending before audio is legitimate near EOF.
assertEquals(
Verdict.SKIP_NEAR_EOF,
ResumeStallPolicy.evaluate(
baselineFrames = 100,
currentFrames = 100,
baselinePositionMs = 3_598_000,
currentPositionMs = 3_599_000,
durationMs = 3_600_000,
windowMs = 1000
)
)
}
@Test
fun frozenFramesWithAdvancingClockMidFileIsStalled() {
assertEquals(
Verdict.STALLED,
ResumeStallPolicy.evaluate(
baselineFrames = 100,
currentFrames = 100,
baselinePositionMs = 60_000,
currentPositionMs = 61_000,
durationMs = 3_600_000,
windowMs = 1000
)
)
}
@Test
fun unknownDurationSkipsEofGuardAndStalls() {
// Live/unknown duration (C.TIME_UNSET) must not suppress detection.
assertEquals(
Verdict.STALLED,
ResumeStallPolicy.evaluate(
baselineFrames = 100,
currentFrames = 100,
baselinePositionMs = 60_000,
currentPositionMs = 61_000,
durationMs = C.TIME_UNSET,
windowMs = 1000
)
)
}
}
@@ -0,0 +1,49 @@
package com.edde746.plezy.exoplayer
import androidx.media3.common.text.Cue
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Test
class SubtitleCueLayoutTest {
@Test
fun concurrentUnpositionedCuesStackFromBottom() {
val first = Cue.Builder().setText("first").build()
val second = Cue.Builder().setText("second").build()
val laidOut = SubtitleCueLayout.layout(listOf(first, second), positionPercent = 100, fontSize = 36f)
assertEquals(Cue.LINE_TYPE_NUMBER, laidOut[0].lineType)
assertEquals(-2f, laidOut[0].line)
assertEquals(Cue.ANCHOR_TYPE_END, laidOut[0].lineAnchor)
assertEquals(-1f, laidOut[1].line)
}
@Test
fun userPositionPreservesStackSpacing() {
val first = Cue.Builder().setText("first").build()
val second = Cue.Builder().setText("second").build()
val laidOut = SubtitleCueLayout.layout(listOf(first, second), positionPercent = 50, fontSize = 36f)
assertEquals(Cue.LINE_TYPE_FRACTION, laidOut[0].lineType)
assertEquals(0.44f, laidOut[0].line, 0.0001f)
assertEquals(0.5f, laidOut[1].line, 0.0001f)
assertEquals(Cue.ANCHOR_TYPE_END, laidOut[0].lineAnchor)
assertEquals(Cue.ANCHOR_TYPE_END, laidOut[1].lineAnchor)
}
@Test
fun explicitCuePositionIsNotOverridden() {
val positioned = Cue.Builder()
.setText("positioned")
.setLine(0.25f, Cue.LINE_TYPE_FRACTION)
.setLineAnchor(Cue.ANCHOR_TYPE_START)
.build()
val laidOut = SubtitleCueLayout.layout(listOf(positioned), positionPercent = 50, fontSize = 36f)
assertSame(positioned, laidOut.single())
}
}
@@ -0,0 +1,78 @@
package com.edde746.plezy.exoplayer
import androidx.media3.ui.AspectRatioFrameLayout
import org.junit.Assert.assertEquals
import org.junit.Test
class SubtitleViewLayoutTest {
@Test
fun letterboxUsesVisibleVideoRectForTextAndBitmapSubtitles() {
val text = textDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT)
val bitmap = bitmapDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT)
assertEquals(SubtitleViewDimensions(1920, 1080), text)
assertEquals(SubtitleViewDimensions(1920, 1080), bitmap)
}
@Test
fun coverKeepsTextOnScreenAndBitmapSubtitlesFullyVisible() {
val text = textDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_ZOOM)
val bitmap = bitmapDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_ZOOM)
assertEquals(SubtitleViewDimensions(2424, 1080), text)
assertEquals(SubtitleViewDimensions(1920, 1080), bitmap)
assertAspectCloseTo16By9(bitmap!!)
}
@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)
assertEquals(SubtitleViewDimensions(2424, 1080), text)
assertEquals(SubtitleViewDimensions(1920, 1080), bitmap)
assertAspectCloseTo16By9(bitmap!!)
}
@Test
fun stretchDoesNotStretchBitmapSubtitlesToScreenAspect() {
val text = textDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FILL)
val bitmap = bitmapDimensions(resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FILL)
assertEquals(SubtitleViewDimensions(2424, 1080), text)
assertEquals(SubtitleViewDimensions(1920, 1080), bitmap)
assertAspectCloseTo16By9(bitmap!!)
}
private fun textDimensions(
resizeMode: Int,
zoomScale: Float = 1f
): SubtitleViewDimensions? = SubtitleViewLayout.textDimensions(
containerWidth = 2424,
containerHeight = 1080,
videoWidth = 1920,
videoHeight = 1080,
pixelRatio = 1f,
resizeMode = resizeMode,
zoomScale = zoomScale
)
private fun bitmapDimensions(
resizeMode: Int,
zoomScale: Float = 1f
): SubtitleViewDimensions? = SubtitleViewLayout.bitmapDimensions(
containerWidth = 2424,
containerHeight = 1080,
videoWidth = 1920,
videoHeight = 1080,
pixelRatio = 1f,
resizeMode = resizeMode,
zoomScale = zoomScale
)
private fun assertAspectCloseTo16By9(dimensions: SubtitleViewDimensions) {
val aspect = dimensions.width.toDouble() / dimensions.height
assertEquals(16.0 / 9.0, aspect, 0.001)
}
}
@@ -0,0 +1,157 @@
package com.edde746.plezy.mpv
import dev.jdtech.mpv.EndFileReason
import dev.jdtech.mpv.LogLevel
import dev.jdtech.mpv.LogMessage
import dev.jdtech.mpv.MpvEvent
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class MpvPlayerPluginTest {
@Test
fun commandWithoutCoreReportsNotInitialized() {
val result = RecordingResult()
MpvPlayerPlugin().onMethodCall(
MethodCall("command", mapOf("args" to listOf("seek", "1", "absolute"))),
result
)
assertEquals("NOT_INITIALIZED", result.errorCode)
assertNull(result.successValue)
}
@Test
fun disposeCompletesEveryPendingInitialization() {
val plugin = MpvPlayerPlugin()
val first = RecordingResult()
val second = RecordingResult()
@Suppress("UNCHECKED_CAST")
val pending = plugin.javaClass.getDeclaredField("pendingInitResults").apply {
isAccessible = true
}.get(plugin) as MutableList<MethodChannel.Result>
pending += first
pending += second
plugin.javaClass.getDeclaredField("isInitializing").apply {
isAccessible = true
setBoolean(plugin, true)
}
val dispose = RecordingResult()
plugin.onMethodCall(MethodCall("dispose", null), dispose)
assertEquals(false, first.successValue)
assertEquals(false, second.successValue)
assertNull(dispose.successValue)
assertTrue(first.completed)
assertTrue(second.completed)
assertTrue(dispose.completed)
assertEquals(0, pending.size)
}
@Test
fun setLogLevelReportsUnsupported() {
val result = RecordingResult()
MpvPlayerPlugin().onMethodCall(
MethodCall("setLogLevel", mapOf("level" to "warn")),
result
)
assertEquals("UNSUPPORTED", result.errorCode)
assertNull(result.successValue)
}
@Test
fun endFileDiagnosticsPreserveReasonIdAndExposeDependencyErrorLog() {
val diagnostics = MpvEndFileDiagnostics()
diagnostics.onStartFile()
diagnostics.onLogMessage(LogMessage("ffmpeg", LogLevel.Error, "Invalid data found when processing input"))
assertEquals(
mapOf(
"reason" to 4,
"message" to "Invalid data found when processing input"
),
diagnostics.onEndFile(MpvEvent.EndFile(EndFileReason.Error))
)
}
@Test
fun endFileDiagnosticsDoNotAttachStaleOrInventedDetails() {
val diagnostics = MpvEndFileDiagnostics()
diagnostics.onLogMessage(LogMessage("ffmpeg", LogLevel.Error, "old failure"))
diagnostics.onStartFile()
assertEquals(mapOf("reason" to 0), diagnostics.onEndFile(MpvEvent.EndFile(EndFileReason.Eof)))
assertEquals(mapOf("reason" to 4), diagnostics.onEndFile(MpvEvent.EndFile(EndFileReason.Error)))
assertNull(diagnostics.onEndFile(MpvEvent.EndFile(null)))
}
@Test
fun endFileEventChannelPayloadKeepsExistingEnvelopeAndAddsMessage() {
val sink = RecordingEventSink()
val plugin = MpvPlayerPlugin()
plugin.onListen(null, sink)
plugin.onEvent(
"end-file",
mapOf(
"reason" to 4,
"message" to "Failed to open stream"
)
)
assertEquals(
mapOf(
"type" to "event",
"name" to "end-file",
"data" to mapOf(
"reason" to 4,
"message" to "Failed to open stream"
)
),
sink.successValue
)
}
private class RecordingResult : MethodChannel.Result {
var successValue: Any? = null
var errorCode: String? = null
var completed: Boolean = false
override fun success(result: Any?) {
completed = true
successValue = result
}
override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) {
completed = true
this.errorCode = errorCode
}
override fun notImplemented() = Unit
}
private class RecordingEventSink : EventChannel.EventSink {
var successValue: Any? = null
override fun success(event: Any?) {
successValue = event
}
override fun error(errorCode: String, errorMessage: String?, errorDetails: Any?) = Unit
override fun endOfStream() = Unit
}
}
@@ -0,0 +1,47 @@
package com.edde746.plezy.shared
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class MediaCodecQueryTest {
@Test
fun recognizesKnownPlatformAndFfmpegSoftwareCodecNames() {
listOf(
"OMX.google.h264.decoder",
"OMX.FFMPEG.VIDEO.DECODER",
"c2.android.avc.decoder",
"c2.google.av1.decoder",
"c2.ffmpeg.vp9.decoder",
"vendor.video.sw.decoder"
).forEach { name ->
assertTrue("expected software codec: $name", MediaCodecQuery.isSoftwareCodecName(name))
}
}
@Test
fun doesNotMisclassifyVendorHardwareCodecNames() {
listOf(
"OMX.qcom.video.decoder.avc",
"OMX.MTK.VIDEO.DECODER.HEVC",
"c2.qti.avc.decoder",
"c2.exynos.hevc.decoder"
).forEach { name ->
assertFalse("expected hardware codec: $name", MediaCodecQuery.isSoftwareCodecName(name))
}
}
@Test
fun api29RequiresPlatformHardwareFlagAndNonSoftwareComponentName() {
assertFalse(MediaCodecQuery.isHardwareAccelerated(29, true, "c2.ffmpeg.aac.decoder"))
assertFalse(MediaCodecQuery.isHardwareAccelerated(29, false, "c2.qti.avc.decoder"))
assertTrue(MediaCodecQuery.isHardwareAccelerated(29, true, "c2.qti.avc.decoder"))
}
@Test
fun preApi29RetainsNameBasedFallback() {
assertFalse(MediaCodecQuery.isHardwareAccelerated(28, true, "OMX.google.h264.decoder"))
assertTrue(MediaCodecQuery.isHardwareAccelerated(28, false, "OMX.qcom.video.decoder.avc"))
}
}
@@ -0,0 +1,51 @@
package com.edde746.plezy.shared
import android.os.Handler
import android.os.Looper
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
@RunWith(RobolectricTestRunner::class)
class MpvContentUriResolverTest {
@Test
fun contentDescriptorOpensOffMainAndCompletesOnMain() {
val mainLooper = Looper.getMainLooper()
val openedOnMain = AtomicBoolean(true)
val completedOnMain = AtomicBoolean(false)
val completed = CountDownLatch(1)
MpvContentUriResolver.resolve(
uriString = "content://downloads/video.mkv",
mainHandler = Handler(mainLooper),
opener = {
openedOnMain.set(Looper.myLooper() == mainLooper)
null
},
onResolved = {
completedOnMain.set(Looper.myLooper() == mainLooper)
completed.countDown()
}
)
var didComplete = false
repeat(100) {
shadowOf(mainLooper).idle()
if (completed.await(10, TimeUnit.MILLISECONDS)) {
didComplete = true
return@repeat
}
}
assertTrue("content URI resolution never completed", didComplete)
assertFalse("content descriptor opened on the main thread", openedOnMain.get())
assertTrue("resolved URI callback did not return on the main thread", completedOnMain.get())
}
}
@@ -0,0 +1,44 @@
package com.edde746.plezy.shared
import android.app.Activity
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.SurfaceHolder
import android.view.ViewGroup
import android.widget.FrameLayout
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class PlayerSurfaceHostTest {
@Test
fun scaffoldCreatesFullScreenBlackVideoLayerBehindFlutterContent() {
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
activity.setContentView(FrameLayout(activity))
val callback = object : SurfaceHolder.Callback {
override fun surfaceCreated(holder: SurfaceHolder) = Unit
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) = Unit
override fun surfaceDestroyed(holder: SurfaceHolder) = Unit
}
val container = PlayerSurfaceHost.createContainer(activity, clipChildren = true)
val surface = PlayerSurfaceHost.createVideoSurface(activity, callback)
container.addView(surface)
val content = PlayerSurfaceHost.attachToContent(activity, container)
assertSame(content, container.parent)
assertEquals(0, content.indexOfChild(container))
assertEquals(ViewGroup.LayoutParams.MATCH_PARENT, container.layoutParams.width)
assertEquals(ViewGroup.LayoutParams.MATCH_PARENT, container.layoutParams.height)
assertEquals(Color.BLACK, (container.background as ColorDrawable).color)
assertTrue(container.clipChildren)
assertEquals(FrameLayout.LayoutParams.MATCH_PARENT, surface.layoutParams.width)
assertEquals(FrameLayout.LayoutParams.MATCH_PARENT, surface.layoutParams.height)
}
}
Binary file not shown.
-22
View File
@@ -2,28 +2,6 @@ allprojects {
repositories {
google()
mavenCentral()
if (providers.gradleProperty("localAssCore").isPresent) {
// Opt-in A/B of a locally built libass native core: build it in the
// libass-android fork with `./gradlew :lib_ass:publishToMavenLocal
// -PVERSION_NAME=0.4.0-local`, then build this app with -PlocalAssCore.
mavenLocal()
} else {
// Production libass native core: the -O3/NEON/asm AAR published on
// the edde746/libass-android fork's releases (the upstream Maven
// artifact io.github.peerless2012:ass ships un-optimized natives —
// see the fork's pinned libass-cmake fix). Resolved as
// <tag>/ass-<tag>.aar with no metadata probing.
exclusiveContent {
forRepository {
ivy {
url = uri("https://github.com/edde746/libass-android/releases/download")
patternLayout { artifact("[revision]/[artifact]-[revision].[ext]") }
metadataSources { artifact() }
}
}
filter { includeModule("io.github.peerless2012", "ass") }
}
}
}
}
Binary file not shown.
Vendored Executable
+160
View File
@@ -0,0 +1,160 @@
#!/usr/bin/env bash
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
+90
View File
@@ -0,0 +1,90 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+9 -33
View File
@@ -1,7 +1,5 @@
// libass ASS subtitle rendering: Kotlin/JNI bindings + Media3 integration
// (extractor, parsers, AssHandler, GL atlas overlay). The native libass core
// (libass.so + prefab headers) comes from the Maven artifact
// io.github.peerless2012:ass; this module compiles its JNI against it.
// Static-linking the native core here avoids shipping a separate libass.so with
// different merge rules from the app.
plugins {
id("com.android.library")
id("org.jetbrains.kotlin.android")
@@ -20,34 +18,19 @@ android {
defaultConfig {
minSdk = 21
consumerProguardFiles("consumer-rules.pro")
if (project.hasProperty("localAssCore")) {
// The locally published A/B core only ships device ABIs (x86 would need
// nasm on the host); match it so prefab resolution doesn't fail.
ndk {
abiFilters += listOf("armeabi-v7a", "arm64-v8a")
}
}
externalNativeBuild {
cmake {
// libass.so in the prefab AAR is built against c++_shared (abi.json: stl=c++_shared);
// prefab validates consumer STL compatibility.
arguments += listOf("-DANDROID_STL=c++_shared")
// HarfBuzz pulls in C++, so the JNI library must use the shared STL that
// the app already pins through libmpv.
// A shared cache keeps per-ABI CMake runs from redownloading libass.
arguments += listOf(
"-DANDROID_STL=c++_shared",
"-DLIBASS_CACHE_DIR=${layout.buildDirectory.get().asFile}/libass-prebuilt"
)
}
}
}
buildFeatures {
prefab = true
}
packaging {
jniLibs {
// libass.so is a prefab IMPORTED target (linked, not owned) — the app packages
// it from the io.github.peerless2012:ass AAR; don't duplicate it here.
excludes.add("**/libass.so")
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
@@ -66,13 +49,6 @@ android {
}
dependencies {
// compileOnly: prefab headers + link-time libass.so come from the AAR; runtime
// packaging of libass.so is the app's implementation dependency.
// -PlocalAssCore swaps in a mavenLocal()-published core for A/B tests (must
// match the app module's version so one libass.so is linked and packaged).
val assCoreVersion = if (project.hasProperty("localAssCore")) "0.4.0-local" else "0.4.1-plezy.1"
compileOnly("io.github.peerless2012:ass:$assCoreVersion@aar")
implementation("androidx.annotation:annotation:1.9.1")
implementation("androidx.annotation:annotation-experimental:1.5.1")
implementation("androidx.media3:media3-exoplayer:1.9.2")
-2
View File
@@ -1,5 +1,3 @@
# Constructed from JNI via FindClass/NewObject (AssKt.c).
-keep class com.edde746.plezy.libass.AssAtlasFrame { *; }
# JNI exports bind by name (Java_com_edde746_plezy_libass_*); keep the names stable.
-keepclasseswithmembernames class com.edde746.plezy.libass.* {
native <methods>;
+440 -116
View File
@@ -1,10 +1,15 @@
// JNI bindings for libass. Exports use standard Java_<package>_<Class>_<method>
// naming so no RegisterNatives/JNI_OnLoad registration is needed.
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <android/log.h>
#include <jni.h>
#include <limits.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
static inline long long nowMs(void) {
@@ -61,7 +66,13 @@ JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_Ass_nativeAssDeinit(JNIEnv*
JNIEXPORT jlong JNICALL
Java_com_edde746_plezy_libass_AssTrack_nativeAssTrackInit(JNIEnv* env, jclass clazz, jlong ass) {
return (jlong)ass_new_track((ASS_Library*)ass);
ASS_Track* track = ass_new_track((ASS_Library*)ass);
if (track != NULL) {
if (ass_track_set_feature(track, ASS_FEATURE_FAST_BLUR, 1) != 0) {
__android_log_print(ANDROID_LOG_WARN, LOG_TAG, "ASS_FEATURE_FAST_BLUR unavailable in libass build");
}
}
return (jlong)track;
}
// Shared body of readBuffer/readChunk: pins the byte array and feeds libass.
@@ -132,10 +143,54 @@ JNIEXPORT jlong JNICALL Java_com_edde746_plezy_libass_AssTrack_nativeAssTrackNex
// --- AssRender ---
// The fork's fontconfig build has no Android font search defaults. A tiny
// process-local config lets /system fonts resolve without adding Context/JNI plumbing.
static char* ensureFontsConf(void) {
const char* tmp = getenv("TMPDIR");
if (tmp == NULL || tmp[0] == '\0') tmp = "/data/local/tmp";
char cacheDir[PATH_MAX];
snprintf(cacheDir, sizeof(cacheDir), "%s/fontconfig", tmp);
mkdir(cacheDir, 0700);
char* confPath = (char*)malloc(PATH_MAX);
if (confPath == NULL) return NULL;
snprintf(confPath, PATH_MAX, "%s/fonts.conf", tmp);
FILE* f = fopen(confPath, "w");
if (f == NULL) {
free(confPath);
return NULL;
}
fprintf(
f,
"<?xml version=\"1.0\"?>\n"
"<!DOCTYPE fontconfig SYSTEM \"fonts.dtd\">\n"
"<fontconfig>\n"
" <dir>/system/fonts</dir>\n"
" <dir>/system/font</dir>\n"
" <dir>/product/fonts</dir>\n"
" <dir>/data/fonts</dir>\n"
" <cachedir>%s</cachedir>\n"
"</fontconfig>\n",
cacheDir);
fclose(f);
return confPath;
}
JNIEXPORT jlong JNICALL
Java_com_edde746_plezy_libass_AssRender_nativeAssRenderInit(JNIEnv* env, jclass clazz, jlong ass) {
ASS_Renderer* assRenderer = ass_renderer_init((ASS_Library*)ass);
ass_set_fonts(assRenderer, NULL, "sans-serif", ASS_FONTPROVIDER_FONTCONFIG, NULL, 1);
if (assRenderer == NULL) return 0;
unsigned threads = ass_set_threads(assRenderer, 0);
if (threads == 0) {
__android_log_print(ANDROID_LOG_WARN, LOG_TAG, "libass threading unavailable in native build");
} else {
__android_log_print(ANDROID_LOG_INFO, LOG_TAG, "libass rendering threads enabled: %u", threads);
}
char* fontsConf = ensureFontsConf();
ass_set_fonts(assRenderer, NULL, "sans-serif", ASS_FONTPROVIDER_FONTCONFIG, fontsConf, 1);
free(fontsConf);
return (jlong)assRenderer;
}
@@ -182,178 +237,312 @@ Java_com_edde746_plezy_libass_AssRender_nativeAssRenderDeinit(JNIEnv* env, jclas
}
}
// (image, original-list index) pair so packing can run in height-sorted order
// while slots stay keyed by list position (= blend order) for pass 2.
typedef struct {
ASS_Image* img;
int idx;
} PackItem;
// Hard cap on atlas pages (see the packing comment below). 4 pages of a GL-max
// texture is far above the worst real frame measured (a 4K-rendered full-screen
// typeset letter needs 3); beyond it tiles are dropped and counted in truncated.
#define MAX_ATLAS_PAGES 4
static int comparePackItemsByHeightDesc(const void* a, const void* b) {
const PackItem* ia = (const PackItem*)a;
const PackItem* ib = (const PackItem*)b;
return ib->img->h - ia->img->h;
// A tile is a <= atlasMaxW x atlasMaxH sub-rect of an ASS_Image. A single image
// can exceed one atlas page only when the render frame is larger than a page
// (>4K, or a GPU whose max texture is below the frame) — multi-page can't split
// one image across pages (a quad samples one texture), so tiling does, keeping
// the never-drop guarantee. (#1436 itself was atlas-AREA overflow, fixed by the
// multi-page pack below, not oversized single images.) Tiles are built in list
// order (= libass blend/painter order, preserved for emission); the single-page
// pack runs height-sorted via a separate key array so emission order is untouched.
typedef struct {
ASS_Image* img; // source image (for bitmap/stride/color/dst_x/dst_y)
int ox, oy; // tile offset within the source bitmap
int tw, th; // tile size (<= atlasMaxW x atlasMaxH)
int page; // atlas page the tile is packed into; -1 if dropped for capacity
int sx, sy; // packed slot within the page; valid when page >= 0
} PackTile;
typedef struct {
int th; // tile height (the sort key)
int idx; // index into the build-order tiles[] array
} TileSortKey;
static int compareTileKeysByHeightDesc(const void* a, const void* b) {
return ((const TileSortKey*)b)->th - ((const TileSortKey*)a)->th;
}
static int imageListHasOutput(ASS_Image* image) {
for (ASS_Image* img = image; img != NULL; img = img->next) {
if (img->w > 0 && img->h > 0) return 1;
}
return 0;
}
// Throttle for truncation warnings (shared across renderers; logging only).
static int truncationLogCounter = 0;
// Frame metadata crosses to Kotlin through a fixed-layout int[] header (filled here,
// read + turned into an AssAtlasFrame by AssRender.kt) instead of constructing the
// object in JNI. A NewObject on an overloaded constructor is fragile under R8: the
// minified release build stripped/rewrote the (I[I[IIIIZ)V ctor the lookup bound by,
// crashing with NoSuchMethodError (#1436 follow-up). Binding a native method by name
// + populating a primitive array has no such reflective dependency. Layout:
// [0]=atlasWidth [1]=quadCount [2]=changed [3]=truncated [4]=requiredPages
// [5]=hasOutput [6]=pageCount
// [7 .. 7+MAX-1] = pageHeights[pageCount]
// [7+MAX .. 7+2*MAX-1] = pageQuadCounts[pageCount]
#define ASS_HEADER_INTS (7 + 2 * MAX_ATLAS_PAGES)
static jint writeAtlasHeader(
JNIEnv* env, jintArray headerBuf, int atlasWidth, int quadCount, int changed, int truncated, int requiredPages,
int hasOutput, int pageCount, const int* pageHeights, const int* pageQuads) {
int hdr[ASS_HEADER_INTS];
memset(hdr, 0, sizeof(hdr));
hdr[0] = atlasWidth;
hdr[1] = quadCount;
hdr[2] = changed;
hdr[3] = truncated;
hdr[4] = requiredPages;
hdr[5] = hasOutput;
hdr[6] = pageCount;
for (int i = 0; i < pageCount && i < MAX_ATLAS_PAGES; i++) {
hdr[7 + i] = pageHeights ? pageHeights[i] : 0;
hdr[7 + MAX_ATLAS_PAGES + i] = pageQuads ? pageQuads[i] : 0;
}
(*env)->SetIntArrayRegion(env, headerBuf, 0, ASS_HEADER_INTS, hdr);
return 1;
}
// Renders a frame into the provided atlas + vertex direct ByteBuffers.
//
// - atlasBuf holds packed ALPHA_8 pixels with row stride atlasMaxW. Only the first
// atlasHeight rows are written; the caller uploads that region to a texture
// allocated once at atlasMaxW × atlasMaxH.
// - atlasBuf holds one or more vertically-stacked ALPHA_8 *pages*, each atlasMaxW ×
// atlasMaxH (row stride atlasMaxW); page p starts at byte offset p*atlasMaxW*atlasMaxH.
// The buffer's capacity bounds how many pages this render may fill; AssAtlasFrame
// reports pageHeights (rows worth uploading per page) and requiredPages.
// - vertexBuf holds a per-quad vertex stream (6 vertices × (2 pos + 2 uv + 4 color)
// floats = 48 floats = 192 bytes per quad). Must match BYTES_PER_QUAD/VERTEX in
// AssSubtitleAtlasPipeline.kt. Ready for a single glDrawArrays(GL_TRIANGLES, 0, N * 6).
// - UVs are normalized against atlasMaxW × atlasMaxH (the allocated texture dims),
// not the packed region, so the texture never needs reallocation.
// - Images are packed in height-sorted rows (minimizes packed height) but vertices
// are emitted in original list order — the list order is libass's painter order.
// AssSubtitleAtlasPipeline.kt. UVs are page-local, normalized against atlasMaxW ×
// atlasMaxH (the per-page texture dims).
// - The common case packs everything into a single height-sorted page (minimizes
// packed height, byte-identical to the prior single-page packer). When that
// overflows (a 4K full-screen sign can exceed one GL-max texture), the packer
// spills into additional pages in list order: page assignment is monotonic in
// libass's painter order, so each page's quads are one contiguous run in the
// vertex stream and drawing the pages in turn reproduces the blend order.
// - Vertices are always emitted in original list order (= libass's painter order).
//
// Never fails on content size: images that don't fit the remaining atlas/vertex
// capacity are dropped and counted in AssAtlasFrame.truncated, so a heavy frame
// degrades instead of going stale. Returns NULL only for missing buffers/handles.
// On changed == 0, returns (0, 0, 0, changed, 0) without touching the buffers —
// caller reuses the atlas texture already on the GPU.
JNIEXPORT jobject JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRenderFrameAtlas(
// Never fails on content size: when the frame needs more pages than the buffer holds
// (requiredPages > pageHeights.size) the caller grows the buffer and re-renders; any
// genuinely undrawable tiles (past MAX_ATLAS_PAGES / the vertex budget) are dropped
// and counted in truncated.
//
// Returns 0 for missing buffers/handles (the caller maps that to a null frame); 1 when
// the header was written. On changed == 0 the header carries (atlasWidth=0, quadCount=0,
// changed, hasOutput) without touching the atlas/vertex buffers — hasOutput lets Kotlin
// distinguish "reuse the previous atlas" from "blank, clear the GL surface."
JNIEXPORT jint JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRenderFrameAtlas(
JNIEnv* env, jclass clazz, jlong render, jlong track, jlong time, jobject atlasBuf, jint atlasMaxW, jint atlasMaxH,
jobject vertexBuf) {
if (!render || !track || !atlasBuf || !vertexBuf || atlasMaxW <= 0 || atlasMaxH <= 0) return NULL;
jclass atlasFrameClass = (*env)->FindClass(env, "com/edde746/plezy/libass/AssAtlasFrame");
if (!atlasFrameClass) return NULL;
jmethodID ctor = (*env)->GetMethodID(env, atlasFrameClass, "<init>", "(IIIII)V");
if (!ctor) return NULL;
jobject vertexBuf, jintArray headerBuf) {
if (!render || !track || !atlasBuf || !vertexBuf || !headerBuf || atlasMaxW <= 0 || atlasMaxH <= 0) return 0;
const long long t0 = nowMs();
int changed;
ASS_Image* image = ass_render_frame((ASS_Renderer*)render, (ASS_Track*)track, time, &changed);
const long long tAss = nowMs();
if (changed == 0 || image == NULL) {
if (changed == 0) {
const int hasOutput = imageListHasOutput(image) ? 1 : 0;
if (tAss - t0 > 40) {
__android_log_print(
ANDROID_LOG_WARN, LOG_TAG, "slow render t=%lldms: ass=%lldms (changed=%d, hasOutput=%d)", (long long)time,
tAss - t0, changed, hasOutput);
}
return writeAtlasHeader(env, headerBuf, 0, 0, changed, 0, 1, hasOutput, 1, NULL, NULL);
}
if (image == NULL) {
if (tAss - t0 > 40) {
__android_log_print(
ANDROID_LOG_WARN, LOG_TAG, "slow render t=%lldms: ass=%lldms (changed=%d, no output)", (long long)time,
tAss - t0, changed);
}
return (*env)->NewObject(env, atlasFrameClass, ctor, 0, 0, 0, changed, 0);
return writeAtlasHeader(env, headerBuf, 0, 0, changed, 0, 1, 0, 1, NULL, NULL);
}
uint8_t* atlasPixels = (uint8_t*)(*env)->GetDirectBufferAddress(env, atlasBuf);
jlong atlasCap = (*env)->GetDirectBufferCapacity(env, atlasBuf);
float* vertices = (float*)(*env)->GetDirectBufferAddress(env, vertexBuf);
jlong vertexCap = (*env)->GetDirectBufferCapacity(env, vertexBuf);
if (!atlasPixels || !vertices) return NULL;
if (!atlasPixels || !vertices) return 0;
if ((jlong)atlasMaxW * atlasMaxH > atlasCap) {
__android_log_print(
ANDROID_LOG_ERROR, LOG_TAG, "atlas buffer smaller than %dx%d (capacity %lld bytes)", atlasMaxW, atlasMaxH,
(long long)atlasCap);
return NULL;
return 0;
}
// 48 floats per quad × 4 bytes = 192 bytes/quad
const int maxQuads = (int)(vertexCap / 192);
const size_t pageBytes = (size_t)atlasMaxW * atlasMaxH;
int providedPages = (int)(atlasCap / (jlong)pageBytes);
if (providedPages < 1) return 0; // one page is guaranteed above; keep the page math safe
if (providedPages > MAX_ATLAS_PAGES) providedPages = MAX_ATLAS_PAGES;
// Split every image into <= atlasMaxW x atlasMaxH tiles, then pack the tiles.
// tiles[] stays in list order (= blend/painter order for emission); keys[] is
// sorted by height for the single-page pack so it produces tight rows.
int total = 0;
for (ASS_Image* img = image; img != NULL; img = img->next) {
if (img->w > 0 && img->h > 0) total++;
}
if (total == 0) {
return (*env)->NewObject(env, atlasFrameClass, ctor, 0, 0, 0, changed, 0);
}
// Pass 1: assign packing slots in height-sorted order so mixed-size frames pack
// tight rows. slotX/slotY are keyed by the image's position in the original
// list; -1 marks images dropped for capacity.
PackItem* items = (PackItem*)malloc(sizeof(PackItem) * (size_t)total);
int* slotX = (int*)malloc(sizeof(int) * (size_t)total);
int* slotY = (int*)malloc(sizeof(int) * (size_t)total);
if (!items || !slotX || !slotY) {
free(items);
free(slotX);
free(slotY);
return NULL;
}
int n = 0;
for (ASS_Image* img = image; img != NULL; img = img->next) {
if (img->w > 0 && img->h > 0) {
items[n].img = img;
items[n].idx = n;
n++;
int cols = (img->w + atlasMaxW - 1) / atlasMaxW;
int rows = (img->h + atlasMaxH - 1) / atlasMaxH;
total += cols * rows;
}
}
qsort(items, (size_t)n, sizeof(PackItem), comparePackItemsByHeightDesc);
if (total == 0) {
return writeAtlasHeader(env, headerBuf, 0, 0, changed, 0, 1, 0, 1, NULL, NULL);
}
int cursorX = 0, cursorY = 0, rowH = 0;
int truncated = 0;
int packedH = 0;
int accepted = 0;
PackTile* tiles = (PackTile*)malloc(sizeof(PackTile) * (size_t)total);
TileSortKey* keys = (TileSortKey*)malloc(sizeof(TileSortKey) * (size_t)total);
if (!tiles || !keys) {
free(tiles);
free(keys);
return 0;
}
int n = 0;
long long srcPixels = 0;
for (int i = 0; i < n; i++) {
ASS_Image* img = items[i].img;
for (ASS_Image* img = image; img != NULL; img = img->next) {
if (img->w <= 0 || img->h <= 0) continue;
srcPixels += (long long)img->w * img->h;
int sx = -1, sy = -1;
if (img->w <= atlasMaxW && accepted < maxQuads) {
int cx = cursorX, cy = cursorY, rh = rowH;
if (cx + img->w > atlasMaxW) {
for (int oy = 0; oy < img->h; oy += atlasMaxH) {
int th = img->h - oy;
if (th > atlasMaxH) th = atlasMaxH;
for (int ox = 0; ox < img->w; ox += atlasMaxW) {
int tw = img->w - ox;
if (tw > atlasMaxW) tw = atlasMaxW;
tiles[n] = (PackTile){.img = img, .ox = ox, .oy = oy, .tw = tw, .th = th, .page = -1, .sx = -1, .sy = -1};
keys[n] = (TileSortKey){.th = th, .idx = n};
n++;
}
}
}
int pageHeights[MAX_ATLAS_PAGES] = {0};
int pageQuads[MAX_ATLAS_PAGES] = {0};
int pageCount = 1;
int requiredPages = 1;
int truncated = 0;
// Pass 1a: height-sorted single page — the common case, minimal packed height
// (byte-identical to the prior single-page packer when the frame fits one page).
qsort(keys, (size_t)n, sizeof(TileSortKey), compareTileKeysByHeightDesc);
int cursorX = 0, cursorY = 0, rowH = 0, packedH = 0, accepted = 0;
for (int i = 0; i < n; i++) {
PackTile* t = &tiles[keys[i].idx];
if (accepted >= maxQuads) break;
int cx = cursorX, cy = cursorY, rh = rowH;
if (cx + t->tw > atlasMaxW) {
cy += rh;
cx = 0;
rh = 0;
}
if (cy + t->th > atlasMaxH) continue; // doesn't fit a single page
t->page = 0;
t->sx = cx;
t->sy = cy;
cursorX = cx + t->tw;
cursorY = cy;
rowH = (t->th > rh) ? t->th : rh;
if (cy + t->th > packedH) packedH = cy + t->th;
accepted++;
}
if (accepted == n) {
pageHeights[0] = packedH;
pageQuads[0] = accepted;
} else {
// Pass 1b: the frame overflows one page. Re-pack in list order, starting a new
// page whenever a tile won't fit the current one. List order keeps the page
// index monotonic in painter order, so each page's quads stay one contiguous run.
for (int i = 0; i < n; i++) {
tiles[i].page = -1;
tiles[i].sx = -1;
tiles[i].sy = -1;
}
int page = 0, cx = 0, cy = 0, rh = 0, placed = 0;
for (int i = 0; i < n; i++) {
PackTile* t = &tiles[i];
if (cx + t->tw > atlasMaxW) {
cy += rh;
cx = 0;
rh = 0;
}
if (cy + img->h <= atlasMaxH) {
sx = cx;
sy = cy;
cursorX = cx + img->w;
cursorY = cy;
rowH = (img->h > rh) ? img->h : rh;
if (cy + img->h > packedH) packedH = cy + img->h;
accepted++;
if (cy + t->th > atlasMaxH) {
page++;
cx = 0;
cy = 0;
rh = 0;
}
if (page + 1 > requiredPages) requiredPages = page + 1;
if (page < providedPages && placed < maxQuads) {
t->page = page;
t->sx = cx;
t->sy = cy;
if (cy + t->th > pageHeights[page]) pageHeights[page] = cy + t->th;
pageQuads[page]++;
placed++;
}
cx += t->tw;
rh = (t->th > rh) ? t->th : rh;
}
if (sx < 0) truncated++;
slotX[items[i].idx] = sx;
slotY[items[i].idx] = sy;
pageCount = (requiredPages < providedPages) ? requiredPages : providedPages;
accepted = placed;
truncated = n - placed;
}
if (truncated > 0 && (truncationLogCounter++ & 63) == 0) {
// Warn only for genuinely-unrecoverable loss. A frame that needs more pages than
// the buffer currently holds, yet fits within MAX_ATLAS_PAGES and the vertex
// budget, is recoverable: the caller grows the buffer and re-renders, so the
// first (discarded) render's truncated > 0 is a false alarm, not data loss. Tiles
// are only truly lost past the page cap or the vertex budget.
const int recoverableGrow = requiredPages <= MAX_ATLAS_PAGES && n <= maxQuads;
if (truncated > 0 && !recoverableGrow && (truncationLogCounter++ & 63) == 0) {
__android_log_print(
ANDROID_LOG_WARN, LOG_TAG, "atlas truncation: %d of %d images dropped (atlas %dx%d, %d quads max)", truncated,
n, atlasMaxW, atlasMaxH, maxQuads);
ANDROID_LOG_WARN, LOG_TAG, "atlas truncation: %d of %d tiles dropped (atlas %dx%d, need %d pages have %d)",
truncated, n, atlasMaxW, atlasMaxH, requiredPages, providedPages);
}
if (accepted == 0) {
free(items);
free(slotX);
free(slotY);
return (*env)->NewObject(env, atlasFrameClass, ctor, 0, 0, 0, changed, truncated);
free(tiles);
free(keys);
return writeAtlasHeader(env, headerBuf, 0, 0, changed, truncated, requiredPages, 1, 1, NULL, NULL);
}
memset(atlasPixels, 0, (size_t)atlasMaxW * packedH);
// Clear only the packed rows of each written page.
for (int p = 0; p < pageCount; p++) {
memset(atlasPixels + (size_t)p * pageBytes, 0, (size_t)atlasMaxW * pageHeights[p]);
}
// Pass 2: walk the original list (= libass's painter/blend order), copying each
// accepted image into its assigned slot and emitting its quad.
// Emit tiles in list order (= libass's painter/blend order), copying each placed
// tile into its page slot and emitting its quad. Monotonic page assignment makes
// each page's quads a contiguous run, matching pageQuads[] for the per-page draw.
int qi = 0;
int k = 0;
for (ASS_Image* img = image; img != NULL; img = img->next) {
if (img->w <= 0 || img->h <= 0) continue;
const int px = slotX[k];
const int py = slotY[k];
k++;
if (px < 0) continue;
for (int i = 0; i < n; i++) {
PackTile* t = &tiles[i];
if (t->page < 0) continue;
ASS_Image* img = t->img;
const int px = t->sx;
const int py = t->sy;
uint8_t* pageBase = atlasPixels + (size_t)t->page * pageBytes;
for (int y = 0; y < img->h; y++) {
uint8_t* dst = atlasPixels + (size_t)(py + y) * atlasMaxW + px;
const uint8_t* src = img->bitmap + (size_t)y * img->stride;
memcpy(dst, src, (size_t)img->w);
for (int y = 0; y < t->th; y++) {
uint8_t* dst = pageBase + (size_t)(py + y) * atlasMaxW + px;
const uint8_t* src = img->bitmap + (size_t)(t->oy + y) * img->stride + t->ox;
memcpy(dst, src, (size_t)t->tw);
}
const float x0 = (float)img->dst_x;
const float y0 = (float)img->dst_y;
const float x1 = x0 + (float)img->w;
const float y1 = y0 + (float)img->h;
const float x0 = (float)(img->dst_x + t->ox);
const float y0 = (float)(img->dst_y + t->oy);
const float x1 = x0 + (float)t->tw;
const float y1 = y0 + (float)t->th;
const float u0 = (float)px / (float)atlasMaxW;
const float v0 = (float)py / (float)atlasMaxH;
const float u1 = (float)(px + img->w) / (float)atlasMaxW;
const float v1 = (float)(py + img->h) / (float)atlasMaxH;
const float u1 = (float)(px + t->tw) / (float)atlasMaxW;
const float v1 = (float)(py + t->th) / (float)atlasMaxH;
const unsigned int c = img->color;
const float r = (float)((c >> 24) & 0xFFu) / 255.0f;
const float g = (float)((c >> 16) & 0xFFu) / 255.0f;
@@ -416,9 +605,8 @@ JNIEXPORT jobject JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRende
qi++;
}
free(items);
free(slotX);
free(slotY);
free(tiles);
free(keys);
// Slow-render breakdown: separates libass's own cost (rasterize/blur/shape)
// from this function's packing + memcpy, so device logs attribute the time.
@@ -426,11 +614,147 @@ JNIEXPORT jobject JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRende
if (tEnd - t0 > 40) {
__android_log_print(
ANDROID_LOG_WARN, LOG_TAG,
"slow render t=%lldms: total=%lldms ass=%lldms pack+copy=%lldms images=%d srcPx=%lldk atlas=%dx%d quads=%d",
(long long)time, tEnd - t0, tAss - t0, tEnd - tAss, n, srcPixels / 1000, atlasMaxW, packedH, qi);
"slow render t=%lldms: total=%lldms ass=%lldms pack+copy=%lldms images=%d srcPx=%lldk "
"atlas=%dx%d pages=%d quads=%d",
(long long)time, tEnd - t0, tAss - t0, tEnd - tAss, n, srcPixels / 1000, atlasMaxW, atlasMaxH, pageCount, qi);
}
// atlasWidth is the full row stride (GLES2 can't upload with stride ≠ width);
// atlasHeight is the packed height — the only rows worth uploading.
return (*env)->NewObject(env, atlasFrameClass, ctor, atlasMaxW, packedH, qi, changed, truncated);
// pageHeights/pageQuadCounts describe the per-page upload + draw ranges.
return writeAtlasHeader(
env, headerBuf, atlasMaxW, qi, changed, truncated, requiredPages, 1, pageCount, pageHeights, pageQuads);
}
// --- AssFrameTimestamps (EGL_ANDROID_get_frame_timestamps) ---
//
// Measures the overlay buffer's ACTUAL on-screen present time so subtitle
// frame-perfection can be checked against the video frame's release time as
// ground truth, instead of the queue time (eglSwapBuffers return) the swap loop
// otherwise sees. The Java EGLExt only exposes eglPresentationTimeANDROID, so the
// frame-timestamp entry points are resolved here via eglGetProcAddress.
//
// All functions run on the GL thread with the pipeline's EGL context current.
// Older NDK eglext.h may predate the extension; fall back to the spec values.
#ifndef EGL_TIMESTAMPS_ANDROID
#define EGL_TIMESTAMPS_ANDROID 0x3430
#endif
#ifndef EGL_COMPOSITION_LATCH_TIME_ANDROID
#define EGL_COMPOSITION_LATCH_TIME_ANDROID 0x3436
#endif
#ifndef EGL_FIRST_COMPOSITION_START_TIME_ANDROID
#define EGL_FIRST_COMPOSITION_START_TIME_ANDROID 0x3437
#endif
#ifndef EGL_DISPLAY_PRESENT_TIME_ANDROID
#define EGL_DISPLAY_PRESENT_TIME_ANDROID 0x343A
#endif
#ifndef EGL_TIMESTAMP_INVALID_ANDROID
#define EGL_TIMESTAMP_INVALID_ANDROID (-1)
#endif
#ifndef EGL_TIMESTAMP_PENDING_ANDROID
#define EGL_TIMESTAMP_PENDING_ANDROID (-2)
#endif
#ifndef EGL_ANDROID_get_frame_timestamps
typedef khronos_stime_nanoseconds_t EGLnsecsANDROID;
typedef EGLBoolean(EGLAPIENTRYP PFNEGLGETNEXTFRAMEIDANDROIDPROC)(EGLDisplay, EGLSurface, EGLuint64KHR*);
typedef EGLBoolean(EGLAPIENTRYP PFNEGLGETFRAMETIMESTAMPSANDROIDPROC)(
EGLDisplay, EGLSurface, EGLuint64KHR, EGLint, const EGLint*, EGLnsecsANDROID*);
typedef EGLBoolean(EGLAPIENTRYP PFNEGLGETFRAMETIMESTAMPSUPPORTEDANDROIDPROC)(EGLDisplay, EGLSurface, EGLint);
#endif
// nativeInit status: success codes are the chosen timestamp source (≥ 0); the
// actual display present time on code 0, and SurfaceFlinger composition timestamps
// (a near-constant ~1-vsync earlier than scanout) on codes 1/2 — a constant bias
// that doesn't hide the inter-layer jitter / multi-vsync outliers we look for.
// Negative codes are failure reasons surfaced to the stats path for diagnosis.
#define FT_SRC_PRESENT 0
#define FT_SRC_COMPOSITION_START 1
#define FT_SRC_COMPOSITION_LATCH 2
#define FT_ERR_NO_SURFACE (-1)
#define FT_ERR_NO_EXTENSION (-2)
#define FT_ERR_NO_PROC (-3)
#define FT_ERR_UNSUPPORTED (-4)
#define FT_ERR_ENABLE_FAILED (-5)
static PFNEGLGETNEXTFRAMEIDANDROIDPROC pEglGetNextFrameId = NULL;
static PFNEGLGETFRAMETIMESTAMPSANDROIDPROC pEglGetFrameTimestamps = NULL;
static PFNEGLGETFRAMETIMESTAMPSUPPORTEDANDROIDPROC pEglGetFrameTimestampSupported = NULL;
static EGLDisplay gFtDisplay = EGL_NO_DISPLAY;
static EGLSurface gFtSurface = EGL_NO_SURFACE;
static EGLint gFtPresentName = EGL_DISPLAY_PRESENT_TIME_ANDROID;
// Probes the extension on the currently-current draw surface and enables capture.
// Re-resolves the display/surface each call so surface recreation is handled.
// Returns one of the FT_* codes above.
JNIEXPORT jint JNICALL Java_com_edde746_plezy_libass_AssFrameTimestamps_nativeInit(JNIEnv* env, jclass clazz) {
gFtSurface = EGL_NO_SURFACE;
EGLDisplay dpy = eglGetCurrentDisplay();
EGLSurface surf = eglGetCurrentSurface(EGL_DRAW);
if (dpy == EGL_NO_DISPLAY || surf == EGL_NO_SURFACE) return FT_ERR_NO_SURFACE;
const char* exts = eglQueryString(dpy, EGL_EXTENSIONS);
if (exts == NULL || strstr(exts, "EGL_ANDROID_get_frame_timestamps") == NULL) {
__android_log_print(ANDROID_LOG_INFO, LOG_TAG, "frame-timestamps: extension not present");
return FT_ERR_NO_EXTENSION;
}
if (pEglGetNextFrameId == NULL) {
pEglGetNextFrameId = (PFNEGLGETNEXTFRAMEIDANDROIDPROC)eglGetProcAddress("eglGetNextFrameIdANDROID");
pEglGetFrameTimestamps = (PFNEGLGETFRAMETIMESTAMPSANDROIDPROC)eglGetProcAddress("eglGetFrameTimestampsANDROID");
pEglGetFrameTimestampSupported =
(PFNEGLGETFRAMETIMESTAMPSUPPORTEDANDROIDPROC)eglGetProcAddress("eglGetFrameTimestampSupportedANDROID");
}
if (pEglGetNextFrameId == NULL || pEglGetFrameTimestamps == NULL || pEglGetFrameTimestampSupported == NULL) {
__android_log_print(ANDROID_LOG_WARN, LOG_TAG, "frame-timestamps: entry points unresolved");
return FT_ERR_NO_PROC;
}
// Prefer true display present; many TV HWCs (e.g. Amlogic) don't report present
// fences but do report SurfaceFlinger composition timestamps. Take the first
// supported — composition timing still pins the swap to a vsync for A-vs-B.
jint status;
if (pEglGetFrameTimestampSupported(dpy, surf, EGL_DISPLAY_PRESENT_TIME_ANDROID)) {
gFtPresentName = EGL_DISPLAY_PRESENT_TIME_ANDROID;
status = FT_SRC_PRESENT;
} else if (pEglGetFrameTimestampSupported(dpy, surf, EGL_FIRST_COMPOSITION_START_TIME_ANDROID)) {
gFtPresentName = EGL_FIRST_COMPOSITION_START_TIME_ANDROID;
status = FT_SRC_COMPOSITION_START;
} else if (pEglGetFrameTimestampSupported(dpy, surf, EGL_COMPOSITION_LATCH_TIME_ANDROID)) {
gFtPresentName = EGL_COMPOSITION_LATCH_TIME_ANDROID;
status = FT_SRC_COMPOSITION_LATCH;
} else {
__android_log_print(ANDROID_LOG_INFO, LOG_TAG, "frame-timestamps: no supported timestamp name");
return FT_ERR_UNSUPPORTED;
}
if (!eglSurfaceAttrib(dpy, surf, EGL_TIMESTAMPS_ANDROID, EGL_TRUE)) {
__android_log_print(ANDROID_LOG_WARN, LOG_TAG, "frame-timestamps: enable failed 0x%x", eglGetError());
return FT_ERR_ENABLE_FAILED;
}
gFtDisplay = dpy;
gFtSurface = surf;
__android_log_print(ANDROID_LOG_INFO, LOG_TAG, "frame-timestamps: enabled (source=%d)", status);
return status;
}
// Frame id the next eglSwapBuffers will produce; call immediately before it.
JNIEXPORT jlong JNICALL
Java_com_edde746_plezy_libass_AssFrameTimestamps_nativeGetNextFrameId(JNIEnv* env, jclass clazz) {
if (pEglGetNextFrameId == NULL || gFtSurface == EGL_NO_SURFACE) return -1;
EGLuint64KHR id = 0;
if (!pEglGetNextFrameId(gFtDisplay, gFtSurface, &id)) return -1;
return (jlong)id;
}
// Present (or composition) time for frameId (System.nanoTime() domain), or the
// PENDING(-2)/INVALID(-1) sentinels. Reported a few frames after the swap.
JNIEXPORT jlong JNICALL
Java_com_edde746_plezy_libass_AssFrameTimestamps_nativeGetDisplayPresentTime(JNIEnv* env, jclass clazz, jlong frameId) {
if (pEglGetFrameTimestamps == NULL || gFtSurface == EGL_NO_SURFACE) return EGL_TIMESTAMP_INVALID_ANDROID;
const EGLint names[1] = {gFtPresentName};
EGLnsecsANDROID values[1] = {0};
if (!pEglGetFrameTimestamps(gFtDisplay, gFtSurface, (EGLuint64KHR)frameId, 1, names, values)) {
// Frame id evicted from SurfaceFlinger's history, or bad surface.
return EGL_TIMESTAMP_INVALID_ANDROID;
}
return (jlong)values[0];
}
+50 -5
View File
@@ -2,9 +2,54 @@ cmake_minimum_required(VERSION 3.22.1)
project("asskt")
# libass headers + libass.so come from the io.github.peerless2012:ass AAR via prefab.
add_library(${CMAKE_PROJECT_NAME} SHARED AssKt.c)
find_package(lib_ass REQUIRED CONFIG)
# Fetching the fork release at configure time keeps per-ABI static archives out
# of git; the pinned hash makes that network step reproducible.
set(LIBASS_VERSION "0.18.3")
set(LIBASS_SHA256 "fc98637752695d7cf9e26b02befaa634dd4cad25a2f38fba80de814bfd310a17")
set(LIBASS_ZIP_URL "https://github.com/edde746/libass/releases/download/${LIBASS_VERSION}/libass-android-${LIBASS_VERSION}.zip")
# Gradle passes one cache root so per-ABI CMake builds share the download.
if(NOT DEFINED LIBASS_CACHE_DIR)
set(LIBASS_CACHE_DIR "${CMAKE_BINARY_DIR}/libass-prebuilt")
endif()
set(LIBASS_ROOT "${LIBASS_CACHE_DIR}/libass-android-${LIBASS_VERSION}")
set(LIBASS_ARCHIVE "${LIBASS_ROOT}/lib/${ANDROID_ABI}/libass.a")
set(LIBASS_HEADER "${LIBASS_ROOT}/include/ass/ass.h")
# The downloaded archive lives under Flutter's root build/ directory, which can
# be deleted without invalidating android/libass/.cxx. Model it as a Ninja output
# so stale CMake configure caches can regenerate it during the build step.
file(MAKE_DIRECTORY "${LIBASS_ROOT}/include")
add_custom_command(
OUTPUT "${LIBASS_ARCHIVE}" "${LIBASS_HEADER}"
COMMAND "${CMAKE_COMMAND}"
"-DLIBASS_VERSION=${LIBASS_VERSION}"
"-DLIBASS_SHA256=${LIBASS_SHA256}"
"-DLIBASS_ZIP_URL=${LIBASS_ZIP_URL}"
"-DLIBASS_CACHE_DIR=${LIBASS_CACHE_DIR}"
"-DLIBASS_ROOT=${LIBASS_ROOT}"
"-DLIBASS_ARCHIVE=${LIBASS_ARCHIVE}"
"-DLIBASS_HEADER=${LIBASS_HEADER}"
"-DANDROID_ABI=${ANDROID_ABI}"
-P "${CMAKE_CURRENT_LIST_DIR}/FetchLibass.cmake"
COMMENT "Preparing fork libass ${LIBASS_VERSION} for ${ANDROID_ABI}"
VERBATIM)
string(REPLACE "-" "_" LIBASS_ABI_TARGET "${ANDROID_ABI}")
add_custom_target(libass_prebuilt_${LIBASS_ABI_TARGET}
DEPENDS "${LIBASS_ARCHIVE}" "${LIBASS_HEADER}")
add_library(ass STATIC IMPORTED)
set_target_properties(ass PROPERTIES
IMPORTED_LOCATION "${LIBASS_ARCHIVE}")
target_include_directories(ass INTERFACE "${LIBASS_ROOT}/include")
add_library(${CMAKE_PROJECT_NAME} SHARED AssKt.c SurfaceTxProbe.c)
add_dependencies(${CMAKE_PROJECT_NAME} libass_prebuilt_${LIBASS_ABI_TARGET})
# HarfBuzz brings C++; link the shared STL that the app already packages.
# (SurfaceTxProbe resolves its libandroid/libsync entry points via dlsym, so no extra link.)
target_link_libraries(${CMAKE_PROJECT_NAME} PRIVATE
lib_ass::ass
log)
ass
log
EGL
c++_shared)
@@ -0,0 +1,47 @@
cmake_minimum_required(VERSION 3.22.1)
foreach(_var IN ITEMS
LIBASS_VERSION
LIBASS_SHA256
LIBASS_ZIP_URL
LIBASS_CACHE_DIR
LIBASS_ROOT
LIBASS_ARCHIVE
LIBASS_HEADER
ANDROID_ABI)
if(NOT DEFINED ${_var} OR "${${_var}}" STREQUAL "")
message(FATAL_ERROR "${_var} is required")
endif()
endforeach()
get_filename_component(_cache_parent "${LIBASS_CACHE_DIR}" DIRECTORY)
file(MAKE_DIRECTORY "${_cache_parent}")
# Android Gradle can build ABI variants in parallel; serialize the shared cache.
file(LOCK "${LIBASS_CACHE_DIR}.lock" GUARD PROCESS TIMEOUT 300)
if(NOT EXISTS "${LIBASS_ARCHIVE}" OR NOT EXISTS "${LIBASS_HEADER}")
file(MAKE_DIRECTORY "${LIBASS_CACHE_DIR}")
set(_libass_zip "${LIBASS_CACHE_DIR}/libass-android-${LIBASS_VERSION}.zip")
message(STATUS "Fetching fork libass ${LIBASS_VERSION} from ${LIBASS_ZIP_URL}")
file(DOWNLOAD "${LIBASS_ZIP_URL}" "${_libass_zip}"
EXPECTED_HASH "SHA256=${LIBASS_SHA256}"
TLS_VERIFY ON
STATUS _libass_dl)
list(GET _libass_dl 0 _libass_dl_code)
if(NOT _libass_dl_code EQUAL 0)
file(REMOVE "${_libass_zip}")
message(FATAL_ERROR "Failed to download libass: ${_libass_dl}")
endif()
file(REMOVE_RECURSE "${LIBASS_ROOT}")
file(ARCHIVE_EXTRACT INPUT "${_libass_zip}" DESTINATION "${LIBASS_CACHE_DIR}")
endif()
if(NOT EXISTS "${LIBASS_ARCHIVE}")
message(FATAL_ERROR "libass archive for ${ANDROID_ABI} was not extracted: ${LIBASS_ARCHIVE}")
endif()
if(NOT EXISTS "${LIBASS_HEADER}")
message(FATAL_ERROR "libass headers were not extracted: ${LIBASS_HEADER}")
endif()
@@ -0,0 +1,317 @@
// EXPERIMENTAL SPIKE — does the codec VIDEO plane's actual present time differ from a
// GL OSD overlay's, and is that difference measurable in-app? (See the memory note
// project_libass_present_time_instrumentation.)
//
// Android exposes no present time for a codec-owned video layer. The one runtime lead is
// API 34 `SurfaceView.applyTransactionToFrame()`: it merges an otherwise-empty,
// callback-bearing transaction with the codec's *next buffer* transaction. The completion
// stats then carry, per surface, the PREVIOUS-RELEASE fence — the moment the buffer the new
// frame replaced stopped being read by the display ≈ when the new codec frame actually
// reached the video plane. Compared in Kotlin to that frame's `releaseTimeNs` target (the
// overlay's own present error is ~0), the delta is the inter-plane lag.
//
// The SurfaceControl transaction-stats / fromJava APIs are API 29/34 while this module's
// minSdk is 21; clang's __builtin_available doesn't guard the Android availability domain in
// this toolchain. So the libandroid entry points are resolved by dlsym (no
// availability-attributed declarations get compiled). Every call site is additionally
// hard-gated to API >= 34 in Kotlin (VideoLayerLatencyProbe).
//
// Fence timestamps are read with the raw SYNC_IOC_FILE_INFO ioctl rather than libsync:
// libsync.so is NOT a public NDK library, so an app's linker namespace blocks dlopen of it.
//
// Compiled into the libass "asskt" .so; called from app Kotlin SurfaceTxProbe.
#include <android/log.h>
#include <dlfcn.h>
#include <jni.h>
#include <poll.h>
#include <pthread.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <time.h>
#include <unistd.h>
#define LOG_TAG "SurfaceTxProbe"
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)
#ifndef SYNC_IOC_MAGIC
#define SYNC_IOC_MAGIC '>'
#endif
struct stp_fence_info {
char obj_name[32];
char driver_name[32];
int32_t status;
uint32_t flags;
uint64_t timestamp_ns;
};
struct stp_file_info {
char name[32];
int32_t status;
uint32_t flags;
uint32_t num_fences;
uint32_t pad;
uint64_t sync_fence_info;
};
#ifndef SYNC_IOC_FILE_INFO
#define SYNC_IOC_FILE_INFO _IOWR(SYNC_IOC_MAGIC, 4, struct stp_file_info)
#endif
// libsync is hidden from app linker namespaces, so use the kernel ioctl directly.
static int64_t readFenceTimeNs(int fd, int* outStatus) {
*outStatus = -1;
if (fd < 0) return -1;
struct stp_file_info probe;
memset(&probe, 0, sizeof(probe));
if (ioctl(fd, SYNC_IOC_FILE_INFO, &probe) < 0) return -1;
*outStatus = probe.status;
if (probe.status != 1 || probe.num_fences == 0) return -1;
struct stp_fence_info* arr = (struct stp_fence_info*)calloc(probe.num_fences, sizeof(struct stp_fence_info));
if (!arr) return -1;
struct stp_file_info req;
memset(&req, 0, sizeof(req));
req.num_fences = probe.num_fences;
req.sync_fence_info = (uint64_t)(uintptr_t)arr;
int64_t t = -1;
if (ioctl(fd, SYNC_IOC_FILE_INFO, &req) == 0) {
for (uint32_t i = 0; i < req.num_fences; i++) {
if ((int64_t)arr[i].timestamp_ns > t) t = (int64_t)arr[i].timestamp_ns;
}
}
free(arr);
return t;
}
typedef struct ASurfaceTransaction ASurfaceTransaction;
typedef struct ASurfaceControl ASurfaceControl;
typedef struct ASurfaceTransactionStats ASurfaceTransactionStats;
typedef void (*OnCompleteFn)(void* context, ASurfaceTransactionStats* stats);
typedef ASurfaceTransaction* (*pf_fromJava)(JNIEnv*, jobject);
typedef void (*pf_setOnComplete)(ASurfaceTransaction*, void*, OnCompleteFn);
typedef int64_t (*pf_latchTime)(ASurfaceTransactionStats*);
typedef void (*pf_getControls)(ASurfaceTransactionStats*, ASurfaceControl***, size_t*);
typedef int (*pf_prevRelease)(ASurfaceTransactionStats*, ASurfaceControl*);
typedef void (*pf_releaseControls)(ASurfaceControl**);
static pf_fromJava p_fromJava = NULL;
static pf_setOnComplete p_setOnComplete = NULL;
static pf_latchTime p_latchTime = NULL;
static pf_getControls p_getControls = NULL;
static pf_prevRelease p_prevRelease = NULL;
static pf_releaseControls p_releaseControls = NULL;
static int gScResolved = 0;
static int gScOk = 0;
static int gScWarningLogged = 0;
// Runtime lookup keeps this API-34 probe buildable with the module's minSdk 21.
static int resolveSc(void) {
if (gScResolved) return gScOk;
gScResolved = 1;
void* h = dlopen("libandroid.so", RTLD_NOW | RTLD_GLOBAL);
if (!h) return 0;
p_fromJava = (pf_fromJava)dlsym(h, "ASurfaceTransaction_fromJava");
p_setOnComplete = (pf_setOnComplete)dlsym(h, "ASurfaceTransaction_setOnComplete");
p_latchTime = (pf_latchTime)dlsym(h, "ASurfaceTransactionStats_getLatchTime");
p_getControls = (pf_getControls)dlsym(h, "ASurfaceTransactionStats_getASurfaceControls");
p_prevRelease = (pf_prevRelease)dlsym(h, "ASurfaceTransactionStats_getPreviousReleaseFenceFd");
p_releaseControls = (pf_releaseControls)dlsym(h, "ASurfaceTransactionStats_releaseASurfaceControls");
gScOk = (p_fromJava && p_setOnComplete && p_latchTime && p_getControls && p_prevRelease && p_releaseControls) ? 1 : 0;
return gScOk;
}
// The completion context is pointer-width, so 32-bit devices need an index side-channel.
#define TAG_RING_SIZE 256
static int64_t gTagRing[TAG_RING_SIZE];
static int gSrcRing[TAG_RING_SIZE];
static int gTagSeq = 0;
static JavaVM* gVm = NULL;
static jclass gProbeClass = NULL;
static jmethodID gOnResult = NULL;
static int gCallbackLookupAttempted = 0;
static pthread_mutex_t gInitLock = PTHREAD_MUTEX_INITIALIZER;
static int64_t nowMonoNs(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (int64_t)ts.tv_sec * 1000000000LL + ts.tv_nsec;
}
static void reportResult(
JNIEnv* env, int64_t tag, int64_t latchNs, int64_t releaseNs, int count, int fenceState, int source, int64_t cbNs) {
if (!env || !gProbeClass || !gOnResult) return;
(*env)->CallStaticVoidMethod(
env, gProbeClass, gOnResult, (jlong)tag, (jlong)latchNs, (jlong)releaseNs, (jint)count, (jint)fenceState,
(jint)source, (jlong)cbNs);
if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
}
// Previous-release fences can still be pending in the binder callback; a worker
// thread keeps SurfaceFlinger's callback dispatch unblocked.
struct fenceJob {
int fd;
int64_t tag;
int64_t latch;
int count;
int source;
};
#define JOB_RING 64
static struct fenceJob gJobs[JOB_RING];
static int gJobHead = 0, gJobTail = 0;
static int gJobDrops = 0;
static pthread_mutex_t gJobLock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t gJobCond = PTHREAD_COND_INITIALIZER;
static pthread_t gReader;
static int gReaderStarted = 0;
static void* readerMain(void* arg);
static int ensureProbeInit(JNIEnv* env, jclass clazz) {
int scOk = 0;
pthread_mutex_lock(&gInitLock);
if (!gVm && (*env)->GetJavaVM(env, &gVm) != JNI_OK) {
LOGW("GetJavaVM failed — transaction probe disabled");
pthread_mutex_unlock(&gInitLock);
return 0;
}
if (!gProbeClass) {
gProbeClass = (*env)->NewGlobalRef(env, clazz);
if (!gProbeClass) {
LOGW("NewGlobalRef(SurfaceTxProbe) failed — transaction probe disabled");
pthread_mutex_unlock(&gInitLock);
return 0;
}
}
if (!gCallbackLookupAttempted) {
gCallbackLookupAttempted = 1;
gOnResult = (*env)->GetStaticMethodID(env, clazz, "onResult", "(JJJIIIJ)V");
if (!gOnResult) {
(*env)->ExceptionClear(env);
LOGW("onResult(JJJIIIJ)V not found — JNI callback disabled (R8 stripped it?)");
}
}
if (!gOnResult) {
pthread_mutex_unlock(&gInitLock);
return 0;
}
scOk = resolveSc();
if (!scOk) {
if (!gScWarningLogged) {
gScWarningLogged = 1;
LOGW("libandroid SurfaceControl transaction-stats API unavailable");
}
pthread_mutex_unlock(&gInitLock);
return 0;
}
if (!gReaderStarted) {
const int rc = pthread_create(&gReader, NULL, readerMain, NULL);
if (rc != 0) {
LOGW("fence reader thread start failed: %d", rc);
pthread_mutex_unlock(&gInitLock);
return 0;
}
gReaderStarted = 1;
}
pthread_mutex_unlock(&gInitLock);
return scOk;
}
static void* readerMain(void* arg) {
(void)arg;
JNIEnv* env = NULL;
if ((*gVm)->AttachCurrentThread(gVm, &env, NULL) != JNI_OK) return NULL;
for (;;) {
pthread_mutex_lock(&gJobLock);
while (gJobHead == gJobTail) pthread_cond_wait(&gJobCond, &gJobLock);
struct fenceJob job = gJobs[gJobTail];
gJobTail = (gJobTail + 1) % JOB_RING;
pthread_mutex_unlock(&gJobLock);
int64_t releaseNs = -1;
int fenceState;
struct pollfd pfd = {.fd = job.fd, .events = POLLIN, .revents = 0};
int pr = poll(&pfd, 1, 250);
if (pr > 0 && (pfd.revents & POLLIN)) {
int st = -1;
releaseNs = readFenceTimeNs(job.fd, &st);
fenceState = (releaseNs > 0) ? 3 : 1;
} else {
fenceState = 2;
}
close(job.fd);
reportResult(env, job.tag, job.latch, releaseNs, job.count, fenceState, job.source, nowMonoNs());
}
return NULL;
}
static void onComplete(void* context, ASurfaceTransactionStats* stats) {
int slot = (int)(intptr_t)context;
__atomic_thread_fence(__ATOMIC_ACQUIRE);
int64_t tag = gTagRing[slot & (TAG_RING_SIZE - 1)];
int source = gSrcRing[slot & (TAG_RING_SIZE - 1)];
int64_t latchNs = p_latchTime ? p_latchTime(stats) : -1;
// Display-global present fences are abort-prone; per-surface release fences are stable here.
int chosenFd = -1;
int count = 0;
ASurfaceControl** controls = NULL;
size_t n = 0;
if (p_getControls) p_getControls(stats, &controls, &n);
count = (int)n;
for (size_t i = 0; i < n; i++) {
int rfd = p_prevRelease ? p_prevRelease(stats, controls[i]) : -1;
if (rfd < 0) continue;
if (chosenFd < 0)
chosenFd = rfd;
else
close(rfd);
}
if (controls && p_releaseControls) p_releaseControls(controls);
if (chosenFd < 0) {
JNIEnv* env = NULL;
int didAttach = 0;
if ((*gVm)->GetEnv(gVm, (void**)&env, JNI_VERSION_1_6) != JNI_OK) {
if ((*gVm)->AttachCurrentThread(gVm, &env, NULL) != JNI_OK) return;
didAttach = 1;
}
reportResult(env, tag, latchNs, -1, count, 0, source, nowMonoNs());
if (didAttach) (*gVm)->DetachCurrentThread(gVm);
return;
}
pthread_mutex_lock(&gJobLock);
int next = (gJobHead + 1) % JOB_RING;
if (next == gJobTail) {
close(chosenFd);
if (gJobDrops++ == 0) LOGW("fence job ring full — dropping samples (slow fence reader?)");
} else {
gJobs[gJobHead].fd = chosenFd;
gJobs[gJobHead].tag = tag;
gJobs[gJobHead].latch = latchNs;
gJobs[gJobHead].count = count;
gJobs[gJobHead].source = source;
gJobHead = next;
pthread_cond_signal(&gJobCond);
}
pthread_mutex_unlock(&gJobLock);
}
JNIEXPORT void JNICALL Java_com_edde746_plezy_exoplayer_SurfaceTxProbe_nativeAttach(
JNIEnv* env, jclass clazz, jobject jtransaction, jlong tag, jint source) {
if (!ensureProbeInit(env, clazz)) return;
int slot = __atomic_fetch_add(&gTagSeq, 1, __ATOMIC_RELAXED) & (TAG_RING_SIZE - 1);
gTagRing[slot] = (int64_t)tag;
gSrcRing[slot] = (int)source;
// Binder carries only the slot index, so the ring write has to win publication.
__atomic_thread_fence(__ATOMIC_RELEASE);
ASurfaceTransaction* tx = p_fromJava(env, jtransaction);
if (!tx) {
LOGW("ASurfaceTransaction_fromJava returned null");
return;
}
p_setOnComplete(tx, (void*)(intptr_t)slot, onComplete);
}
@@ -4,18 +4,65 @@ package com.edde746.plezy.libass
* Result of a packed-atlas render. The atlas pixel data is stored in the direct ByteBuffer
* that was passed into [AssRender.renderFrameAtlas]; the vertex stream is in the other.
*
* @param atlasWidth atlas row stride in pixels (= the allocated width; 0 when [changed] == 0)
* @param atlasHeight packed atlas height in pixels — the rows worth uploading
* @param quadCount number of quads; the vertex buffer holds [quadCount] * 6 vertices
* @param changed libass change flag (0 = no change, 1 = positions, 2 = content)
* @param truncated images dropped because they exceeded the atlas/vertex capacity;
* the frame is incomplete but never stale (> 0 should be rare —
* it means even the GL-max-sized atlas couldn't fit the frame)
* The atlas may span more than one *page* — a heavy full-screen sign can produce more
* sub-pixels than a single GL-max texture holds. Pages are vertically stacked in the
* atlas ByteBuffer (page `p` at byte offset `p * atlasWidth * atlasMaxHeight`), each its
* own texture, and are drawn in turn. Quads are emitted in libass painter order and page
* assignment is monotonic in that order, so each page's quads form one contiguous run in
* the vertex stream ([pageQuadCounts]); the runner uploads page `p`, then draws its run.
*
* Built in Kotlin by [AssRender.renderFrameAtlas] from the int[] header the native
* renderer fills (see `writeAtlasHeader` in AssKt.c) — never constructed from JNI, so
* the minifier may obfuscate it freely without breaking the native boundary.
*
* @param atlasWidth atlas row stride in pixels (= the allocated width; same for every
* page; 0 when [changed] == 0)
* @param pageHeights packed height (rows worth uploading) of each page; `size` = page count
* @param pageQuadCounts quads on each page, contiguous in the vertex stream in this order;
* `size` = page count, `sum` = [quadCount]
* @param quadCount total quads; the vertex buffer holds [quadCount] * 6 vertices
* @param changed libass change flag (0 = no change, 1 = positions, 2 = content)
* @param truncated images dropped because the frame needed more than [requiredPages]
* pages of capacity or exceeded the vertex budget; the frame is
* incomplete but never stale (should be unreachable for real content)
* @param requiredPages pages this frame needs to render completely. When it exceeds
* [pageHeights].size the caller must grow the atlas buffer and
* re-render; the rendered pages are still valid in the meantime.
* @param hasOutput true when libass reported at least one visible image for this
* timestamp, even when [changed] is 0 and the buffers were not
* rewritten. false means this timestamp should be blank.
*/
class AssAtlasFrame(
val atlasWidth: Int,
val atlasHeight: Int,
val pageHeights: IntArray,
val pageQuadCounts: IntArray,
val quadCount: Int,
val changed: Int,
val truncated: Int
)
val truncated: Int,
val requiredPages: Int,
val hasOutput: Boolean
) {
/** Number of atlas pages this frame occupies. */
val pageCount: Int get() = pageHeights.size
/** Packed height of the first page; the only page in the common single-page case. */
val atlasHeight: Int get() = if (pageHeights.isNotEmpty()) pageHeights[0] else 0
/** Single-page convenience: blank/unchanged frames and tests. */
constructor(
atlasWidth: Int,
atlasHeight: Int,
quadCount: Int,
changed: Int,
truncated: Int,
hasOutput: Boolean
) : this(atlasWidth, intArrayOf(atlasHeight), intArrayOf(quadCount), quadCount, changed, truncated, 1, hasOutput)
constructor(
atlasWidth: Int,
atlasHeight: Int,
quadCount: Int,
changed: Int,
truncated: Int
) : this(atlasWidth, atlasHeight, quadCount, changed, truncated, quadCount > 0)
}
@@ -0,0 +1,71 @@
package com.edde746.plezy.libass
/**
* Thin binding over the `EGL_ANDROID_get_frame_timestamps` extension.
*
* The atlas pipeline pins each overlay swap to the video frame's `releaseTimeNs`,
* but the swap loop can only measure when [android.opengl.EGL14.eglSwapBuffers]
* *returns* — i.e. when the buffer was queued, not when SurfaceFlinger actually
* presented it. That can't reveal a one-vsync compositor latch offset, which is
* exactly the error frame-perfection work chases. This binding reads the buffer's
* *actual on-screen present time* so it can be compared against `releaseTimeNs`
* (the video frame's vsync target) as ground truth.
*
* `android.opengl.EGLExt` exposes only `eglPresentationTimeANDROID`; the
* frame-timestamp entry points are resolved natively via `eglGetProcAddress`.
*
* Requires Android 10 (API 29)+ and the extension; probe with [nativeInit].
* All calls must run on the GL thread with the pipeline's EGL context current.
*/
internal object AssFrameTimestamps {
/** Present time not yet reported by SurfaceFlinger; query the frame again later. */
const val PENDING = -2L
/** The frame was dropped/never presented, or its id was evicted from history. */
const val INVALID = -1L
// [nativeInit] status. Success codes are the timestamp source in use (≥ 0):
// true scanout present (SRC_PRESENT) or — where the HWC reports no present fence,
// common on TV SoCs — a SurfaceFlinger composition timestamp ~1 vsync earlier
// (SRC_COMPOSITION_*; a constant bias, harmless to the jitter/outlier analysis).
// Negative codes are failure reasons, surfaced to the stats path for diagnosis.
const val SRC_PRESENT = 0
const val SRC_COMPOSITION_START = 1
const val SRC_COMPOSITION_LATCH = 2
const val ERR_NO_SURFACE = -1
const val ERR_NO_EXTENSION = -2
const val ERR_NO_PROC = -3
const val ERR_UNSUPPORTED = -4
const val ERR_ENABLE_FAILED = -5
/** Short label for a [nativeInit] status code, for logs/getStats. */
fun sourceLabel(status: Int): String = when (status) {
SRC_PRESENT -> "present"
SRC_COMPOSITION_START -> "comp-start"
SRC_COMPOSITION_LATCH -> "comp-latch"
ERR_NO_SURFACE -> "off:no-surface"
ERR_NO_EXTENSION -> "off:no-ext"
ERR_NO_PROC -> "off:no-proc"
ERR_UNSUPPORTED -> "off:unsupported"
ERR_ENABLE_FAILED -> "off:enable-failed"
else -> "off:$status"
}
/**
* Probes the extension on the currently-current draw surface and enables
* timestamp capture, preferring true present then composition timestamps.
* Returns an `SRC_*` code (≥ 0) on success or an `ERR_*` code (< 0). Re-resolves
* the surface each call, so it is safe to re-invoke after surface recreation.
*/
@JvmStatic external fun nativeInit(): Int
/** Frame id the next `eglSwapBuffers` will produce; call immediately before it. */
@JvmStatic external fun nativeGetNextFrameId(): Long
/**
* Present (or composition) time for [frameId] in the `System.nanoTime()` domain,
* or the [PENDING]/[INVALID] sentinels. Results are deferred a few frames past
* the swap, so a caller drains pending ids lazily.
*/
@JvmStatic external fun nativeGetDisplayPresentTime(frameId: Long): Long
}
@@ -8,6 +8,10 @@ class AssRender(nativeAss: Long, private val lock: ReentrantLock) {
companion object {
/** Must match MAX_ATLAS_PAGES + the header layout in AssKt.c (`writeAtlasHeader`). */
private const val MAX_ATLAS_PAGES = 4
private const val HEADER_INTS = 7 + 2 * MAX_ATLAS_PAGES
@JvmStatic
external fun nativeAssRenderInit(ass: Long): Long
@@ -29,6 +33,12 @@ class AssRender(nativeAss: Long, private val lock: ReentrantLock) {
@JvmStatic
external fun nativeAssRenderSetUseMargins(render: Long, use: Boolean)
/**
* Renders into [atlasBuf]/[vertexBuf] and writes frame metadata into [header]
* (layout per `writeAtlasHeader` in AssKt.c). Returns 1 when the header was written,
* 0 for missing buffers/handles. The frame object is built on the Kotlin side from
* the header so the JNI boundary never constructs it (R8-safe; see [renderFrameAtlas]).
*/
@JvmStatic
external fun nativeAssRenderFrameAtlas(
render: Long,
@@ -37,8 +47,9 @@ class AssRender(nativeAss: Long, private val lock: ReentrantLock) {
atlasBuf: ByteBuffer,
atlasMaxWidth: Int,
atlasMaxHeight: Int,
vertexBuf: ByteBuffer
): AssAtlasFrame?
vertexBuf: ByteBuffer,
header: IntArray
): Int
@JvmStatic
external fun nativeAssRenderDeinit(render: Long)
@@ -46,6 +57,10 @@ class AssRender(nativeAss: Long, private val lock: ReentrantLock) {
private var nativeRender: Long = nativeAssRenderInit(nativeAss)
/** Reusable JNI frame-metadata header (see `writeAtlasHeader` in AssKt.c). Calls to
* [renderFrameAtlas] are serialized by [lock], so one buffer is safe to reuse. */
private val frameHeader = IntArray(HEADER_INTS)
@Volatile
var released = false
private set
@@ -109,26 +124,31 @@ class AssRender(nativeAss: Long, private val lock: ReentrantLock) {
withNative { nativeAssRenderSetUseMargins(it, use) }
}
/**
* Renders a frame into a packed ALPHA_8 texture atlas plus a single vertex stream
* ready for `glDrawArrays(GL_TRIANGLES, 0, quadCount * 6)`.
*
* UVs are normalized against ([atlasMaxW], [atlasMaxH]) — the allocated texture
* dims — so the caller can allocate the texture once and `glTexSubImage2D` only
* the packed rows. Images that exceed the capacity are dropped and counted in
* [AssAtlasFrame.truncated]; the render never fails on content size.
*
* @param atlasBuf direct ByteBuffer receiving the packed pixels (≥ atlasMaxW × atlasMaxH)
* @param atlasMaxW atlas row stride in pixels (bound by `GL_MAX_TEXTURE_SIZE`)
* @param atlasMaxH atlas height in pixels (bound by `GL_MAX_TEXTURE_SIZE`)
* @param vertexBuf direct ByteBuffer receiving the vertex stream (192 bytes per quad)
*/
/** How long the most recent [renderFrameAtlas] waited to acquire the shared
* libass lock (contended by track dialogue/font feeding), in milliseconds. */
@Volatile
var lastLockWaitMs: Long = 0
private set
/**
* Renders a frame into a packed ALPHA_8 texture atlas plus a vertex stream.
*
* The atlas may span one or more vertically-stacked pages (a dense full-screen
* sign can exceed a single GL-max texture); vertices stay in libass painter order,
* grouped per page ([AssAtlasFrame.pageQuadCounts]). The caller uploads each page
* to its own texture and draws it with its own `glDrawArrays`, reproducing the
* blend order. UVs are page-local, normalized against ([atlasMaxW], [atlasMaxH]).
*
* Never fails on content size: when the frame needs more pages than [atlasBuf]
* holds, [AssAtlasFrame.requiredPages] signals the caller to grow the buffer and
* re-render; only tiles past `MAX_ATLAS_PAGES` or the vertex budget are dropped
* and counted in [AssAtlasFrame.truncated].
*
* @param atlasBuf direct ByteBuffer receiving the stacked pages (≥ atlasMaxW × atlasMaxH per page)
* @param atlasMaxW per-page atlas row stride in pixels (bound by `GL_MAX_TEXTURE_SIZE`)
* @param atlasMaxH per-page atlas height in pixels (bound by `GL_MAX_TEXTURE_SIZE`)
* @param vertexBuf direct ByteBuffer receiving the vertex stream (192 bytes per quad)
*/
fun renderFrameAtlas(
time: Long,
atlasBuf: ByteBuffer,
@@ -142,7 +162,21 @@ class AssRender(nativeAss: Long, private val lock: ReentrantLock) {
if (released || nativeRender == 0L) return null
val t = track ?: return null
if (t.released || t.nativeAssTrack == 0L) return null
return nativeAssRenderFrameAtlas(nativeRender, t.nativeAssTrack, time, atlasBuf, atlasMaxW, atlasMaxH, vertexBuf)
val header = frameHeader
val status =
nativeAssRenderFrameAtlas(nativeRender, t.nativeAssTrack, time, atlasBuf, atlasMaxW, atlasMaxH, vertexBuf, header)
if (status == 0) return null
val pageCount = header[6]
return AssAtlasFrame(
atlasWidth = header[0],
pageHeights = IntArray(pageCount) { header[7 + it] },
pageQuadCounts = IntArray(pageCount) { header[7 + MAX_ATLAS_PAGES + it] },
quadCount = header[1],
changed = header[2],
truncated = header[3],
requiredPages = header[4],
hasOutput = header[5] != 0
)
}
}
@@ -17,6 +17,7 @@ import com.edde746.plezy.libass.Ass
import com.edde746.plezy.libass.AssRender
import com.edde746.plezy.libass.AssTrack
import com.edde746.plezy.libass.media.parser.AssHeaderParser
import com.edde746.plezy.libass.media.widget.AssAtlasPipelineConfig
/**
* Handles ASS subtitle rendering and integration with ExoPlayer.
@@ -185,13 +186,15 @@ class AssHandler(
* (re)created or the selected track changes, so renderer state survives both.
*/
private fun applyRenderState(render: AssRender) {
// Storage (script/video authoring size) stays full-res; only the frame and
// margins follow RENDER_SCALE so the raster shrinks while layout is unchanged.
if (videoSize.isValid) render.setStorageSize(videoSize.width, videoSize.height)
when {
surfaceSize.isValid -> render.setFrameSize(surfaceSize.width, surfaceSize.height)
surfaceSize.isValid -> render.setFrameSize(scaledForRender(surfaceSize.width), scaledForRender(surfaceSize.height))
// Fallback frame until the overlay surface reports its size.
videoSize.isValid -> render.setFrameSize(videoSize.width, videoSize.height)
videoSize.isValid -> render.setFrameSize(scaledForRender(videoSize.width), scaledForRender(videoSize.height))
}
margins?.let { m -> render.setMargins(m[0], m[1], m[2], m[3]) }
margins?.let { m -> render.setMargins(scaledForRender(m[0]), scaledForRender(m[1]), scaledForRender(m[2]), scaledForRender(m[3])) }
render.setUseMargins(useMargins)
}
@@ -220,7 +223,7 @@ class AssHandler(
if (surfaceSize.width == width && surfaceSize.height == height) return
Log.i("AssHandler", "setOverlaySurfaceSize: width = $width, height = $height")
surfaceSize = Size(width, height)
render?.setFrameSize(width, height)
render?.setFrameSize(scaledForRender(width), scaledForRender(height))
}
/**
@@ -230,9 +233,13 @@ class AssHandler(
*/
fun setMargins(top: Int, bottom: Int, left: Int, right: Int) {
margins = intArrayOf(top, bottom, left, right)
render?.setMargins(top, bottom, left, right)
render?.setMargins(scaledForRender(top), scaledForRender(bottom), scaledForRender(left), scaledForRender(right))
}
/** Frame/margin extents go to libass at the overlay's render resolution; the GL
* side scales the result back up. Identity unless RENDER_SCALE < 1. */
private fun scaledForRender(px: Int): Int = AssAtlasPipelineConfig.scaledForRender(px)
/** mpv's sub-ass-force-margins: anchor non-positioned events to the visible frame. */
fun setUseMargins(use: Boolean) {
useMargins = use
@@ -383,4 +390,16 @@ class AssHandler(
*/
private val Size.isValid
get() = width > 0 && height > 0
companion object {
/**
* Sets the global libass overlay render scale (fraction of the surface resolution; 1.0 = no
* downscale). Cheaper raster for the render-bound tail on weak GPUs, at some sharpness. Set
* before/at playback init — [AssAtlasPipelineConfig.scaledForRender] reads it on the next
* frame-size apply (overlay surface create / size change), so it takes effect from playback.
*/
fun setRenderScale(scale: Float) {
AssAtlasPipelineConfig.renderScale = scale.coerceIn(0.2f, 1.0f)
}
}
}
@@ -23,6 +23,7 @@ class AssSubtitleSurfaceView(
SurfaceHolder.Callback {
private var pipeline: AssAtlasPipeline? = null
private var preSwapProbe: ((Long) -> Unit)? = null
init {
setZOrderMediaOverlay(true)
@@ -30,6 +31,16 @@ class AssSubtitleSurfaceView(
holder.addCallback(this)
}
/**
* Hook invoked on the GL thread just before each pinned overlay swap, with that swap's target
* releaseTimeNs. Set by the app's latency calibrator; cleared (null) once it converges.
* Survives pipeline recreation (re-applied in [surfaceCreated]).
*/
fun setPreSwapProbe(hook: ((Long) -> Unit)?) {
preSwapProbe = hook
pipeline?.preSwapProbe = hook
}
fun requestRender(presentationTimeUs: Long, releaseTimeNs: Long) {
pipeline?.requestRender(presentationTimeUs, releaseTimeNs)
}
@@ -75,20 +86,83 @@ class AssSubtitleSurfaceView(
/** Speculation rounds skipped (paused, pending request, no confident cadence). */
val specSkips: Long get() = pipeline?.specSkips ?: 0L
/** changed==0/no-output renders forced into explicit transparent swaps. */
val blankClearCount: Long get() = pipeline?.blankClearCount ?: 0L
/** Cache-warming prefetch renders of upcoming events. */
val prefetchCount: Long get() = pipeline?.prefetchCount ?: 0L
/** Frame requests replaced before the libass worker serviced them. */
val coalescedRequestCount: Long get() = pipeline?.coalescedRequestCount ?: 0L
/** Completed libass results discarded because renderer state changed before handoff. */
val staleGenerationCount: Long get() = pipeline?.staleGenerationCount ?: 0L
/** Completed overlay snapshots skipped because newer completed content superseded them. */
val supersededBeforeSwapCount: Long get() = pipeline?.supersededBeforeSwapCount ?: 0L
/** Completed overlay snapshots skipped because renderer state changed before swap. */
val staleBeforeSwapCount: Long get() = pipeline?.staleBeforeSwapCount ?: 0L
/** Minimum lead of changed-content pinned swaps vs the video frame's release
* time, in ms (negative = late); null until one happened. */
val minLeadChangedMs: Long? get() = pipeline?.minLeadChangedMs?.takeIf { it != Long.MAX_VALUE }
/** Current compositor phase lead applied by the atlas pipeline, in ms. */
val phaseLeadMs: Long get() = pipeline?.phaseLeadMs ?: 0L
/** Most recent pinned swap lead vs its target release time, in ms. */
val lastSwapLeadMs: Long get() = pipeline?.lastSwapLeadMs ?: 0L
/** Most recent pinned swap headroom when GL work started, in ms. */
val lastSwapHeadroomMs: Long get() = pipeline?.lastSwapHeadroomMs ?: 0L
/** Most recent phase-led wait before swap, in ms. */
val lastScheduledSleepMs: Long get() = pipeline?.lastScheduledSleepMs ?: 0L
/** Adaptive swap lead actually in effect (half the measured refresh interval), in ms. */
val swapLeadMs: Long get() = pipeline?.swapLeadMs ?: 0L
/** True once the EGL frame-timestamp extension is probed and capturing present
* times (API 26+, real device). False on the emulator / pre-26 / no driver support. */
val presentTimingEnabled: Boolean get() = pipeline?.presentTimingEnabled ?: false
/** Active present-time source, or why it's off (present/comp-start/comp-latch/off:…). */
val presentSource: String get() = pipeline?.presentSource ?: "off:no-pipeline"
/** Actual on-screen present time of the most recent measured swap minus its
* target release time, in ms (negative = before the video frame's vsync). The
* frame-perfection ground truth; null until a swap has been measured. */
val lastPresentErrorMs: Long? get() = pipeline?.lastPresentErrorMs.takeIf { presentMeasuredCount > 0 }
/** Largest-magnitude present error observed, in ms; null until measured. */
val worstPresentErrorMs: Long? get() = pipeline?.worstPresentErrorMs.takeIf { presentMeasuredCount > 0 }
/** Pinned swaps whose actual present time was read back from SurfaceFlinger. */
val presentMeasuredCount: Long get() = pipeline?.presentMeasuredCount ?: 0L
/** Swaps SurfaceFlinger reported as dropped/never-presented. */
val presentInvalidCount: Long get() = pipeline?.presentInvalidCount ?: 0L
/** Pending present-time reads evicted unread because the ring filled. */
val presentDroppedCount: Long get() = pipeline?.presentDroppedCount ?: 0L
/** Present-error distribution in vsync-interval units:
* [≤−1.5, (−1.5,−0.5), (−0.5,+0.5), [+0.5,+1.5), ≥+1.5]. Middle = frame-perfect. */
val presentErrorHistogram: List<Long> get() = pipeline?.presentErrorHistogram ?: emptyList()
override fun surfaceCreated(holder: SurfaceHolder) {
val rect = holder.surfaceFrame
assHandler.setOverlaySurfaceSize(rect.width(), rect.height())
val lowRam = (context.getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager)
?.isLowRamDevice ?: false
pipeline = AssAtlasPipeline(holder.surface, rect.width(), rect.height(), assHandler, lowRam)
.also { it.start() }
// Display refresh drives the present-error histogram's vsync-relative buckets.
val refreshRate = display?.refreshRate?.takeIf { it >= 1f } ?: 60f
pipeline = AssAtlasPipeline(holder.surface, rect.width(), rect.height(), assHandler, lowRam, refreshRate)
.also {
it.preSwapProbe = preSwapProbe
it.start()
}
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
@@ -1,7 +1,6 @@
package com.edde746.plezy.libass.media.widget
import com.edde746.plezy.libass.AssAtlasFrame
import kotlin.math.abs
/**
* Decision core of the speculative render-ahead pipeline.
@@ -99,6 +98,10 @@ internal class SpecRenderEngine(
var specSkips = 0L
private set
@Volatile
var blankClearCount = 0L
private set
/**
* Services a render request for [ptsUs]. [pinned] is false for invalidate
* repaints (paused margin changes etc.), which never feed the cadence
@@ -107,10 +110,11 @@ internal class SpecRenderEngine(
fun service(ptsUs: Long, pinned: Boolean): Outcome {
if (pinned) updateDeltaEstimator(ptsUs)
val ptsMs = toLibassMs(ptsUs)
if (specPtsUs != UNSET) {
val eps = epsilonUs()
val specPtsMs = toLibassMs(specPtsUs)
val genNow = stateGeneration()
val hit = genNow == specGen && eps > 0 && abs(ptsUs - specPtsUs) <= eps
val hit = genNow == specGen && ptsMs == specPtsMs
val slot = if (specIsLibassLast) libassLastSlot else specSlot
val frame = libassLastFrame
val specPts = specPtsUs
@@ -118,23 +122,32 @@ internal class SpecRenderEngine(
if (hit && slot >= 0 && frame != null) {
specHits++
lastPostedSlot = slot
debugLog?.invoke("hit pts=${ptsUs / 1000}ms spec=${specPts / 1000}ms d=${(ptsUs - specPts) / 1000}ms slot=$slot")
debugLog?.invoke(
"hit pts=${ptsMs}ms spec=${specPtsMs}ms dUs=${ptsUs - specPts} slot=$slot"
)
return Outcome.Post(slot, frame, newContent = false, specHit = true)
}
specMisses++
debugLog?.invoke(
"miss pts=${ptsUs / 1000}ms spec=${specPts / 1000}ms d=${(ptsUs - specPts) / 1000}ms eps=${eps / 1000}ms " +
"miss pts=${ptsMs}ms spec=${specPtsMs}ms dUs=${ptsUs - specPts} " +
"gen=${if (genNow == specGen) "ok" else "CHANGED"} slot=$slot frame=${frame != null}"
)
} else {
debugLog?.invoke("no-spec pts=${ptsUs / 1000}ms")
debugLog?.invoke("no-spec pts=${ptsMs}ms")
}
// On-demand render. Preferring libassLastSlot as the target makes changed == 0
// unambiguous: the buffers were untouched and already hold the right content.
// On-demand render. For changed == 0 with visible output, the buffers were
// untouched and libassLastSlot already holds the right content.
val target = renderTargetSlot() ?: return Outcome.Skip
val frame = renderAt(ptsUs / 1000, target) ?: return Outcome.Skip
val frame = renderAt(ptsMs, target) ?: return Outcome.Skip
if (frame.changed == 0) {
if (isImplicitBlank(frame)) {
blankClearCount++
libassLastSlot = target
libassLastFrame = frame
lastPostedSlot = target
return Outcome.Post(target, frame, newContent = true, specHit = false)
}
val lastSlot = libassLastSlot
val lastFrame = libassLastFrame ?: return Outcome.Skip
if (lastSlot < 0) return Outcome.Skip
@@ -169,13 +182,21 @@ internal class SpecRenderEngine(
}
val gen = stateGeneration()
val specPts = servicedPtsUs + medianDeltaUs()
val frame = renderAt(specPts / 1000, target) ?: run {
val frame = renderAt(toLibassMs(specPts), target) ?: run {
specSkips++
return null
}
specGen = gen
specPtsUs = specPts
if (frame.changed == 0) {
if (isImplicitBlank(frame)) {
blankClearCount++
libassLastSlot = target
libassLastFrame = frame
specIsLibassLast = false
specSlot = target
return SpecWrite(target, frame)
}
// Content at specPts is identical to libass's last render — nothing was
// written; a hit will repost libassLastSlot (and GL will skip the upload).
specIsLibassLast = true
@@ -189,6 +210,8 @@ internal class SpecRenderEngine(
return SpecWrite(target, frame)
}
private fun isImplicitBlank(frame: AssAtlasFrame): Boolean = !frame.hasOutput && libassLastFrame?.hasOutput == true
/**
* Pre-renders [ptsUs] (an upcoming event's start) purely to warm the
* renderer's glyph/bitmap caches before that content is actually needed —
@@ -204,7 +227,7 @@ internal class SpecRenderEngine(
fun prefetch(ptsUs: Long): SpecWrite? {
specPtsUs = UNSET
val target = renderTargetSlot() ?: return null
val frame = renderAt(ptsUs / 1000, target) ?: return null
val frame = renderAt(toLibassMs(ptsUs), target) ?: return null
prefetchCount++
if (frame.changed == 0) return null
libassLastSlot = target
@@ -253,13 +276,12 @@ internal class SpecRenderEngine(
return copy[deltaCount / 2]
}
private fun epsilonUs(): Long = if (deltaValid()) minOf(medianDeltaUs() / 2, EPSILON_CAP_US) else 0L
private fun toLibassMs(ptsUs: Long): Long = Math.floorDiv(ptsUs, 1_000L)
private companion object {
const val UNSET = Long.MIN_VALUE
const val DELTA_SAMPLES = 8
const val MIN_DELTA_SAMPLES = 4
const val MAX_DELTA_US = 250_000L
const val EPSILON_CAP_US = 8_000L
}
}
@@ -53,7 +53,9 @@ class SpecRenderEngineTest {
fun changed(quads: Int = 5) = AssAtlasFrame(2048, 100, quads, 2, 0)
fun unchanged() = AssAtlasFrame(0, 0, 0, 0, 0)
fun unchanged() = AssAtlasFrame(0, 0, 0, 0, 0, hasOutput = true)
fun blankUnchanged() = AssAtlasFrame(0, 0, 0, 0, 0, hasOutput = false)
}
@Test
@@ -74,15 +76,40 @@ class SpecRenderEngineTest {
}
@Test
fun `hit tolerates jitter within epsilon`() {
fun `hit tolerates jitter only within the same libass millisecond`() {
val h = Harness()
val last = h.prime()
val outcome = h.engine.service(last + DELTA + 3_000, pinned = true)
val outcome = h.engine.service(last + DELTA + 999, pinned = true)
assertTrue((outcome as SpecRenderEngine.Outcome.Post).specHit)
}
@Test
fun `jitter crossing a libass millisecond boundary misses`() {
val h = Harness()
val last = h.prime()
val before = h.calls.size
h.script.add(changed())
val outcome = h.engine.service(last + DELTA + 1_000, pinned = true)
assertTrue(outcome is SpecRenderEngine.Outcome.Post)
assertFalse((outcome as SpecRenderEngine.Outcome.Post).specHit)
assertEquals(before + 1, h.calls.size)
assertEquals(1L, h.engine.specMisses)
}
@Test
fun `negative pts floors to the preceding libass millisecond`() {
val h = Harness()
h.script.add(changed())
h.engine.service(-1, pinned = true)
assertEquals(-1L, h.calls.last().timeMs)
}
@Test
fun `seek misses and renders on demand into the spec slot`() {
val h = Harness()
@@ -201,6 +228,23 @@ class SpecRenderEngineTest {
assertEquals(SpecRenderEngine.Outcome.Skip, h.engine.service(0, pinned = true))
}
@Test
fun `changed 0 without output clears previous content`() {
val h = Harness()
h.script.add(changed())
val first = h.engine.service(0, pinned = true) as SpecRenderEngine.Outcome.Post
h.script.add(blankUnchanged())
val outcome = h.engine.service(DELTA, pinned = true) as SpecRenderEngine.Outcome.Post
assertTrue(outcome.newContent)
assertFalse(outcome.specHit)
assertFalse(outcome.frame.hasOutput)
assertEquals(0, outcome.frame.quadCount)
assertTrue("blank frame should use a fresh metadata slot", outcome.slot != first.slot)
assertEquals(1L, h.engine.blankClearCount)
}
@Test
fun `renderer gone skips`() {
val h = Harness()
@@ -246,6 +290,34 @@ class SpecRenderEngineTest {
assertNotNull(first) // first slot existed; hit reposts whichever slot was last rendered
}
@Test
fun `speculative changed 0 without output clears on hit`() {
val h = Harness()
h.script.add(changed())
h.engine.service(0, pinned = true)
var pts = 0L
repeat(4) {
pts += DELTA
h.script.add(changed())
h.engine.service(pts, pinned = true)
}
h.script.add(blankUnchanged())
val write = h.engine.speculateAfter(pts, pinned = true, hasPending = false)
assertNotNull(write)
assertFalse(write!!.frame.hasOutput)
val before = h.calls.size
val outcome = h.engine.service(pts + DELTA, pinned = true) as SpecRenderEngine.Outcome.Post
assertTrue(outcome.specHit)
assertFalse(outcome.newContent)
assertFalse(outcome.frame.hasOutput)
assertEquals(0, outcome.frame.quadCount)
assertEquals(before, h.calls.size)
assertEquals(1L, h.engine.blankClearCount)
}
@Test
fun `speculative write reports slot for seq bump`() {
val h = Harness()
-2
View File
@@ -24,6 +24,4 @@ plugins {
}
include(":app")
// libass subtitle module (Kotlin/JNI bindings + Media3 glue); the native libass
// core stays the upstream Maven artifact io.github.peerless2012:ass.
include(":libass")
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 96 96"><path fill="currentColor" fill-rule="evenodd" d="M48 96C74.5097 96 96 74.5097 96 48C96 21.4903 74.5097 0 48 0C21.4903 0 0 21.4903 0 48C0 74.5097 21.4903 96 48 96ZM80.0001 52C80.0001 67.464 67.4641 80 52.0001 80C36.5361 80 24.0001 67.464 24.0001 52C24.0001 49.1303 24.4318 46.3615 25.2338 43.7548C27.4288 48.6165 32.3194 52 38.0001 52C45.7321 52 52.0001 45.732 52.0001 38C52.0001 32.3192 48.6166 27.4287 43.755 25.2337C46.3616 24.4317 49.1304 24 52.0001 24C67.4641 24 80.0001 36.536 80.0001 52Z" clip-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 583 B

+15 -2
View File
@@ -22,6 +22,9 @@
97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; };
B1D51A6A2F00110000000001 /* MpvPlayerCoreBase.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1D51A6A2F00110000000002 /* MpvPlayerCoreBase.swift */; };
B1D51A6A2F00110000000005 /* MpvPlayerPluginShared.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1D51A6A2F00110000000006 /* MpvPlayerPluginShared.swift */; };
B1D51A6A2F0011000000000C /* MpvAudioPlayerCore.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1D51A6A2F0011000000000D /* MpvAudioPlayerCore.swift */; };
B1D51A6A2F0011000000000E /* MpvAudioPlayerPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1D51A6A2F0011000000000F /* MpvAudioPlayerPlugin.swift */; };
B1D51A6A2F0011000000000A /* AtmosProbePlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1D51A6A2F0011000000000B /* AtmosProbePlugin.swift */; };
B1D51A6A2F00110000000008 /* ExternalDisplayManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1D51A6A2F00110000000007 /* ExternalDisplayManager.swift */; };
78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; };
/* End PBXBuildFile section */
@@ -75,6 +78,9 @@
97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
B1D51A6A2F00110000000002 /* MpvPlayerCoreBase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = MpvPlayerCoreBase.swift; path = ../shared/apple/MpvPlayer/MpvPlayerCoreBase.swift; sourceTree = SOURCE_ROOT; };
B1D51A6A2F00110000000006 /* MpvPlayerPluginShared.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = MpvPlayerPluginShared.swift; path = ../shared/apple/MpvPlayer/MpvPlayerPluginShared.swift; sourceTree = SOURCE_ROOT; };
B1D51A6A2F0011000000000D /* MpvAudioPlayerCore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = MpvAudioPlayerCore.swift; path = ../shared/apple/MpvPlayer/MpvAudioPlayerCore.swift; sourceTree = SOURCE_ROOT; };
B1D51A6A2F0011000000000F /* MpvAudioPlayerPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = MpvAudioPlayerPlugin.swift; path = ../shared/apple/MpvPlayer/MpvAudioPlayerPlugin.swift; sourceTree = SOURCE_ROOT; };
B1D51A6A2F0011000000000B /* AtmosProbePlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = AtmosProbePlugin.swift; path = ../shared/apple/AtmosProbe/AtmosProbePlugin.swift; sourceTree = SOURCE_ROOT; };
B1D51A6A2F00110000000007 /* ExternalDisplayManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ExternalDisplayManager.swift; sourceTree = "<group>"; };
BB346A1D0705AB171F80B11B /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; };
DE48FF2E074644167608B23D /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = "<group>"; };
@@ -126,6 +132,9 @@
children = (
B1D51A6A2F00110000000002 /* MpvPlayerCoreBase.swift */,
B1D51A6A2F00110000000006 /* MpvPlayerPluginShared.swift */,
B1D51A6A2F0011000000000D /* MpvAudioPlayerCore.swift */,
B1D51A6A2F0011000000000F /* MpvAudioPlayerPlugin.swift */,
B1D51A6A2F0011000000000B /* AtmosProbePlugin.swift */,
B1D51A6A2F00110000000007 /* ExternalDisplayManager.swift */,
6A8A46222EDB370C0057B88C /* MpvPlayerCore.swift */,
6A8A46232EDB370C0057B88C /* MpvPlayerPlugin.swift */,
@@ -417,6 +426,9 @@
files = (
B1D51A6A2F00110000000001 /* MpvPlayerCoreBase.swift in Sources */,
B1D51A6A2F00110000000005 /* MpvPlayerPluginShared.swift in Sources */,
B1D51A6A2F0011000000000C /* MpvAudioPlayerCore.swift in Sources */,
B1D51A6A2F0011000000000E /* MpvAudioPlayerPlugin.swift in Sources */,
B1D51A6A2F0011000000000A /* AtmosProbePlugin.swift in Sources */,
B1D51A6A2F00110000000008 /* ExternalDisplayManager.swift in Sources */,
6A8A46252EDB370C0057B88C /* MpvPlayerPlugin.swift in Sources */,
6A8A46262EDB370C0057B88C /* MpvPlayerCore.swift in Sources */,
@@ -715,6 +727,7 @@
MARKETING_VERSION = 1.0.0;
PRODUCT_BUNDLE_IDENTIFIER = com.edde746.plezy;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
@@ -788,8 +801,8 @@
isa = XCRemoteSwiftPackageReference;
repositoryURL = "https://github.com/edde746/MPVKit";
requirement = {
kind = revision;
revision = 245b69dce22156e81b79c84cfcb748358b674e47;
kind = exactVersion;
version = 1.0.12;
};
};
/* End XCRemoteSwiftPackageReference section */
@@ -40,7 +40,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/edde746/MPVKit",
"state" : {
"revision" : "245b69dce22156e81b79c84cfcb748358b674e47"
"revision" : "a453d675493a8abe26dc90f9dc484bc582628358",
"version" : "1.0.12"
}
},
{
@@ -57,8 +58,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/getsentry/sentry-cocoa",
"state" : {
"revision" : "16cd512711375fa73f25ae5e373f596bdf4251ae",
"version" : "8.58.0"
"revision" : "dad229c665bfd043c5d80ac7aa77717cbd19a1c3",
"version" : "8.58.3"
}
},
{
@@ -40,7 +40,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/edde746/MPVKit",
"state" : {
"revision" : "245b69dce22156e81b79c84cfcb748358b674e47"
"revision" : "a453d675493a8abe26dc90f9dc484bc582628358",
"version" : "1.0.12"
}
},
{
+12 -2
View File
@@ -14,11 +14,12 @@ import MediaPlayer
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
// Configure audio session for media playback
// Configure audio session for media playback. Not activated here: the
// session is non-mixing, so activation stops other apps' audio — it is
// claimed when playback actually starts.
do {
let session = AVAudioSession.sharedInstance()
try session.setCategory(.playback, mode: .default)
try session.setActive(true)
} catch {
print("Failed to configure audio session: \(error)")
}
@@ -36,6 +37,15 @@ import MediaPlayer
MpvPlayerPlugin.register(with: registrar)
}
// Register the audio-only MPV player plugin (music playback)
if let registrar = engineBridge.pluginRegistry.registrar(forPlugin: "MpvAudioPlayerPlugin") {
MpvAudioPlayerPlugin.register(with: registrar)
}
if let registrar = engineBridge.pluginRegistry.registrar(forPlugin: "AtmosProbePlugin") {
AtmosProbePlugin.register(with: registrar)
}
if let registrar = engineBridge.pluginRegistry.registrar(forPlugin: "DeviceAdjustmentChannel") {
registerDeviceAdjustmentChannel(messenger: registrar.messenger())
}
+7 -5
View File
@@ -1,6 +1,7 @@
import '../media/media_backend.dart';
import '../models/plex/plex_home_user.dart';
import '../services/plex_auth_service.dart';
import '../utils/url_utils.dart';
/// Identifier of a backend kind a [Connection] points at. Lighter-weight than
/// [MediaBackend] for places that only care about persistence/auth shape
@@ -233,7 +234,7 @@ class JellyfinConnection extends Connection {
JellyfinConnection({
required this.id,
required this.baseUrl,
required String baseUrl,
List<String>? baseUrls,
required this.serverName,
required this.serverMachineId,
@@ -245,7 +246,8 @@ class JellyfinConnection extends Connection {
this.status = ConnectionStatus.unknown,
required this.createdAt,
this.lastAuthenticatedAt,
}) : baseUrls = _normalizeBaseUrls(baseUrl, baseUrls);
}) : baseUrl = canonicalizeBaseUrl(baseUrl),
baseUrls = _normalizeBaseUrls(baseUrl, baseUrls);
@override
ConnectionKind get kind => ConnectionKind.jellyfin;
@@ -273,9 +275,9 @@ class JellyfinConnection extends Connection {
final seen = <String>{};
void add(String url) {
final trimmed = url.trim();
if (trimmed.isEmpty || !seen.add(trimmed)) return;
result.add(trimmed);
final normalized = canonicalizeBaseUrl(url);
if (normalized.isEmpty || !seen.add(normalized)) return;
result.add(normalized);
}
add(activeBaseUrl);
+3 -4
View File
@@ -3,6 +3,7 @@ import 'dart:convert';
import '../models/plex/plex_home.dart';
import '../models/plex/plex_home_user.dart';
import '../profiles/profile.dart';
import '../profiles/plex_home_cache_codec.dart';
import '../profiles/profile_registry.dart';
import '../services/plex_auth_service.dart';
import '../services/server_registry.dart';
@@ -225,9 +226,7 @@ class ConnectionBootstrap {
final raw = storage.getPlexHomeUsersCacheJson(connectionId);
if (raw == null || raw.isEmpty) return null;
try {
final decoded = jsonDecode(raw);
if (decoded is! List) return null;
return decoded.whereType<Map<String, dynamic>>().map(PlexHomeUser.fromJson).toList();
return decodePlexHomeUsersCache(raw);
} catch (e, st) {
appLogger.w('Migration: failed to read Plex Home cache for $connectionId', error: e, stackTrace: st);
return null;
@@ -238,7 +237,7 @@ class ConnectionBootstrap {
try {
final users = await _plexHomeUserFetcher(account.accountToken);
if (users.isNotEmpty) {
await storage.savePlexHomeUsersCache(account.id, users.map((u) => u.toJson()).toList());
await storage.savePlexHomeUsersCache(account.id, encodePlexHomeUsersCache(users));
appLogger.i('Migration: fetched ${users.length} Plex Home users for ${account.id}');
}
return users;
-26
View File
@@ -1,7 +1,6 @@
import 'dart:async';
import 'dart:convert';
import 'package:collection/collection.dart';
import 'package:drift/drift.dart';
import '../database/app_database.dart';
@@ -41,17 +40,6 @@ class ConnectionRegistry {
return _rowToConnection(row);
}
/// Returns the user's preferred connection — either the row marked
/// [Connections.isDefault], or the only row if exactly one exists, or
/// null when no connections are stored.
Future<Connection?> getDefault() async {
final rows = await _db.select(_db.connections).get();
if (rows.isEmpty) return null;
final flagged = rows.firstWhereOrNull((r) => r.isDefault);
final picked = flagged ?? (rows.length == 1 ? rows.single : null);
return picked == null ? null : _rowToConnection(picked);
}
/// Insert or replace [connection]. If this is the first stored connection
/// it is automatically marked default; re-upserting an existing row keeps
/// the row's current `isDefault` (so token/metadata refreshes don't clear
@@ -130,13 +118,6 @@ class ConnectionRegistry {
return all.whereType<PlexAccountConnection>().toList();
}
/// All Jellyfin connections in insertion order. Symmetric helper to
/// [listPlexAccounts].
Future<List<JellyfinConnection>> listJellyfin() async {
final all = await list();
return all.whereType<JellyfinConnection>().toList();
}
/// Lookup a [PlexAccountConnection] by id. Returns `null` if no row
/// matches OR the row exists but isn't a Plex account.
Future<PlexAccountConnection?> getPlexAccount(String id) async {
@@ -144,13 +125,6 @@ class ConnectionRegistry {
return c is PlexAccountConnection ? c : null;
}
/// Lookup a [JellyfinConnection] by id. Returns `null` if no row matches
/// OR the row exists but isn't a Jellyfin connection.
Future<JellyfinConnection?> getJellyfin(String id) async {
final c = await get(id);
return c is JellyfinConnection ? c : null;
}
Future<Connection?> _rowToConnection(ConnectionRow row) async {
try {
final json = jsonDecode(row.configJson) as Map<String, dynamic>;
+124
View File
@@ -0,0 +1,124 @@
import '../profiles/plex_home_service.dart';
import '../profiles/profile_connection_registry.dart';
import '../services/plex_auth_service.dart';
import '../services/storage_service.dart';
import '../utils/app_logger.dart';
import 'connection.dart';
import 'connection_registry.dart';
/// Outcome of [registerPlexAccountFromToken]. [homeUsersFetched] is false
/// when the `/home/users` fetch failed — first-sign-in flows can't build
/// any profile without it and must not conflate that with "no users".
/// [existedBefore] tells add-flows whether a cancelled attach should
/// remove the account again (it was created solely for the attach).
typedef PlexAccountRegistration = ({
PlexAccountConnection connection,
bool homeUsersFetched,
bool existedBefore,
String username,
String email,
});
/// Shared post-auth pipeline for a fresh plex.tv [token]: resolve the
/// account identity, persist the [PlexAccountConnection] (folding in a
/// legacy client-id-keyed row from an earlier failed identity lookup), and
/// refresh its Plex Home users. Used by the first-sign-in AuthScreen and
/// the add-account settings flow so identity/dedup policy can't drift.
Future<PlexAccountRegistration> registerPlexAccountFromToken({
required String token,
required ConnectionRegistry connections,
required ProfileConnectionRegistry profileConnections,
required StorageService storage,
required PlexHomeService plexHome,
}) async {
final auth = await PlexAuthService.create();
try {
// Account identity from plex.tv — the uuid is what makes multi-account
// work (the clientIdentifier is per-device and identical for every Plex
// account on this install). Falls back to the client identifier only
// when the user-info call fails outright; a later successful sign-in
// migrates that legacy row below.
String username = '';
String email = '';
String accountUuid = '';
try {
final info = await auth.getUserInfo(token);
username = (info['username'] as String?) ?? '';
email = (info['email'] as String?) ?? '';
accountUuid = (info['uuid'] as String?)?.trim() ?? '';
} catch (e) {
appLogger.d('getUserInfo after Plex sign-in failed (using fallback identity): $e');
}
final servers = await auth.fetchServers(token);
final connection = PlexAccountConnection(
id: 'plex.${accountUuid.isNotEmpty ? accountUuid : auth.clientIdentifier}',
accountToken: token,
clientIdentifier: auth.clientIdentifier,
accountLabel: username.isNotEmpty ? username : (email.isNotEmpty ? email : 'Plex'),
servers: servers,
createdAt: DateTime.now(),
lastAuthenticatedAt: DateTime.now(),
);
final legacyId = 'plex.${auth.clientIdentifier}';
final existedBefore =
await connections.get(connection.id) != null ||
(accountUuid.isNotEmpty &&
legacyId != connection.id &&
await connections.get(legacyId) is PlexAccountConnection);
await connections.upsert(connection);
if (accountUuid.isNotEmpty) {
await _migrateLegacyClientIdRow(
replacement: connection,
clientIdentifier: auth.clientIdentifier,
connections: connections,
profileConnections: profileConnections,
storage: storage,
);
}
// Fetch home users now so pickers surface the account's virtual
// profiles immediately.
final homeUsersFetched = await plexHome.refresh(connection);
return (
connection: connection,
homeUsersFetched: homeUsersFetched,
existedBefore: existedBefore,
username: username,
email: email,
);
} finally {
auth.dispose();
}
}
/// A row keyed by the per-device client identifier (created when an earlier
/// sign-in couldn't resolve the account uuid) would duplicate the account —
/// and collides with every other account on this device. Fold it into the
/// uuid-keyed [replacement]: re-point its join rows, then remove it.
///
/// Virtual profile ids that embedded the legacy account id are not
/// rewritten; their (rare) borrowed rows become orphans that the startup
/// prune and post-removal settle already clean up.
Future<void> _migrateLegacyClientIdRow({
required PlexAccountConnection replacement,
required String clientIdentifier,
required ConnectionRegistry connections,
required ProfileConnectionRegistry profileConnections,
required StorageService storage,
}) async {
final legacyId = 'plex.$clientIdentifier';
if (legacyId == replacement.id) return;
final legacy = await connections.get(legacyId);
if (legacy is! PlexAccountConnection) return;
final rows = await profileConnections.listForConnection(legacyId);
for (final row in rows) {
await profileConnections.upsert(row.copyWith(connectionId: replacement.id));
}
await storage.clearPlexHomeUsersCache(legacyId);
// The FK cascade drops the legacy rows we just re-pointed copies of.
await connections.remove(legacyId);
appLogger.i('Migrated legacy Plex account row $legacyId → ${replacement.id}');
}
+69 -54
View File
@@ -61,7 +61,7 @@ class AppDatabase extends _$AppDatabase {
AppDatabase.forTesting(super.e);
@override
int get schemaVersion => 15;
int get schemaVersion => 16;
@override
MigrationStrategy get migration {
@@ -214,6 +214,13 @@ class AppDatabase extends _$AppDatabase {
() => m.addColumn(downloadedMedia, downloadedMedia.mediaSourceId),
);
}
if (from < 16) {
appLogger.i('Adding includeSpecials column to SyncRules (v16 migration)');
await _ignoreAlreadyExists(
'SyncRules.includeSpecials column',
() => m.addColumn(syncRules, syncRules.includeSpecials),
);
}
},
);
}
@@ -270,6 +277,23 @@ class AppDatabase extends _$AppDatabase {
.get();
}
SimpleSelectStatement<$OfflineWatchProgressTable, OfflineWatchProgressItem> _watchActionsQuery(
Expression<bool> Function($OfflineWatchProgressTable table) matchesKey, {
String? profileId,
bool filterProfile = false,
String? clientScopeId,
bool filterClientScope = false,
}) {
return select(offlineWatchProgress)
..where(
(t) =>
matchesKey(t) &
(filterProfile ? _nullableTextPredicate(t.profileId, profileId) : const Constant(true)) &
(filterClientScope ? _clientScopePredicate(t.clientScopeId, clientScopeId) : const Constant(true)),
)
..orderBy([(t) => OrderingTerm.desc(t.updatedAt), (t) => OrderingTerm.desc(t.id)]);
}
/// Get the latest action for a specific item
Future<OfflineWatchProgressItem?> getLatestWatchAction(
String globalKey, {
@@ -278,16 +302,13 @@ class AppDatabase extends _$AppDatabase {
String? clientScopeId,
bool filterClientScope = false,
}) {
return (select(offlineWatchProgress)
..where(
(t) =>
t.globalKey.equals(globalKey) &
(filterProfile ? _nullableTextPredicate(t.profileId, profileId) : const Constant(true)) &
(filterClientScope ? _clientScopePredicate(t.clientScopeId, clientScopeId) : const Constant(true)),
)
..orderBy([(t) => OrderingTerm.desc(t.updatedAt), (t) => OrderingTerm.desc(t.id)])
..limit(1))
.getSingleOrNull();
return (_watchActionsQuery(
(t) => t.globalKey.equals(globalKey),
profileId: profileId,
filterProfile: filterProfile,
clientScopeId: clientScopeId,
filterClientScope: filterClientScope,
)..limit(1)).getSingleOrNull();
}
Future<List<OfflineWatchProgressItem>> getWatchActionsForKey(
@@ -297,15 +318,13 @@ class AppDatabase extends _$AppDatabase {
String? clientScopeId,
bool filterClientScope = false,
}) {
return (select(offlineWatchProgress)
..where(
(t) =>
t.globalKey.equals(globalKey) &
(filterProfile ? _nullableTextPredicate(t.profileId, profileId) : const Constant(true)) &
(filterClientScope ? _clientScopePredicate(t.clientScopeId, clientScopeId) : const Constant(true)),
)
..orderBy([(t) => OrderingTerm.desc(t.updatedAt), (t) => OrderingTerm.desc(t.id)]))
.get();
return _watchActionsQuery(
(t) => t.globalKey.equals(globalKey),
profileId: profileId,
filterProfile: filterProfile,
clientScopeId: clientScopeId,
filterClientScope: filterClientScope,
).get();
}
Future<Map<String, List<OfflineWatchProgressItem>>> getWatchActionsForKeys(
@@ -315,15 +334,11 @@ class AppDatabase extends _$AppDatabase {
Map<String, String?>? clientScopeIdsByGlobalKey,
}) async {
if (globalKeys.isEmpty) return const {};
final rows =
await (select(offlineWatchProgress)
..where(
(t) =>
t.globalKey.isIn(globalKeys) &
(filterProfile ? _nullableTextPredicate(t.profileId, profileId) : const Constant(true)),
)
..orderBy([(t) => OrderingTerm.desc(t.updatedAt), (t) => OrderingTerm.desc(t.id)]))
.get();
final rows = await _watchActionsQuery(
(t) => t.globalKey.isIn(globalKeys),
profileId: profileId,
filterProfile: filterProfile,
).get();
final result = <String, List<OfflineWatchProgressItem>>{};
for (final action in rows) {
@@ -346,31 +361,13 @@ class AppDatabase extends _$AppDatabase {
bool filterProfile = false,
Map<String, String?>? clientScopeIdsByGlobalKey,
}) async {
if (globalKeys.isEmpty) return {};
// Query all actions for the given keys
final allActions =
await (select(offlineWatchProgress)
..where(
(t) =>
t.globalKey.isIn(globalKeys) &
(filterProfile ? _nullableTextPredicate(t.profileId, profileId) : const Constant(true)),
)
..orderBy([(t) => OrderingTerm.desc(t.updatedAt), (t) => OrderingTerm.desc(t.id)]))
.get();
// Group by globalKey and take the latest (first due to ordering)
final result = <String, OfflineWatchProgressItem>{};
for (final action in allActions) {
if (clientScopeIdsByGlobalKey != null && clientScopeIdsByGlobalKey.containsKey(action.globalKey)) {
final expectedScope = clientScopeIdsByGlobalKey[action.globalKey];
if (!_clientScopeValuesMatch(action.clientScopeId, expectedScope)) continue;
}
// Only keep the first (latest) action for each key
result.putIfAbsent(action.globalKey, () => action);
}
return result;
final actionsByKey = await getWatchActionsForKeys(
globalKeys,
profileId: profileId,
filterProfile: filterProfile,
clientScopeIdsByGlobalKey: clientScopeIdsByGlobalKey,
);
return {for (final entry in actionsByKey.entries) entry.key: entry.value.first};
}
bool _clientScopeValuesMatch(String? actual, String? expected) {
@@ -511,6 +508,11 @@ class AppDatabase extends _$AppDatabase {
return delete(offlineWatchProgress).go();
}
/// Drop a removed profile's queued watch actions (profile teardown).
Future<void> deleteWatchActionsForProfile(String profileId) async {
await (delete(offlineWatchProgress)..where((t) => t.profileId.equals(profileId))).go();
}
Future<List<SyncRuleItem>> getSyncRules({String? profileId}) {
final query = select(syncRules);
if (profileId != null) {
@@ -532,6 +534,7 @@ class AppDatabase extends _$AppDatabase {
required int episodeCount,
int mediaIndex = 0,
String downloadFilter = 'unwatched',
bool includeSpecials = true,
}) async {
// [insertOnConflictUpdate] defaults the conflict target to the primary
// key (`id`), which is auto-incremented — the conflict never triggers
@@ -549,6 +552,7 @@ class AppDatabase extends _$AppDatabase {
createdAt: DateTime.now().millisecondsSinceEpoch,
mediaIndex: Value(mediaIndex),
downloadFilter: Value(downloadFilter),
includeSpecials: Value(includeSpecials),
),
onConflict: DoUpdate(
(_) => SyncRulesCompanion(
@@ -559,6 +563,7 @@ class AppDatabase extends _$AppDatabase {
episodeCount: Value(episodeCount),
mediaIndex: Value(mediaIndex),
downloadFilter: Value(downloadFilter),
includeSpecials: Value(includeSpecials),
),
target: [syncRules.globalKey],
),
@@ -611,6 +616,16 @@ class AppDatabase extends _$AppDatabase {
await (delete(syncRules)..where((t) => t.globalKey.equals(globalKey))).go();
}
/// Drop a removed profile's sync rules (profile teardown).
Future<void> deleteSyncRulesForProfile(String profileId) async {
await (delete(syncRules)..where((t) => t.profileId.equals(profileId))).go();
}
/// Drop every sync rule (full logout).
Future<void> clearAllSyncRules() async {
await delete(syncRules).go();
}
/// Get all downloaded media items (for syncing watch states)
Future<List<DownloadedMediaItem>> getAllDownloadedMetadata() {
return (select(downloadedMedia)..where((t) => t.status.equals(DownloadStatus.completed.index))).get();
+78 -3
View File
@@ -3150,6 +3150,21 @@ class $SyncRulesTable extends SyncRules
requiredDuringInsert: false,
defaultValue: const Constant('unwatched'),
);
static const VerificationMeta _includeSpecialsMeta = const VerificationMeta(
'includeSpecials',
);
@override
late final GeneratedColumn<bool> includeSpecials = GeneratedColumn<bool>(
'include_specials',
aliasedName,
false,
type: DriftSqlType.bool,
requiredDuringInsert: false,
defaultConstraints: GeneratedColumn.constraintIsAlways(
'CHECK ("include_specials" IN (0, 1))',
),
defaultValue: const Constant(true),
);
@override
List<GeneratedColumn> get $columns => [
id,
@@ -3164,6 +3179,7 @@ class $SyncRulesTable extends SyncRules
lastExecutedAt,
mediaIndex,
downloadFilter,
includeSpecials,
];
@override
String get aliasedName => _alias ?? actualTableName;
@@ -3267,6 +3283,15 @@ class $SyncRulesTable extends SyncRules
),
);
}
if (data.containsKey('include_specials')) {
context.handle(
_includeSpecialsMeta,
includeSpecials.isAcceptableOrUnknown(
data['include_specials']!,
_includeSpecialsMeta,
),
);
}
return context;
}
@@ -3324,6 +3349,10 @@ class $SyncRulesTable extends SyncRules
DriftSqlType.string,
data['${effectivePrefix}download_filter'],
)!,
includeSpecials: attachedDatabase.typeMapping.read(
DriftSqlType.bool,
data['${effectivePrefix}include_specials'],
)!,
);
}
@@ -3346,6 +3375,7 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
final int? lastExecutedAt;
final int mediaIndex;
final String downloadFilter;
final bool includeSpecials;
const SyncRuleItem({
required this.id,
required this.profileId,
@@ -3359,6 +3389,7 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
this.lastExecutedAt,
required this.mediaIndex,
required this.downloadFilter,
required this.includeSpecials,
});
@override
Map<String, Expression> toColumns(bool nullToAbsent) {
@@ -3377,6 +3408,7 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
}
map['media_index'] = Variable<int>(mediaIndex);
map['download_filter'] = Variable<String>(downloadFilter);
map['include_specials'] = Variable<bool>(includeSpecials);
return map;
}
@@ -3396,6 +3428,7 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
: Value(lastExecutedAt),
mediaIndex: Value(mediaIndex),
downloadFilter: Value(downloadFilter),
includeSpecials: Value(includeSpecials),
);
}
@@ -3417,6 +3450,7 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
lastExecutedAt: serializer.fromJson<int?>(json['lastExecutedAt']),
mediaIndex: serializer.fromJson<int>(json['mediaIndex']),
downloadFilter: serializer.fromJson<String>(json['downloadFilter']),
includeSpecials: serializer.fromJson<bool>(json['includeSpecials']),
);
}
@override
@@ -3435,6 +3469,7 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
'lastExecutedAt': serializer.toJson<int?>(lastExecutedAt),
'mediaIndex': serializer.toJson<int>(mediaIndex),
'downloadFilter': serializer.toJson<String>(downloadFilter),
'includeSpecials': serializer.toJson<bool>(includeSpecials),
};
}
@@ -3451,6 +3486,7 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
Value<int?> lastExecutedAt = const Value.absent(),
int? mediaIndex,
String? downloadFilter,
bool? includeSpecials,
}) => SyncRuleItem(
id: id ?? this.id,
profileId: profileId ?? this.profileId,
@@ -3466,6 +3502,7 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
: this.lastExecutedAt,
mediaIndex: mediaIndex ?? this.mediaIndex,
downloadFilter: downloadFilter ?? this.downloadFilter,
includeSpecials: includeSpecials ?? this.includeSpecials,
);
SyncRuleItem copyWithCompanion(SyncRulesCompanion data) {
return SyncRuleItem(
@@ -3491,6 +3528,9 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
downloadFilter: data.downloadFilter.present
? data.downloadFilter.value
: this.downloadFilter,
includeSpecials: data.includeSpecials.present
? data.includeSpecials.value
: this.includeSpecials,
);
}
@@ -3508,7 +3548,8 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
..write('createdAt: $createdAt, ')
..write('lastExecutedAt: $lastExecutedAt, ')
..write('mediaIndex: $mediaIndex, ')
..write('downloadFilter: $downloadFilter')
..write('downloadFilter: $downloadFilter, ')
..write('includeSpecials: $includeSpecials')
..write(')'))
.toString();
}
@@ -3527,6 +3568,7 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
lastExecutedAt,
mediaIndex,
downloadFilter,
includeSpecials,
);
@override
bool operator ==(Object other) =>
@@ -3543,7 +3585,8 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
other.createdAt == this.createdAt &&
other.lastExecutedAt == this.lastExecutedAt &&
other.mediaIndex == this.mediaIndex &&
other.downloadFilter == this.downloadFilter);
other.downloadFilter == this.downloadFilter &&
other.includeSpecials == this.includeSpecials);
}
class SyncRulesCompanion extends UpdateCompanion<SyncRuleItem> {
@@ -3559,6 +3602,7 @@ class SyncRulesCompanion extends UpdateCompanion<SyncRuleItem> {
final Value<int?> lastExecutedAt;
final Value<int> mediaIndex;
final Value<String> downloadFilter;
final Value<bool> includeSpecials;
const SyncRulesCompanion({
this.id = const Value.absent(),
this.profileId = const Value.absent(),
@@ -3572,6 +3616,7 @@ class SyncRulesCompanion extends UpdateCompanion<SyncRuleItem> {
this.lastExecutedAt = const Value.absent(),
this.mediaIndex = const Value.absent(),
this.downloadFilter = const Value.absent(),
this.includeSpecials = const Value.absent(),
});
SyncRulesCompanion.insert({
this.id = const Value.absent(),
@@ -3586,6 +3631,7 @@ class SyncRulesCompanion extends UpdateCompanion<SyncRuleItem> {
this.lastExecutedAt = const Value.absent(),
this.mediaIndex = const Value.absent(),
this.downloadFilter = const Value.absent(),
this.includeSpecials = const Value.absent(),
}) : serverId = Value(serverId),
ratingKey = Value(ratingKey),
globalKey = Value(globalKey),
@@ -3605,6 +3651,7 @@ class SyncRulesCompanion extends UpdateCompanion<SyncRuleItem> {
Expression<int>? lastExecutedAt,
Expression<int>? mediaIndex,
Expression<String>? downloadFilter,
Expression<bool>? includeSpecials,
}) {
return RawValuesInsertable({
if (id != null) 'id': id,
@@ -3619,6 +3666,7 @@ class SyncRulesCompanion extends UpdateCompanion<SyncRuleItem> {
if (lastExecutedAt != null) 'last_executed_at': lastExecutedAt,
if (mediaIndex != null) 'media_index': mediaIndex,
if (downloadFilter != null) 'download_filter': downloadFilter,
if (includeSpecials != null) 'include_specials': includeSpecials,
});
}
@@ -3635,6 +3683,7 @@ class SyncRulesCompanion extends UpdateCompanion<SyncRuleItem> {
Value<int?>? lastExecutedAt,
Value<int>? mediaIndex,
Value<String>? downloadFilter,
Value<bool>? includeSpecials,
}) {
return SyncRulesCompanion(
id: id ?? this.id,
@@ -3649,6 +3698,7 @@ class SyncRulesCompanion extends UpdateCompanion<SyncRuleItem> {
lastExecutedAt: lastExecutedAt ?? this.lastExecutedAt,
mediaIndex: mediaIndex ?? this.mediaIndex,
downloadFilter: downloadFilter ?? this.downloadFilter,
includeSpecials: includeSpecials ?? this.includeSpecials,
);
}
@@ -3691,6 +3741,9 @@ class SyncRulesCompanion extends UpdateCompanion<SyncRuleItem> {
if (downloadFilter.present) {
map['download_filter'] = Variable<String>(downloadFilter.value);
}
if (includeSpecials.present) {
map['include_specials'] = Variable<bool>(includeSpecials.value);
}
return map;
}
@@ -3708,7 +3761,8 @@ class SyncRulesCompanion extends UpdateCompanion<SyncRuleItem> {
..write('createdAt: $createdAt, ')
..write('lastExecutedAt: $lastExecutedAt, ')
..write('mediaIndex: $mediaIndex, ')
..write('downloadFilter: $downloadFilter')
..write('downloadFilter: $downloadFilter, ')
..write('includeSpecials: $includeSpecials')
..write(')'))
.toString();
}
@@ -6842,6 +6896,7 @@ typedef $$SyncRulesTableCreateCompanionBuilder =
Value<int?> lastExecutedAt,
Value<int> mediaIndex,
Value<String> downloadFilter,
Value<bool> includeSpecials,
});
typedef $$SyncRulesTableUpdateCompanionBuilder =
SyncRulesCompanion Function({
@@ -6857,6 +6912,7 @@ typedef $$SyncRulesTableUpdateCompanionBuilder =
Value<int?> lastExecutedAt,
Value<int> mediaIndex,
Value<String> downloadFilter,
Value<bool> includeSpecials,
});
class $$SyncRulesTableFilterComposer
@@ -6927,6 +6983,11 @@ class $$SyncRulesTableFilterComposer
column: $table.downloadFilter,
builder: (column) => ColumnFilters(column),
);
ColumnFilters<bool> get includeSpecials => $composableBuilder(
column: $table.includeSpecials,
builder: (column) => ColumnFilters(column),
);
}
class $$SyncRulesTableOrderingComposer
@@ -6997,6 +7058,11 @@ class $$SyncRulesTableOrderingComposer
column: $table.downloadFilter,
builder: (column) => ColumnOrderings(column),
);
ColumnOrderings<bool> get includeSpecials => $composableBuilder(
column: $table.includeSpecials,
builder: (column) => ColumnOrderings(column),
);
}
class $$SyncRulesTableAnnotationComposer
@@ -7053,6 +7119,11 @@ class $$SyncRulesTableAnnotationComposer
column: $table.downloadFilter,
builder: (column) => column,
);
GeneratedColumn<bool> get includeSpecials => $composableBuilder(
column: $table.includeSpecials,
builder: (column) => column,
);
}
class $$SyncRulesTableTableManager
@@ -7098,6 +7169,7 @@ class $$SyncRulesTableTableManager
Value<int?> lastExecutedAt = const Value.absent(),
Value<int> mediaIndex = const Value.absent(),
Value<String> downloadFilter = const Value.absent(),
Value<bool> includeSpecials = const Value.absent(),
}) => SyncRulesCompanion(
id: id,
profileId: profileId,
@@ -7111,6 +7183,7 @@ class $$SyncRulesTableTableManager
lastExecutedAt: lastExecutedAt,
mediaIndex: mediaIndex,
downloadFilter: downloadFilter,
includeSpecials: includeSpecials,
),
createCompanionCallback:
({
@@ -7126,6 +7199,7 @@ class $$SyncRulesTableTableManager
Value<int?> lastExecutedAt = const Value.absent(),
Value<int> mediaIndex = const Value.absent(),
Value<String> downloadFilter = const Value.absent(),
Value<bool> includeSpecials = const Value.absent(),
}) => SyncRulesCompanion.insert(
id: id,
profileId: profileId,
@@ -7139,6 +7213,7 @@ class $$SyncRulesTableTableManager
lastExecutedAt: lastExecutedAt,
mediaIndex: mediaIndex,
downloadFilter: downloadFilter,
includeSpecials: includeSpecials,
),
withReferenceMapper: (p0) => p0
.map((e) => (e.readTable(table), BaseReferences(db, table, e)))
+68 -11
View File
@@ -22,9 +22,8 @@ extension DownloadDatabaseOperations on AppDatabase {
await (delete(downloadOwners)..where((t) => t.profileId.equals(profileId) & t.globalKey.equals(globalKey))).go();
}
Future<void> removeDownloadOwnersForProfile(String profileId) async {
if (profileId.isEmpty) return;
await (delete(downloadOwners)..where((t) => t.profileId.equals(profileId))).go();
Future<void> clearAllDownloadOwners() async {
await delete(downloadOwners).go();
}
Future<Set<String>> getDownloadOwnerKeysForProfile(String profileId) async {
@@ -55,22 +54,32 @@ extension DownloadDatabaseOperations on AppDatabase {
final connectionRows = await select(connections).get();
final connectionIds = connectionRows.map((row) => row.id).toSet();
return candidates
.where((row) {
if (localProfileIds.contains(row.profileId)) return true;
final plexHome = parsePlexHomeProfileId(row.profileId);
if (plexHome != null) return connectionIds.contains(plexHome.accountConnectionId);
return localProfileIds.isEmpty;
})
.where((row) => _isValidDownloadOwner(row, localProfileIds: localProfileIds, connectionIds: connectionIds))
.toList(growable: false);
}
/// Claim pre-v17 shared download rows for [profileId]. Rows that already
/// have any owner are left untouched so later profiles do not inherit them.
/// have any valid owner are left untouched so later profiles do not
/// inherit them.
///
/// Runs on every profile switch — validity context is computed once and
/// applied in memory instead of the per-download full-table rescan
/// `getDownloadOwnerCount` would do.
Future<void> adoptLegacyDownloadsForProfile(String profileId) async {
if (profileId.isEmpty) return;
final rows = await select(downloadedMedia).get();
if (rows.isEmpty) return;
final owners = await select(downloadOwners).get();
final localProfileIds = (await select(profiles).get()).map((row) => row.id).toSet();
final connectionIds = (await select(connections).get()).map((row) => row.id).toSet();
final ownedKeys = <String>{
for (final owner in owners)
if (_isValidDownloadOwner(owner, localProfileIds: localProfileIds, connectionIds: connectionIds))
owner.globalKey,
};
for (final row in rows) {
if (await getDownloadOwnerCount(row.globalKey) == 0) {
if (!ownedKeys.contains(row.globalKey)) {
await addDownloadOwner(profileId: profileId, globalKey: row.globalKey);
}
}
@@ -238,6 +247,43 @@ extension DownloadDatabaseOperations on AppDatabase {
.get();
}
/// Downloaded tracks belonging to an album (parentRatingKey). Mirrors
/// [getEpisodesBySeason] but filters on type so an id collision with a
/// season key can never mix media kinds.
Future<List<DownloadedMediaItem>> getTracksByAlbum(
String albumKey, {
ServerId? serverId,
String? clientScopeId,
bool filterClientScope = false,
}) {
return (select(downloadedMedia)..where(
(t) =>
t.type.equals('track') &
t.parentRatingKey.equals(albumKey) &
_optionalServerPredicate(t.serverId, serverIdOrNull(serverId)) &
_optionalClientScopePredicate(t.clientScopeId, clientScopeId, filterClientScope: filterClientScope),
))
.get();
}
/// Downloaded tracks belonging to an artist (grandparentRatingKey). Mirrors
/// [getEpisodesByShow] with the same type filter as [getTracksByAlbum].
Future<List<DownloadedMediaItem>> getTracksByArtist(
String artistKey, {
ServerId? serverId,
String? clientScopeId,
bool filterClientScope = false,
}) {
return (select(downloadedMedia)..where(
(t) =>
t.type.equals('track') &
t.grandparentRatingKey.equals(artistKey) &
_optionalServerPredicate(t.serverId, serverIdOrNull(serverId)) &
_optionalClientScopePredicate(t.clientScopeId, clientScopeId, filterClientScope: filterClientScope),
))
.get();
}
Future<List<DownloadedMediaItem>> getDownloadsByServerId(ServerId serverId) {
return (select(downloadedMedia)..where((t) => t.serverId.equals(serverId))).get();
}
@@ -271,3 +317,14 @@ extension DownloadDatabaseOperations on AppDatabase {
return item?.bgTaskId;
}
}
bool _isValidDownloadOwner(
DownloadOwnerItem owner, {
required Set<String> localProfileIds,
required Set<String> connectionIds,
}) {
if (localProfileIds.contains(owner.profileId)) return true;
final plexHome = parsePlexHomeProfileId(owner.profileId);
if (plexHome != null) return connectionIds.contains(plexHome.accountConnectionId);
return localProfileIds.isEmpty;
}
+4 -3
View File
@@ -101,6 +101,7 @@ class SyncRules extends Table {
IntColumn get lastExecutedAt => integer().nullable()();
IntColumn get mediaIndex => integer().withDefault(const Constant(0))();
TextColumn get downloadFilter => text().withDefault(const Constant('unwatched'))();
BoolColumn get includeSpecials => boolean().withDefault(const Constant(true))();
}
/// Persisted media-server connections.
@@ -192,9 +193,9 @@ class ProfileConnections extends Table {
// No FK on profile_id: Plex Home profiles are virtual (built by
// Profile.virtualPlexHome from PlexHomeService's live cache, never
// persisted in `profiles`), so an FK here would reject every join row
// they need. The two profile-delete sites clean up join rows manually
// via ProfileConnectionRegistry.removeAllForProfile before calling
// ProfileRegistry.remove.
// they need. Profile deletion instead cleans up join rows explicitly
// (removeAllProfileConnectionsAndCleanup in profile_connection_cleanup)
// before calling ProfileRegistry.remove.
TextColumn get profileId => text()();
TextColumn get connectionId => text().references(Connections, #id, onDelete: KeyAction.cascade)();
TextColumn get userToken => text().withDefault(const Constant(''))();
@@ -92,6 +92,12 @@ class MediaServerHttpException extends MediaServerException {
type == MediaServerHttpErrorType.connectionError ||
type == MediaServerHttpErrorType.receiveTimeout;
/// Whether the request was aborted client-side (client teardown or an
/// explicit abort), as opposed to failing against the server. A cancelled
/// fetch says nothing about the server's actual content — callers must not
/// treat it as an empty result.
bool get isCancellation => type == MediaServerHttpErrorType.cancelled;
@override
String toString() {
final parts = <String>[type.name];
+7 -1
View File
@@ -37,12 +37,17 @@ class CardFocusScope extends InheritedWidget {
class CardFocusBorder extends StatelessWidget {
const CardFocusBorder({
super.key,
required this.borderRadius,
this.borderRadius = FocusTheme.defaultBorderRadius,
this.borderRadii,
this.strokeAlign = BorderSide.strokeAlignOutside,
required this.child,
});
final double borderRadius;
/// Per-corner radii; overrides [borderRadius] when set (M3E grouped cards).
final BorderRadius? borderRadii;
final double strokeAlign;
final Widget child;
@@ -58,6 +63,7 @@ class CardFocusBorder extends StatelessWidget {
context,
isFocused: showFocus,
borderRadius: borderRadius,
radii: borderRadii,
borderStrokeAlign: strokeAlign,
),
child: child,
@@ -0,0 +1,63 @@
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart' show KeyEventResult, VoidCallback;
import 'dpad_navigator.dart';
/// Tracks the timer and physical key state for a D-pad SELECT long press.
///
/// Focus loss, context-menu dispatch, and transferred/touch gesture suppression
/// stay with the caller because their behavior differs between widgets. The TV
/// guide program selector also stays local: it captures a program at key-down
/// and resets its state before opening program details.
class DpadSelectLongPressController {
static const defaultDuration = Duration(milliseconds: 500);
Timer? _timer;
bool _isKeyDown = false;
KeyEventResult handleKeyEvent(
KeyEvent event, {
Duration duration = defaultDuration,
required bool Function() isOwnerActive,
required VoidCallback onShortPress,
required VoidCallback onLongPress,
}) {
if (!event.logicalKey.isSelectKey) return KeyEventResult.ignored;
if (event is KeyDownEvent) {
// Some platforms report another down instead of a repeat. Only the
// transition from up to down may start (or restart) the timer.
if (!_isKeyDown) {
_isKeyDown = true;
_timer?.cancel();
_timer = Timer(duration, () {
if (!isOwnerActive() || !_isKeyDown) return;
SelectKeyUpSuppressor.suppressSelectUntilKeyUp();
onLongPress();
});
}
return KeyEventResult.handled;
}
if (event is KeyRepeatEvent) return KeyEventResult.handled;
if (event is KeyUpEvent) {
final timerWasActive = _timer?.isActive ?? false;
_timer?.cancel();
if (timerWasActive && _isKeyDown) onShortPress();
_isKeyDown = false;
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
void reset() {
_timer?.cancel();
_isKeyDown = false;
}
void dispose() => reset();
}
+28 -3
View File
@@ -24,17 +24,20 @@ class FocusTheme {
return Theme.of(context).extension<MonoTokens>()?.fast ?? const Duration(milliseconds: 150);
}
/// [radii] overrides [borderRadius] when per-corner radii are needed
/// (M3E grouped cards: large outer / small inner corners).
static BoxDecoration focusDecoration(
BuildContext context, {
required bool isFocused,
double borderRadius = defaultBorderRadius,
BorderRadius? radii,
double borderStrokeAlign = BorderSide.strokeAlignInside,
Color? color,
}) {
final focusColor = color ?? getFocusBorderColor(context);
return BoxDecoration(
borderRadius: BorderRadius.circular(borderRadius),
borderRadius: radii ?? BorderRadius.circular(borderRadius),
border: Border.all(
color: isFocused ? focusColor : Colors.transparent,
width: focusBorderWidth,
@@ -65,10 +68,32 @@ class FocusTheme {
/// Build focus decoration with background color instead of border.
/// Useful for video controls where it should match the native hover style.
static BoxDecoration focusBackgroundDecoration({required bool isFocused, double borderRadius = defaultBorderRadius}) {
/// [radii] overrides [borderRadius] when per-corner radii are needed.
static BoxDecoration focusBackgroundDecoration({
required bool isFocused,
double borderRadius = defaultBorderRadius,
BorderRadius? radii,
}) {
return BoxDecoration(
borderRadius: BorderRadius.circular(borderRadius),
borderRadius: radii ?? BorderRadius.circular(borderRadius),
color: isFocused ? Colors.white.withValues(alpha: 0.2) : Colors.transparent,
);
}
/// Focus background fill derived from the theme's text color, so it stays
/// visible on BOTH light and dark surfaces — the white-based
/// [focusBackgroundDecoration] disappears on light ones. This is the mono
/// convention used by [TrackRow], the navigation rail, and the music player
/// surfaces. Prefer this for any new mono-themed surface.
static BoxDecoration textFillFocusDecoration(
BuildContext context, {
required bool isFocused,
double borderRadius = defaultBorderRadius,
BorderRadius? radii,
}) {
return BoxDecoration(
borderRadius: radii ?? BorderRadius.circular(borderRadius),
color: isFocused ? tokens(context).text.withValues(alpha: 0.12) : Colors.transparent,
);
}
}
+34 -29
View File
@@ -5,6 +5,7 @@ import '../widgets/clickable_cursor.dart';
import 'focus_theme.dart';
import 'input_mode_tracker.dart';
import 'key_event_utils.dart';
import 'owned_focus_node_binding.dart';
typedef FocusableActionBuilder = Widget Function(BuildContext context, FocusableActionBuildState state);
@@ -94,9 +95,8 @@ class FocusableActionBar extends StatefulWidget {
}
class FocusableActionBarState extends State<FocusableActionBar> {
late List<OwnedFocusNodeBinding> _focusBindings;
late List<FocusNode> _focusNodes;
late List<bool> _ownsFocusNodes;
late List<VoidCallback> _focusListeners;
late List<bool> _focusStates;
bool _hasAnyFocus = false;
@@ -131,27 +131,28 @@ class FocusableActionBarState extends State<FocusableActionBar> {
}
void _initNodes() {
_focusNodes = List.generate(
widget.actions.length,
(i) => widget.actions[i].focusNode ?? FocusNode(debugLabel: widget.actions[i].debugLabel ?? 'ActionBar[$i]'),
);
_ownsFocusNodes = List.generate(widget.actions.length, (i) => widget.actions[i].focusNode == null);
_focusListeners = [];
_focusStates = List.generate(widget.actions.length, (i) => _focusNodes[i].hasFocus);
_hasAnyFocus = _focusNodes.any((node) => node.hasFocus);
for (var i = 0; i < _focusNodes.length; i++) {
final idx = i;
void listener() {
final hasFocus = _focusNodes[idx].hasFocus;
if (_focusStates[idx] != hasFocus) {
setState(() => _focusStates[idx] = hasFocus);
}
_notifyRowFocusIfChanged();
}
_focusListeners.add(listener);
_focusNodes[i].addListener(listener);
_focusBindings = [];
_focusNodes = [];
_focusStates = List<bool>.filled(widget.actions.length, false);
for (var i = 0; i < widget.actions.length; i++) {
final index = i;
final binding = OwnedFocusNodeBinding();
binding.bind(
externalNode: widget.actions[i].focusNode,
debugLabel: widget.actions[i].debugLabel ?? 'ActionBar[$i]',
listener: () {
final hasFocus = _focusNodes[index].hasFocus;
if (_focusStates[index] != hasFocus) {
setState(() => _focusStates[index] = hasFocus);
}
_notifyRowFocusIfChanged();
},
);
_focusBindings.add(binding);
_focusNodes.add(binding.node);
_focusStates[i] = binding.node.hasFocus;
}
_hasAnyFocus = _focusNodes.any((node) => node.hasFocus);
}
void _notifyRowFocusIfChanged() {
@@ -162,11 +163,8 @@ class FocusableActionBarState extends State<FocusableActionBar> {
}
void _disposeNodes() {
for (var i = 0; i < _focusNodes.length; i++) {
_focusNodes[i].removeListener(_focusListeners[i]);
if (_ownsFocusNodes[i]) {
_focusNodes[i].dispose();
}
for (final binding in _focusBindings) {
binding.dispose();
}
}
@@ -181,7 +179,7 @@ class FocusableActionBarState extends State<FocusableActionBar> {
final isKeyboard = InputModeTracker.isKeyboardMode(context);
final duration = FocusTheme.getAnimationDuration(context);
return Row(
final row = Row(
mainAxisSize: widget.mainAxisSize,
children: [
for (var i = 0; i < widget.actions.length; i++) ...[
@@ -190,13 +188,20 @@ class FocusableActionBarState extends State<FocusableActionBar> {
],
],
);
// While focus is outside the row (the common state — the user is browsing
// content), every button is equally dimmed, so dim once at row level:
// each sub-1.0 opacity is its own saveLayer, i.e. a full render-pass
// switch on the tiled GPUs low-end TVs use, and these bars sit on screen
// permanently. Per-button dims (below) take over only while the row holds
// focus; mid-transition the two multiply, which stays visually seamless.
return AnimatedOpacity(opacity: isKeyboard && !_hasAnyFocus ? 0.6 : 1.0, duration: duration, child: row);
}
Widget _buildButton(int index, bool isKeyboard, Duration duration) {
final action = widget.actions[index];
final isFocused = _focusStates[index];
final showFocus = isFocused && isKeyboard;
final opacity = isKeyboard && !isFocused ? 0.6 : 1.0;
final opacity = isKeyboard && _hasAnyFocus && !isFocused ? 0.6 : 1.0;
final buildState = FocusableActionBuildState(
focusNode: _focusNodes[index],
+29 -39
View File
@@ -1,9 +1,10 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../utils/scroll_utils.dart';
import 'owned_focus_node_binding.dart';
import 'dpad_navigator.dart';
import 'dpad_select_long_press_controller.dart';
import 'key_event_utils.dart';
class ChipKeyCallbacks {
@@ -44,10 +45,9 @@ class ChipKeyCallbacks {
/// 6. Call [disposeFocusNode] in your `dispose`
/// 7. Use [focusNode] and [isFocused] in your build method
mixin FocusableChipStateMixin<T extends StatefulWidget> on State<T> {
FocusNode? _internalFocusNode;
final _focusNodeBinding = OwnedFocusNodeBinding();
bool _isFocused = false;
Timer? _longPressTimer;
bool _isSelectKeyDown = false;
final _selectLongPress = DpadSelectLongPressController();
/// Override to return the widget's optional external focus node.
FocusNode? get widgetFocusNode;
@@ -56,36 +56,40 @@ mixin FocusableChipStateMixin<T extends StatefulWidget> on State<T> {
String get debugLabel;
/// The active focus node (external if provided, otherwise internal).
FocusNode get focusNode {
return widgetFocusNode ?? (_internalFocusNode ??= FocusNode(debugLabel: debugLabel));
}
FocusNode get focusNode => _focusNodeBinding.node;
/// Whether this widget is currently focused.
bool get isFocused => _isFocused;
/// Call this in your `initState` to set up the focus listener.
void initFocusNode() {
focusNode.addListener(_onFocusChange);
_focusNodeBinding.bind(externalNode: widgetFocusNode, listener: _onFocusChange, debugLabel: debugLabel);
}
/// Call this in your `didUpdateWidget` with the old widget's focusNode.
void updateFocusNode(FocusNode? oldFocusNode) {
if (oldFocusNode != widgetFocusNode) {
oldFocusNode?.removeListener(_onFocusChange);
focusNode.addListener(_onFocusChange);
_focusNodeBinding.bind(externalNode: widgetFocusNode, listener: _onFocusChange, debugLabel: debugLabel);
}
}
/// Call this in your `dispose` to clean up the focus listener.
void disposeFocusNode() {
focusNode.removeListener(_onFocusChange);
_internalFocusNode?.dispose();
_longPressTimer?.cancel();
_focusNodeBinding.dispose();
_selectLongPress.dispose();
}
void _onFocusChange() {
if (mounted) {
setState(() => _isFocused = focusNode.hasFocus);
final hasFocus = focusNode.hasFocus;
setState(() => _isFocused = hasFocus);
if (!hasFocus) {
_selectLongPress.reset();
}
// Same convention as FocusableTileStateMixin: a chip inside a
// scrollable strip (TabChipStrip, filter bars) reveals itself on
// focus; a no-op when no ancestor scrollable exists.
if (focusNode.hasFocus) scrollContextToCenter(context);
}
}
@@ -109,35 +113,21 @@ mixin FocusableChipStateMixin<T extends StatefulWidget> on State<T> {
}
if (SelectKeyUpSuppressor.consumeIfSuppressed(event)) {
if (event is KeyUpEvent && key.isSelectKey) {
_selectLongPress.reset();
}
return KeyEventResult.handled;
}
// SELECT key with long press support
if (key.isSelectKey) {
if (callbacks.onLongPress != null) {
if (event is KeyDownEvent) {
if (!_isSelectKeyDown) {
_isSelectKeyDown = true;
_longPressTimer?.cancel();
_longPressTimer = Timer(const Duration(milliseconds: 500), () {
if (mounted) {
SelectKeyUpSuppressor.suppressSelectUntilKeyUp();
callbacks.onLongPress?.call();
}
});
}
return KeyEventResult.handled;
} else if (event is KeyRepeatEvent) {
return KeyEventResult.handled;
} else if (event is KeyUpEvent) {
final timerWasActive = _longPressTimer?.isActive ?? false;
_longPressTimer?.cancel();
if (timerWasActive && _isSelectKeyDown) {
callbacks.onSelect?.call();
}
_isSelectKeyDown = false;
return KeyEventResult.handled;
}
return _selectLongPress.handleKeyEvent(
event,
isOwnerActive: () => mounted,
onShortPress: () => callbacks.onSelect?.call(),
onLongPress: callbacks.onLongPress!,
);
} else if (callbacks.onSelect != null) {
return handleOneShotSelect(event, callbacks.onSelect!);
}
@@ -145,7 +135,7 @@ mixin FocusableChipStateMixin<T extends StatefulWidget> on State<T> {
// Context menu key triggers long press directly
if (event.isActionable && key.isContextMenuKey && callbacks.onLongPress != null) {
SelectKeyUpSuppressor.suppressSelectUntilKeyUp();
_selectLongPress.reset();
callbacks.onLongPress!();
return KeyEventResult.handled;
}
+172 -77
View File
@@ -8,6 +8,7 @@ import '../utils/platform_detector.dart';
import '../utils/text_input_diagnostics.dart';
import '../widgets/tv_virtual_keyboard.dart';
import 'dpad_navigator.dart';
import 'owned_focus_node_binding.dart';
bool _usesTvKeyboard(bool enableTvKeyboard) => enableTvKeyboard && PlatformDetector.isTV();
@@ -26,6 +27,30 @@ enum TvKeyboardAutoOpenBehavior {
never,
}
/// Imperative handle to the TV on-screen keyboard of a [FocusableTextField] /
/// [FocusableTextFormField]. Pass the same instance to the field's
/// `tvKeyboardController`; the field's host attaches itself on mount.
///
/// Only meaningful on TV. On other platforms the OSK never exists, so every
/// method is an effective no-op.
class TvKeyboardController {
_FocusableTextInputHostState? _host;
void _attach(_FocusableTextInputHostState host) => _host = host;
void _detach(_FocusableTextInputHostState host) {
if (identical(_host, host)) _host = null;
}
/// Dismiss the OSK if it is open (and prevent it from auto-reopening while
/// the field keeps focus). No-op when nothing is open.
void closeKeyboard() => _host?._dismissTvKeyboard();
/// Focus the field but do NOT open the OSK for this focus entry. Used as a
/// fallback landing spot (e.g. a remote search that returned no results) so
/// the remote isn't stranded on an off-screen element.
void focusInputWithoutKeyboard() => _host?._focusWithoutKeyboard();
}
String _describeTextInputKey(KeyEvent event) {
return 'type=${event.runtimeType} logical=${event.logicalKey.keyLabel}/${event.logicalKey.keyId} '
'physical=${event.physicalKey.usbHidUsage} deviceType=${event.deviceType} character=${event.character}';
@@ -108,20 +133,25 @@ KeyEventResult _handleInputKey({
VoidCallback? onNavigateDown,
}) {
final key = event.logicalKey;
final diagnosticsEnabled = TextInputDiagnostics.enabled;
KeyEventResult finish(KeyEventResult result, String reason) {
_logTvTextInput(
'result=$result reason=$reason key=(${_describeTextInputKey(event)}) '
'usesTvKeyboard=$usesTvKeyboard enabled=$enabled textLength=${controller.text.length} '
'selection=${controller.selection} onNav(up=${onNavigateUp != null},down=${onNavigateDown != null},'
'left=${onNavigateLeft != null},right=${onNavigateRight != null}) onSelect=${onSelect != null} onBack=${onBack != null}',
);
if (diagnosticsEnabled) {
_logTvTextInput(
'result=$result reason=$reason key=(${_describeTextInputKey(event)}) '
'usesTvKeyboard=$usesTvKeyboard enabled=$enabled textLength=${controller.text.length} '
'selection=${controller.selection} onNav(up=${onNavigateUp != null},down=${onNavigateDown != null},'
'left=${onNavigateLeft != null},right=${onNavigateRight != null}) onSelect=${onSelect != null} onBack=${onBack != null}',
);
}
return result;
}
_logTvTextInput(
'received key=(${_describeTextInputKey(event)}) usesTvKeyboard=$usesTvKeyboard enabled=$enabled '
'textLength=${controller.text.length} selection=${controller.selection}',
);
if (diagnosticsEnabled) {
_logTvTextInput(
'received key=(${_describeTextInputKey(event)}) usesTvKeyboard=$usesTvKeyboard enabled=$enabled '
'textLength=${controller.text.length} selection=${controller.selection}',
);
}
if (_shouldPassNativeTvKeyToPlatform(usesTvKeyboard: usesTvKeyboard, enabled: enabled, event: event)) {
return finish(KeyEventResult.skipRemainingHandlers, 'pass-native-tv-key-to-platform');
@@ -218,10 +248,12 @@ KeyEventResult _handleInputKey({
bool _shouldPassNativeTvKeyToPlatform({required bool usesTvKeyboard, required bool enabled, required KeyEvent event}) {
if (!enabled || usesTvKeyboard || !PlatformDetector.isTV()) {
_logTvTextInput(
'native-pass=false reason=disabled-or-custom-keyboard enabled=$enabled usesTvKeyboard=$usesTvKeyboard '
'isTv=${PlatformDetector.isTV()} key=(${_describeTextInputKey(event)})',
);
if (TextInputDiagnostics.enabled) {
_logTvTextInput(
'native-pass=false reason=disabled-or-custom-keyboard enabled=$enabled usesTvKeyboard=$usesTvKeyboard '
'isTv=${PlatformDetector.isTV()} key=(${_describeTextInputKey(event)})',
);
}
return false;
}
@@ -231,10 +263,12 @@ bool _shouldPassNativeTvKeyToPlatform({required bool usesTvKeyboard, required bo
// native TV navigation cannot rely on deviceType.
final key = event.logicalKey;
final shouldPass = key.isDpadDirection || key.isBackKey || event.isTvSelectEvent;
_logTvTextInput(
'native-pass=$shouldPass reason=${shouldPass ? "remote-navigation-key" : "not-navigation-key"} '
'key=(${_describeTextInputKey(event)})',
);
if (TextInputDiagnostics.enabled) {
_logTvTextInput(
'native-pass=$shouldPass reason=${shouldPass ? "remote-navigation-key" : "not-navigation-key"} '
'key=(${_describeTextInputKey(event)})',
);
}
return shouldPass;
}
@@ -365,6 +399,14 @@ void _defaultEditingComplete(TextInputAction? textInputAction) {
}
}
({int start, int end}) _normalizedSelectionRange(TextEditingValue value) {
final selection = value.selection;
if (!selection.isValid) {
return (start: value.text.length, end: value.text.length);
}
return (start: selection.start.clamp(0, value.text.length), end: selection.end.clamp(0, value.text.length));
}
void _insertText({
required TextEditingController controller,
required String text,
@@ -373,13 +415,9 @@ void _insertText({
ValueChanged<String>? onChanged,
}) {
final value = controller.value;
final selection = value.selection;
final start = selection.isValid
? (selection.start < selection.end ? selection.start : selection.end)
: value.text.length;
final end = selection.isValid
? (selection.start > selection.end ? selection.start : selection.end)
: value.text.length;
final range = _normalizedSelectionRange(value);
final start = range.start;
final end = range.end;
final newText = value.text.replaceRange(start, end, text);
_replaceTextValue(
controller: controller,
@@ -401,13 +439,9 @@ void _backspace({
ValueChanged<String>? onChanged,
}) {
final value = controller.value;
final selection = value.selection;
final start = selection.isValid
? (selection.start < selection.end ? selection.start : selection.end)
: value.text.length;
final end = selection.isValid
? (selection.start > selection.end ? selection.start : selection.end)
: value.text.length;
final range = _normalizedSelectionRange(value);
final start = range.start;
final end = range.end;
if (start != end) {
_replaceTextRange(
controller,
@@ -437,13 +471,9 @@ void _deleteForward({
ValueChanged<String>? onChanged,
}) {
final value = controller.value;
final selection = value.selection;
final start = selection.isValid
? (selection.start < selection.end ? selection.start : selection.end)
: value.text.length;
final end = selection.isValid
? (selection.start > selection.end ? selection.start : selection.end)
: value.text.length;
final range = _normalizedSelectionRange(value);
final start = range.start;
final end = range.end;
if (start != end) {
_replaceTextRange(
controller,
@@ -527,6 +557,7 @@ abstract class _FocusableTextInputBase extends StatelessWidget {
final bool enabled;
final bool enableTvKeyboard;
final TvKeyboardAutoOpenBehavior tvKeyboardAutoOpenBehavior;
final TvKeyboardController? tvKeyboardController;
final bool obscureText;
final bool autocorrect;
final bool enableSuggestions;
@@ -560,6 +591,7 @@ abstract class _FocusableTextInputBase extends StatelessWidget {
this.enabled = true,
this.enableTvKeyboard = true,
this.tvKeyboardAutoOpenBehavior = TvKeyboardAutoOpenBehavior.onFocus,
this.tvKeyboardController,
this.obscureText = false,
this.autocorrect = true,
this.enableSuggestions = true,
@@ -597,6 +629,23 @@ abstract class _FocusableTextInputBase extends StatelessWidget {
}
}
({
TextInputType? keyboardType,
bool readOnly,
bool? showCursor,
bool? enableInteractiveSelection,
VoidCallback? onTap,
})
_tvInputConfiguration(bool usesTvKeyboard, VoidCallback openKeyboard) {
return (
keyboardType: usesTvKeyboard ? TextInputType.none : keyboardType,
readOnly: usesTvKeyboard,
showCursor: usesTvKeyboard ? true : null,
enableInteractiveSelection: usesTvKeyboard ? false : enableInteractiveSelection,
onTap: usesTvKeyboard ? openKeyboard : null,
);
}
KeyEventResult _handleKey(BuildContext context, FocusNode node, KeyEvent event, VoidCallback openKeyboard) {
return _handleInputKey(
controller: controller,
@@ -623,7 +672,6 @@ abstract class _FocusableTextInputBase extends StatelessWidget {
}
Widget buildFocusableInput(
BuildContext context,
Widget Function(bool usesTvKeyboard, FocusNode focusNode, VoidCallback openKeyboard) builder,
) {
return _FocusableTextInputHost(input: this, builder: builder);
@@ -641,7 +689,7 @@ class _FocusableTextInputHost extends StatefulWidget {
}
class _FocusableTextInputHostState extends State<_FocusableTextInputHost> {
FocusNode? _ownedFocusNode;
final OwnedFocusNodeBinding _focusNodeBinding = OwnedFocusNodeBinding();
FocusNode? _installedFocusNode;
FocusOnKeyEventCallback? _previousOnKeyEvent;
late final FocusOnKeyEventCallback _keyHandler = _handleKey;
@@ -655,16 +703,27 @@ class _FocusableTextInputHostState extends State<_FocusableTextInputHost> {
bool _hasSeenTvKeyboardFocus = false;
bool _suppressTvKeyboardForCurrentFocus = false;
FocusNode get _effectiveFocusNode =>
widget.input.focusNode ?? (_ownedFocusNode ??= FocusNode(debugLabel: 'FocusableTextInput'));
FocusNode get _effectiveFocusNode => _focusNodeBinding.node;
@override
void initState() {
super.initState();
_focusNodeBinding.bind(externalNode: widget.input.focusNode, debugLabel: 'FocusableTextInput');
widget.input.tvKeyboardController?._attach(this);
}
@override
void didUpdateWidget(_FocusableTextInputHost oldWidget) {
super.didUpdateWidget(oldWidget);
if (!identical(oldWidget.input.tvKeyboardController, widget.input.tvKeyboardController)) {
oldWidget.input.tvKeyboardController?._detach(this);
widget.input.tvKeyboardController?._attach(this);
}
if (oldWidget.input.focusNode != widget.input.focusNode) {
// An open keyboard dialog intentionally survives rebuilds and focusNode
// swaps; it is closed only when this host unmounts — see dispose.
_restoreInstalledHandler();
_focusNodeBinding.bind(externalNode: widget.input.focusNode, debugLabel: 'FocusableTextInput');
_suppressTvKeyboardAutoOpen = false;
_tvKeyboardOpenScheduled = false;
_hasSeenTvKeyboardFocus = false;
@@ -675,6 +734,7 @@ class _FocusableTextInputHostState extends State<_FocusableTextInputHost> {
@override
void dispose() {
widget.input.tvKeyboardController?._detach(this);
_restoreInstalledHandler();
// The keyboard is a navigator route — it must not outlive the field that
// opened it (e.g. a form section swapped out while the keyboard is up).
@@ -683,7 +743,7 @@ class _FocusableTextInputHostState extends State<_FocusableTextInputHost> {
if (keyboard != null) {
WidgetsBinding.instance.addPostFrameCallback((_) => keyboard.close());
}
_ownedFocusNode?.dispose();
_focusNodeBinding.dispose();
super.dispose();
}
@@ -694,25 +754,29 @@ class _FocusableTextInputHostState extends State<_FocusableTextInputHost> {
void _syncNativeTextInputFocus() {
final focused = _installedFocusNode?.hasFocus == true && widget.input.enabled && widget.input._usesNativeTvKeyboard;
_logTvTextInput(
'Host.syncNativeTextInputFocus focused=$focused installed=${_installedFocusNode?.debugLabel} '
'hasFocus=${_installedFocusNode?.hasFocus} enabled=${widget.input.enabled} '
'usesNativeTvKeyboard=${widget.input._usesNativeTvKeyboard}',
);
if (TextInputDiagnostics.enabled) {
_logTvTextInput(
'Host.syncNativeTextInputFocus focused=$focused installed=${_installedFocusNode?.debugLabel} '
'hasFocus=${_installedFocusNode?.hasFocus} enabled=${widget.input.enabled} '
'usesNativeTvKeyboard=${widget.input._usesNativeTvKeyboard}',
);
}
_setNativeTextInputFocused(focused);
}
void _syncTvKeyboardAutoOpen() {
final focused = _installedFocusNode?.hasFocus == true && widget.input.enabled && widget.input._hasTvKeyboard;
final visible = _canShowTvKeyboard;
_logTvTextInput(
'Host.syncTvKeyboardAutoOpen focused=$focused open=$_tvKeyboardOpen scheduled=$_tvKeyboardOpenScheduled '
'suppressed=$_suppressTvKeyboardAutoOpen behavior=${widget.input.tvKeyboardAutoOpenBehavior} '
'seenFocus=$_hasSeenTvKeyboardFocus suppressCurrent=$_suppressTvKeyboardForCurrentFocus '
'installed=${_installedFocusNode?.debugLabel} '
'hasFocus=${_installedFocusNode?.hasFocus} enabled=${widget.input.enabled} '
'usesTvKeyboard=${widget.input._hasTvKeyboard} visible=$visible',
);
if (TextInputDiagnostics.enabled) {
_logTvTextInput(
'Host.syncTvKeyboardAutoOpen focused=$focused open=$_tvKeyboardOpen scheduled=$_tvKeyboardOpenScheduled '
'suppressed=$_suppressTvKeyboardAutoOpen behavior=${widget.input.tvKeyboardAutoOpenBehavior} '
'seenFocus=$_hasSeenTvKeyboardFocus suppressCurrent=$_suppressTvKeyboardForCurrentFocus '
'installed=${_installedFocusNode?.debugLabel} '
'hasFocus=${_installedFocusNode?.hasFocus} enabled=${widget.input.enabled} '
'usesTvKeyboard=${widget.input._hasTvKeyboard} visible=$visible',
);
}
if (!focused) {
_suppressTvKeyboardForCurrentFocus = false;
@@ -818,6 +882,35 @@ class _FocusableTextInputHostState extends State<_FocusableTextInputHost> {
);
}
/// Dismiss an open OSK imperatively (e.g. a companion-remote search that must
/// show results instead of the keyboard). Suppresses auto-reopen so a field
/// that regains focus when the dialog route pops does not relaunch it.
void _dismissTvKeyboard() {
// No-op when nothing is up: setting the suppress flag here (with no
// compensating unfocus to clear it) would block a later legitimate
// auto-open when the user deliberately focuses the field.
if (!_tvKeyboardOpen && !_tvKeyboardOpenScheduled) return;
_tvKeyboardOpenScheduled = false;
_suppressTvKeyboardAutoOpen = true;
_tvKeyboardHandle?.close();
}
/// Focus the field without opening the OSK for this focus entry. Suppress is
/// set BEFORE requestFocus so the resulting focus-change sync already sees it;
/// the flag persists for this focus and resets on the next unfocus. If a
/// same-turn focus request supersedes this one, clear the unused suppression
/// after Flutter resolves its pending focus change.
void _focusWithoutKeyboard() {
_suppressTvKeyboardAutoOpen = true;
_tvKeyboardOpenScheduled = false;
final focusNode = _installedFocusNode ?? _effectiveFocusNode;
focusNode.requestFocus();
scheduleMicrotask(() {
if (!mounted || focusNode.hasFocus || _tvKeyboardOpen || _tvKeyboardOpenScheduled) return;
_suppressTvKeyboardAutoOpen = false;
});
}
void _setNativeTextInputFocused(bool focused) {
if (_reportedNativeTextInputFocused == focused) {
_logTvTextInput('Host.setNativeTextInputFocused no-op focused=$focused');
@@ -907,6 +1000,7 @@ class FocusableTextField extends _FocusableTextInputBase {
super.enabled,
super.enableTvKeyboard,
super.tvKeyboardAutoOpenBehavior,
super.tvKeyboardController,
super.obscureText,
super.autocorrect,
super.enableSuggestions,
@@ -925,14 +1019,14 @@ class FocusableTextField extends _FocusableTextInputBase {
@override
Widget build(BuildContext context) {
return buildFocusableInput(
context,
(usesTvKeyboard, effectiveFocusNode, openKeyboard) => TextField(
return buildFocusableInput((usesTvKeyboard, effectiveFocusNode, openKeyboard) {
final tvInput = _tvInputConfiguration(usesTvKeyboard, openKeyboard);
return TextField(
controller: controller,
focusNode: effectiveFocusNode,
enabled: enabled,
decoration: decoration,
keyboardType: usesTvKeyboard ? TextInputType.none : keyboardType,
keyboardType: tvInput.keyboardType,
textInputAction: textInputAction,
inputFormatters: inputFormatters,
onChanged: onChanged,
@@ -948,12 +1042,12 @@ class FocusableTextField extends _FocusableTextInputBase {
textAlign: textAlign,
textCapitalization: textCapitalization,
style: style,
readOnly: usesTvKeyboard,
showCursor: usesTvKeyboard ? true : null,
enableInteractiveSelection: usesTvKeyboard ? false : enableInteractiveSelection,
onTap: usesTvKeyboard ? openKeyboard : null,
),
);
readOnly: tvInput.readOnly,
showCursor: tvInput.showCursor,
enableInteractiveSelection: tvInput.enableInteractiveSelection,
onTap: tvInput.onTap,
);
});
}
}
@@ -983,6 +1077,7 @@ class FocusableTextFormField extends _FocusableTextInputBase {
super.enabled,
super.enableTvKeyboard,
super.tvKeyboardAutoOpenBehavior,
super.tvKeyboardController,
super.obscureText,
super.autocorrect,
super.enableSuggestions,
@@ -1001,14 +1096,14 @@ class FocusableTextFormField extends _FocusableTextInputBase {
@override
Widget build(BuildContext context) {
return buildFocusableInput(
context,
(usesTvKeyboard, effectiveFocusNode, openKeyboard) => TextFormField(
return buildFocusableInput((usesTvKeyboard, effectiveFocusNode, openKeyboard) {
final tvInput = _tvInputConfiguration(usesTvKeyboard, openKeyboard);
return TextFormField(
controller: controller,
focusNode: effectiveFocusNode,
enabled: enabled,
decoration: decoration,
keyboardType: usesTvKeyboard ? TextInputType.none : keyboardType,
keyboardType: tvInput.keyboardType,
textInputAction: textInputAction,
inputFormatters: inputFormatters,
onChanged: onChanged,
@@ -1027,11 +1122,11 @@ class FocusableTextFormField extends _FocusableTextInputBase {
textAlign: textAlign,
textCapitalization: textCapitalization,
style: style,
readOnly: usesTvKeyboard,
showCursor: usesTvKeyboard ? true : null,
enableInteractiveSelection: usesTvKeyboard ? false : enableInteractiveSelection,
onTap: usesTvKeyboard ? openKeyboard : null,
),
);
readOnly: tvInput.readOnly,
showCursor: tvInput.showCursor,
enableInteractiveSelection: tvInput.enableInteractiveSelection,
onTap: tvInput.onTap,
);
});
}
}
+7 -16
View File
@@ -1,42 +1,33 @@
import 'package:flutter/material.dart';
import '../utils/scroll_utils.dart';
import 'owned_focus_node_binding.dart';
/// Manages the internal/external FocusNode lifecycle for list-tile widgets and
/// auto-scrolls the tile into view when it gains focus.
mixin FocusableTileStateMixin<T extends StatefulWidget> on State<T> {
late FocusNode _effectiveFocusNode;
bool _ownsNode = false;
final _focusNodeBinding = OwnedFocusNodeBinding();
FocusNode? get widgetFocusNode;
FocusNode get effectiveFocusNode => _effectiveFocusNode;
FocusNode get effectiveFocusNode => _focusNodeBinding.node;
void initFocusNode() {
if (widgetFocusNode != null) {
_effectiveFocusNode = widgetFocusNode!;
_ownsNode = false;
} else {
_effectiveFocusNode = FocusNode();
_ownsNode = true;
}
_effectiveFocusNode.addListener(_onFocusChange);
_focusNodeBinding.bind(externalNode: widgetFocusNode, listener: _onFocusChange);
}
void updateFocusNode(FocusNode? oldFocusNode) {
if (oldFocusNode != widgetFocusNode) {
disposeFocusNode();
initFocusNode();
_focusNodeBinding.bind(externalNode: widgetFocusNode, listener: _onFocusChange);
}
}
void disposeFocusNode() {
_effectiveFocusNode.removeListener(_onFocusChange);
if (_ownsNode) _effectiveFocusNode.dispose();
_focusNodeBinding.dispose();
}
void _onFocusChange() {
if (_effectiveFocusNode.hasFocus) {
if (effectiveFocusNode.hasFocus) {
scrollContextToCenter(context);
}
}
+100 -95
View File
@@ -1,5 +1,3 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
@@ -7,9 +5,11 @@ import '../widgets/clickable_cursor.dart';
import '../utils/text_input_diagnostics.dart';
import 'card_focus_scope.dart';
import 'dpad_navigator.dart';
import 'dpad_select_long_press_controller.dart';
import 'focus_glow_overlay.dart';
import 'focus_theme.dart';
import 'input_mode_tracker.dart';
import 'owned_focus_node_binding.dart';
import 'key_event_utils.dart';
String _describeFocusableKey(KeyEvent event) {
@@ -68,6 +68,10 @@ class FocusableWrapper extends StatefulWidget {
/// Border radius for the focus indicator.
final double borderRadius;
/// Per-corner radii for the focus indicator; overrides [borderRadius] when
/// set (M3E grouped cards: large outer / small inner corners).
final BorderRadius? borderRadii;
/// Whether to scroll the widget into view when focused.
final bool autoScroll;
@@ -138,6 +142,7 @@ class FocusableWrapper extends StatefulWidget {
this.autofocus = false,
this.focusNode,
this.borderRadius = FocusTheme.defaultBorderRadius,
this.borderRadii,
this.autoScroll = true,
this.scrollAlignment = 0.5,
this.useComfortableZone = false,
@@ -160,48 +165,42 @@ class FocusableWrapper extends StatefulWidget {
}
class _FocusableWrapperState extends State<FocusableWrapper> with SingleTickerProviderStateMixin {
late FocusNode _focusNode;
bool _ownsNode = false;
final OwnedFocusNodeBinding _focusNodeBinding = OwnedFocusNodeBinding();
FocusNode get _focusNode => _focusNodeBinding.node;
bool _isFocused = false;
late final AnimationController _animationController;
late Animation<double> _scaleAnimation;
// Created lazily on first focus/keyboard-mode build: touch scrolling builds
// hundreds of these wrappers and must not pay for a Ticker per card.
AnimationController? _animationController;
Animation<double>? _scaleAnimation;
// Long-press detection for SELECT key
Timer? _longPressTimer;
bool _isSelectKeyDown = false;
final _selectLongPress = DpadSelectLongPressController();
@override
void initState() {
super.initState();
_initFocusNode();
_initAnimations();
_bindFocusNode();
}
void _initFocusNode() {
if (widget.focusNode != null) {
_focusNode = widget.focusNode!;
_ownsNode = false;
} else {
_focusNode = FocusNode(
debugLabel: widget.semanticLabel ?? 'FocusableWrapper',
canRequestFocus: widget.canRequestFocus,
);
_ownsNode = true;
}
void _bindFocusNode() {
_focusNodeBinding.bind(externalNode: widget.focusNode, debugLabel: widget.semanticLabel ?? 'FocusableWrapper');
_focusNode.canRequestFocus = widget.canRequestFocus;
}
void _initAnimations() {
_animationController = AnimationController(vsync: this, duration: const Duration(milliseconds: 150));
_scaleAnimation = _createScaleAnimation();
AnimationController _ensureAnimationController() {
final existing = _animationController;
if (existing != null) return existing;
final controller = AnimationController(vsync: this, duration: const Duration(milliseconds: 150));
_animationController = controller;
_scaleAnimation = _createScaleAnimation(controller);
return controller;
}
Animation<double> _createScaleAnimation() {
Animation<double> _createScaleAnimation(AnimationController controller) {
return Tween<double>(
begin: 1.0,
end: widget.focusScale,
).animate(CurvedAnimation(parent: _animationController, curve: Curves.easeOutCubic));
).animate(CurvedAnimation(parent: controller, curve: Curves.easeOutCubic));
}
@override
@@ -210,10 +209,7 @@ class _FocusableWrapperState extends State<FocusableWrapper> with SingleTickerPr
// Handle focusNode changes
if (widget.focusNode != oldWidget.focusNode) {
if (_ownsNode) {
_focusNode.dispose();
}
_initFocusNode();
_bindFocusNode();
}
// Update canRequestFocus
@@ -222,17 +218,18 @@ class _FocusableWrapperState extends State<FocusableWrapper> with SingleTickerPr
}
if (widget.focusScale != oldWidget.focusScale) {
_scaleAnimation = _createScaleAnimation();
final controller = _animationController;
if (controller != null) {
_scaleAnimation = _createScaleAnimation(controller);
}
}
}
@override
void dispose() {
_longPressTimer?.cancel();
_animationController.dispose();
if (_ownsNode) {
_focusNode.dispose();
}
_selectLongPress.dispose();
_animationController?.dispose();
_focusNodeBinding.dispose();
super.dispose();
}
@@ -244,15 +241,14 @@ class _FocusableWrapperState extends State<FocusableWrapper> with SingleTickerPr
// Reset long press state when focus is lost
if (!hasFocus) {
_longPressTimer?.cancel();
_isSelectKeyDown = false;
_selectLongPress.reset();
}
// Animate scale
if (hasFocus) {
_animationController.forward();
_ensureAnimationController().forward();
} else {
_animationController.reverse();
_animationController?.reverse();
}
// Auto-scroll into view
@@ -351,19 +347,27 @@ class _FocusableWrapperState extends State<FocusableWrapper> with SingleTickerPr
KeyEventResult _handleKeyEvent(FocusNode node, KeyEvent event) {
final key = event.logicalKey;
final diagnosticsEnabled = TextInputDiagnostics.enabled;
KeyEventResult finish(KeyEventResult result, String reason) {
_logFocusableWrapper(
'node=${node.debugLabel} result=$result reason=$reason key=(${_describeFocusableKey(event)}) '
'onNav(up=${widget.onNavigateUp != null},down=${widget.onNavigateDown != null},'
'left=${widget.onNavigateLeft != null},right=${widget.onNavigateRight != null}) '
'onSelect=${widget.onSelect != null} onBack=${widget.onBack != null}',
);
if (diagnosticsEnabled) {
_logFocusableWrapper(
'node=${node.debugLabel} result=$result reason=$reason key=(${_describeFocusableKey(event)}) '
'onNav(up=${widget.onNavigateUp != null},down=${widget.onNavigateDown != null},'
'left=${widget.onNavigateLeft != null},right=${widget.onNavigateRight != null}) '
'onSelect=${widget.onSelect != null} onBack=${widget.onBack != null}',
);
}
return result;
}
_logFocusableWrapper('node=${node.debugLabel} received key=(${_describeFocusableKey(event)})');
if (diagnosticsEnabled) {
_logFocusableWrapper('node=${node.debugLabel} received key=(${_describeFocusableKey(event)})');
}
if (SelectKeyUpSuppressor.consumeIfSuppressed(event)) {
if (event is KeyUpEvent && key.isSelectKey) {
_selectLongPress.reset();
}
return finish(KeyEventResult.handled, 'select-key-up-suppressed');
}
@@ -385,33 +389,15 @@ class _FocusableWrapperState extends State<FocusableWrapper> with SingleTickerPr
// Handle SELECT key with optional long-press detection
if (key.isSelectKey) {
if (widget.enableLongPress) {
if (event is KeyDownEvent) {
// Only start timer on initial press, not repeats
if (!_isSelectKeyDown) {
_isSelectKeyDown = true;
_longPressTimer?.cancel();
_longPressTimer = Timer(widget.longPressDuration, () {
// Long press detected
if (mounted) {
SelectKeyUpSuppressor.suppressSelectUntilKeyUp();
widget.onLongPress?.call();
}
});
}
return finish(KeyEventResult.handled, 'select-long-press-down');
} else if (event is KeyRepeatEvent) {
// Consume repeat events to prevent system sounds
return finish(KeyEventResult.handled, 'select-long-press-repeat');
} else if (event is KeyUpEvent) {
final timerWasActive = _longPressTimer?.isActive ?? false;
_longPressTimer?.cancel();
if (timerWasActive && _isSelectKeyDown) {
// Timer still active - short press
widget.onSelect?.call();
}
// If timer already fired, long press was triggered - do nothing on key up
_isSelectKeyDown = false;
return finish(KeyEventResult.handled, 'select-long-press-up');
final result = _selectLongPress.handleKeyEvent(
event,
duration: widget.longPressDuration,
isOwnerActive: () => mounted,
onShortPress: () => widget.onSelect?.call(),
onLongPress: () => widget.onLongPress?.call(),
);
if (result != KeyEventResult.ignored) {
return finish(result, 'select-long-press');
}
} else if (widget.onSelect != null) {
return finish(handleOneShotSelect(event, widget.onSelect!), 'one-shot-select');
@@ -425,7 +411,7 @@ class _FocusableWrapperState extends State<FocusableWrapper> with SingleTickerPr
// Context menu key
if (key.isContextMenuKey) {
SelectKeyUpSuppressor.suppressSelectUntilKeyUp();
_selectLongPress.reset();
widget.onLongPress?.call();
return finish(KeyEventResult.handled, 'context-menu');
}
@@ -461,23 +447,28 @@ class _FocusableWrapperState extends State<FocusableWrapper> with SingleTickerPr
@override
Widget build(BuildContext context) {
final duration = FocusTheme.getAnimationDuration(context);
// Only show focus effects during keyboard/d-pad navigation
final showFocus = _isFocused && InputModeTracker.isKeyboardMode(context);
// Only show focus effects during keyboard/d-pad navigation. In pointer/
// touch mode no card ever shows focus chrome, so skip the animated
// scale/border wrappers entirely — they cost real build time multiplied
// by every card in a grid. The Focus node stays mounted so d-pad
// traversal finds the cards the moment keyboard mode activates (which
// rebuilds this widget via the inherited dependency below).
final isKeyboardMode = InputModeTracker.isKeyboardMode(context);
final showFocus = _isFocused && isKeyboardMode;
// Update animation duration if theme changes
if (_animationController.duration != duration) {
_animationController.duration = duration;
}
Widget inner;
if (!isKeyboardMode) {
inner = widget.child;
} else {
final duration = FocusTheme.getAnimationDuration(context);
final controller = _ensureAnimationController();
// Update animation duration if theme changes
if (controller.duration != duration) {
controller.duration = duration;
}
Widget result = Focus(
focusNode: _focusNode,
autofocus: widget.autofocus,
descendantsAreFocusable: widget.descendantsAreFocusable,
onFocusChange: _handleFocusChange,
onKeyEvent: _handleKeyEvent,
child: AnimatedBuilder(
animation: _scaleAnimation,
inner = AnimatedBuilder(
animation: _scaleAnimation!,
builder: (context, child) {
final shouldScale = showFocus && !widget.disableScale;
// The glow (full-bleed cards) is drawn in an overlay above siblings so
@@ -487,11 +478,16 @@ class _FocusableWrapperState extends State<FocusableWrapper> with SingleTickerPr
card = CardFocusScope(showFocus: showFocus, child: widget.child);
} else {
final focusDecoration = widget.useBackgroundFocus
? FocusTheme.focusBackgroundDecoration(isFocused: showFocus, borderRadius: widget.borderRadius)
? FocusTheme.focusBackgroundDecoration(
isFocused: showFocus,
borderRadius: widget.borderRadius,
radii: widget.borderRadii,
)
: FocusTheme.focusDecoration(
context,
isFocused: showFocus,
borderRadius: widget.borderRadius,
radii: widget.borderRadii,
color: widget.focusColor,
);
card = AnimatedContainer(
@@ -509,9 +505,18 @@ class _FocusableWrapperState extends State<FocusableWrapper> with SingleTickerPr
child: card,
);
}
return Transform.scale(scale: shouldScale ? _scaleAnimation.value : 1.0, child: card);
return Transform.scale(scale: shouldScale ? _scaleAnimation!.value : 1.0, child: card);
},
),
);
}
Widget result = Focus(
focusNode: _focusNode,
autofocus: widget.autofocus,
descendantsAreFocusable: widget.descendantsAreFocusable,
onFocusChange: _handleFocusChange,
onKeyEvent: _handleKeyEvent,
child: inner,
);
// Add semantics if label provided
+33
View File
@@ -0,0 +1,33 @@
/// Routes vertical D-pad movement between ordered hub rows.
///
/// A valid target and the bottom boundary are consumed. The top boundary can
/// either invoke an explicit focus handoff or propagate to the row's
/// `onNavigateUp` callback.
bool navigateVerticalHubRows({
required int hubCount,
required int hubIndex,
required bool isUp,
required void Function(int targetIndex) requestFocus,
void Function()? onTopBoundary,
void Function()? onBottomBoundary,
bool propagateTopBoundary = false,
}) {
if (hubCount <= 0) return false;
final targetIndex = isUp ? hubIndex - 1 : hubIndex + 1;
if (targetIndex < 0) {
if (onTopBoundary != null) {
onTopBoundary();
return true;
}
return !propagateTopBoundary;
}
if (targetIndex >= hubCount) {
onBottomBoundary?.call();
return true;
}
requestFocus(targetIndex);
return true;
}

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