Compare commits

...
865 Commits
Author SHA1 Message Date
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
github-actions[bot] 06bd9d775d chore: bump version to 2.7.0 2026-06-14 13:22:49 +00:00
edde746 d6487e24c9 fix(tv): keep sidebar transparent 2026-06-14 14:53:56 +02:00
edde746 c404589382 style(native): fix formatting 2026-06-14 14:04:52 +02:00
edde746 f1689a7794 fix(tvos): keep audio passthrough opt-in 2026-06-14 13:49:57 +02:00
edde746 a861a4110f feat(player): add mobile edge adjustments 2026-06-14 13:40:16 +02:00
edde746 e7809b3160 fix(player): harden pinch zoom activation 2026-06-14 11:08:14 +02:00
edde746 edd0618e64 fix: harden playback and discover state 2026-06-14 09:44:04 +02:00
edde746 849e62df7e fix(jellyfin): honor continue watching action
close #1334
2026-06-14 07:25:40 +02:00
edde746 e1c0df3bd7 fix(ci): resolve sanity check failures 2026-06-14 06:55:58 +02:00
edde746 349b5b0513 fix(tv): stop playback behind menu 2026-06-14 06:27:00 +02:00
edde746 3ad049cb28 fix(player): clear stale mpv fallback switch 2026-06-14 00:27:41 +02:00
edde746 656cf1158b fix(libraries): restore tvOS empty tab focus
close #1330
2026-06-14 00:05:44 +02:00
edde746 f3cb508649 fix(player): wait for mpv subtitles after load
close #1331
2026-06-13 23:52:19 +02:00
edde746 c39b5a5cf1 feat(player): show cache limit in perf overlay 2026-06-13 21:21:15 +02:00
edde746 9ff3099a9d fix(player): update MPVKit and stream buffering 2026-06-13 20:51:14 +02:00
edde746 c24a2aade0 fix(images): preserve media image filter quality 2026-06-13 18:19:23 +02:00
edde746 8f862d1ca0 fix(jellyfin): sort series episodes
close #1329
2026-06-13 17:12:48 +02:00
edde746 b56608f94f fix(media): show source rating badges on TV
close #1327
2026-06-13 15:58:36 +02:00
edde746 2876e1bf78 fix(media): catch menu client and refresh failures 2026-06-13 13:25:48 +02:00
edde746 ebd850b0d5 fix(profiles): guard pin dialog route pops 2026-06-13 13:25:41 +02:00
edde746 f3f962a7c9 fix(database): swallow legacy documents lookup failures 2026-06-13 13:25:34 +02:00
edde746 49ae1fdc34 fix(cache): use app-private image cache 2026-06-13 13:25:26 +02:00
edde746 dc769bda41 fix(android): fall back when cronet init fails 2026-06-13 13:23:41 +02:00
edde746 75ba6b0627 fix(player): isolate dispose teardown races 2026-06-13 13:23:29 +02:00
edde746 1e40d21bd8 fix(discovery): handle udp datagram socket errors 2026-06-13 13:23:22 +02:00
edde746 3c43874342 fix(tvos): update mpvkit audio passthrough 2026-06-13 10:24:15 +02:00
edde746 4f422f1485 fix(plex): persist transcode audio stream switches
close #1326
2026-06-13 10:15:08 +02:00
edde746 85d9b6ebab fix(tvos): hide unsupported playback options 2026-06-13 10:13:02 +02:00
edde746 90662e2173 fix(player): scale mpv stream ring buffer for poorly interleaved mp4/mov 2026-06-12 22:21:17 +02:00
edde746 24980aff95 feat(subs): render resolution setting for the avfoundation VO 2026-06-12 21:05:28 +02:00
edde746 804261605b docs(player): note live session and progress tracker client pinning 2026-06-12 17:12:25 +02:00
edde746 8a65c78999 fix(plex): retry related hubs and skip unchanged threshold mirror 2026-06-12 17:12:25 +02:00
edde746 979db254d1 perf(providers): delta-fetch newly-online servers instead of full refetch
Discover and libraries now fetch only the servers that came online since
the last pass and merge the results; already-loaded servers are not
refetched. Both providers also own their online-servers listener
(registered in the constructor, removed in dispose), so profile switches
no longer leak listeners that kept disposed providers refetching.
2026-06-12 17:12:18 +02:00
edde746 18ebe77806 fix(jellyfin): page show/season folder children incrementally 2026-06-12 17:12:09 +02:00
edde746 0de856e929 fix(settings): refuse overlapping runAsync at runtime 2026-06-12 17:12:03 +02:00
edde746 a6d82b4637 fix(livetv): stop abandoned sessions when a tune is superseded or unmounts 2026-06-12 17:11:58 +02:00
edde746 acfb79c857 refactor(livetv): tune protocol methods go private behind the session 2026-06-12 16:18:09 +02:00
edde746 dcfe0f8308 refactor(player): live playback drives LiveTvPlaybackSession 2026-06-12 16:15:20 +02:00
edde746 23a423fe85 refactor(livetv): playback session lifecycle behind LiveTvSupport 2026-06-12 16:06:12 +02:00
edde746 b2cb874b73 fix(discover): refresh content when a server comes online mid-session 2026-06-12 15:56:09 +02:00
edde746 f671f367ea refactor(discover): DiscoverProvider owns hubs and continue-watching 2026-06-12 15:53:26 +02:00
edde746 665603b314 fix(jellyfin): bounded transient retry on hub surfaces 2026-06-12 15:33:58 +02:00
edde746 0d7dd093c4 fix(jellyfin): flip server status when all endpoints are exhausted 2026-06-12 15:26:39 +02:00
edde746 c849a213f0 refactor(net): shared FailoverHttpClient for both backends 2026-06-12 15:22:52 +02:00
edde746 49ff0854c0 refactor(profiles): profile-scoped provider subtree keyed by active profile 2026-06-12 14:44:10 +02:00
edde746 5047057521 test(cache): cover per-backend applyWatchState mutations 2026-06-12 14:35:50 +02:00
edde746 e28e2b9371 refactor(media): folder browsing via MediaServerClient interface 2026-06-12 14:33:38 +02:00
edde746 bb92b6083b refactor(player): clarify requested vs session-effective media source id 2026-06-12 14:21:12 +02:00
edde746 acdae74587 refactor(offline): single connectivity subscription in OfflineModeProvider 2026-06-12 14:18:49 +02:00
edde746 5e4449247b fix(downloads): inject visibility-aware client resolver 2026-06-12 14:16:24 +02:00
edde746 c2fe142293 refactor(watch): WatchActions owns mark-watched orchestration and events 2026-06-12 14:09:21 +02:00
edde746 431b0f9b0c refactor(ui): shared watched indicator overlay 2026-06-12 13:56:47 +02:00
edde746 959e6e9398 refactor(watch): single watched-progress predicate 2026-06-12 13:49:46 +02:00
edde746 18e47d2327 refactor(ui): share android keyboard-mode system-back guard 2026-06-12 13:48:06 +02:00
edde746 b2e5e02204 refactor(library): reuse grid column formula in fetch-size estimate 2026-06-12 13:48:06 +02:00
edde746 e6a488a4e2 fix(settings): resolve tv-dependent defaults at read time 2026-06-12 13:45:37 +02:00
edde746 75d0164a8b fix(offline): persist plex watched threshold for offline use 2026-06-12 13:43:29 +02:00
edde746 05251edaf3 fix(tv): close virtual keyboard when its text field unmounts
The keyboard is a navigator route, so a screen swapping out its form
left it floating over the new content. showTvVirtualKeyboard now
returns a route handle and the field host closes it on dispose.
2026-06-12 13:36:01 +02:00
edde746 892dfee381 fix(tv): keyboard no longer opens over jellyfin quick connect screen
Auto-starting quick connect from inside the probe's runAsync let the
probe's finally clear busy mid-initiate; the re-enabled form then took
focus fallback on the URL field, auto-opening the TV keyboard. Sequence
the two busy scopes and debug-assert against overlapping runAsync.
2026-06-12 13:35:55 +02:00
edde746 7f1eb3a818 fix(focus): back over a dialog no longer pops the underlying screen 2026-06-12 13:19:29 +02:00
edde746 bd0a0c5d6b feat(android): loudness normalization for exoplayer via audiofx
close #1289
2026-06-12 12:38:57 +02:00
edde746 71b05fd4b2 fix(ui): unwatched count badge grows as pill, caps at 999+
close #1310
2026-06-12 09:11:56 +02:00
edde746 587609d7f6 fix(tv): hug poster with focus border and add focus glow toggle
close #1278
2026-06-12 08:50:29 +02:00
edde746 cceba28d0a fix(i18n): request localized Plex labels
close #1311
2026-06-12 07:59:35 +02:00
edde746 03c623e8c7 perf(grids): rebuild media grids on width change, not every scroll tick 2026-06-12 07:18:34 +02:00
edde746 2b34f4a9d7 perf(tv): reduced visual-effects tier for low-end devices 2026-06-12 06:30:38 +02:00
edde746 ad3cc6b986 feat(player): language-first audio & subtitle track labels
close #1307
2026-06-12 04:16:39 +02:00
edde746 133db721a2 fix(livetv): auto-catch-up stale guide window to now
close #1297
2026-06-12 04:13:59 +02:00
edde746 a03d30fa45 fix(android): eliminate per-byte buffer ops in DV bitstream sanitizer 2026-06-12 04:05:35 +02:00
edde746 62abd3c30a feat(jellyfin): simpler, code-first Quick Connect screen 2026-06-12 03:16:58 +02:00
edde746 97ba02f45e fix: flashbang 2026-06-12 02:40:42 +02:00
edde746 0f1bf5e011 perf(jellyfin): skip per-folder user data in folder tree listings 2026-06-12 02:18:28 +02:00
edde746 d816d82a38 fix(folders): row context menus, dpad left to sidebar, faster Jellyfin listings 2026-06-12 02:00:42 +02:00
edde746 c89c88647e fix(android): package libmpv's NDK r29 libc++_shared.so deterministically 2026-06-12 01:51:51 +02:00
edde746 3599b0b0e1 fix(startup): no-servers flash on fresh login + faster connect splash
- start binder before navigating from auth, mark isBinding synchronously
- overlap plex.tv resource refresh with optimistic cached-metadata connect,
  reconcile tokens/membership in background once it lands
- cached endpoint probe gets a head start on the race instead of serially
  blocking it
- defer phase-1 HTTPS upgrade off the splash critical path
- per-server connect progress stream for incremental splash checkmarks
- startup timing instrumentation (bind/fetch/race/connect elapsedMs)
2026-06-12 01:46:43 +02:00
edde746 1adb89c6b3 feat(android): frame-accurate libass pipeline + optimized native core 2026-06-12 01:45:19 +02:00
edde746 7ec1c2ebdc fix(player): anchor libass overlay to video rect for correct zoom/cover positioning 2026-06-11 12:49:21 +02:00
edde746 7ec062deaf fix(player): pinch zoom flicker from per-tick relayout and filter churn
close #1261
2026-06-11 12:29:34 +02:00
edde746 a5c7d5b52a refactor(watch-together): host-authoritative declarative sync protocol
Replaces the imperative play/pause/seek/positionSync message soup with a
single host-authored PlaybackState (seq-ordered, anchor-extrapolated,
phase machine: loading/waitingForPeers/paused/playing) that doubles as
the heartbeat, plus guest status reports and host-applied control
requests. Fixes the guest seek-back loop while the host loads (readiness
was keyed on a pre-load !buffering snapshot and heartbeats broadcast
frozen positions), adds real group buffering coordination (stall grace,
scheduled simultaneous resumes, 15s safety timeout), rate-nudge drift
correction with passthrough-aware seek fallback, session-scoped message
handling (no lost messages during episode-switch detach gaps), and an
expected-state ledger replacing the racy remote-action flag.
2026-06-11 09:42:38 +02:00
edde746 e54bbd11f1 feat(player): passthrough state tracking + sync-layer position/passthrough getters
Includes the mpv passthrough rate-suspend wiring (passthrough cannot
scaletempo; suspended while rate != 1.0) that the new getters report.
2026-06-11 09:16:01 +02:00
edde746 38afdab2e4 fix: support mx player variants
close #1304
2026-06-11 08:35:19 +02:00
edde746 f214c50c15 fix(player): responsive double-tap skip stacking
single tap stacks while the skip pill is visible, feedback shows before
the seek (instant on transcode restarts), fade-out hide timer is tracked so
a re-shown pill isn't killed mid-spree, and tap pairing uses the platform
kDoubleTapTimeout
2026-06-11 07:15:31 +02:00
edde746 1fc081ed6b fix(player): eager timeline scrub gesture and stable slider tree
close #1302
2026-06-11 07:15:31 +02:00
edde746 cbaed8cdfb fix(livetv): tune current guide programs on tv
close #1298
2026-06-11 07:15:31 +02:00
github-actions[bot] eac0e26696 chore: update cask to 2.6.0 2026-06-10 19:45:34 +00:00
github-actions[bot] 77af810d1f chore: bump version to 2.6.0 2026-06-10 19:04:45 +00:00
edde746 1292d7ac34 fix(dovi): bump MPVKit to v1.0.2 for profile 8 DV hardware decode
close #1262
2026-06-10 20:26:11 +02:00
edde746 e75ab94eb9 fix(tv): make osk search key focus results
The TV keyboard dialog froze the field's callbacks at open time, so the
search screen's done key fell through to unfocus() once results arrived.
Resolve callbacks against the latest field widget at invoke time, and
give the search screen a TV submit handler that focuses the first result
or flushes the pending debounce.
2026-06-10 16:37:35 +02:00
edde746 804bea8e9a fix(android): keep only the active dynamic HDR metadata in DV bitstreams
close #1296
2026-06-10 15:39:51 +02:00
edde746 0502dd7ba0 fix(discover): resolve hero watch state in build 2026-06-10 15:10:52 +02:00
edde746 3221a0cb1a feat: add continue watching details navigation
close #1295
2026-06-10 12:50:32 +02:00
edde746 e7efa458e5 fix(images): preserve fallback placeholder size
close #1293
2026-06-10 09:55:22 +02:00
edde746 9b48f26463 refactor(watch): shared point-of-use resolution across consumers
Adds context.withFreshWatchState/readFreshWatchState and sweeps the
remaining session-critical readers: context menu actions, folder tree
rows, discover hero, and TV spotlight minutes-left.
2026-06-10 05:38:33 +02:00
edde746 903b8eced8 refactor(detail): drop hand-patched watch state for store resolution
Delete the per-event list patching, parent-count adjustment, and the
screen-local progress overlay; rows and the hero resolve against
WatchStateStore at build. Also backfill parentId on playable-descendant
pages so hierarchy resolution covers season detail pages.
2026-06-10 05:30:52 +02:00
edde746 3753967caf fix(watch): resolve watch state per item at cards and playback open
Cards consult the hierarchy-aware store so container marks flip episode
rows instantly and a stale per-episode patch can no longer shadow a newer
show/season mark; playback opens with the session-fresh resume offset.
2026-06-10 05:23:09 +02:00
edde746 516925cf50 refactor(watch): promote overlay to hierarchy-aware WatchStateStore
Resolution now considers parentChain ancestors (newest event wins) and
watched patches set container leaf counts, so container marks reach
descendant cards and vice versa.
2026-06-10 05:18:02 +02:00
edde746 cd9498abb8 refactor(player): centralize playback opening
close #1280
2026-06-10 02:26:26 +02:00
edde746 18642cae15 fix(tv): correct grid calculation
close #1288
2026-06-09 12:47:47 +02:00
edde746 92063bd58f fix(playback): skip redundant mark-watched
close #1287
2026-06-09 12:19:27 +02:00
edde746 726281ed44 fix(tvos): top shelf sync 2026-06-09 08:06:42 +02:00
edde746 e02daa89b8 fix(tvos): stop Home nav auto-playing continue watching
close #1281
2026-06-09 06:10:22 +02:00
edde746 7de7802368 fix(hubs): keep recently-added detail scoped to its library
close #1282
2026-06-08 22:03:28 +02:00
edde746 d44a8994ce fix(discover): open server tasks with remote
close #1272
2026-06-08 08:23:57 +02:00
edde746 42d9168941 fix(player): stabilize mobile content strip 2026-06-08 00:50:22 +02:00
edde746 38616770e5 fix(i18n): localize season & episode labels in downloads tree 2026-06-07 21:46:44 +02:00
edde746 bf7558f80d fix(i18n): localize generic season names from server
close #1271
2026-06-07 21:46:24 +02:00
edde746 381e82d61a fix(detail): highlight next unwatched ep when not in continue watching
close #1269
2026-06-07 18:42:41 +02:00
edde746 9cebcb97c5 feat(plex): add Plays and User Rating sort options
close #1264
2026-06-07 17:50:36 +02:00
edde746 eef73e6447 fix: expand home hub previews
close #1268
2026-06-07 17:35:56 +02:00
edde746 e8df18e7b2 fix(jellyfin): order continue watching + up next by recency 2026-06-07 16:34:18 +02:00
github-actions[bot] 54512b8f93 chore: update cask to 2.5.0 2026-06-07 12:45:47 +00:00
github-actions[bot]andedde746 1e0988e381 chore: bump version to 2.5.0 2026-06-07 14:19:17 +02:00
edde746 8efd8f1dc8 fix(jellyfin): upload artwork as binary 2026-06-07 13:32:07 +02:00
edde746 38868e0078 fix: use device name for companion remote
close #1256
2026-06-07 12:58:13 +02:00
edde746 273d0c7985 fix(back): don't short-circuit side-nav back chain to home
The side-nav host's onSystemBack called _handleMainBack on the system
route-pop path, jumping straight to the home tab and skipping the dpad
back chain (content -> top tabs -> sidebar). Restore the original inert
behavior: canPop:false blocks the route-pop and the key path owns the
chain; the host still closes an open sheet on back. Bottom-nav unchanged.
2026-06-07 10:05:57 +02:00
edde746 4728564e0c refactor(back): host-owned system back in main_screen
Both main_screen hosts (side-nav + bottom-nav) drop their PopScopes and
pass canPop:false + onSystemBack to OverlaySheetHost, so a system back
with a sheet open closes the sheet instead of running tab-nav/exit. Key
(dpad) back path unchanged; onSystemBack mirrors it for a pure popRoute.
2026-06-07 10:05:57 +02:00
edde746 489bf914af refactor(back): host-owned sheet back in hub + media detail
hub_detail and media_detail (TV + non-TV) drop their hand-rolled PopScopes
and pass canPop/onSystemBack to OverlaySheetHost. Keeps appbar-focus-first
and Android-keyboard block behavior; fixes system-back-with-sheet-open
leaking to a screen pop. iOS swipe-back preserved.
2026-06-07 09:20:02 +02:00
edde746 248b5fd91a refactor(back): adopt host-owned sheet back in watch-together + player
watch_together, video_player, mobile_remote and live_tv_show_schedule now
pass canPop/onSystemBack to OverlaySheetHost instead of hand-rolling a
PopScope. Restores the iOS swipe-back on watch_together and centralizes
the sheet-close-on-back logic.
2026-06-07 09:13:49 +02:00
edde746 bbf7b1f9da feat(overlay-sheet): opt-in PopScope so the host owns system back
Adds nullable canPop + onSystemBack to OverlaySheetHost. When canPop is
set, the host installs its own PopScope that closes an open sheet on a
system/route back instead of popping the screen; null keeps today's
behavior. Lets screens drop their hand-rolled sheet-back PopScopes.
2026-06-07 09:06:29 +02:00
edde746 83899a38f3 fix(tvos): sync version 2026-06-07 08:51:02 +02:00
edde746 cda4c1e78a fix(watch-together): enable dpad long-press to open recent room actions
close #1259
2026-06-07 08:51:02 +02:00
edde746 01e5814943 fix(video): consolidate auto-skip cancellation 2026-06-07 06:13:14 +02:00
edde746 3cca29512d fix: bump MPVKit to v1.0.1 for profile 8 Dolby Vision decode
Routes all single-layer DV profile 8 (incl. compat 0) through the Apple
DV decode path, so VideoToolbox decodes it in hardware as true Dolby
Vision instead of failing over to software HDR10. Refs #1262.
2026-06-06 16:06:31 +02:00
edde746 8139fc2b17 fix(tvos): make HDR toggle disable Dolby Vision
HDR-off now forces SDR display criteria for DV like it does for HDR10,
and the runtime toggle re-applies the criteria. Refs #1262 (part A).
2026-06-06 14:17:52 +02:00
edde746 1ef4032666 feat: add startup section setting
close #1240
2026-06-06 13:08:02 +02:00
edde746 4c4b18e2cd fix(i18n): localize hardcoded UI strings
close #1257
2026-06-06 11:45:34 +02:00
edde746 f74314bbf0 fix(livetv): debounce rapid time-shift skips to stop overshoot 2026-06-06 10:48:51 +02:00
edde746 32421e4c84 fix(tv): reach app bar actions via up from tabs
close #1202
2026-06-06 08:51:08 +02:00
edde746 d90cc61541 fix(tv): symmetric full-card focus glow via overlay
close #1231
2026-06-06 05:09:07 +02:00
edde746 6b3e49d410 fix(ios): recover frozen video after Control Center
close #1232
2026-06-06 00:49:19 +02:00
edde746 a9b812f66c fix(test): restore CI unit tests 2026-06-05 20:34:44 +02:00
edde746 0fd0506551 feat(media): lazily page detail episodes
close #1245
2026-06-05 19:26:02 +02:00
edde746 e6ca5f254d fix(ios): correct anamorphic video aspect ratio
close #1244
2026-06-05 10:15:03 +02:00
edde746 de3219abb9 fix: align bottom sheet back header 2026-06-05 06:30:26 +02:00
edde746 8201d8dcda feat(libraries): add mobile browse options sheet 2026-06-04 20:41:34 +02:00
edde746 aed420525c feat(nav): move mobile settings to home menu 2026-06-04 16:41:02 +02:00
edde746 75b1c86306 feat(ui): add m3 app menus 2026-06-04 16:22:31 +02:00
edde746 43012da2b8 feat(tvos): add top shelf support 2026-06-04 15:38:12 +02:00
edde746 145881318e fix: harden server-scoped state 2026-06-04 13:47:06 +02:00
edde746 79c06b82d3 fix(jellyfin): align default track selection 2026-06-04 10:35:14 +02:00
edde746 e5bbdc06f9 feat(jellyfin): show media quality labels 2026-06-04 09:56:10 +02:00
edde746 0e7ff609b6 feat(media): show video and audio quality labels
close #1115
2026-06-04 08:20:12 +02:00
edde746 f3e108e867 fix(tvos): suppress duplicate select playback 2026-06-03 17:31:15 +02:00
edde746 92bfae322e fix(tvos): handle play pause remote
close #1230
2026-06-03 14:19:23 +02:00
edde746 08491511e9 fix(video): prevent play next EOF loop
close #1228
2026-06-02 15:52:14 +02:00
edde746 24b5080c38 fix(video): stabilize player chrome overlays 2026-06-02 14:20:24 +02:00
edde746 985c279b1f fix(exoplayer): correct transcode seek position double-count 2026-06-02 06:23:08 +02:00
edde746 cb2e56442d fix(subtitles): show search without subtitle tracks
close #1219
2026-06-01 19:08:17 +02:00
edde746 a425798bae fix(video): iOS video zoom 2026-06-01 15:21:41 +02:00
edde746 1020188883 fix(video): restore stretch fit startup 2026-06-01 12:40:59 +02:00
edde746 caf192fd78 fix(jellyfin): defer initial URL keyboard
close #1217
2026-06-01 11:49:21 +02:00
edde746 74b8dc4561 refactor: type server identifiers 2026-06-01 11:06:03 +02:00
edde746 7b59dac26b fix: stabilize detail action focus
close #1218
2026-06-01 08:34:38 +02:00
edde746 09f5121732 feat(metadata): add Jellyfin edit support 2026-06-01 08:34:38 +02:00
edde746 8f9d20a2e4 feat(jellyfin): add extras support 2026-06-01 08:34:38 +02:00
edde746 273f129b68 fix(i18n): remove unsupported newline guidance 2026-06-01 08:34:38 +02:00
github-actions[bot] 483c0b504e chore: update cask to 2.4.1 2026-06-01 01:13:01 +00:00
github-actions[bot] 7c38668a51 chore: bump version to 2.4.1 2026-06-01 00:56:52 +00:00
edde746 eba553413c fix(macos): allow LuaJIT under hardened runtime
close #1214
2026-06-01 02:46:37 +02:00
edde746 f8658027b8 fix(android): guard display HDR mode API
close #1215
2026-06-01 02:46:37 +02:00
github-actions[bot] 58bceb29cb chore: update cask to 2.4.0 2026-05-31 19:54:37 +00:00
github-actions[bot] c5d8f9c62b chore: bump version to 2.4.0 2026-05-31 19:30:17 +00:00
edde746 4ffa3d30f6 fix(player): preserve shader toggle preset
close #1208
2026-05-31 21:25:46 +02:00
edde746 d5c8778074 fix: harden reconnect and playback regressions 2026-05-31 20:33:38 +02:00
edde746 c6c76d6828 fix(dialogs): own text input resources 2026-05-31 15:34:00 +02:00
edde746 9cfc6c0f4a fix(tv): stabilize osk dismissal 2026-05-31 15:22:13 +02:00
edde746 2eae450aa0 fix(jellyfin): preserve add screen dpad focus 2026-05-31 15:00:35 +02:00
edde746 1b5334e72f fix(jellyfin): harden local discovery flow 2026-05-31 14:33:31 +02:00
edde746 e3db54940d feat(jellyfin): add local server discovery
close #1188
2026-05-31 10:51:08 +02:00
edde746 656d512858 ci: add build platform toggles 2026-05-31 09:26:55 +02:00
edde746 d9135e0d25 fix(player): log display HDR capabilities 2026-05-31 08:48:21 +02:00
edde746 4f636dfffd fix(ci): install libmpv scripting deps 2026-05-31 07:54:37 +02:00
edde746 6438b444bf fix(player): clarify Dolby Vision playback logging 2026-05-31 06:56:18 +02:00
edde746 8413e1e5a7 fix(player): reduce sync offset dpad step 2026-05-31 06:38:25 +02:00
edde746 5671f6e5d1 fix(plex): send playback session stream header 2026-05-31 06:30:51 +02:00
edde746 a4a0475fdb fix(player): let macOS shortcuts pass through
close #1206
2026-05-31 03:03:52 +02:00
edde746 9a740b91c1 fix(plex): select available playback version 2026-05-31 02:21:15 +02:00
edde746 63ab80fa82 fix(player): switch refresh rate before ExoPlayer open 2026-05-31 00:28:54 +02:00
edde746 0bb085c70c feat(macos): support start in fullscreen setting
close #1200
2026-05-30 23:58:38 +02:00
edde746 9825ce3c7c fix: select first playable Plex Part instead of always Part[0]
close #1201
2026-05-30 21:37:01 +02:00
edde746 f5012b36ea fix(media-detail): collapse action buttons that overflow small screens 2026-05-30 17:20:16 +02:00
edde746 6111c381af fix(libraries): reload when a server connects after initial load 2026-05-30 14:01:01 +02:00
edde746 00fce3a997 fix(downloads): cap aggregate progress below 100% until all episodes complete
Rounding the smoothed per-episode progress could fill the ring to 100% while a download was still finishing; only report 100% once every queued episode is complete. Also drop the stale episode-count diagnostic log that read leafCount/_totalEpisodeCounts solely for logging after the denominator change.
2026-05-30 08:48:44 +02:00
edde746 b8417f0277 style(downloads): apply dart format to download_utils.dart
Merged via #1195 without formatting; aligns it with the repo's dart format pre-commit gate.
2026-05-30 08:48:03 +02:00
DarkmaddaandGitHub 4148c1c8ff fix(downloads): scope show progress to queued episodes; manage completed downloads (#1195)
Progress ring now measures completion against the episodes actually queued (episodes.length) instead of the show's full leafCount, and advances smoothly using per-episode progress. The completed show/season download button reopens the download-options dialog (with a Delete row) so users can fetch more episodes or switch to sync instead of only deleting.
2026-05-30 08:40:17 +02:00
edde746 9e5098f356 fix(trackers): respect server completion threshold
close #1194
2026-05-30 08:30:06 +02:00
edde746 139eed9ca9 fix(templates): require substantive issue-form fields 2026-05-30 07:33:06 +02:00
23efb02636 fix(browse): keep show in browse after deleting its downloads
The browse grid listens for DeletionEvents and decrements each show's
leafCount, evicting the show when the count hits zero. Download-only
deletions (isDownloadOnly: true) fired one event per episode, so deleting
every downloaded episode of a show drove its leafCount to zero and removed
it from browse - even though the content still exists on the server.

Browse is online-only (the Libraries tab is hidden when offline) and always
reflects server-side content, so it must ignore download-only deletions.
Add a guard at the top of onDeletionEvent, matching the existing
isDownloadOnly contract already honored by media_detail_screen.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-30 07:20:54 +02:00
Timo KoxandGitHub 294996eac1 feat(player): add end-of-video sleep timer option (#1111)
close #540
2026-05-30 07:16:01 +02:00
edde746 a4f0b92b4e fix(windows): stop taskbar icon flashing on minimize after playback 2026-05-30 03:01:48 +02:00
Micah MorrisonandGitHub 7cac050500 feat(playback): add option to exit fullscreen on player close (#1174)
Adds a setting to automatically exit fullscreen when the video player is closed.
2026-05-30 02:38:35 +02:00
edde746 1685ecc991 fix(playback): prevent native subtitle autoselect 2026-05-30 00:05:29 +02:00
edde746 a71711de5f fix(ci): update database schema expectation 2026-05-29 23:45:01 +02:00
edde746 7534a6c60a fix(downloads): apply progress watch snapshots 2026-05-29 21:37:27 +02:00
edde746 dba01f14bb fix(playback): harden watch progress edge cases 2026-05-29 21:16:01 +02:00
edde746 d93ea9813f fix(playback): harden offline source reporting 2026-05-29 19:55:01 +02:00
edde746 7501f461b9 fix(playback): sync downloaded watch progress
close #1171, close #1183
2026-05-29 19:55:01 +02:00
edde746 5e5702c961 fix: resume playback after iOS audio route changes
close #1185
2026-05-29 11:04:27 +02:00
edde746 4b477a4fe3 build(tvos): bump engine to 3.44.0+3 2026-05-29 08:29:18 +02:00
edde746 50ff514be8 feat(tv): wrap on-screen keyboard focus at edges 2026-05-29 05:03:10 +02:00
edde746 1c7a083d6c build(linux): enable lua and javascript in libmpv 2026-05-29 03:32:45 +02:00
edde746 097e48d705 fix(tv): trap d-pad focus at button row edges
close #1181
2026-05-29 03:31:53 +02:00
edde746 a931d5910b fix(tv): let text fields fall back to directional traversal
close #1176
2026-05-29 03:30:54 +02:00
edde746 1cd585eecb feat(android): sync external player progress
close #1175
2026-05-29 00:58:45 +02:00
edde746 9981b277c6 test: cover jellyfin trickplay aspect ratio 2026-05-29 00:18:53 +02:00
edde746 2b7ea5fe02 feat(video): add custom zoom controls
close #1159
2026-05-29 00:06:47 +02:00
edde746 47276e1bac feat(tv): add optional full-card layouts 2026-05-28 22:33:06 +02:00
edde746andGitHub c8670a8d6a Merge pull request #1178 from micahmo/fix/plex-bif-aspect-ratio
Fix scrub preview aspect ratio
2026-05-28 22:05:37 +02:00
Micah Morrison 9cc32e125b Fix BIF scrub preview aspect ratio and raise desktop size limit 2026-05-28 15:46:08 -04:00
edde746 4217da1a8f fix(android): recover ExoPlayer audio failures 2026-05-28 09:31:19 +02:00
edde746 704c37f97f fix(ui): tighten media detail spacing 2026-05-28 08:16:27 +02:00
edde746 0c8e0fc2ec fix(i18n): update Bulgarian generated strings 2026-05-28 05:55:55 +02:00
edde746 d6315a0f75 feat(desktop): improve snackbar behavior 2026-05-28 04:48:36 +02:00
edde746 92cdbdd723 chore: remove local MPVKit checkout 2026-05-28 04:07:27 +02:00
edde746andDimitar Topper Maznekov 3939ba809f feat(i18n): add Bulgarian language
Co-authored-by: Dimitar "Topper" Maznekov <23097319+TopperBG@users.noreply.github.com>
2026-05-28 04:01:37 +02:00
edde746 6642348a96 feat(jellyfin): support multiple server urls 2026-05-28 03:43:46 +02:00
edde746 0b29673a5e fix(plex): use provider continue watching hub
close #1166
2026-05-28 01:29:29 +02:00
edde746 3747a74cb3 fix(pip): guard callbacks after dispose 2026-05-28 01:14:38 +02:00
edde746 bcb7f1d3c1 fix(android): disable flutter deeplink routing 2026-05-28 00:48:59 +02:00
edde746 7b56b90f24 fix(main): guard tvOS menu updates after dispose 2026-05-28 00:37:07 +02:00
edde746 ba62129414 fix(playback): support Apple DV conversion 2026-05-28 00:33:20 +02:00
edde746 e559a6125d fix(detail): isolate overlay sheet scrolling 2026-05-28 00:29:13 +02:00
edde746 869b4fe230 chore: bump MPVKit 2026-05-28 00:14:06 +02:00
edde746 3b4110d7e5 fix(android): improve Dolby Vision fallback 2026-05-27 21:02:48 +02:00
edde746 7b4e399013 chore: bump MPVKit 2026-05-27 06:52:03 +02:00
edde746 5788d93e89 feat(profiles): sort by recent use
close #1151
2026-05-27 06:52:03 +02:00
edde746 08a806e457 fix(playback): restore system ui after video
close #1152
2026-05-27 06:52:03 +02:00
edde746 e45bfadc14 feat(libraries): add nav quick picker
close #1144
2026-05-27 06:52:03 +02:00
edde746 56cfb95af5 fix(playback): apply default quality to jellyfin
close #1150
2026-05-27 00:02:23 +02:00
github-actions[bot] 8e8942fb36 chore: update cask to 2.3.0 2026-05-26 21:34:32 +00:00
github-actions[bot] 02f2657d18 chore: bump version to 2.3.0 2026-05-26 21:13:32 +00:00
edde746 39709e5c42 test(tv): update keyboard focus expectations 2026-05-26 23:00:44 +02:00
edde746 a101ee76d6 fix(downloads): prevent duplicate native tasks
close #1141
2026-05-26 22:43:05 +02:00
edde746 4eadec5b17 fix(tv): pass root menu to system 2026-05-26 18:27:26 +02:00
edde746 be86a33057 fix(discover): hide duplicate continue watching
close #1113
2026-05-26 14:48:16 +02:00
edde746 ce19b9dfa7 fix(ui): theme recommendation text colors 2026-05-26 14:05:26 +02:00
edde746 15cc85147a fix(tv): improve virtual keyboard input 2026-05-26 14:01:20 +02:00
edde746 3fc3baef83 fix(tv): reveal details without input 2026-05-26 12:02:48 +02:00
edde746 91b926acac fix(android): respect vtt subtitle position 2026-05-26 06:34:59 +02:00
edde746 8b2ff18842 fix(android): improve mpeg-ts seeking 2026-05-26 03:14:19 +02:00
edde746 1958f8ca7e feat(jellyfin): add folder browsing and playback 2026-05-26 01:39:39 +02:00
edde746 8e53232961 fix(jellyfin): avoid side-loading negotiated subtitles 2026-05-25 23:39:55 +02:00
edde746 cec8993b80 fix: update win_http 2026-05-25 23:19:59 +02:00
edde746 366ae67341 feat(jellyfin): add unwatched library filter
close #1116
2026-05-25 22:43:39 +02:00
edde746 50be8565d9 fix(tv): prefer show art for episode backdrops
close #1123
2026-05-25 21:08:33 +02:00
edde746 9365fcf246 fix(tv): keep alpha bar alphabet visible 2026-05-25 16:17:27 +02:00
edde746 8d4ef2757a fix(ios): update MPVKit PiP subtitles 2026-05-25 15:31:41 +02:00
edde746 6b147e2053 fix(ios): enable PiP subtitles 2026-05-25 04:47:55 +02:00
github-actions[bot] 5fa8326341 chore: bump version to 2.2.1 2026-05-24 17:06:57 +00:00
edde746 c8cded70ef fix(tv): polish media detail rails
close #1117
2026-05-24 19:06:06 +02:00
edde746 8fe51075be fix(android): force display mode matching 2026-05-24 18:39:41 +02:00
edde746 d24c95f1e1 fix(android): trust Media3 TrueHD passthrough 2026-05-24 18:09:42 +02:00
edde746 1c8be031ae chore(ios): declare export compliance 2026-05-24 15:10:58 +02:00
github-actions[bot] 83c47b529c chore: update cask to 2.2.0 2026-05-24 06:17:35 +00:00
github-actions[bot] 9dce396fb4 chore: bump version to 2.2.0 2026-05-24 05:53:47 +00:00
edde746 eeaa831cc2 fix(search): guard stale refresh callbacks 2026-05-24 07:37:02 +02:00
edde746 f1a02ade17 fix(android): guard desktop fullscreen calls 2026-05-24 07:22:56 +02:00
edde746 dcd0b03096 fix(downloads): repair offline artwork 2026-05-24 05:27:19 +02:00
edde746 a189ee5774 fix(offline): honor settled profile visibility 2026-05-24 03:12:33 +02:00
edde746 e74df0d245 fix(plex): fail open on unknown transcode capability 2026-05-24 00:39:30 +02:00
edde746andGitHub d980540c09 Merge pull request #1024 from Mofeywalker/feat/harmonize-playback-speeds
fix: add missing 0.25 speed steps
2026-05-23 21:49:33 +02:00
edde746 a51215952f docs: remove duplicate screenshot link 2026-05-23 20:52:06 +02:00
edde746 993a0e4666 fix(tv): route remote keys to native text input 2026-05-23 19:19:59 +02:00
edde746 4c43d6fdec fix(jellyfin): prefer direct playback by default 2026-05-23 18:38:38 +02:00
edde746 1c58a12c90 fix(jellyfin): omit audio index from static fallback 2026-05-23 16:35:09 +02:00
edde746 b6d23ed089 fix(startup): speed offline fallback
close #1108
2026-05-23 16:00:00 +02:00
edde746 3a042d79f6 fix(player): persist shader hotkey toggles
close #1105
2026-05-23 01:37:57 +02:00
edde746 1a73fc585b fix(player): align playback settings label
close #1106
2026-05-23 00:34:16 +02:00
edde746 8ec2795da1 fix(tv): stabilize long rail focus scrolling 2026-05-22 23:55:54 +02:00
edde746 cbea1c8d8f fix(tv): correct long hub row focus scrolling 2026-05-22 21:32:26 +02:00
edde746 048d22cb99 fix(livetv): expand program summaries 2026-05-22 20:52:21 +02:00
edde746 31c01ab3e0 chore(site): update tv screenshots 2026-05-22 17:15:51 +02:00
edde746 16e31303ae fix(tv): keep spotlight background static 2026-05-22 17:06:51 +02:00
edde746 e301fec38c fix(ci): clear unused parameter warnings 2026-05-22 16:04:39 +02:00
edde746 e1e9adbb01 fix(ios): handle status bar scroll taps
close #1101
2026-05-22 15:40:03 +02:00
edde746 636ecc9d3a fix(tv): fit fallback logo titles 2026-05-22 13:34:30 +02:00
edde746 fc231a9e72 fix(playlists): load paginated items mutably
close #1100
2026-05-22 05:28:03 +02:00
edde746 c354193187 fix(tv): fade media detail transitions 2026-05-22 04:30:22 +02:00
edde746 bb7ed72073 fix(tv): stabilize detail preplay layout 2026-05-22 04:13:00 +02:00
edde746 fea973a72a fix(tv): smooth sidebar expansion behavior 2026-05-22 03:54:34 +02:00
edde746 487c7b87f6 fix(nav): hide active sidebar background during focus 2026-05-22 02:21:06 +02:00
edde746 afc94a50fc fix(tv): push sidebar content without resizing 2026-05-22 01:38:29 +02:00
edde746 2ebd730201 fix(tv): displace content beside sidebar 2026-05-22 00:14:16 +02:00
edde746 0dd7d7c522 feat(tv): push content beside sidebar 2026-05-21 21:01:14 +02:00
edde746 eaf0f4fa1a fix(tv): stabilize browse rail focus and loading 2026-05-21 18:17:00 +02:00
edde746 743a8668ec feat(tv): refine sidebar backdrop 2026-05-21 17:04:23 +02:00
edde746 6a74ff083f fix(mpv): avoid forcing HDR colorspace hint 2026-05-21 16:01:15 +02:00
edde746 9dc3a1a1b1 feat(tv): improve hub rail experience 2026-05-21 15:57:02 +02:00
edde746 2b45557743 fix(android): preserve mpv frame-rate startup position 2026-05-21 09:58:13 +02:00
edde746 11b97e626e fix(gamepad): update reconnect dependency 2026-05-21 08:41:03 +02:00
edde746 d8f69f7acd fix(plex): copy mkv attachments during transcode
close #1083
2026-05-21 08:08:25 +02:00
edde746 b547f8a47f fix(android): gate mpv startup refresh on display switch 2026-05-21 02:59:11 +02:00
edde746 f4c83bedc0 chore(tv): guard text input diagnostics 2026-05-21 00:42:19 +02:00
edde746 0582ab2947 fix(livetv): show active recording indicators
close #1076
2026-05-21 00:19:21 +02:00
edde746 209101796b refactor: use private named constructor params 2026-05-20 23:48:29 +02:00
edde746 448a5d084c fix(tv): hide season poster tab setting 2026-05-20 22:22:46 +02:00
edde746 1ebfee9354 fix(android): stabilize TrueHD tunneling 2026-05-20 21:00:02 +02:00
edde746 29e0654d47 fix(windows): launch VLC from default install path
close #1085
2026-05-20 20:16:34 +02:00
edde746 f565684842 fix(ci): stabilize analyzer and linux builds 2026-05-20 19:10:46 +02:00
edde746 5d6f34f756 fix(android): preserve tracks on DV reload 2026-05-20 18:27:42 +02:00
edde746 73735c5a00 fix(ci): unblock analyzer and windows build 2026-05-20 18:10:21 +02:00
edde746 c93a266722 fix(plex): support no-burn transcode subtitles 2026-05-20 17:21:31 +02:00
edde746 2b167a60f5 fix(jellyfin): pin merged version playback 2026-05-20 05:27:48 +02:00
edde746 63e807dd58 fix(tv): focus flattened episode rows
close #1081
2026-05-20 03:55:48 +02:00
edde746 16e3500c49 fix(android): gate TrueHD passthrough 2026-05-20 02:23:57 +02:00
edde746 6e47a5fbcf fix(tv): hide hero setting 2026-05-19 22:57:24 +02:00
edde746 b18774d60b fix(tv): complete detail rail behavior 2026-05-19 20:23:17 +02:00
edde746 0383a77b56 fix(jellyfin): pin version playback source 2026-05-19 20:12:19 +02:00
edde746 d58007a9e2 fix(ios): keep PiP timebase renderer-owned 2026-05-19 20:09:23 +02:00
edde746 7d60875e19 fix(tv): refine browse rail layout 2026-05-19 19:30:57 +02:00
edde746 6be1b7c486 fix(android): unwrap DV supplemental samples 2026-05-19 18:26:41 +02:00
edde746 88c65e1857 chore(tv): add text input routing diagnostics 2026-05-19 14:42:34 +02:00
edde746 95ff95d397 fix(player): capture media screenshots
close #1077
2026-05-19 14:17:42 +02:00
edde746 1978d710da fix(ci): unblock Flutter 3.44 checks 2026-05-19 12:38:43 +02:00
edde746 423be62218 fix(tv): pause gamepad during native text input 2026-05-19 12:10:49 +02:00
edde746 d2650667b8 fix(tv): preserve native text input routing 2026-05-19 11:17:44 +02:00
edde746 48cf8accfa fix(jellyfin): resolve versions on demand 2026-05-19 10:54:04 +02:00
edde746 565885cc1e fix(ios): add privacy usage descriptions 2026-05-19 09:31:26 +02:00
edde746 d0e74151b8 fix(ios): update MPVKit renderer recovery 2026-05-18 23:48:22 +02:00
edde746 89c9c6c49b chore(tvos): align Flutter engine with 3.44 2026-05-18 23:31:54 +02:00
edde746 e98d7febdd chore: upgrade Flutter to 3.44 2026-05-18 22:52:51 +02:00
edde746 55ee2c270d fix(android): strip DV init data 2026-05-18 22:06:39 +02:00
edde746 81b05f00df fix(ci): pin Flutter stable version 2026-05-18 20:37:00 +02:00
edde746 f4f2571168 fix(android): apply dv conversion mode during init 2026-05-18 20:32:34 +02:00
edde746 d85a622fbe fix(jellyfin): restore collection query compatibility 2026-05-18 19:24:07 +02:00
edde746 d3e8dcef86 fix(windows): pin patched connectivity_plus 2026-05-18 19:05:08 +02:00
edde746 e9c93415a8 fix(macos): guard MoltenVK heaps 2026-05-18 17:37:46 +02:00
edde746 68e27fdbb3 feat(remote): remember manual host address
close #1074
2026-05-18 17:22:10 +02:00
edde746 a679bae354 fix(android): expose DV conversion setting 2026-05-18 16:30:14 +02:00
edde746 5a68711f7b feat(ui): add pointer cursors to clickable controls
close #1068
2026-05-18 15:56:41 +02:00
edde746 324d145292 fix(jellyfin): support external audio playback 2026-05-18 13:43:58 +02:00
edde746 d004342c98 chore: add website source 2026-05-18 13:15:17 +02:00
edde746 d3d7957b62 docs: improve readme links and downloads 2026-05-18 12:35:04 +02:00
edde746 0e94558548 fix(jellyfin): reduce collection query cost 2026-05-18 10:33:10 +02:00
edde746 8d14a14781 docs: update readme showcase 2026-05-18 06:16:26 +02:00
edde746andGitHub 20f704a56d Merge pull request #1070 from PsychotherapistSam/main
fix(player): adjust performance overlay padding
2026-05-18 06:13:06 +02:00
github-actions[bot] 93f0da7a27 chore: bump version to 2.1.1 2026-05-17 22:30:27 +00:00
edde746 8b3f8856f7 fix(scroll): avoid pending scroll timers 2026-05-18 00:23:17 +02:00
edde746 39fb828580 fix(ios): update MPVKit subtitle geometry
close #1071
2026-05-18 00:10:14 +02:00
edde746 3e0f7b4f86 fix(libraries): stabilize alpha and sort controls 2026-05-17 22:36:15 +02:00
Sam 7e9f62dc7f fix(player): adjust performance overlay padding 2026-05-17 21:14:00 +02:00
edde746 c855dba3be fix(media): paginate large server lists 2026-05-17 20:25:39 +02:00
edde746 e726f9f528 fix(media): align detail hero spacing 2026-05-17 16:17:38 +02:00
edde746 2c54baca34 docs: clarify feature availability 2026-05-17 15:40:49 +02:00
github-actions[bot] 232d98c4ce chore: update cask to 2.1.0 2026-05-17 12:15:25 +00:00
github-actions[bot] d93c81a7cb chore: bump version to 2.1.0 2026-05-17 11:44:29 +00:00
edde746 326d53415b chore: bump build 2026-05-17 13:43:57 +02:00
edde746 87db591792 feat(livetv): group guide by source 2026-05-17 06:41:47 +02:00
edde746 6bad454830 feat(player): add screenshot shortcut
close #1055
2026-05-16 23:50:08 +02:00
edde746 cfd4aa307d fix(plex): tolerate transient resource failures 2026-05-16 22:54:53 +02:00
edde746 3798a0c332 fix(ci): update generated tracker mapping 2026-05-16 21:55:18 +02:00
edde746 be0e9686b5 fix(search): rank media search results
close #1056
2026-05-16 21:40:22 +02:00
edde746 7ec45274bd fix(media): prevent detail action layout churn 2026-05-16 21:09:41 +02:00
edde746 3e74937386 feat(trackers): sync anime watch state by episode 2026-05-16 20:54:39 +02:00
edde746 310c4280fc feat(ratings): add tracker rating sheet
close #1031
2026-05-16 18:03:30 +02:00
edde746 ee6e327b12 fix(media): hide poster loading icons 2026-05-16 14:12:28 +02:00
edde746 e71dcdaa6c fix(libraries): tighten browse chip spacing 2026-05-16 13:23:07 +02:00
edde746 1b969953b5 fix(libraries): refresh all tabs 2026-05-16 12:24:26 +02:00
edde746 7690a16efe feat(tv): add spotlight browse layouts 2026-05-16 11:56:12 +02:00
edde746 91298294b0 fix(tvos): stabilize remote select handling 2026-05-15 22:16:24 +02:00
edde746 5df3ec0c12 fix(playback): use display criteria for matching 2026-05-15 19:46:04 +02:00
edde746 ef4980db09 fix(tv): preserve native keyboard navigation
close #1051
2026-05-15 19:05:38 +02:00
edde746 e37602421b fix(discover): expose full continue watching
close #1045
2026-05-15 18:49:23 +02:00
edde746 562d19c207 fix(watch-together): restore host resume
close #1052
2026-05-15 18:33:02 +02:00
edde746 e54bbb2214 fix(ios): restore video presentation 2026-05-15 18:16:07 +02:00
edde746 db2a2c34d2 fix(apple): update MPVKit release 2026-05-15 18:14:13 +02:00
edde746 12b006ee0c fix(tvos): prime display criteria from metadata 2026-05-14 19:51:33 +02:00
edde746 be3efa8335 fix(ios): update MPVKit subtitle cropping 2026-05-14 15:44:00 +02:00
edde746 d1d549d602 fix(android): restore flutter textureview 2026-05-14 11:03:54 +02:00
edde746 7de2a62c55 fix(tvos): update MPVKit teardown 2026-05-14 10:33:57 +02:00
edde746 7b4a37e576 fix(downloads): clean orphaned temp files
close #1040
2026-05-14 09:05:06 +02:00
edde746 5a46857035 fix(companion): respect remote server setting
close #1038
2026-05-14 02:23:43 +02:00
edde746 7ffb20b501 fix(libraries): respect grouping type 2026-05-14 02:01:41 +02:00
edde746 856ac83e6a fix(tv): use textureview 2026-05-13 19:34:20 +02:00
edde746 fb8fc1db1c fix(tvos): support 2nd gen Siri Remote 2026-05-13 18:44:53 +02:00
Micah Morrison 76e8ea6901 Respect episode/season grouping type when browsing library 2026-05-13 11:56:37 -04:00
edde746 e8c27f00a7 fix(tvos): avoid unsupported native clients 2026-05-13 17:12:50 +02:00
edde746 9f19f550c3 fix(tvos): bump MPVKit pacing build 2026-05-13 15:46:29 +02:00
edde746 fce794cd6c fix(discover): preserve library order on home
close #1034
2026-05-13 15:26:23 +02:00
edde746 8f9947a874 fix(trackers): use catalog totals for anime completion
close #1025
2026-05-13 15:07:19 +02:00
edde746 126e6b9349 fix(trackers): sync scoped anime progress 2026-05-13 14:10:01 +02:00
edde746 fcbe459177 feat(cache): cleanup orphaned plexImageCache directory on startup 2026-05-13 11:06:52 +02:00
edde746 0e296f8659 fix(livetv): show guide without favorites 2026-05-13 09:22:17 +02:00
edde746 12073ea134 fix(player): clear stale tracks before opening media
close #1028
2026-05-13 09:22:17 +02:00
edde746 8aea796dbd feat(jellyfin): expand library sort options
close #1032
2026-05-13 08:00:45 +02:00
edde746 9af6f32157 fix(player): harden initialization lifecycle 2026-05-13 06:28:09 +02:00
edde746 b0f1a5d4f1 fix(tv): back button Menu on Siri Remote 2026-05-12 22:46:38 +02:00
edde746 de62c8530f fix(tvos): subtitle HDR path and player dispose hardening 2026-05-12 22:46:38 +02:00
edde746 0f4629f52b fix(tvos): explicitly link AVKit for avDisplayManager category 2026-05-12 22:46:38 +02:00
edde746 de129fbb0a fix(trackers): preserve Plex library context 2026-05-12 22:46:38 +02:00
edde746 3a01fa25a7 fix(tv): pin engine to 3.41.6+7 for Up/Down dpad fix 2026-05-12 22:46:38 +02:00
edde746 86c19fc1fc fix(downloads): pin downloader cleanup
close #1026
close #921
2026-05-12 19:10:35 +02:00
edde746 ae1f6d7822 fix(tvOS): trigger native Dolby Vision via preferredDisplayCriteria 2026-05-12 16:21:00 +02:00
edde746 4577f26aa8 fix(lifecycle): abort HTTP before close 2026-05-12 15:11:16 +02:00
Moritz Fey fd26f470a5 fix: add missing 0.25 speed steps 2026-05-12 11:46:31 +02:00
edde746 bae127e459 fix(database): handle cross-drive desktop DB migration
close #1022
2026-05-12 10:41:32 +02:00
edde746 606627cd0c fix(search): use backend icons for server indicator 2026-05-12 08:25:52 +02:00
edde746 3ddd89113c fix(livetv): show recording indicators in guide
close #1015
2026-05-12 06:53:52 +02:00
edde746 5139e39ed4 fix(sentry): upload symbols with dart plugin 2026-05-12 06:40:54 +02:00
edde746 3a6012cc21 fix(lifecycle): guard async state updates 2026-05-12 06:11:14 +02:00
edde746 37b1a26cde fix(profile): prevent duplicate PIN dialog pops 2026-05-12 05:49:38 +02:00
edde746 e5922f4870 fix(plex): restore library filters and sorts
close #1020
2026-05-12 05:36:48 +02:00
edde746 ae7f4a7871 fix(jellyfin): unblock large library loading
close #1018
2026-05-12 05:28:20 +02:00
edde746 9e85aa7be6 fix(tv): handle native text input completion 2026-05-12 01:00:03 +02:00
edde746 fd69fe668a test(tvOS): align virtual keyboard select expectation 2026-05-11 18:31:09 +02:00
edde746 9085d4d94b fix(tvOS): route dpad clicks through engine 2026-05-11 18:08:56 +02:00
edde746 0775ea0d26 fix(tv): restore profile pin keypad input
close #1011
2026-05-11 15:13:37 +02:00
edde746 d901f5efc2 fix(jellyfin): direct stream live tv
close #1010
2026-05-11 13:50:46 +02:00
edde746 fcd8198fcb fix(plex): use promoted home hubs
close #1004
2026-05-11 13:18:43 +02:00
edde746 fd1eaf9d96 fix(plex): respect per-show season display
close #1008
2026-05-11 12:55:59 +02:00
edde746 d0bd919ff4 refactor: migrate models to freezed + json_serializable 2026-05-11 12:54:26 +02:00
edde746 2bbd31d927 feat(jellyfin): add actor media browsing
close #1005
2026-05-11 11:54:37 +02:00
edde746 617f200cb5 fix(android): avoid pixel eac3 decoder fallback
close #1007
2026-05-11 11:14:32 +02:00
edde746 b96d734e8c fix(jellyfin): load collections from boxsets root
close #1006
2026-05-11 11:11:22 +02:00
edde746 89f256138d fix(player): flush mpv buffers on frame-rate startup 2026-05-11 10:50:11 +02:00
edde746 9b248a7a5b fix(macos): restore video layer on focus 2026-05-11 10:13:05 +02:00
github-actions[bot] 8d76dff353 chore: update cask to 2.0.0 2026-05-11 05:30:32 +00:00
github-actions[bot] eff75d2029 chore: bump version to 2.0.0 2026-05-11 05:11:41 +00:00
edde746 f9615491b3 refactor(media): migrate media item to freezed 2026-05-11 07:01:46 +02:00
edde746 4252bd88e9 docs: mention jellyfin support 2026-05-11 05:29:31 +02:00
edde746 00917a0393 refactor(media): split media and jellyfin client 2026-05-11 05:24:07 +02:00
edde746 4cdcd2f2e4 feat(sheets): position desktop sheets near cursor 2026-05-11 05:07:00 +02:00
edde746 27006cfa99 fix(profiles): localize profile UI strings 2026-05-11 04:43:21 +02:00
edde746 bdbd667584 feat(discord): self-host rich presence posters 2026-05-11 04:19:41 +02:00
edde746 4b243d38b9 fix(player): hide stale next marker
close #1003
2026-05-11 02:47:15 +02:00
edde746 cd31b2e2e6 fix(subtitles): remember search language
close #1002
2026-05-11 02:40:50 +02:00
edde746 f185ebd554 fix(downloads): improve sync rules navigation
close #1001
2026-05-10 23:18:09 +02:00
edde746 7d679c9d78 fix(player): gate frame-rate refresh on mpv playback-restart 2026-05-10 22:23:13 +02:00
edde746 17184881f3 chore(i18n): tighten translation copy 2026-05-10 15:45:39 +02:00
edde746 a39a2a25eb fix(profiles): improve pin entry 2026-05-10 14:58:55 +02:00
edde746 e0f1695260 fix(profiles): lazy-load plex auth 2026-05-10 14:35:25 +02:00
edde746 d0ffd49f69 fix(startup): recover failed server bind 2026-05-10 14:27:33 +02:00
edde746 bfb6aa01b9 fix(apple): use platform-specific mpv rendering 2026-05-10 13:33:02 +02:00
edde746 6f273b0aa8 fix(apple): align local network permissions 2026-05-10 09:39:43 +02:00
edde746 3a93ec80ec fix(jellyfin): include movie home hubs 2026-05-10 00:53:20 +02:00
edde746 dd0fd1c828 fix(profiles): reuse switch flow for menu 2026-05-10 00:36:08 +02:00
edde746 ec93062600 fix(app): harden playback and plex flows 2026-05-10 00:35:01 +02:00
edde746 822333bf34 fix(media): align rate chip 2026-05-09 15:11:15 +02:00
edde746 ffc20b26d4 fix(player): block tv background media resume
close #990
2026-05-09 14:37:00 +02:00
edde746 3a612df3d3 chore: remove in-app review 2026-05-09 11:47:37 +02:00
edde746 afda61119e fix(macos): sync restored fullscreen chrome 2026-05-09 11:35:36 +02:00
edde746 bb66ab6526 fix(player): sync restored volume state 2026-05-09 11:10:49 +02:00
edde746 ec2b94e367 fix(plex): increase Plex TV timeout 2026-05-09 10:46:19 +02:00
edde746 5401b5005f perf(player): reduce timeline layout churn 2026-05-09 10:02:32 +02:00
edde746 d38f7cf78f perf(player): reduce playback UI churn 2026-05-09 09:38:25 +02:00
edde746 633ce11c88 chore(deps): update MPVKit 2026-05-09 09:17:03 +02:00
edde746 7a3f63683e fix(ui): refresh stale watch state 2026-05-09 06:00:36 +02:00
edde746 3e6ebcdb6a fix(player): refresh Android MPV decoder on startup 2026-05-09 05:10:51 +02:00
edde746 c38c0cf55d fix(jellyfin): hide unsupported continue watching removal
close #995
2026-05-09 04:41:13 +02:00
edde746 5d2302b322 fix(player): stabilize Apple timeline progress 2026-05-08 12:34:07 +02:00
edde746 51a8b971f6 fix(jellyfin): keep poster fallback after recycling 2026-05-08 10:33:49 +02:00
edde746 3319df4538 fix(ui): improve context menu behavior 2026-05-08 09:53:08 +02:00
edde746 1e6bd01987 fix(player): harden Apple PiP handling 2026-05-08 07:40:41 +02:00
edde746 e10cc7d273 fix(player): accumulate repeated seeks 2026-05-08 06:57:41 +02:00
edde746 19dea4b31e refactor(ui): share bottom sheet scaffold 2026-05-08 06:50:34 +02:00
edde746 653fada5dc refactor(player): move quality picker into playback settings 2026-05-08 06:24:59 +02:00
edde746 65b42bca3f fix(android): stabilize mpv frame-rate startup 2026-05-08 06:12:04 +02:00
edde746 5fe5534bae fix(jellyfin): bound home artwork load 2026-05-08 06:06:09 +02:00
edde746 f07feaaa52 fix(plex): repair alpha jump bar 2026-05-08 05:36:39 +02:00
edde746 92014404f5 chore(apple): sync MPVKit package locks 2026-05-08 03:10:02 +02:00
edde746 e2a7a7ab4b chore(apple): bump MPVKit pin 2026-05-08 03:09:05 +02:00
edde746 cedd448ef2 feat(apple): use AVFoundation mpv output 2026-05-08 02:39:42 +02:00
edde746 2208d6c637 fix(database): tolerate retried v14 migration 2026-05-07 11:27:12 +02:00
edde746 187eeb19d3 fix(plex): retry slow library hubs 2026-05-07 04:14:31 +02:00
edde746 955c75db60 fix(nav): improve back exit behavior 2026-05-07 03:06:04 +02:00
edde746 9446f976a4 fix(tv): support hardware keyboard input 2026-05-07 00:52:34 +02:00
edde746 7988c83bec fix: improve d-pad focus navigation 2026-05-07 00:27:58 +02:00
edde746 ebec3ad20c fix: autofocus jellyfin server url 2026-05-06 13:19:01 +02:00
edde746 3b18b44cd2 fix(tv): show provider choices on login 2026-05-06 12:47:39 +02:00
edde746 cf4fc74d68 fix: make text fields focusable in traversal 2026-05-06 12:06:55 +02:00
edde746 c75c87f527 fix(android): sync mpv display fps override 2026-05-06 10:47:40 +02:00
edde746 e71c39271c fix(windows): recover mpv audio output 2026-05-06 10:22:04 +02:00
edde746 de547884f8 fix(tvos): stabilize remote input and player build 2026-05-06 08:47:13 +02:00
edde746 4700cc5bd4 fix: change icons 2026-05-06 07:46:02 +02:00
edde746 07d25f5d5f fix(android): stop forcing mpv display sync 2026-05-06 06:19:18 +02:00
edde746 1f09c07e96 feat(player): toggle chapter timeline markers
close #973
2026-05-06 05:26:47 +02:00
edde746 e8769e7059 fix(android): detect tv mode beyond leanback
close #980
2026-05-06 02:57:55 +02:00
edde746 88430ba7b6 feat(ios): support external display playback
close #984
2026-05-06 02:17:20 +02:00
edde746 25a2187bf4 refactor: reduce settings and media selector duplication 2026-05-06 01:33:54 +02:00
edde746 fb084d3ea1 fix(plex): stabilize Linux endpoint failover 2026-05-06 00:51:00 +02:00
edde746 da7aef4548 fix(profiles): avoid placeholder profile on first launch 2026-05-06 00:32:15 +02:00
edde746 91c23786f2 refactor: reduce model and focus boilerplate 2026-05-06 00:26:44 +02:00
edde746 18a5041334 fix(tvos): stabilize Siri Remote input 2026-05-05 23:49:31 +02:00
edde746 94dbae0af9 fix(playback): prevent spurious seek jumps
close #946
2026-05-05 09:52:19 +02:00
edde746 05c4d6dff3 feat(playback): restart before previous episode
close #979
2026-05-05 08:28:17 +02:00
edde746 ef2db78310 fix(jellyfin): fall back from missing season posters
close #981
2026-05-05 07:53:36 +02:00
edde746 955bc9548c refactor: adopt shared mixins, helpers, and sliver widgets 2026-05-05 03:06:56 +02:00
edde746 ef8026797c fix(tvos): sync build version from pubspec 2026-05-05 00:23:32 +02:00
edde746 ed4be7b96d refactor: strip obvious comments 2026-05-04 22:40:18 +02:00
edde746 fdaff3687d fix(playback): keep Plex playlist queue when entering the player
close #978
2026-05-04 21:34:14 +02:00
edde746 f573eda657 ci: fix build dependency cache 2026-05-04 13:23:23 +02:00
edde746 708a1391e3 fix(desktop): hide hub hover arrows when row isn't scrollable 2026-05-04 10:53:55 +02:00
edde746 9e4230597f fix(jellyfin): label per-library hubs with library name
close #975
2026-05-04 10:24:01 +02:00
edde746 720d0d2604 feat(livetv): add DVR and recording support 2026-05-04 09:31:53 +02:00
edde746 dee12ac336 bump tvOS engine to 3.41.6+1 2026-05-04 06:12:06 +02:00
edde746 5f9f0964b2 fix(exoplayer): stack overlapping SRT subtitle cues 2026-05-04 01:19:32 +02:00
edde746 bf89925d6a fix(android): preserve display mode across backend fallback 2026-05-04 01:19:32 +02:00
edde746 aa6e9648bb fix(templates): add Both option to feature request media server dropdown
close #971
2026-05-03 20:35:11 +02:00
edde746 c4b9da0950 refactor(images): replace flutter cache manager 2026-05-03 20:09:23 +02:00
edde746 c7b023222c fix(exoplayer): apply subtitle sync to ASS subtitles
close #936
2026-05-03 11:13:35 +02:00
edde746 060926b749 fix(macos): avoid double disposing mpv core 2026-05-03 10:59:30 +02:00
edde746 aa3c83bad1 fix(jellyfin): handle external transcode subtitles 2026-05-03 10:12:11 +02:00
edde746 70606c8ac5 fix(jellyfin): align playback and browse requests 2026-05-03 09:33:42 +02:00
edde746 5010833da9 fix(mpv): avoid blocking runtime calls 2026-05-03 08:23:44 +02:00
edde746 f5901389e0 fix(macos): restore traffic lights on player exit 2026-05-03 06:52:51 +02:00
edde746 11e1a1464e fix(playback): sync resume progress on exit 2026-05-03 06:45:54 +02:00
edde746 2664caf004 test(jellyfin): align watched fixtures with played flag 2026-05-03 03:45:00 +02:00
edde746 8594a7bc52 fix(jellyfin): respect played flag for watched state
close #965
2026-05-03 03:29:39 +02:00
edde746 8a7d767e54 fix(tvos): remove top shelf image alpha 2026-05-03 02:39:11 +02:00
edde746 d09893470f ci: isolate pub dependency cache 2026-05-03 02:27:03 +02:00
edde746 a40879849b fix(tvos): hide browser auth option 2026-05-03 02:00:39 +02:00
edde746 20953152b6 fix(tvos): dismiss overlays with back 2026-05-03 01:50:26 +02:00
edde746 876a44b244 feat(tvos): add virtual keyboard input 2026-05-03 01:32:58 +02:00
edde746 e9a706fa72 fix(tvos): enable wakelock plugin 2026-05-03 01:26:12 +02:00
edde746 8820c0e059 fix: avoid clear logo fallback shift 2026-05-02 22:38:11 +02:00
edde746 45770e1ad6 fix: unblock watch together resume
close #961
2026-05-02 22:36:49 +02:00
edde746 afdec05dbf fix: retry Plex home hubs
close #962
2026-05-02 19:18:42 +02:00
edde746 81e036dc4f feat: support Jellyfin media segments
close #960
2026-05-02 18:30:12 +02:00
edde746 8555254e81 fix(library): defer browse scroll reset 2026-05-02 11:31:18 +02:00
edde746 1781fc06ae fix: merge Jellyfin next up into continue watching 2026-05-02 11:19:04 +02:00
edde746 810f1e5da5 fix: stabilize hidden library focus traversal 2026-05-02 10:03:36 +02:00
edde746 244b291255 refactor: share controller disposal and Plex DTO parsing 2026-05-02 09:43:08 +02:00
edde746 7fc136f592 refactor: reduce settings and mapper boilerplate 2026-05-02 09:05:23 +02:00
edde746 130e0d6f40 refactor: streamline settings bindings 2026-05-02 08:44:27 +02:00
edde746 8fabf56337 refactor: split playback and media hotspots 2026-05-02 06:33:05 +02:00
edde746 b1e218f0ad chore: optimize workflow caching 2026-05-02 06:21:29 +02:00
edde746 624e8a2991 refactor: share settings and profile flows 2026-05-02 02:35:07 +02:00
edde746 0ac5f49e5e chore: clear analyzer hints 2026-05-02 02:34:26 +02:00
edde746 de6f8d6cb6 refactor: share media stream mapping 2026-05-02 02:29:46 +02:00
edde746 b42ee26840 refactor: share tracker auth plumbing 2026-05-02 02:02:50 +02:00
edde746 50bc245677 refactor: share low-risk UI and tracker helpers 2026-05-02 01:58:50 +02:00
edde746 646832c6b1 chore: bump version 2026-05-02 01:45:33 +02:00
edde746 43242673fb fix(profile): avoid PIN prompt on restart 2026-05-02 01:23:21 +02:00
edde746 87aa7d9d81 fix(library): reset browse grid focus from tab bar 2026-05-02 01:08:06 +02:00
edde746 91d9aad721 fix: improve subtitle search focus navigation 2026-05-02 01:05:54 +02:00
edde746 221902c946 fix(library): reset outer scroll when switching libraries 2026-05-02 00:22:19 +02:00
edde746 8a8c2ecb87 fix: reload migrated profiles before startup 2026-05-01 23:08:21 +02:00
edde746 f6c6808352 feat(library): scroll tabs and chips with content 2026-05-01 22:34:59 +02:00
edde746 036d99f11f perf(android): optimize DV conversion hot path
Remove avoidable per-RPU allocations and copies during DV fallback conversion, and add debug controls to force conversion modes while profiling playback.
2026-05-01 17:50:59 +02:00
edde746 e78f7cee5e fix: shrink short library sheets 2026-05-01 08:31:29 +02:00
edde746 f03c84e8dc fix: group mobile library dropdown by server 2026-05-01 07:55:15 +02:00
edde746 d5a12c404a fix: show library actions drag handle 2026-05-01 07:22:10 +02:00
edde746 dc74300ef5 fix: avoid macOS fullscreen playback stalls
close #934
2026-05-01 07:04:37 +02:00
edde746 b2c3fe61b3 fix: use runner Swift for native formatting 2026-05-01 06:56:56 +02:00
edde746 97e65a811c fix: hide backup settings on TV
close #937
2026-05-01 06:56:56 +02:00
edde746 d9d66fe54e fix: add HTTP fallback for native Plex hostnames 2026-05-01 06:45:10 +02:00
edde746 ed7dae601a fix: avoid duplicate play next countdown
close #942
2026-05-01 06:44:56 +02:00
edde746 024af35bf5 chore: add native formatting checks 2026-05-01 05:56:49 +02:00
edde746 9bd5732f2b chore: clean up redundant comments 2026-05-01 05:02:26 +02:00
edde746 117d1b8882 fix: fall back to wide hero art 2026-05-01 04:52:48 +02:00
edde746 f6aad1b8fc fix: allow downloaded detail artwork network fallback
close #948
2026-05-01 04:40:03 +02:00
edde746 c602936d2a fix: support forced skip marker fallback
close #956
2026-05-01 04:35:30 +02:00
edde746 a351ca70ba fix: localize remaining i18n strings 2026-05-01 04:12:55 +02:00
edde746andGitHub 396a5a8453 Merge pull request #955 from bryceknz/fix/951-test-expectations
Fix media version label tests
2026-05-01 03:54:39 +02:00
Bryce Kehoe db6d5cadd9 fix(media): uppercase named resolution labels
Display non-numeric Plex resolution labels in uppercase while preserving p suffixes for numeric heights.
2026-05-01 02:27:05 +01:00
Bryce Kehoe 5568266c99 test(media): fix UHD label expectations
Assert exact display labels for resolution-only media versions so the test matches displayLabel output without codec/container fields.
2026-05-01 02:27:05 +01:00
edde746 a605db31f9 fix: split app database tests for lint 2026-05-01 03:24:15 +02:00
edde746 35ca723c20 chore: update issue templates 2026-05-01 03:20:49 +02:00
edde746 7057ee93ac fix: defer profile binding before selection 2026-05-01 03:16:32 +02:00
edde746 6cde5b6bd1 style: format database generated code 2026-05-01 01:54:56 +02:00
edde746 08564bba20 feat: merge jellyfin support 2026-05-01 01:54:56 +02:00
edde746 495f2e3640 chore: update SDK constraints 2026-05-01 01:47:05 +02:00
edde746 31d2d9dc98 feat: jellyfin 2026-05-01 01:20:36 +02:00
edde746andGitHub 68d34f81a0 Merge pull request #952 from bryceknz/fix/951-uhd-version-labels
Fix UHD version labels
2026-05-01 00:59:30 +02:00
Bryce Kehoe e733a0abc7 test(media): cover UHD version labels
Add display label coverage for numeric resolutions and UHD values returned by Plex.
2026-04-30 22:09:54 +01:00
Bryce Kehoe c800baeb25 fix(media): format UHD version labels
Normalize Plex 4k/8k resolution values for display so version pickers show 4K/8K instead of appending a p suffix.
2026-04-30 22:09:54 +01:00
github-actions[bot] 4080c812d2 chore: update cask to 1.35.2 2026-04-30 14:50:20 +00:00
github-actions[bot] 617bf64105 chore: bump version to 1.35.2 2026-04-30 14:06:58 +00:00
edde746 9f19082d47 fix(android): hole-punch video and libass surfaces on API 36+ 2026-04-30 16:04:16 +02:00
github-actions[bot] 5b9719b96f chore: update cask to 1.35.1 2026-04-28 03:41:25 +00:00
github-actions[bot] 3fd4320e52 chore: bump version to 1.35.1 2026-04-28 03:18:12 +00:00
edde746 d66e5af289 fix(livetv): fall back to legacy channels endpoint when cloud guide errors 2026-04-28 04:21:40 +02:00
edde746 c5867861eb fix(playback): coalesce concurrent player init to fix MPV hang 2026-04-28 04:16:02 +02:00
edde746 fdede5f643 chore: dart format focusable_tab_chip.dart 2026-04-28 04:16:02 +02:00
edde746andGitHub bb0f70c75c Merge pull request #926 from micahmo/feature/show-posters
Show season posters on tab in show view
2026-04-27 15:31:39 +02:00
Micah Morrison dcffb74529 Gate season posters on tab behind a setting 2026-04-27 09:28:57 -04:00
github-actions[bot] d8f665ef97 chore: update cask to 1.35.0 2026-04-27 12:08:50 +00:00
github-actions[bot] 6bd203f606 chore: bump version to 1.35.0 2026-04-27 11:44:11 +00:00
edde746 240389fb6d fix(ci): upload symbols outside release path 2026-04-27 13:23:30 +02:00
edde746 ca6cb46ba8 fix: upload symbols as individual files 2026-04-27 12:44:59 +02:00
edde746 616ed72503 fix: exclude mal/anilist/simkl session keys from settings export 2026-04-27 12:17:34 +02:00
Micah Morrison 310d4b46b2 Show season posters on tab in show view 2026-04-26 15:11:24 -04:00
edde746 d6b47f9d51 fix(windows): suppress Steam Input duplicate actions 2026-04-26 20:46:25 +02:00
edde746 19a0128363 feat(playback): add ArtCNN shader presets
close #924
2026-04-26 20:29:38 +02:00
edde746 3433dcb21c fix(downloads): clean up stale SAF target file before re-enqueue 2026-04-26 19:15:06 +02:00
edde746 62e3cbcfd0 fix(playback): chain adjacent-episode load behind play queue 2026-04-26 18:44:35 +02:00
edde746 4688e1eb5e style: wrap long if-condition flagged by dart format 2026-04-26 18:44:35 +02:00
edde746 f5e0e8c8b5 feat(settings): add "Start in fullscreen" option on Windows/Linux
close #923
2026-04-26 18:12:30 +02:00
edde746 8c8fc13baf fix(playback): skip deleted/inaccessible Plex media versions before play
close #919
2026-04-26 18:12:30 +02:00
edde746andGitHub a9a8fa388e Merge pull request #925 from crtdll/main
fix(windows): fixed black screen while navigating between videos in full screen
2026-04-26 18:05:07 +02:00
CameronandGitHub 6371d7a36e fix(windows): fixed black screen while navigating between videos in full screen 2026-04-26 16:59:50 +01:00
edde746 425da3ab7d fix(overlay-sheet): wrap barrier in Positioned.fill 2026-04-25 19:59:36 +02:00
edde746 7aaa373bdf revert: desktop image eviction threshold to 1.5GB 2026-04-25 17:12:17 +02:00
edde746 23d958fac8 fix(downloads): guard ensureAbsolutePath against RangeError on short paths 2026-04-25 14:10:37 +02:00
edde746 e61f0002e5 test: episode nav, track selection, play queue, more mixins 2026-04-25 13:54:08 +02:00
edde746 303bd406c2 test: watch_together provider, more mixins, services, utils 2026-04-25 13:44:15 +02:00
edde746 ce7e936931 test: complex provider, mixin, and service tests 2026-04-25 13:29:48 +02:00
edde746 f049c65623 test: provider/mixin/service tests + visibleForTesting reset hooks 2026-04-25 13:15:01 +02:00
edde746 7f8c066062 test: add provider and drift database tests 2026-04-25 13:04:08 +02:00
edde746 edff1f29db test: scaffolding + first provider test (hidden_libraries) 2026-04-25 12:56:38 +02:00
edde746 87696d77d1 refactor(models): json_serializable for 9 manual fromJson models 2026-04-25 12:52:43 +02:00
edde746 0dbcda25e7 refactor(models): json_serializable for plex_filter 2026-04-25 12:45:54 +02:00
edde746 ebbcc60e13 perf(screens): cache Theme.of in hot media detail/discover paths 2026-04-25 12:44:15 +02:00
edde746 1ce561a1ad perf(images): add memCacheHeight to direct CachedNetworkImage sites 2026-04-25 12:37:41 +02:00
edde746 c36fee17dd refactor(providers): apply DisposableChangeNotifierMixin to 11 providers 2026-04-25 12:35:52 +02:00
edde746 eeed34e2df perf(folder-tree): use ListView.builder for lazy row build 2026-04-25 12:32:23 +02:00
edde746 52b70a0080 perf(mediaquery): use scoped accessors (sizeOf, paddingOf, etc.) 2026-04-25 12:30:53 +02:00
edde746 feba5b6f74 lint: enforce unawaited_futures, prefer_final_locals, etc. 2026-04-25 12:27:28 +02:00
edde746 c2cd2dea37 perf: cap hero decode, lower desktop image eviction threshold 2026-04-25 11:59:56 +02:00
edde746 5d87c6808d refactor(prefs): route services through sharedCache 2026-04-25 11:13:12 +02:00
edde746 0531c33b0c refactor(settings): typed Pref<T> declarations 2026-04-25 10:52:34 +02:00
edde746 e4e8299981 refactor: showLoadingDialog helper, json_serializable for plex_home 2026-04-25 03:25:09 +02:00
edde746 d0a93d57dd refactor: codebase review cleanup 2026-04-25 03:16:11 +02:00
edde746 1949c22b85 fix(trackers): dialog cancel pops screen behind 2026-04-24 23:32:13 +02:00
edde746 3a69e49ab8 perf: parallelize playback startup 2026-04-24 23:20:31 +02:00
edde746 df94e83592 fix(trackers): cancel connect immediately 2026-04-24 20:54:38 +02:00
edde746 1de91a598c refactor(tvos): cleanup 2026-04-24 20:21:30 +02:00
edde746 49a86e402c fix: stabilize grid column count when alpha bar shows 2026-04-24 19:19:39 +02:00
edde746 3d023962e1 feat: server grouping, hidden-library browsing
close #557, close #827
2026-04-24 19:11:25 +02:00
edde746 a13cfedbce fix(tvos): app store builds 2026-04-24 17:35:22 +02:00
edde746 2b59de91c7 chore: dart format 2026-04-24 14:19:07 +02:00
edde746 2479e1faaa feat: tvos support 2026-04-24 14:11:24 +02:00
edde746 77401bef32 fix(android): saf download deletion 2026-04-24 13:07:06 +02:00
edde746 e961bc6293 refactor: share tracker/trakt auth and connect flow 2026-04-24 12:32:25 +02:00
edde746 bf2584d90f feat: per-tracker library whitelist/blacklist
close #917
2026-04-24 10:30:16 +02:00
edde746 e8729a4e27 feat: oauth proxy for mal/anilist auth 2026-04-24 09:46:45 +02:00
edde746 1582fdbd5b feat: mal/anilist/simkl progress sync
close #914
2026-04-24 08:29:49 +02:00
edde746 431c20f817 feat: match/unmatch metadata 2026-04-23 19:02:14 +02:00
edde746 4a5cb224b1 feat: swap chapters/queue player icons 2026-04-23 18:26:03 +02:00
edde746 d5d9da046e feat: toggle auto update check on startup
close #913
2026-04-23 18:06:27 +02:00
edde746 0c6796ebe7 fix: desktop double-click fullscreen full area 2026-04-23 15:25:38 +02:00
edde746 d73b9182cc fix: stable image cache key across window resize 2026-04-23 13:58:25 +02:00
edde746 39bcd9b943 feat(android): flutter surfaceview rendering 2026-04-23 10:10:34 +02:00
edde746 ca5d87143b feat: global fullscreen toggle (F11 + sidebar)
close #907
2026-04-23 07:43:46 +02:00
edde746 1e54344ec3 feat: toggle episode number on cards 2026-04-22 21:35:03 +02:00
edde746 c10cf55f2d feat: transcoding 2026-04-22 21:07:12 +02:00
edde746 05aeee1124 test(server): relay integration coverage 2026-04-22 15:24:34 +02:00
edde746 74c6af2980 feat(server): persist rooms across restarts 2026-04-22 14:57:41 +02:00
edde746 0883fe2e36 chore(server): tune bugs memory limits 2026-04-22 14:29:36 +02:00
edde746 e95475f845 feat(sentry): symbol upload and hang tracking 2026-04-22 12:44:37 +02:00
edde746 b2cd0c2c37 fix: retry live tv tune, clamp timeline duration 2026-04-22 08:45:02 +02:00
edde746 06b3c9645c test: assert dispose completer fires 2026-04-22 02:44:54 +02:00
edde746 557ef69697 fix: guard setState/context against disposed widget 2026-04-21 22:29:57 +02:00
edde746 eb49ead83b fix: paginate collection/playlist/person endpoints
close #903
2026-04-21 21:51:20 +02:00
edde746 e2be6a0093 chore: remove jscpd and sonarqube 2026-04-21 20:26:19 +02:00
edde746 d4235a286a test: unit tests for utils, models, settings mpv parser 2026-04-21 20:09:58 +02:00
edde746 fd701e5d1f fix: restrict failover to working endpoint network class
close #902
2026-04-21 19:20:57 +02:00
edde746 e6c1923b0e refactor(exoplayer): drop duplicated mpv box-fit translation 2026-04-21 18:23:46 +02:00
edde746 839465b7f2 feat(exoplayer): box-fit modes (letterbox/cover/stretch) 2026-04-21 18:17:25 +02:00
edde746 7c331e51e6 fix: auto-skip credits honors auto-play-next
close #901
2026-04-21 17:37:31 +02:00
edde746 775998466d i18n: rename audio normalization to normalize loudness
close #896
2026-04-21 17:35:18 +02:00
edde746 ee020d81bd refactor: trakt/download hardening and cleanup sweep 2026-04-21 13:57:03 +02:00
edde746 93d196572f fix: clamp playlist focus index on remove 2026-04-21 12:36:15 +02:00
edde746 f69068eb63 feat(db): index DownloadedMedia hot columns 2026-04-21 12:05:50 +02:00
edde746 1edf3da984 refactor: consolidate dialogs to DialogActionButton 2026-04-21 12:05:21 +02:00
edde746 4665f2a5d8 fix: dispose services and subscriptions, persist client id 2026-04-21 12:04:48 +02:00
edde746 fd898e0567 fix: json parse safety, stop mutating input maps 2026-04-21 12:03:32 +02:00
edde746 48ba923f47 chore: bump mpvkit and libmpv-android 2026-04-21 10:39:24 +02:00
edde746 e1c9ce6f71 fix: gate http fallback for hostname https, throw on non-2xx in failover
close #900
2026-04-21 08:39:28 +02:00
edde746 5937e5c721 refactor: extract shared mixins and helpers to dedupe 2026-04-20 21:25:50 +02:00
edde746 3b7b532a8d fix: exclude trakt keys from settings export 2026-04-20 21:17:00 +02:00
edde746 bc57ffb930 feat: export/import settings 2026-04-20 20:17:57 +02:00
edde746 1fd415ae31 feat(android): display switch delay
close #894
2026-04-20 17:34:54 +02:00
edde746 6d265e7bae feat: episode next/prev hotkeys
close #897
2026-04-20 16:34:46 +02:00
edde746 4667b104d2 docs: refresh readme features 2026-04-20 13:52:19 +02:00
github-actions[bot] 2f524cffae chore: update cask to 1.34.2 2026-04-20 11:36:26 +00:00
github-actions[bot] 87215d9e7b chore: bump version to 1.34.2 2026-04-20 11:15:06 +00:00
edde746 65e19706f8 fix(exoplayer): external sub attach, non-ass render
close #895
2026-04-20 13:14:32 +02:00
edde746 f96342bd81 chore: bump libass to fp-3
close #893
2026-04-20 11:55:21 +02:00
github-actions[bot] f7a6ab25c3 chore: update cask to 1.34.1 2026-04-20 06:57:27 +00:00
github-actions[bot] fa88d35b2b chore: bump version to 1.34.1 2026-04-20 06:15:51 +00:00
edde746 64d5c1f6aa fix: force rediscover on manual reconnect 2026-04-20 08:15:16 +02:00
github-actions[bot] 56baa48223 chore: bump version to 1.34.0 2026-04-20 06:13:39 +00:00
edde746 ad3edd4652 feat: log connection failure detail 2026-04-19 23:05:22 +02:00
edde746 81bac6ee9b fix(exoplayer): libass performance 2026-04-19 23:01:40 +02:00
edde746 a715f4e26b feat: collection/playlist sync rules 2026-04-19 17:45:03 +02:00
edde746 6115c21b44 chore: prune unused i18n keys 2026-04-19 14:48:18 +02:00
edde746 f367260acd chore: i18n cleanup script 2026-04-19 14:47:52 +02:00
edde746 7f8b827c0e fix: reset completion latch on stream recovery
close #664
2026-04-19 14:08:20 +02:00
edde746 0a1abfcbbb fix: video playback tile description 2026-04-19 13:42:58 +02:00
edde746 f53592f32b fix: live tv dvr seek via keyboard/remote
close #789
2026-04-19 13:13:38 +02:00
edde746 fd1d187ede feat: timeline thumbnail on dpad key-repeat
close #805
2026-04-19 12:24:14 +02:00
edde746 b4e78febc0 feat: donation button 2026-04-19 11:52:46 +02:00
edde746 ff2928b18f feat: trakt integration
close #617
2026-04-19 11:31:27 +02:00
edde746 8b34307975 fix: re-select audio on renderer capabilities change
close #889
2026-04-18 18:36:44 +02:00
edde746 9cca40420c fix: guard player back pop with canPop 2026-04-18 18:08:51 +02:00
edde746 3da51f9d64 chore: pre-commit ci hook, dart format 2026-04-18 12:40:35 +02:00
edde746 2bd9e6655f feat: rate pill, fix snackbar placement
close #886
2026-04-18 08:37:43 +02:00
edde746 d2b01100a5 feat: force TV mode setting
close #885
2026-04-17 19:41:28 +02:00
edde746 47837edb01 fix: apply display matching on fullscreen enter 2026-04-17 15:03:50 +02:00
edde746 91057c12a4 feat: bold/italic subtitle toggles
close #883
2026-04-17 15:03:23 +02:00
edde746 66b32468eb fix: serialize file picker calls 2026-04-17 14:13:20 +02:00
edde746 1e62c6c756 feat: bandwidth limit modal on stream 500 2026-04-17 13:12:07 +02:00
edde746 f8132e7bdb fix: focus media detail info rows
close #758
2026-04-17 05:23:18 +02:00
edde746 dec2e1c9fc fix: add media3 hls dependency
close #881
2026-04-17 04:42:46 +02:00
edde746 ee20965218 fix: pin EPG titles, filter cloud channel list
close #614
2026-04-17 04:28:19 +02:00
edde746 2e429840d2 fix: fan out multi-airing EPG metadata
close #563
2026-04-17 03:36:27 +02:00
edde746 e63920e23b fix: native monitor-aware fullscreen on windows 2026-04-16 23:13:15 +02:00
edde746 11d2e40e34 fix: downsample offline hero art and clear logo 2026-04-16 22:50:58 +02:00
edde746 ddb4a91b08 fix: downsample local artwork in offline grids 2026-04-16 22:44:01 +02:00
edde746 157669bd76 feat: folder view thumbnails and rich metadata
close #821
2026-04-16 17:06:07 +02:00
edde746 f055759c7a fix: suppress position sync when app backgrounded 2026-04-16 15:43:08 +02:00
edde746 34815f22ee fix: watch together server races, reconnect readiness, session end 2026-04-16 15:24:44 +02:00
edde746 1d3ae3e1c5 fix: watch together bugs and server write serialization 2026-04-16 14:00:24 +02:00
edde746 3cf1ebc09b fix: watch together room re-join and participant discovery
close #875
2026-04-16 13:17:24 +02:00
edde746 360741674d feat: sync rules for downloads
close #867
2026-04-16 12:52:48 +02:00
edde746 c369f2c3d7 refactor: remove dead code across codebase 2026-04-16 08:14:42 +02:00
edde746 65e22fbbbd refactor: remove dead download code 2026-04-16 07:27:05 +02:00
edde746 74b2d76fea refactor: remove dead SAF copy methods 2026-04-16 07:27:05 +02:00
edde746 6c61e0e4c9 feat: namedTimeout for Sentry context 2026-04-16 07:27:05 +02:00
edde746 a60e1e7f42 feat: ExoPlayer audio-delay and sub-delay support
close #869
2026-04-16 06:44:46 +02:00
edde746 1b1c4b741b filter Windows disk-full errors from Sentry 2026-04-16 06:25:24 +02:00
edde746 f9d8549e56 fix: clamp tooltip upper bound to prevent ArgumentError 2026-04-16 06:13:45 +02:00
edde746 bdd9d24d32 fix: fallback to IOClient on WinHttp init failure 2026-04-16 06:11:13 +02:00
edde746 a7ba837cb1 fix: prevent white screen when no servers available 2026-04-16 06:02:18 +02:00
edde746 d04781e4b3 fix: use baseline x86_64 mpv build for older CPU compat 2026-04-16 04:19:43 +02:00
edde746 f87f0b0807 fix: suppress spurious media pause during frame rate switch
close #871
2026-04-16 04:11:33 +02:00
edde746 59346f4b67 fix: restore playWhenReady after renderer recreation 2026-04-16 03:42:46 +02:00
edde746 06174af16c fix: ensure crashpad_handler has executable permissions in .deb
close #870
2026-04-15 23:25:00 +02:00
edde746 f1867ddeb7 fix: preserve PiP during episode auto-play
close #865
2026-04-15 23:16:04 +02:00
edde746 79f7de1b4c chore: regenerate podfile locks 2026-04-15 17:53:46 +02:00
edde746 15de88463c fix: disable native HTTP error capturing in sentry 2026-04-15 17:51:28 +02:00
github-actions[bot] c032d97c5f chore: update cask to 1.33.1 2026-04-15 10:20:55 +00:00
github-actions[bot] 2eca47ab69 chore: bump version to 1.33.1 2026-04-15 10:02:27 +00:00
edde746 caa70dd460 fix: remove camera permission and hasCamera check 2026-04-15 12:01:55 +02:00
github-actions[bot] 6b0e65b563 chore: bump version to 1.33.0 2026-04-15 09:28:37 +00:00
edde746 e0308be8bb fix: mounted check in _toggleLibraryVisibility 2026-04-15 11:04:16 +02:00
edde746 4663c435c9 fix: artwork directory null crash on orientation change 2026-04-15 06:11:07 +02:00
edde746 8380980abd fix: update background_downloader fork ref 2026-04-15 00:32:18 +02:00
edde746 771c431188 fix: treat 500 as permanent failure, show error in UI 2026-04-14 22:29:05 +02:00
edde746 1e1bb9176a feat: watch together buffering indicators 2026-04-14 22:07:13 +02:00
edde746 6eb5c847af fix: download cleanup, retry circuit breaker, SAF resume 2026-04-14 21:54:00 +02:00
edde746 e50fdc4eb9 feat: circular dpad and filled nav chips on remote screen 2026-04-14 13:29:42 +02:00
edde746 4edf1a8c42 fix: auto-start remote server after home data loads 2026-04-14 13:03:34 +02:00
edde746 cb455d379c feat: inline discovery in remote screen 2026-04-14 12:58:41 +02:00
edde746 d093023ce7 feat: replace QR remote pairing with encrypted LAN discovery
Replace session ID + PIN auth with HKDF-derived home secret and
per-session AES-256-GCM encrypted channel. Auto-start remote server
on host devices, auto-discover hosts via authenticated UDP broadcast.
2026-04-14 12:33:40 +02:00
edde746 a55650bc40 fix: skip QR scanner on devices without cameras 2026-04-14 06:53:51 +02:00
edde746 6cbf0980c5 fix: filter HTTPClientError and DiscordStateException from sentry 2026-04-14 06:43:53 +02:00
edde746 4cb65c1bfa feat: mouse back button navigation 2026-04-14 06:30:18 +02:00
edde746 f30e47dbd7 fix: enforce min 2x DPR for TV image transcoding
close #860
2026-04-14 05:55:43 +02:00
edde746 7ab6b9720f feat: increase subtitle sync slider range to ±60s
close #851
2026-04-14 04:24:53 +02:00
edde746 2f7c87d437 fix: subtitle background not rendering on mpv 0.38+
close #773
2026-04-13 23:59:47 +02:00
edde746 bc4b4955da feat: auto-remove watched downloads, server watched threshold
close #856
2026-04-13 22:46:49 +02:00
edde746 f7e3408c86 fix: guard empty list access in alpha jump bar and download tree 2026-04-13 22:07:21 +02:00
edde746 2126a38f39 fix: bounds-safe action bar focus node access 2026-04-13 22:00:36 +02:00
edde746 b81f6eaa96 feat: watch together recent rooms, plex usernames, action toasts, shorter codes
close #855
2026-04-13 14:02:21 +02:00
edde746 17eb37cb37 fix: back navigation on screens with no app bar actions
close #854
2026-04-13 11:33:15 +02:00
github-actions[bot] 9208aa8d16 chore: update cask to 1.32.0 2026-04-13 06:35:14 +00:00
github-actions[bot] bd7f7894ed chore: bump version to 1.32.0 2026-04-13 06:03:17 +00:00
edde746 6dfdb62df8 feat: relay connection limits and container memory caps 2026-04-13 07:55:28 +02:00
edde746 3be302d69f feat: set sentry environment per distribution channel 2026-04-13 02:38:28 +02:00
edde746 66ebc547f0 fix: filter disk-full and dbus socket errors from sentry 2026-04-13 02:05:24 +02:00
edde746 3366b83a89 fix: hide spoilers in watch next thumbnails
close #849
2026-04-12 11:12:37 +02:00
edde746 cd3db94b5d fix: guard library dropdown against empty list 2026-04-12 10:14:43 +02:00
edde746 d56067e7cc fix: skip back navigation when overlay route is on top 2026-04-12 10:11:11 +02:00
edde746 7c3cee692c fix: one-shot select key activation in focus helpers 2026-04-12 10:00:26 +02:00
edde746 a948d82c24 switch from glitchtip 2026-04-12 09:11:42 +02:00
edde746 77893bb9ba fix: detail screen section alignment 2026-04-12 01:37:08 +02:00
edde746 1b2ecd9de4 fix: standardize bool parsing with flexibleBool helper
close #844
2026-04-11 21:22:15 +02:00
edde746andGitHub b92842f9ac Merge pull request #842 from jordankoehn/fix-live-tv-join-session-edge-case
Fix Live TV join session edge case
2026-04-11 08:09:51 +02:00
edde746 91d191b3d8 fix: file info bitrate units, multi-track display, tv scrolling
close #840, close #841
2026-04-11 08:04:12 +02:00
Jordan Koehn 21accaa883 Fix Live TV join session edge case
Under the circumstance that guide data is not available, program start
is equal to current time. So program start should be ignored so one can
tune to the oldest available recording offset.
2026-04-10 22:34:32 -04:00
edde746 c6f2e949a7 fix: use configured skip setting for dpad/timeline seeking
close #751, close #790
2026-04-10 22:31:41 +02:00
edde746 9d9d9bb311 feat: add square art and logo editing to metadata editor
close #837
2026-04-10 18:38:54 +02:00
edde746 0b20300572 fix: noisy audio pause on android tv 2026-04-10 10:24:19 +02:00
edde746 f47bcb69fd feat: auto-hide performance overlay with controls
close #834
2026-04-10 01:30:26 +02:00
edde746 c20bb93f1f fix: always show track selection button
close #833
2026-04-09 23:52:02 +02:00
edde746 497259ca16 fix: close http clients on server replacement 2026-04-09 23:34:01 +02:00
edde746 4322ffc6e5 fix: disable android tv pip lifecycle regressions 2026-04-09 06:39:17 +02:00
edde746 8b40e0993f fix: normalize EOF playback state
close #828
2026-04-09 05:55:03 +02:00
edde746 966b6371f5 fix: preserve download server affinity 2026-04-09 04:51:35 +02:00
edde746 5b493a70b0 feat: show snackbar on playback speed change
close #824
2026-04-09 03:48:14 +02:00
edde746 1cb793d781 feat: add sub-ass-override setting 2026-04-08 19:35:18 +02:00
edde746 7f237c9c7b refactor: reuse showTextInputDialog for episode count input 2026-04-08 18:08:39 +02:00
edde746 d0934295b0 feat: download all playlist items
close #241
2026-04-08 12:37:03 +02:00
edde746 8d40ba3011 fix: reduce blank space in media card bottom 2026-04-08 07:21:21 +02:00
edde746 f926deb63b feat: clickable cast members to browse actor filmography
close #723
2026-04-08 05:17:37 +02:00
edde746 b82c612f94 fix: remove unused parameter in focusable_slider 2026-04-08 04:40:12 +02:00
edde746 e7ae108c49 chore: bump win_http to 0.2.0 2026-04-08 04:24:06 +02:00
edde746 08689df2f5 chore: update Podfile.lock 2026-04-08 01:58:26 +02:00
edde746 87c308f6ca feat: use win_http on Windows 2026-04-08 01:54:40 +02:00
edde746 15b22f75a8 refactor: replace dio with package:http 2026-04-08 00:43:08 +02:00
edde746 8e7431e7e5 feat: download options picker for series/seasons 2026-04-07 22:59:35 +02:00
edde746 c034f9b66e fix: request utf-8 encoding for external subtitles
close #817
2026-04-07 18:34:47 +02:00
edde746 5cf53f8cfa fix: chapter keyboard shortcuts navigate chapters not episodes
close #820
2026-04-07 17:58:00 +02:00
edde746 e4de7f1ecb fix(tv): reduce live stream reconnect delay for faster fallback 2026-04-07 15:37:36 +02:00
edde746 bf9913ba0f fix(tv): re-tune on live stream fallback, fix decision 400 throw 2026-04-07 10:52:54 +02:00
edde746 6ac8c905c9 fix(tv): live stream direct-stream fallback chain 2026-04-07 07:58:42 +02:00
edde746 603b5b5105 fix: pip aspect ratio clamp values outside android limits 2026-04-07 07:35:03 +02:00
edde746 7528dcec71 fix: connection selection failover and timeout budget 2026-04-07 06:49:51 +02:00
github-actions[bot] d96848181d chore: update cask to 1.31.3 2026-04-07 04:28:16 +00:00
github-actions[bot] 16b6ea8f29 chore: bump version to 1.31.3 2026-04-07 04:11:07 +00:00
edde746 7150ea2987 fix: log reason for https upgrade failure 2026-04-07 05:48:44 +02:00
edde746 bc2febf480 fix: prefer https endpoints, catch h2 protocol errors 2026-04-07 05:48:44 +02:00
github-actions[bot] 11ec48a506 chore: update cask to 1.31.2 2026-04-07 02:40:18 +00:00
1281 changed files with 266151 additions and 51994 deletions
+9
View File
@@ -0,0 +1,9 @@
BasedOnStyle: Google
AlignAfterOpenBracket: AlwaysBreak
ColumnLimit: 120
IndentWidth: 2
ContinuationIndentWidth: 4
DerivePointerAlignment: false
LineEnding: LF
PointerAlignment: Left
SortIncludes: true
-19
View File
@@ -1,19 +0,0 @@
.git
build/
.dart_tool/
.idea/
*.tar.gz
nul
libmpv-prefix/
steamfiles/
pubspec_overrides.yaml
# Flutter ephemeral / generated plugin symlinks
linux/flutter/ephemeral/
windows/flutter/
macos/Flutter/
ios/Flutter/
android/.gradle/
android/app/build/
.flutter-plugins
.flutter-plugins-dependencies
+28
View File
@@ -0,0 +1,28 @@
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
[*.{c,cc,cpp,h,hpp,m,mm}]
indent_style = space
indent_size = 2
[*.dart]
indent_style = space
indent_size = 2
[*.{kt,kts,java}]
indent_style = space
indent_size = 2
ij_kotlin_code_style_defaults = KOTLIN_OFFICIAL
ktlint_code_style = android_studio
ktlint_standard_max-line-length = disabled
ktlint_standard_no-wildcard-imports = disabled
ktlint_standard_property-naming = disabled
[*.swift]
indent_style = space
indent_size = 2
+21
View File
@@ -0,0 +1,21 @@
#!/usr/bin/env bash
set -uo pipefail
if [ "${SKIP_HOOKS:-}" = "1" ]; then
echo "[pre-commit] skipped (SKIP_HOOKS=1)"
exit 0
fi
GIT_DIR="$(git rev-parse --git-dir)"
if [ -f "$GIT_DIR/MERGE_MSG" ] || [ -f "$GIT_DIR/MERGE_HEAD" ] || [ -f "$GIT_DIR/REVERT_HEAD" ]; then
echo "[pre-commit] skipped (merge/revert in progress)"
exit 0
fi
if git diff --cached --quiet; then
echo "[pre-commit] nothing staged — skipping checks"
exit 0
fi
ROOT="$(git rev-parse --show-toplevel)"
exec "$ROOT/scripts/ci_checks.sh"
+1
View File
@@ -1 +1,2 @@
github: edde746
liberapay: edde746
+15
View File
@@ -68,16 +68,31 @@ body:
- Windows
- macOS
- Android TV
- tvOS
- Linux
validations:
required: true
- type: dropdown
id: media-server
attributes:
label: Media Server
description: Are you using Jellyfin or Plex?
multiple: true
options:
- Jellyfin
- Plex
validations:
required: true
- type: input
id: device
attributes:
label: Device Information
description: What device are you using?
placeholder: e.g., iPhone 14 Pro, Pixel 7, Chrome on macOS
validations:
required: true
- type: textarea
id: logs
@@ -41,6 +41,8 @@ body:
1. As a user, I would...
2. This would help me...
3. The benefit would be...
validations:
required: true
- type: dropdown
id: platform
@@ -54,8 +56,23 @@ body:
- Windows
- macOS
- Android TV
- tvOS
- Linux
- All platforms
validations:
required: true
- type: dropdown
id: media-server
attributes:
label: Media Server
description: Which media server(s) is this for?
multiple: true
options:
- Jellyfin
- Plex
validations:
required: true
- type: textarea
id: additional
+259 -56
View File
@@ -2,13 +2,45 @@ name: Build
on:
workflow_dispatch:
inputs:
build_android:
description: Build Android
default: true
type: boolean
build_ios:
description: Build iOS
default: true
type: boolean
build_macos:
description: Build macOS
default: true
type: boolean
build_windows:
description: Build Windows
default: true
type: boolean
build_linux:
description: Build Linux
default: true
type: boolean
env:
SENTRY_DART_DEFINE: ${{ github.repository == 'edde746/plezy' && '--dart-define=ENABLE_SENTRY=true' || '' }}
GIT_COMMIT_DART_DEFINE: --dart-define=GIT_COMMIT=${{ github.sha }}
SENTRY_ENV_DART_DEFINE: --dart-define=SENTRY_ENVIRONMENT=github
DONATIONS_DART_DEFINE: --dart-define=ENABLE_DONATIONS=true
LINUX_APT_PACKAGES: >
clang cmake meson ninja-build pkg-config nasm libgtk-3-dev libevdev-dev liblzma-dev
libstdc++-12-dev libasound2-dev libass-dev libfreetype-dev libfontconfig-dev libfribidi-dev
libharfbuzz-dev libepoxy-dev libegl-dev libgl-dev libgnutls28-dev libpipewire-0.3-dev
libva-dev libvdpau-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev
libxss-dev libxpresent-dev libxkbcommon-dev libpulse-dev libdbus-1-dev libdrm-dev
libgbm-dev libwayland-dev wayland-protocols liblcms2-dev libmujs-dev liblua5.2-dev
ruby ruby-dev rubygems build-essential rpm libarchive-tools imagemagick libcurl4-openssl-dev
jobs:
build-android:
if: ${{ inputs.build_android }}
runs-on: ubuntu-latest
permissions:
id-token: write
@@ -27,16 +59,16 @@ jobs:
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-${{ hashFiles('**/pubspec.lock') }}
restore-keys: |
${{ runner.os }}-pub-
key: ${{ runner.os }}-${{ runner.arch }}-pub-v2-${{ hashFiles('pubspec.yaml', 'pubspec.lock') }}
- name: Cache Gradle
uses: actions/cache@v4
@@ -49,7 +81,7 @@ jobs:
${{ runner.os }}-gradle-
- name: Install dependencies
run: flutter pub get
run: flutter pub get --enforce-lockfile --no-example
- name: Configure Android signing
run: |
@@ -62,7 +94,14 @@ jobs:
EOF
- name: Build APKs
run: flutter build apk --release --split-per-abi --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }}
run: flutter build apk --release --split-per-abi --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-android-apk ${{ env.DONATIONS_DART_DEFINE }} --obfuscate --split-debug-info=debug-info/android-apk --extra-gen-snapshot-options=--save-obfuscation-map=debug-info/android-apk/obfuscation.map.json
- name: Upload symbols to bugs.plezy.app
if: github.repository == 'edde746/plezy'
env:
BUGS_ADMIN_TOKEN: ${{ secrets.BUGS_ADMIN_TOKEN }}
SENTRY_DIST: github-android-apk
run: ./scripts/upload-symbols.sh android-apk
- name: Clean up keystore
if: always()
@@ -92,6 +131,7 @@ jobs:
plezy-android-x86_64.tar.gz
build-ios:
if: ${{ inputs.build_ios }}
runs-on: macos-26
permissions:
id-token: write
@@ -104,16 +144,16 @@ jobs:
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-${{ hashFiles('**/pubspec.lock') }}
restore-keys: |
${{ runner.os }}-pub-
key: ${{ runner.os }}-${{ runner.arch }}-pub-v2-${{ hashFiles('pubspec.yaml', 'pubspec.lock') }}
- name: Cache CocoaPods
uses: actions/cache@v4
@@ -127,10 +167,17 @@ jobs:
${{ runner.os }}-pods-
- name: Install dependencies
run: flutter pub get
run: flutter pub get --enforce-lockfile --no-example
- name: Build iOS (no codesign)
run: flutter build ios --release --no-codesign --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }}
run: flutter build ios --release --no-codesign --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-ios ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/ios
- name: Upload symbols to bugs.plezy.app
if: github.repository == 'edde746/plezy'
env:
BUGS_ADMIN_TOKEN: ${{ secrets.BUGS_ADMIN_TOKEN }}
SENTRY_DIST: github-ios
run: ./scripts/upload-symbols.sh ios
- name: Create IPA
run: |
@@ -150,6 +197,7 @@ jobs:
path: plezy-ios.ipa
build-macos:
if: ${{ inputs.build_macos }}
runs-on: macos-26
permissions:
id-token: write
@@ -162,16 +210,16 @@ jobs:
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-${{ hashFiles('**/pubspec.lock') }}
restore-keys: |
${{ runner.os }}-pub-
key: ${{ runner.os }}-${{ runner.arch }}-pub-v2-${{ hashFiles('pubspec.yaml', 'pubspec.lock') }}
- name: Cache CocoaPods
uses: actions/cache@v4
@@ -185,10 +233,17 @@ jobs:
${{ runner.os }}-macos-pods-
- name: Install dependencies
run: flutter pub get
run: flutter pub get --enforce-lockfile --no-example
- name: Build macOS
run: flutter build macos --release --dart-define=ENABLE_UPDATE_CHECK=true ${{ env.SENTRY_DART_DEFINE }} ${{ env.GIT_COMMIT_DART_DEFINE }}
run: flutter build macos --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-macos ${{ env.DONATIONS_DART_DEFINE }} --split-debug-info=debug-info/macos
- name: Upload symbols to bugs.plezy.app
if: github.repository == 'edde746/plezy'
env:
BUGS_ADMIN_TOKEN: ${{ secrets.BUGS_ADMIN_TOKEN }}
SENTRY_DIST: github-macos
run: ./scripts/upload-symbols.sh macos
- name: Import Code Signing Certificate
env:
@@ -244,6 +299,11 @@ jobs:
APP_PATH="build/macos/Build/Products/Release/Plezy.app"
echo "Verifying signature..."
codesign -dvvv "$APP_PATH"
echo "Verifying signed entitlements..."
codesign -d --entitlements :- "$APP_PATH" > "$RUNNER_TEMP/macos-entitlements.plist"
/usr/libexec/PlistBuddy -c "Print" "$RUNNER_TEMP/macos-entitlements.plist"
/usr/libexec/PlistBuddy -c "Print :com.apple.security.cs.allow-jit" "$RUNNER_TEMP/macos-entitlements.plist"
/usr/libexec/PlistBuddy -c "Print :com.apple.security.cs.allow-unsigned-executable-memory" "$RUNNER_TEMP/macos-entitlements.plist"
codesign --verify --deep --strict --verbose=2 "$APP_PATH"
- name: Notarize Application
@@ -314,6 +374,7 @@ jobs:
macos-dmg-size.txt
build-windows-x64:
if: ${{ inputs.build_windows }}
runs-on: windows-latest
permissions:
contents: read
@@ -324,22 +385,36 @@ jobs:
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 }}-pub-${{ hashFiles('**/pubspec.lock') }}
restore-keys: |
${{ runner.os }}-pub-
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
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 }}
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
@@ -348,35 +423,54 @@ jobs:
path: build/windows/x64/runner/Release/
build-windows-arm64:
if: ${{ inputs.build_windows }}
runs-on: windows-11-arm
permissions:
contents: read
steps:
- uses: actions/checkout@v4
- name: Cache Windows native dependencies
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') }}
- name: Install 7-Zip
if: steps.windows-native-cache.outputs.cache-hit != 'true'
run: choco install 7zip -y
- 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: |
~\AppData\Local\Pub\Cache
key: ${{ runner.os }}-arm64-pub-${{ hashFiles('**/pubspec.lock') }}
restore-keys: |
${{ runner.os }}-arm64-pub-
key: ${{ runner.os }}-${{ runner.arch }}-pub-v2-${{ hashFiles('pubspec.yaml', 'pubspec.lock') }}
- name: Install dependencies
run: flutter pub get
run: flutter pub get --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 }}
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: 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
- name: Upload arm64 build
uses: actions/upload-artifact@v4
@@ -386,6 +480,7 @@ jobs:
package-windows:
needs: [build-windows-x64, build-windows-arm64]
if: ${{ inputs.build_windows }}
runs-on: windows-latest
permissions:
id-token: write
@@ -468,6 +563,7 @@ jobs:
win-installer-size.txt
build-linux-x64:
if: ${{ inputs.build_linux }}
runs-on: ubuntu-latest
permissions:
id-token: write
@@ -480,27 +576,38 @@ jobs:
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-${{ hashFiles('**/pubspec.lock') }}
restore-keys: |
${{ runner.os }}-pub-
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: clang cmake meson ninja-build pkg-config nasm libgtk-3-dev libevdev-dev liblzma-dev libstdc++-12-dev libasound2-dev libass-dev libfreetype-dev libfontconfig-dev libfribidi-dev libharfbuzz-dev libepoxy-dev libegl-dev libgl-dev libgnutls28-dev libpipewire-0.3-dev libva-dev libvdpau-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxss-dev libxpresent-dev libxkbcommon-dev libpulse-dev libdbus-1-dev libdrm-dev libgbm-dev libwayland-dev wayland-protocols liblcms2-dev ruby ruby-dev rubygems build-essential rpm libarchive-tools imagemagick libcurl4-openssl-dev
packages: ${{ env.LINUX_APT_PACKAGES }}
version: 1.1
- name: Install Linux dependencies
run: |
sudo apt-get update
sudo apt-get install -y clang cmake meson ninja-build pkg-config nasm libgtk-3-dev libevdev-dev liblzma-dev libstdc++-12-dev libasound2-dev libass-dev libfreetype-dev libfontconfig-dev libfribidi-dev libharfbuzz-dev libepoxy-dev libegl-dev libgl-dev libgnutls28-dev libpipewire-0.3-dev libva-dev libvdpau-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxss-dev libxpresent-dev libxkbcommon-dev libpulse-dev libdbus-1-dev libdrm-dev libgbm-dev libwayland-dev wayland-protocols liblcms2-dev ruby ruby-dev rubygems build-essential rpm libarchive-tools imagemagick libcurl4-openssl-dev
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
@@ -517,13 +624,20 @@ jobs:
run: sudo gem install fpm
- name: Install dependencies
run: flutter pub get
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 }}
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
env:
PKG_CONFIG_PATH: ${{ github.workspace }}/libmpv-prefix/lib/pkgconfig:${{ github.workspace }}/libmpv-prefix/lib/x86_64-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-x64
run: ./scripts/upload-symbols.sh linux-x64
- name: Build Linux Packages
run: ARCH_SUFFIX=x64 OUTPUT_DIR=$GITHUB_WORKSPACE python3 linux/packaging/build-packages.py
@@ -576,6 +690,7 @@ jobs:
plezy-linux-x64.pkg.tar.zst
build-linux-arm64:
if: ${{ inputs.build_linux }}
runs-on: ubuntu-24.04-arm
permissions:
id-token: write
@@ -588,27 +703,38 @@ jobs:
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 }}-arm64-pub-${{ hashFiles('**/pubspec.lock') }}
restore-keys: |
${{ runner.os }}-arm64-pub-
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: clang cmake meson ninja-build pkg-config nasm libgtk-3-dev libevdev-dev liblzma-dev libstdc++-12-dev libasound2-dev libass-dev libfreetype-dev libfontconfig-dev libfribidi-dev libharfbuzz-dev libepoxy-dev libegl-dev libgl-dev libgnutls28-dev libpipewire-0.3-dev libva-dev libvdpau-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxss-dev libxpresent-dev libxkbcommon-dev libpulse-dev libdbus-1-dev libdrm-dev libgbm-dev libwayland-dev wayland-protocols liblcms2-dev ruby ruby-dev rubygems build-essential rpm libarchive-tools imagemagick libcurl4-openssl-dev
packages: ${{ env.LINUX_APT_PACKAGES }}
version: 1.1
- name: Install Linux dependencies
run: |
sudo apt-get update
sudo apt-get install -y clang cmake meson ninja-build pkg-config nasm libgtk-3-dev libevdev-dev liblzma-dev libstdc++-12-dev libasound2-dev libass-dev libfreetype-dev libfontconfig-dev libfribidi-dev libharfbuzz-dev libepoxy-dev libegl-dev libgl-dev libgnutls28-dev libpipewire-0.3-dev libva-dev libvdpau-dev libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxss-dev libxpresent-dev libxkbcommon-dev libpulse-dev libdbus-1-dev libdrm-dev libgbm-dev libwayland-dev wayland-protocols liblcms2-dev ruby ruby-dev rubygems build-essential rpm libarchive-tools imagemagick libcurl4-openssl-dev
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
@@ -625,13 +751,20 @@ jobs:
run: sudo gem install fpm
- name: Install dependencies
run: flutter pub get
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 }}
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: |
@@ -694,7 +827,8 @@ jobs:
plezy-linux-arm64.pkg.tar.zst
create-release:
needs: [build-android, build-ios, build-macos, package-windows, build-linux-x64, build-linux-arm64]
needs: [build-android, build-ios, build-macos, build-windows-x64, build-windows-arm64, package-windows, build-linux-x64, build-linux-arm64]
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:
contents: write
@@ -704,10 +838,61 @@ jobs:
sparse-checkout: pubspec.yaml
sparse-checkout-cone-mode: false
- name: Download all artifacts
- name: Download Android artifacts
if: ${{ inputs.build_android }}
uses: actions/download-artifact@v4
with:
path: artifacts
name: android-apk
path: artifacts/android-apk
- name: Download iOS artifact
if: ${{ inputs.build_ios }}
uses: actions/download-artifact@v4
with:
name: ios-ipa
path: artifacts/ios-ipa
- name: Download macOS artifact
if: ${{ inputs.build_macos }}
uses: actions/download-artifact@v4
with:
name: macos-dmg
path: artifacts/macos-dmg
- name: Download Windows x64 artifact
if: ${{ inputs.build_windows }}
uses: actions/download-artifact@v4
with:
name: windows-x64-portable
path: artifacts/windows-x64-portable
- name: Download Windows arm64 artifact
if: ${{ inputs.build_windows }}
uses: actions/download-artifact@v4
with:
name: windows-arm64-portable
path: artifacts/windows-arm64-portable
- name: Download Windows installer artifact
if: ${{ inputs.build_windows }}
uses: actions/download-artifact@v4
with:
name: windows-installer
path: artifacts/windows-installer
- name: Download Linux x64 artifacts
if: ${{ inputs.build_linux }}
uses: actions/download-artifact@v4
with:
name: linux-x64
path: artifacts/linux-x64
- name: Download Linux arm64 artifacts
if: ${{ inputs.build_linux }}
uses: actions/download-artifact@v4
with:
name: linux-arm64
path: artifacts/linux-arm64
- name: Display structure of downloaded files
run: ls -R artifacts
@@ -790,21 +975,39 @@ jobs:
echo "Generated appcast.xml:"
cat appcast.xml
- name: Collect release files
id: release-files
run: |
{
echo 'files<<EOF'
if [ "${{ inputs.build_android }}" = "true" ]; then
echo artifacts/android-apk/plezy-android-arm64-v8a.tar.gz
echo artifacts/android-apk/plezy-android-armeabi-v7a.tar.gz
echo artifacts/android-apk/plezy-android-x86_64.tar.gz
fi
if [ "${{ inputs.build_ios }}" = "true" ]; then
echo artifacts/ios-ipa/plezy-ios.ipa
fi
if [ "${{ inputs.build_macos }}" = "true" ]; then
echo artifacts/macos-dmg/plezy-macos.dmg
fi
if [ "${{ inputs.build_windows }}" = "true" ]; then
echo artifacts/windows-x64-portable/plezy-windows-x64-portable.7z
echo artifacts/windows-arm64-portable/plezy-windows-arm64-portable.7z
echo artifacts/windows-installer/plezy-windows-installer.exe
fi
if [ "${{ inputs.build_linux }}" = "true" ]; then
echo 'artifacts/linux-x64/*'
echo 'artifacts/linux-arm64/*'
fi
echo appcast.xml
echo EOF
} >> "$GITHUB_OUTPUT"
- name: Create Release
uses: softprops/action-gh-release@v1
with:
files: |
artifacts/android-apk/plezy-android-arm64-v8a.tar.gz
artifacts/android-apk/plezy-android-armeabi-v7a.tar.gz
artifacts/android-apk/plezy-android-x86_64.tar.gz
artifacts/ios-ipa/plezy-ios.ipa
artifacts/macos-dmg/plezy-macos.dmg
artifacts/windows-x64-portable/plezy-windows-x64-portable.7z
artifacts/windows-arm64-portable/plezy-windows-arm64-portable.7z
artifacts/windows-installer/plezy-windows-installer.exe
artifacts/linux-x64/*
artifacts/linux-arm64/*
appcast.xml
files: ${{ steps.release-files.outputs.files }}
draft: true
prerelease: false
generate_release_notes: true
+36 -9
View File
@@ -23,22 +23,31 @@ jobs:
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-v2-${{ hashFiles('**/pubspec.lock') }}
restore-keys: |
${{ runner.os }}-pub-v2-
key: ${{ runner.os }}-pub-v3-${{ hashFiles('**/pubspec.yaml', '**/pubspec.lock') }}
- name: Install dependencies
run: |
flutter pub get
- name: Verify generated files committed
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
- name: Verify formatting
run: |
# Find all Dart files excluding generated files
@@ -106,16 +115,16 @@ jobs:
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-v2-${{ hashFiles('**/pubspec.lock') }}
restore-keys: |
${{ runner.os }}-pub-v2-
key: ${{ runner.os }}-pub-v3-${{ hashFiles('**/pubspec.yaml', '**/pubspec.lock') }}
- name: Install dependencies
run: |
@@ -130,6 +139,24 @@ jobs:
echo "No tests found, skipping test execution"
fi
native-format:
name: Native Formatting
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: Verify native formatting
run: scripts/format_native.sh --check
dependency-check:
name: Dependency Validation
runs-on: ubuntu-latest
@@ -143,16 +170,16 @@ jobs:
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-v2-${{ hashFiles('**/pubspec.lock') }}
restore-keys: |
${{ runner.os }}-pub-v2-
key: ${{ runner.os }}-pub-v3-${{ hashFiles('**/pubspec.yaml', '**/pubspec.lock') }}
- name: Verify dependencies
run: |
-27
View File
@@ -1,27 +0,0 @@
name: SonarQube
on:
workflow_dispatch:
jobs:
sonarqube:
name: SonarQube
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Flutter
uses: subosito/flutter-action@v2
with:
channel: "stable"
cache: true
- name: Install dependencies
run: flutter pub get
- name: SonarQube Scan
uses: SonarSource/sonarqube-scan-action@v6
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
+16
View File
@@ -34,6 +34,20 @@ migrate_working_dir/
/build/
/debug-info/
# tvOS: build artifacts and generated assets (regenerated by xcode_appletv.sh)
tvos/build/
tvos/Pods/
tvos/Podfile.lock
tvos/Runner.xcworkspace/xcuserdata/
tvos/Runner.xcodeproj/xcuserdata/
tvos/Runner.xcodeproj/project.xcworkspace/xcuserdata/
tvos/Flutter/Generated.xcconfig
tvos/Flutter/flutter_export_environment.sh
tvos/Flutter/libPods-Runner.a
tvos/tvos_flutter_assets/
tvos/Runner/GeneratedPluginRegistrant.h
tvos/Runner/GeneratedPluginRegistrant.m
# Symbolication related
app.*.symbols
@@ -55,3 +69,5 @@ duplication-report/
**/fastlane/**/
**/fastlane/report.xml
maestro/**/*.png
server/deploy.sh
-21
View File
@@ -1,21 +0,0 @@
{
"threshold": 5,
"reporters": ["html", "console"],
"ignore": [
"**/*.g.dart",
"**/*.freezed.dart",
"**/*.mocks.dart",
"**/generated/**",
"**/*.config.dart"
],
"absolute": true,
"gitignore": true,
"format": ["dart"],
"minLines": 5,
"minTokens": 50,
"output": "./duplication-report",
"mode": "strict",
"formatsExts": {
"dart": ["dart"]
}
}
+10
View File
@@ -0,0 +1,10 @@
{
"indentation" : {
"spaces" : 2
},
"lineLength" : 120,
"maximumBlankLines" : 1,
"respectsExistingLineBreaks" : true,
"rules" : {},
"version" : 1
}
+5 -3
View File
@@ -10,7 +10,8 @@
## Development
- Follow Dart/Flutter conventions
- Run `dart format .` to format your code (note: generated files like `*.g.dart` are excluded from CI checks)
- Run `dart format .` to format Dart code (note: generated files like `*.g.dart` are excluded from CI checks)
- Run `scripts/format_native.sh --fix` to format Kotlin, Swift, C++, C, Objective-C, and native headers
- Run `flutter analyze` before submitting to check for issues
- Run `flutter test` if tests are available
- Test your changes thoroughly
@@ -19,8 +20,9 @@
The project includes automated CI checks that run on all pull requests:
1. **Code Formatting**: Ensures code follows Dart formatting standards
- Run locally: `dart format .` to format all files
1. **Code Formatting**: Ensures code follows Dart and native formatting standards
- Run locally: `dart format .` to format Dart files
- Run locally: `scripts/format_native.sh --fix` to format native files
- Note: CI only checks non-generated files (excludes `.g.dart`, `.freezed.dart`)
- Generated files are reformatted automatically by build tools
+3 -3
View File
@@ -1,10 +1,10 @@
cask "plezy" do
version "1.31.1"
sha256 "8f10cf123a1e3afdb8f386ce822170bc7eb1df6b9d50077d449d6891c1528505"
version "2.7.1"
sha256 "b649195b030add21f3901dabfc90e3f893e08171c51928a7327f19b4ac9150c5"
url "https://github.com/edde746/plezy/releases/download/#{version}/plezy-macos.dmg"
name "Plezy"
desc "Modern Plex client built with Flutter"
desc "Modern Plex and Jellyfin client built with Flutter"
homepage "https://github.com/edde746/plezy"
livecheck do
+102 -38
View File
@@ -3,13 +3,19 @@
Plezy
</h1>
A modern Plex client for desktop and mobile. Built with Flutter for native performance and a clean interface.
A modern client for Plex and Jellyfin on desktop, mobile, and TV. Built with Flutter for native performance and a clean interface.
<p align="center">
<img src="assets/screenshots/macos-home.png" alt="Plezy macOS Home Screen" width="800" />
<p>
<a href="https://plezy.app">Website</a> ·
<a href="https://plezy.app/#screenshots">Screenshots</a> ·
<a href="#download">Download</a> ·
<a href="CONTRIBUTING.md">Contributing</a> ·
<a href="LICENSE">License</a>
</p>
*More screenshots in the [screenshots folder](assets/screenshots/#readme)*
<p align="center">
<img src="assets/readme-showcase.webp" alt="Plezy mobile screenshots" width="900" />
</p>
## Download
@@ -17,9 +23,15 @@ A modern Plex client for desktop and mobile. Built with Flutter for native perfo
<a href='https://play.google.com/store/apps/details?id=com.edde746.plezy'><img height='60' alt='Get it on Google Play' src='./assets/play-store-badge.png'/></a>
<a href='https://www.amazon.com/gp/product/B0GK65CVS1'><img height='60' alt='Available at the Amazon App Store' src='./assets/amazon-badge.png'/></a>
- [Windows (x64, arm64)](https://github.com/edde746/plezy/releases/latest/download/plezy-windows-installer.exe)
- [macOS (x64, arm64)](https://github.com/edde746/plezy/releases/latest/download/plezy-macos.dmg)
- [Linux (x64, arm64)](https://github.com/edde746/plezy/releases/latest) - .deb, .rpm, .pkg.tar.zst, and portable tar.gz available
| Platform | Download |
| --- | --- |
| Windows | [Installer (x64, arm64)](https://github.com/edde746/plezy/releases/latest/download/plezy-windows-installer.exe) · [Portable x64](https://github.com/edde746/plezy/releases/latest/download/plezy-windows-x64-portable.7z) · [Portable arm64](https://github.com/edde746/plezy/releases/latest/download/plezy-windows-arm64-portable.7z) |
| macOS | [DMG (x64, arm64)](https://github.com/edde746/plezy/releases/latest/download/plezy-macos.dmg) |
| Linux x64 | [.deb](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-x64.deb) · [.rpm](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-x64.rpm) · [.pkg.tar.zst](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-x64.pkg.tar.zst) · [portable tar.gz](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-x64.tar.gz) |
| Linux arm64 | [.deb](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-arm64.deb) · [.rpm](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-arm64.rpm) · [.pkg.tar.zst](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-arm64.pkg.tar.zst) · [portable tar.gz](https://github.com/edde746/plezy/releases/latest/download/plezy-linux-arm64.tar.gz) |
Package managers:
- [Nix](https://search.nixos.org/packages?channel=unstable&query=plezy) - Community package by [@mio-19](https://github.com/mio-19) and [@MiniHarinn](https://github.com/MiniHarinn)
- **Homebrew** (macOS):
```bash
@@ -32,48 +44,74 @@ A modern Plex client for desktop and mobile. Built with Flutter for native perfo
```
- **WinGet** (Windows):
```bash
winget install edde746.plezy
winget install edde746.Plezy
```
## Features
### 🔐 Authentication
- Sign in with Plex
- Automatic server discovery and smart connection selection
- Persistent sessions with auto-login
### <img src="assets/readme_icons/browse.svg" height="20" alt="" align="center" /> Browse & Discover
- Libraries, collections, and playlists
- Discover hub — Continue Watching, Next Up, trending, and recommendations
- Cross-server search
- Filtering, sorting, and alphabetical jump navigation
- Extras — trailers, deleted scenes, behind-the-scenes
### 📚 Media Browsing
- Browse libraries with rich metadata
- Advanced search across all media
- Collections and playlists
### 🎬 Playback
### <img src="assets/readme_icons/playback.svg" height="20" alt="" align="center" /> Playback
- Wide codec support (HEVC, AV1, VP9, and more)
- HDR and Dolby Vision (not Linux)
- Full ASS/SSA subtitle support
- Audio and subtitle preferences synced with Plex profile
- HDR and Dolby Vision[^1]
- Full ASS/SSA subtitles with customizable styling
- Online subtitle search & download[^2]
- Audio & subtitle choices remembered per title
- Progress sync and resume
- Auto-play next episode
- Auto-play next episode with skip intro / skip credits
- Chapter navigation with thumbnail scrub previews
- Playback speed, audio sync offset, sleep timer
- Ambient lighting and GLSL shader presets[^3]
- Picture-in-Picture[^4]
- Refresh-rate matching[^5]
- External player launch (VLC, MX Player, etc.)
### 📺 Live TV & DVR
- EPG guide grid
- Channel tuning
- DVR recording rules and scheduled recordings
- Multi-server DVR support
### <img src="assets/readme_icons/live-tv.svg" height="20" alt="" align="center" /> Live TV & DVR
- Live TV channel browsing with favorites
- DVR support with EPG guide, recording rules, and scheduled recordings[^2]
- Multi-server Live TV support where available
### 📥 Downloads
### <img src="assets/readme_icons/downloads.svg" height="20" alt="" align="center" /> Downloads & Offline
- Download media for offline viewing
- Background downloads with queue management
- Background queue with pause / resume
- Sync rules for automatic downloads
- Offline browsing with watch state sync-back on reconnect
### 👥 Watch Together
### <img src="assets/readme_icons/watch-together.svg" height="20" alt="" align="center" /> Watch Together
- Synchronized playback with friends
- Real-time play/pause and seek sync
- Real-time play / pause / seek sync
### <img src="assets/readme_icons/integrations.svg" height="20" alt="" align="center" /> Integrations
- Discord Rich Presence[^7]
- Trakt, MyAnimeList, AniList, and Simkl tracking & rating
- Plezy Remote — control desktop and TV from mobile
- Watch Next row[^6]
### <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]
- Settings import/export
- Localized in English plus 14 translations
[^1]: Not available on Linux.
[^2]: Plex only.
[^3]: Not available on iOS or tvOS.
[^4]: Android, iOS, and macOS.
[^5]: Windows, Android, and tvOS.
[^6]: Android TV only.
[^7]: Desktop only.
## Building from Source
### Prerequisites
- Flutter SDK 3.8.1+
- A Plex account with server access
- Flutter SDK 3.38.4+
- A Plex account or Jellyfin server with user credentials
### Setup
@@ -81,20 +119,46 @@ A modern Plex client for desktop and mobile. Built with Flutter for native perfo
git clone https://github.com/edde746/plezy.git
cd plezy
flutter pub get
dart run build_runner build
scripts/codegen.sh
flutter run
```
### Code Generation
After modifying model classes:
After modifying model classes or other generated sources:
```bash
dart run build_runner build --delete-conflicting-outputs
scripts/codegen.sh
```
After modifying translations:
```bash
dart run slang
```
### Local Checks
```bash
scripts/ci_checks.sh
```
To install the same pre-commit checks locally:
```bash
scripts/setup_hooks.sh
```
## Contributing
See [CONTRIBUTING.md](CONTRIBUTING.md) for development workflow, formatting, tests, and translation guidelines.
## License
Plezy is licensed under [GPL-3.0](LICENSE).
## Acknowledgments
- Built with [Flutter](https://flutter.dev)
- Designed for [Plex Media Server](https://www.plex.tv)
- Playback powered by [mpv](https://mpv.io) via [MPVKit](https://github.com/mpvkit/MPVKit) and [libmpv-android](https://github.com/jarnedemeulemeester/libmpv-android)
- Supports [Plex Media Server](https://www.plex.tv) and [Jellyfin](https://jellyfin.org)
- Playback powered by [mpv](https://mpv.io), [MPVKit](https://github.com/mpvkit/MPVKit), Android [ExoPlayer](https://developer.android.com/media/media3/exoplayer), [libass-android](https://github.com/peerless2012/libass-android), and [libmpv-android](https://github.com/jarnedemeulemeester/libmpv-android)
+10
View File
@@ -7,6 +7,16 @@ analyzer:
plugins:
- dart_code_linter
linter:
rules:
unawaited_futures: true
cancel_subscriptions: true
close_sinks: true
use_super_parameters: true
prefer_final_locals: true
prefer_final_in_for_each: true
avoid_print: true
dart_code_linter:
extends:
- package:dart_code_linter/presets/recommended.yaml
+159 -137
View File
@@ -1,191 +1,213 @@
import java.util.Properties
import java.io.FileInputStream
import java.util.Properties
plugins {
id("com.android.application")
id("kotlin-android")
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
id("dev.flutter.flutter-gradle-plugin")
id("com.android.application")
id("kotlin-android")
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
id("dev.flutter.flutter-gradle-plugin")
}
val mpvVersion = "v1.0.6"
val mpvVersion = "v1.0.7"
val mpvDir = layout.buildDirectory.dir("libmpv").get().asFile
val mpvAar = "libmpv-release.aar"
val downloadLibmpv by tasks.registering {
val stamp = File(mpvDir, ".version")
outputs.upToDateWhen { stamp.exists() && stamp.readText().trim() == mpvVersion }
doLast {
mpvDir.mkdirs()
val url = "https://github.com/edde746/libmpv-android/releases/download/$mpvVersion/$mpvAar"
exec { commandLine("curl", "-sfL", url, "-o", File(mpvDir, mpvAar).absolutePath) }
stamp.writeText(mpvVersion)
}
val stamp = File(mpvDir, ".version")
outputs.upToDateWhen { stamp.exists() && stamp.readText().trim() == mpvVersion }
doLast {
mpvDir.mkdirs()
val url = "https://github.com/edde746/libmpv-android/releases/download/$mpvVersion/$mpvAar"
exec { commandLine("curl", "-sfL", url, "-o", File(mpvDir, mpvAar).absolutePath) }
stamp.writeText(mpvVersion)
}
}
val assVersion = "safety-2"
val assDir = layout.buildDirectory.dir("libass").get().asFile
val assAars = listOf("lib_ass-release.aar", "lib_ass_kt-release.aar", "lib_ass_media-release.aar")
val downloadLibass by tasks.registering {
val stamp = File(assDir, ".version")
outputs.upToDateWhen { stamp.exists() && stamp.readText().trim() == assVersion }
doLast {
assDir.mkdirs()
val baseUrl = "https://github.com/edde746/libass-android/releases/download/$assVersion"
assAars.forEach { name ->
val dest = File(assDir, name)
exec { commandLine("curl", "-sfL", "$baseUrl/$name", "-o", dest.absolutePath) }
}
stamp.writeText(assVersion)
// Extract libc++_shared.so from the libmpv AAR so the app source set can package
// it with top merge priority (see packaging { jniLibs } and sourceSets below).
val extractMpvLibcxx by tasks.registering {
dependsOn(downloadLibmpv)
val aar = File(mpvDir, mpvAar)
val outDir = File(mpvDir, "libcxx")
inputs.file(aar)
outputs.dir(outDir)
doLast {
outDir.deleteRecursively() // drop stale ABIs from a previous AAR version
outDir.mkdirs()
exec {
commandLine(
"unzip",
"-q",
"-o",
aar.absolutePath,
"jni/*/libc++_shared.so",
"-d",
outDir.absolutePath
)
}
}
}
val doviVersion = "2.3.1"
val doviDir = layout.buildDirectory.dir("libdovi").get().asFile
val doviAbis = mapOf(
"arm64-v8a" to "aarch64-linux-android",
"armeabi-v7a" to "armv7-linux-androideabi",
"x86" to "i686-linux-android",
"x86_64" to "x86_64-linux-android",
"arm64-v8a" to "aarch64-linux-android",
"armeabi-v7a" to "armv7-linux-androideabi",
"x86" to "i686-linux-android",
"x86_64" to "x86_64-linux-android"
)
val downloadLibdovi by tasks.registering {
val stamp = File(doviDir, ".version")
outputs.upToDateWhen { stamp.exists() && stamp.readText().trim() == doviVersion }
doLast {
doviDir.mkdirs()
val baseUrl = "https://github.com/edde746/libdovi-builds/releases/download/v$doviVersion"
doviAbis.forEach { (abi, triple) ->
val archive = File(doviDir, "$triple.tar.gz")
exec { commandLine("curl", "-sfL", "$baseUrl/libdovi-$triple.tar.gz", "-o", archive.absolutePath) }
val outDir = File(doviDir, "$abi/lib")
outDir.mkdirs()
exec { commandLine("tar", "-xzf", archive.absolutePath, "-C", outDir.absolutePath) }
archive.delete()
}
stamp.writeText(doviVersion)
val stamp = File(doviDir, ".version")
outputs.upToDateWhen { stamp.exists() && stamp.readText().trim() == doviVersion }
doLast {
doviDir.mkdirs()
val baseUrl = "https://github.com/edde746/libdovi-builds/releases/download/v$doviVersion"
doviAbis.forEach { (abi, triple) ->
val archive = File(doviDir, "$triple.tar.gz")
exec { commandLine("curl", "-sfL", "$baseUrl/libdovi-$triple.tar.gz", "-o", archive.absolutePath) }
val outDir = File(doviDir, "$abi/lib")
outDir.mkdirs()
exec { commandLine("tar", "-xzf", archive.absolutePath, "-C", outDir.absolutePath) }
archive.delete()
}
stamp.writeText(doviVersion)
}
}
android {
namespace = "com.edde746.plezy"
compileSdk = flutter.compileSdkVersion
ndkVersion = flutter.ndkVersion
namespace = "com.edde746.plezy"
compileSdk = flutter.compileSdkVersion
ndkVersion = flutter.ndkVersion
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
kotlinOptions {
jvmTarget = JavaVersion.VERSION_11.toString()
}
kotlinOptions {
jvmTarget = JavaVersion.VERSION_11.toString()
}
defaultConfig {
applicationId = "com.edde746.plezy"
// You can update the following values to match your application needs.
// For more information, see: https://flutter.dev/to/review-gradle-config.
minSdk = 25 // Fire OS 6.x (API 25); overrides libmpv-android's minSdk=26
targetSdk = flutter.targetSdkVersion
versionCode = flutter.versionCode
versionName = flutter.versionName
externalNativeBuild {
cmake {
arguments += listOf(
"-DDOVI_ENABLE_LIBDOVI=ON",
"-DDOVI_LIBDOVI_PREBUILT_ROOT=${doviDir.absolutePath}"
)
}
}
if (System.getenv("AMAZON") != null) {
versionCode = (flutter.versionCode ?: 0) + 3000
ndk {
abiFilters += listOf("armeabi-v7a", "arm64-v8a")
}
}
}
defaultConfig {
applicationId = "com.edde746.plezy"
// You can update the following values to match your application needs.
// For more information, see: https://flutter.dev/to/review-gradle-config.
minSdk = 25 // Fire OS 6.x (API 25); overrides libmpv-android's minSdk=26
targetSdk = flutter.targetSdkVersion
versionCode = flutter.versionCode
versionName = flutter.versionName
externalNativeBuild {
cmake {
path = file("src/main/cpp/CMakeLists.txt")
}
cmake {
arguments += listOf(
"-DDOVI_ENABLE_LIBDOVI=ON",
"-DDOVI_LIBDOVI_PREBUILT_ROOT=${doviDir.absolutePath}"
)
}
}
signingConfigs {
create("release") {
val keystorePropertiesFile = rootProject.file("key.properties")
if (keystorePropertiesFile.exists()) {
val keystoreProperties = Properties()
keystoreProperties.load(FileInputStream(keystorePropertiesFile))
keyAlias = keystoreProperties["keyAlias"] as String
keyPassword = keystoreProperties["keyPassword"] as String
storeFile = file(keystoreProperties["storeFile"] as String)
storePassword = keystoreProperties["storePassword"] as String
}
}
if (System.getenv("AMAZON") != null) {
versionCode = (flutter.versionCode ?: 0) + 3000
ndk {
abiFilters += listOf("armeabi-v7a", "arm64-v8a")
}
}
}
buildTypes {
release {
// Only use release signing if key.properties exists (not in CI/CD)
val keystorePropertiesFile = rootProject.file("key.properties")
if (keystorePropertiesFile.exists()) {
signingConfig = signingConfigs.getByName("release")
}
// If key.properties doesn't exist, it will use debug signing for CI builds
ndk {
debugSymbolLevel = "FULL"
}
}
externalNativeBuild {
cmake {
path = file("src/main/cpp/CMakeLists.txt")
}
}
packaging {
jniLibs {
// Resolve conflict between libass-android and libmpv native libraries
pickFirsts.add("lib/*/libc++_shared.so")
}
signingConfigs {
create("release") {
val keystorePropertiesFile = rootProject.file("key.properties")
if (keystorePropertiesFile.exists()) {
val keystoreProperties = Properties()
keystoreProperties.load(FileInputStream(keystorePropertiesFile))
keyAlias = keystoreProperties["keyAlias"] as String
keyPassword = keystoreProperties["keyPassword"] as String
storeFile = file(keystoreProperties["storeFile"] as String)
storePassword = keystoreProperties["storePassword"] as String
}
}
}
buildTypes {
release {
// Only use release signing if key.properties exists (not in CI/CD)
val keystorePropertiesFile = rootProject.file("key.properties")
if (keystorePropertiesFile.exists()) {
signingConfig = signingConfigs.getByName("release")
}
// If key.properties doesn't exist, it will use debug signing for CI builds
ndk {
debugSymbolLevel = "FULL"
}
}
}
packaging {
jniLibs {
// pickFirst only suppresses the duplicate libc++ merge error; the
// sourceSets rule below makes libmpv's newer runtime win for
// std::from_chars<float>, while older native consumers remain ABI-compatible.
pickFirsts.add("lib/*/libc++_shared.so")
}
}
sourceSets {
getByName("main") {
// PROJECT-scope jniLibs merge ahead of subprojects/AARs, so dependency
// order cannot accidentally select the older libc++ copy.
jniLibs.srcDir(File(mpvDir, "libcxx/jni"))
}
}
}
flutter {
source = "../.."
source = "../.."
}
// Download libdovi before any CMake/native build task
tasks.matching { it.name.contains("CMake") || it.name.contains("externalNative") }.configureEach {
dependsOn(downloadLibdovi)
dependsOn(downloadLibdovi)
}
// Download libmpv and libass AARs before compilation
tasks.matching { it.name.startsWith("pre") && it.name.endsWith("Build") }.configureEach {
dependsOn(downloadLibmpv)
dependsOn(downloadLibass)
dependsOn(downloadLibmpv, extractMpvLibcxx)
}
// 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)
}
dependencies {
implementation(files(File(mpvDir, mpvAar)))
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0")
implementation(files(File(mpvDir, mpvAar)))
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0")
// Android TV Watch Next integration
implementation("androidx.tvprovider:tvprovider:1.0.0")
// Android TV Watch Next integration
implementation("androidx.tvprovider:tvprovider:1.0.0")
// Media3 ExoPlayer for Android
implementation("androidx.media3:media3-exoplayer:1.9.2")
implementation("androidx.media3:media3-ui:1.9.2")
implementation("androidx.media3:media3-common:1.9.2")
// Media3 ExoPlayer for Android
implementation("androidx.media3:media3-exoplayer:1.9.2")
implementation("androidx.media3:media3-exoplayer-hls:1.9.2")
implementation("androidx.media3:media3-ui:1.9.2")
implementation("androidx.media3:media3-common:1.9.2")
// Cronet for HTTP/2 multiplexing + better connection management
implementation("androidx.media3:media3-datasource-cronet:1.9.2")
implementation("org.chromium.net:cronet-embedded:143.7445.0")
// Cronet for HTTP/2 multiplexing + better connection management
implementation("androidx.media3:media3-datasource-cronet:1.9.2")
implementation("org.chromium.net:cronet-embedded:143.7445.0")
// FFmpeg audio decoder for unsupported codecs (ALAC, DTS, TrueHD, etc.)
implementation("org.jellyfin.media3:media3-ffmpeg-decoder:1.9.0+1")
// FFmpeg audio decoder for unsupported codecs (ALAC, DTS, TrueHD, etc.)
implementation("org.jellyfin.media3:media3-ffmpeg-decoder:1.9.0+1")
// libass-android for ASS/SSA subtitle rendering
assAars.forEach { implementation(files(File(assDir, it))) }
// Keeping libass in-project lets its static core share the app's native
// packaging rules.
implementation(project(":libass"))
testImplementation("junit:junit:4.13.2")
}
+6 -2
View File
@@ -5,13 +5,13 @@
<!-- Internet access permissions -->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
<!-- Camera permission for QR code scanning (companion remote pairing) -->
<uses-permission android:name="android.permission.CAMERA"/>
<!-- PIP and media session foreground service permissions -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK"/>
<uses-permission android:name="android.permission.REORDER_TASKS"/>
<!-- Background download notifications and foreground service -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
@@ -23,6 +23,7 @@
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" tools:node="remove" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" tools:node="remove" />
<!-- Android TV support (not required, but allow detection) -->
<uses-feature android:name="android.software.leanback" android:required="false" />
<!-- Android TV Watch Next integration -->
@@ -59,6 +60,9 @@
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<meta-data
android:name="flutter_deeplinking_enabled"
android:value="false" />
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
+103 -83
View File
@@ -1,7 +1,9 @@
#include <jni.h>
#include <android/log.h>
#include <jni.h>
#include <cstring>
#include <new>
#include <vector>
#define TAG "DoviBridge"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
@@ -12,115 +14,133 @@
#endif
static const char* BRIDGE_VERSION = "1.0.0";
static constexpr jint CONVERT_FAILED = -1;
static constexpr jint DESTINATION_TOO_SMALL = -2;
static constexpr jint MAX_RPU_INPUT_SIZE = 8192;
static constexpr size_t MAX_RPU_OUTPUT_SIZE = 16384;
extern "C" JNIEXPORT jbyteArray JNICALL
Java_com_edde746_plezy_exoplayer_DoviBridge_nativeConvertDv7RpuToDv81(
JNIEnv *env, jclass, jbyteArray payload, jint mode) {
extern "C" JNIEXPORT jint JNICALL Java_com_edde746_plezy_exoplayer_DoviBridge_nativeConvertDv7RpuToDv81(
JNIEnv* env, jclass, jbyteArray payload, jint payload_offset, jint payload_length, jbyteArray output,
jint output_offset, jint output_capacity, jint mode) {
#if !DOVI_REAL_LINKED
return nullptr;
return CONVERT_FAILED;
#else
if (payload == nullptr) return nullptr;
if (payload == nullptr || output == nullptr) return CONVERT_FAILED;
if (payload_offset < 0 || payload_length <= 0 || output_offset < 0 || output_capacity < 0) {
return CONVERT_FAILED;
}
jsize len = env->GetArrayLength(payload);
if (len <= 0) return nullptr;
const jsize payload_array_len = env->GetArrayLength(payload);
const jsize output_array_len = env->GetArrayLength(output);
if (payload_offset > payload_array_len || payload_length > payload_array_len - payload_offset) {
return CONVERT_FAILED;
}
if (output_offset > output_array_len) return DESTINATION_TOO_SMALL;
// Valid RPU NALs are typically <2 KiB; reject unreasonable sizes
if (len > 8192) {
LOGW("RPU payload too large (%d bytes), skipping", len);
return nullptr;
}
const jsize logical_output_len = output_capacity < output_array_len ? output_capacity : output_array_len;
if (output_offset > logical_output_len) return DESTINATION_TOO_SMALL;
// Copy to native heap so libdovi never touches JVM heap memory.
// GetByteArrayElements on ART may return a direct heap pointer; any
// out-of-bounds access by libdovi would corrupt adjacent JVM objects.
auto *buf = new (std::nothrow) uint8_t[static_cast<size_t>(len)];
if (buf == nullptr) return nullptr;
// Valid RPU NALs are typically <2 KiB; reject unreasonable sizes
if (payload_length > MAX_RPU_INPUT_SIZE) {
LOGW("RPU payload too large (%d bytes), skipping", payload_length);
return CONVERT_FAILED;
}
env->GetByteArrayRegion(payload, 0, len, reinterpret_cast<jbyte *>(buf));
if (env->ExceptionCheck()) {
delete[] buf;
return nullptr;
}
// Copy to native heap so libdovi never touches JVM heap memory.
// Do not use GetPrimitiveArrayCritical here: it can block concurrent GC
// compaction during sustained playback. A thread-local scratch buffer avoids
// per-frame heap churn while keeping libdovi away from JVM heap memory.
thread_local std::vector<uint8_t> scratch;
try {
scratch.resize(static_cast<size_t>(payload_length));
} catch (...) {
return CONVERT_FAILED;
}
// Try dovi_parse_unspec62_nalu first (handles escaped NALs), fallback to dovi_parse_rpu
DoviRpuOpaque *rpu = dovi_parse_unspec62_nalu(buf, static_cast<size_t>(len));
env->GetByteArrayRegion(payload, payload_offset, payload_length, reinterpret_cast<jbyte*>(scratch.data()));
if (env->ExceptionCheck()) {
return CONVERT_FAILED;
}
// Try dovi_parse_unspec62_nalu first (handles escaped NALs), fallback to dovi_parse_rpu
const auto rpu_len = static_cast<size_t>(payload_length);
DoviRpuOpaque* rpu = dovi_parse_unspec62_nalu(scratch.data(), rpu_len);
if (rpu == nullptr) {
return CONVERT_FAILED;
}
const char* err = dovi_rpu_get_error(rpu);
if (err != nullptr) {
// Fallback: try dovi_parse_rpu (raw RPU without NAL framing)
dovi_rpu_free(rpu);
rpu = dovi_parse_rpu(scratch.data(), rpu_len);
if (rpu == nullptr) {
delete[] buf;
return nullptr;
return CONVERT_FAILED;
}
const char *err = dovi_rpu_get_error(rpu);
err = dovi_rpu_get_error(rpu);
if (err != nullptr) {
// Fallback: try dovi_parse_rpu (raw RPU without NAL framing)
dovi_rpu_free(rpu);
rpu = dovi_parse_rpu(buf, static_cast<size_t>(len));
if (rpu == nullptr) {
delete[] buf;
return nullptr;
}
err = dovi_rpu_get_error(rpu);
if (err != nullptr) {
LOGW("RPU parse failed: %s", err);
dovi_rpu_free(rpu);
delete[] buf;
return nullptr;
}
LOGW("RPU parse failed: %s", err);
dovi_rpu_free(rpu);
return CONVERT_FAILED;
}
}
delete[] buf;
// Mode 2 matches Kodi's P8.1 compatibility path and sets luma/chroma curves to no-op.
int32_t ret = dovi_convert_rpu_with_mode(rpu, static_cast<uint8_t>(mode));
if (ret != 0) {
err = dovi_rpu_get_error(rpu);
LOGW("RPU conversion failed (mode %d): %s", mode, err ? err : "unknown");
dovi_rpu_free(rpu);
return CONVERT_FAILED;
}
// Convert to target profile (mode 2 = P8.1 with no-op curves)
int32_t ret = dovi_convert_rpu_with_mode(rpu, static_cast<uint8_t>(mode));
if (ret != 0) {
err = dovi_rpu_get_error(rpu);
LOGW("RPU conversion failed (mode %d): %s", mode, err ? err : "unknown");
dovi_rpu_free(rpu);
return nullptr;
}
// Write back as UNSPEC62 NAL
const DoviData *out = dovi_write_unspec62_nalu(rpu);
if (out == nullptr || out->data == nullptr || out->len == 0) {
err = dovi_rpu_get_error(rpu);
LOGW("RPU write failed: %s", err ? err : "unknown");
if (out != nullptr) dovi_data_free(out);
dovi_rpu_free(rpu);
return nullptr;
}
if (out->len > 16384) {
LOGW("RPU output unexpectedly large (%zu bytes), discarding", out->len);
dovi_data_free(out);
dovi_rpu_free(rpu);
return nullptr;
}
jbyteArray result = env->NewByteArray(static_cast<jsize>(out->len));
if (result != nullptr) {
env->SetByteArrayRegion(result, 0, static_cast<jsize>(out->len),
reinterpret_cast<const jbyte *>(out->data));
}
// Write back as UNSPEC62 NAL
const DoviData* out = dovi_write_unspec62_nalu(rpu);
if (out == nullptr || out->data == nullptr || out->len == 0) {
err = dovi_rpu_get_error(rpu);
LOGW("RPU write failed: %s", err ? err : "unknown");
if (out != nullptr) dovi_data_free(out);
dovi_rpu_free(rpu);
return CONVERT_FAILED;
}
if (out->len > MAX_RPU_OUTPUT_SIZE) {
LOGW("RPU output unexpectedly large (%zu bytes), discarding", out->len);
dovi_data_free(out);
dovi_rpu_free(rpu);
return CONVERT_FAILED;
}
return result;
const auto writable = static_cast<size_t>(logical_output_len - output_offset);
if (out->len > writable) {
dovi_data_free(out);
dovi_rpu_free(rpu);
return DESTINATION_TOO_SMALL;
}
env->SetByteArrayRegion(
output, output_offset, static_cast<jsize>(out->len), reinterpret_cast<const jbyte*>(out->data));
const bool write_failed = env->ExceptionCheck();
const auto written = static_cast<jint>(out->len);
dovi_data_free(out);
dovi_rpu_free(rpu);
return write_failed ? CONVERT_FAILED : written;
#endif
}
extern "C" JNIEXPORT jboolean JNICALL
Java_com_edde746_plezy_exoplayer_DoviBridge_nativeIsConversionPathReady(
JNIEnv *, jclass) {
Java_com_edde746_plezy_exoplayer_DoviBridge_nativeIsConversionPathReady(JNIEnv*, jclass) {
#if DOVI_REAL_LINKED
return JNI_TRUE;
return JNI_TRUE;
#else
return JNI_FALSE;
return JNI_FALSE;
#endif
}
extern "C" JNIEXPORT jstring JNICALL
Java_com_edde746_plezy_exoplayer_DoviBridge_nativeGetBridgeVersion(
JNIEnv *env, jclass) {
return env->NewStringUTF(BRIDGE_VERSION);
Java_com_edde746_plezy_exoplayer_DoviBridge_nativeGetBridgeVersion(JNIEnv* env, jclass) {
return env->NewStringUTF(BRIDGE_VERSION);
}
File diff suppressed because it is too large Load Diff
@@ -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,206 @@
package com.edde746.plezy.exoplayer
import android.media.audiofx.DynamicsProcessing
import android.media.audiofx.LoudnessEnhancer
import android.os.Build
import androidx.annotation.RequiresApi
/**
* Session-bound loudness normalization approximating mpv's
* `loudnorm=I=-14:TP=-3:LRA=4` filter (#1289).
*
* API 28+: DynamicsProcessing with a single full-range compressor band as a
* slow AGC plus a limiter for the true-peak ceiling. API 25-27, or when the
* device lacks the DynamicsProcessing effect HAL: LoudnessEnhancer (fixed
* makeup gain with built-in limiting).
*
* Effects bind to the audio session, so they survive AudioTrack re-creation
* (seeks, format changes) while the session id is stable. They only process
* PCM mixer streams — the caller must force decoded PCM output and disable
* tunneling while enabled. DynamicsProcessing parameters are per-channel, so
* the effect is re-created when the output channel count changes (dialogue
* lives in the center channel of 5.1 PCM).
*/
class AudioNormalizationEffect(private val log: (String, String, String) -> Unit) {
private companion object {
const val EFFECT_PRIORITY = 0
// DynamicsProcessing — tuned for movie mixes whose dialogue sits around
// -27 LUFS: compress above threshold, make up toward I=-14, limit at TP=-3.
const val FRAME_DURATION_MS = 10f
const val MBC_CUTOFF_HZ = 20_000f
const val MBC_ATTACK_MS = 30f
const val MBC_RELEASE_MS = 300f
const val MBC_RATIO = 4f
const val MBC_THRESHOLD_DB = -34f
const val MBC_KNEE_DB = 6f
const val MBC_NOISE_GATE_DB = -90f // effectively disabled
const val MBC_EXPANDER_RATIO = 1f // no downward expansion
const val MBC_POST_GAIN_DB = 15f
const val LIMITER_ATTACK_MS = 1f
const val LIMITER_RELEASE_MS = 60f
const val LIMITER_RATIO = 10f
const val LIMITER_THRESHOLD_DB = -3f
const val DEFAULT_CHANNEL_COUNT = 2
const val MAX_CHANNEL_COUNT = 8
// LoudnessEnhancer fallback: fixed boost, internally limited.
const val LOUDNESS_ENHANCER_GAIN_MB = 900 // +9 dB
}
private var dynamicsProcessing: DynamicsProcessing? = null
private var loudnessEnhancer: LoudnessEnhancer? = null
private var attachedSessionId = 0
private var attachedChannelCount = 0
val isActive: Boolean get() = dynamicsProcessing != null || loudnessEnhancer != null
/** For stats/QA: which engine is processing. */
val describe: String
get() = when {
dynamicsProcessing != null -> "DynamicsProcessing"
loudnessEnhancer != null -> "LoudnessEnhancer"
else -> "off"
}
/** Attach to [sessionId]; idempotent for an unchanged (session, channels) pair. */
fun attach(sessionId: Int, channelCount: Int?) {
val channels = (channelCount ?: DEFAULT_CHANNEL_COUNT).coerceIn(1, MAX_CHANNEL_COUNT)
if (sessionId == attachedSessionId && channels == attachedChannelCount && isActive) return
release()
if (sessionId == 0) return // AUDIO_SESSION_ID_UNSET — retry on onAudioSessionIdChanged
attachedSessionId = sessionId
attachedChannelCount = channels
if (Build.VERSION.SDK_INT >= 28 && tryDynamicsProcessing(sessionId, channels)) return
tryLoudnessEnhancer(sessionId)
}
fun release() {
dynamicsProcessing?.let { effect ->
runCatching { effect.setEnabled(false) }
runCatching { effect.release() }
}
dynamicsProcessing = null
loudnessEnhancer?.let { effect ->
runCatching { effect.setEnabled(false) }
runCatching { effect.release() }
}
loudnessEnhancer = null
attachedSessionId = 0
attachedChannelCount = 0
}
@RequiresApi(28)
private fun tryDynamicsProcessing(sessionId: Int, channelCount: Int): Boolean = try {
val band = DynamicsProcessing.MbcBand(
// inUse
true,
MBC_CUTOFF_HZ,
MBC_ATTACK_MS,
MBC_RELEASE_MS,
MBC_RATIO,
MBC_THRESHOLD_DB,
MBC_KNEE_DB,
MBC_NOISE_GATE_DB,
MBC_EXPANDER_RATIO,
// preGain
0f,
MBC_POST_GAIN_DB
)
val mbc = DynamicsProcessing.Mbc(
// inUse
true,
// enabled
true,
// bandCount
1
).apply { setBand(0, band) }
val limiter = DynamicsProcessing.Limiter(
// inUse
true,
// enabled
true,
// linkGroup
0,
LIMITER_ATTACK_MS,
LIMITER_RELEASE_MS,
LIMITER_RATIO,
LIMITER_THRESHOLD_DB,
// postGain
0f
)
val channel = DynamicsProcessing.Channel(
// inputGain
0f,
// preEqInUse
false,
// preEqBandCount
0,
// mbcInUse
true,
// mbcBandCount
1,
// postEqInUse
false,
// postEqBandCount
0,
// limiterInUse
true
).apply {
setMbc(mbc)
setLimiter(limiter)
}
val config = DynamicsProcessing.Config.Builder(
DynamicsProcessing.VARIANT_FAVOR_FREQUENCY_RESOLUTION,
channelCount,
// preEqInUse
false,
// preEqBandCount
0,
// mbcInUse
true,
// mbcBandCount
1,
// postEqInUse
false,
// postEqBandCount
0,
// limiterInUse
true
)
.setPreferredFrameDuration(FRAME_DURATION_MS)
.setAllChannelsTo(channel)
.build()
dynamicsProcessing = DynamicsProcessing(EFFECT_PRIORITY, sessionId, config).apply { setEnabled(true) }
log("info", "audio-normalization", "DynamicsProcessing attached (session=$sessionId, channels=$channelCount)")
true
} catch (e: Exception) {
log(
"warn",
"audio-normalization",
"DynamicsProcessing unavailable (${e.javaClass.simpleName}: ${e.message}); trying LoudnessEnhancer"
)
dynamicsProcessing = null
false
}
private fun tryLoudnessEnhancer(sessionId: Int) {
try {
loudnessEnhancer = LoudnessEnhancer(sessionId).apply {
setTargetGain(LOUDNESS_ENHANCER_GAIN_MB)
setEnabled(true)
}
log("info", "audio-normalization", "LoudnessEnhancer attached (session=$sessionId, gain=${LOUDNESS_ENHANCER_GAIN_MB}mB)")
} catch (e: Exception) {
loudnessEnhancer = null
attachedSessionId = 0
attachedChannelCount = 0
log(
"warn",
"audio-normalization",
"No loudness effect available on this device (${e.javaClass.simpleName}: ${e.message})"
)
}
}
}
@@ -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)
@@ -19,149 +19,151 @@ import androidx.media3.extractor.TrackOutput
*/
@androidx.media3.common.util.UnstableApi
class CuelessSeekExtractorWrapper(
private val delegate: Extractor,
private val delegate: Extractor
) : Extractor {
companion object {
private const val TAG = "CuelessSeek"
// MKV Cluster element ID: 0x1F43B675 (4-byte EBML Class-D ID)
private val CLUSTER_ID = byteArrayOf(0x1F, 0x43, 0xB6.toByte(), 0x75)
private const val SCAN_BUFFER_SIZE = 8192
// Max bytes to scan for a Cluster boundary before giving up
private const val MAX_SCAN_BYTES = 1024 * 1024 // 1 MB
companion object {
private const val TAG = "CuelessSeek"
// MKV Cluster element ID: 0x1F43B675 (4-byte EBML Class-D ID)
private val CLUSTER_ID = byteArrayOf(0x1F, 0x43, 0xB6.toByte(), 0x75)
private const val SCAN_BUFFER_SIZE = 8192
// Max bytes to scan for a Cluster boundary before giving up
private const val MAX_SCAN_BYTES = 1024 * 1024 // 1 MB
}
private var inputLength: Long = C.LENGTH_UNSET.toLong()
private var needsClusterResync = false
private var isApproximateSeeking = false
private var pendingSeekTimeUs: Long = C.TIME_UNSET
override fun sniff(input: ExtractorInput): Boolean = delegate.sniff(input)
override fun init(output: ExtractorOutput) {
delegate.init(SeekInterceptingOutput(output))
}
override fun read(input: ExtractorInput, seekPosition: PositionHolder): Int {
if (inputLength == C.LENGTH_UNSET.toLong()) {
inputLength = input.length
}
private var inputLength: Long = C.LENGTH_UNSET.toLong()
private var needsClusterResync = false
private var isApproximateSeeking = false
private var pendingSeekTimeUs: Long = C.TIME_UNSET
override fun sniff(input: ExtractorInput): Boolean = delegate.sniff(input)
override fun init(output: ExtractorOutput) {
delegate.init(SeekInterceptingOutput(output))
if (needsClusterResync) {
needsClusterResync = false
return scanForCluster(input, seekPosition)
}
return delegate.read(input, seekPosition)
}
override fun read(input: ExtractorInput, seekPosition: PositionHolder): Int {
if (inputLength == C.LENGTH_UNSET.toLong()) {
inputLength = input.length
override fun seek(position: Long, timeUs: Long) {
if (isApproximateSeeking && position > 0) {
needsClusterResync = true
pendingSeekTimeUs = timeUs
}
delegate.seek(position, timeUs)
}
override fun release() = delegate.release()
/**
* Scan forward from the current input position to find the next MKV Cluster
* element ID (0x1F43B675). Returns [Extractor.RESULT_SEEK] with the Cluster's
* byte position so ExoPlayer repositions the DataSource there.
*/
private fun scanForCluster(input: ExtractorInput, seekPosition: PositionHolder): Int {
val buffer = ByteArray(SCAN_BUFFER_SIZE)
var totalScanned = 0L
// Carry over last 3 bytes across buffer boundaries to detect split IDs
var carry = ByteArray(0)
while (totalScanned < MAX_SCAN_BYTES) {
val toRead = minOf(SCAN_BUFFER_SIZE, (MAX_SCAN_BYTES - totalScanned).toInt())
val bytesRead: Int
try {
bytesRead = input.read(buffer, 0, toRead)
} catch (_: Exception) {
break
}
if (bytesRead == C.RESULT_END_OF_INPUT) break
// Combine carry + new data for scanning
val scanData = if (carry.isNotEmpty()) carry + buffer.copyOf(bytesRead) else buffer.copyOf(bytesRead)
for (i in 0..scanData.size - 4) {
if (scanData[i] == CLUSTER_ID[0] &&
scanData[i + 1] == CLUSTER_ID[1] &&
scanData[i + 2] == CLUSTER_ID[2] &&
scanData[i + 3] == CLUSTER_ID[3]
) {
// Compute the absolute byte position of this Cluster
val clusterPosition = input.position - bytesRead - carry.size + i
Log.d(TAG, "Found Cluster at byte $clusterPosition (scanned ${totalScanned + i} bytes)")
seekPosition.position = clusterPosition
delegate.seek(clusterPosition, pendingSeekTimeUs)
pendingSeekTimeUs = C.TIME_UNSET
return Extractor.RESULT_SEEK
}
if (needsClusterResync) {
needsClusterResync = false
return scanForCluster(input, seekPosition)
}
return delegate.read(input, seekPosition)
}
// Keep last 3 bytes as carry for next iteration
carry = if (scanData.size >= 3) scanData.copyOfRange(scanData.size - 3, scanData.size) else scanData.copyOf()
totalScanned += bytesRead
}
override fun seek(position: Long, timeUs: Long) {
if (isApproximateSeeking && position > 0) {
needsClusterResync = true
pendingSeekTimeUs = timeUs
// Failed to find a Cluster — fall back to position 0
Log.w(TAG, "No Cluster found after scanning $totalScanned bytes, resetting to start")
seekPosition.position = 0
delegate.seek(0, 0)
return Extractor.RESULT_SEEK
}
/**
* ExtractorOutput wrapper that intercepts [seekMap] calls to replace
* [SeekMap.Unseekable] with an approximate proportional SeekMap.
*/
private inner class SeekInterceptingOutput(
private val delegate: ExtractorOutput
) : ExtractorOutput {
override fun track(id: Int, type: Int): TrackOutput = delegate.track(id, type)
override fun endTracks() = delegate.endTracks()
override fun seekMap(seekMap: SeekMap) {
if (seekMap is SeekMap.Unseekable) {
val durationUs = seekMap.durationUs
if (durationUs != C.TIME_UNSET && durationUs > 0) {
Log.i(TAG, "Replacing Unseekable with approximate SeekMap (duration=${durationUs / 1_000_000}s)")
isApproximateSeeking = true
delegate.seekMap(ApproximateSeekMap(durationUs))
return
}
delegate.seek(position, timeUs)
}
// File has real Cues or unknown duration — pass through
isApproximateSeeking = false
delegate.seekMap(seekMap)
}
}
override fun release() = delegate.release()
/**
* Approximate SeekMap that estimates byte positions proportionally.
* Used when the MKV has no Cues but has a known duration.
*/
private inner class ApproximateSeekMap(
private val durationUs: Long
) : SeekMap {
/**
* Scan forward from the current input position to find the next MKV Cluster
* element ID (0x1F43B675). Returns [Extractor.RESULT_SEEK] with the Cluster's
* byte position so ExoPlayer repositions the DataSource there.
*/
private fun scanForCluster(input: ExtractorInput, seekPosition: PositionHolder): Int {
val buffer = ByteArray(SCAN_BUFFER_SIZE)
var totalScanned = 0L
// Carry over last 3 bytes across buffer boundaries to detect split IDs
var carry = ByteArray(0)
override fun isSeekable(): Boolean = true
while (totalScanned < MAX_SCAN_BYTES) {
val toRead = minOf(SCAN_BUFFER_SIZE, (MAX_SCAN_BYTES - totalScanned).toInt())
val bytesRead: Int
try {
bytesRead = input.read(buffer, 0, toRead)
} catch (_: Exception) {
break
}
if (bytesRead == C.RESULT_END_OF_INPUT) break
override fun getDurationUs(): Long = durationUs
// Combine carry + new data for scanning
val scanData = if (carry.isNotEmpty()) carry + buffer.copyOf(bytesRead) else buffer.copyOf(bytesRead)
for (i in 0..scanData.size - 4) {
if (scanData[i] == CLUSTER_ID[0] &&
scanData[i + 1] == CLUSTER_ID[1] &&
scanData[i + 2] == CLUSTER_ID[2] &&
scanData[i + 3] == CLUSTER_ID[3]
) {
// Compute the absolute byte position of this Cluster
val clusterPosition = input.position - bytesRead - carry.size + i
Log.d(TAG, "Found Cluster at byte $clusterPosition (scanned ${totalScanned + i} bytes)")
seekPosition.position = clusterPosition
delegate.seek(clusterPosition, pendingSeekTimeUs)
pendingSeekTimeUs = C.TIME_UNSET
return Extractor.RESULT_SEEK
}
}
// Keep last 3 bytes as carry for next iteration
carry = if (scanData.size >= 3) scanData.copyOfRange(scanData.size - 3, scanData.size) else scanData.copyOf()
totalScanned += bytesRead
}
// Failed to find a Cluster — fall back to position 0
Log.w(TAG, "No Cluster found after scanning $totalScanned bytes, resetting to start")
seekPosition.position = 0
delegate.seek(0, 0)
return Extractor.RESULT_SEEK
}
/**
* ExtractorOutput wrapper that intercepts [seekMap] calls to replace
* [SeekMap.Unseekable] with an approximate proportional SeekMap.
*/
private inner class SeekInterceptingOutput(
private val delegate: ExtractorOutput,
) : ExtractorOutput {
override fun track(id: Int, type: Int): TrackOutput = delegate.track(id, type)
override fun endTracks() = delegate.endTracks()
override fun seekMap(seekMap: SeekMap) {
if (seekMap is SeekMap.Unseekable) {
val durationUs = seekMap.durationUs
if (durationUs != C.TIME_UNSET && durationUs > 0) {
Log.i(TAG, "Replacing Unseekable with approximate SeekMap (duration=${durationUs / 1_000_000}s)")
isApproximateSeeking = true
delegate.seekMap(ApproximateSeekMap(durationUs))
return
}
}
// File has real Cues or unknown duration — pass through
isApproximateSeeking = false
delegate.seekMap(seekMap)
}
}
/**
* Approximate SeekMap that estimates byte positions proportionally.
* Used when the MKV has no Cues but has a known duration.
*/
private inner class ApproximateSeekMap(
private val durationUs: Long,
) : SeekMap {
override fun isSeekable(): Boolean = true
override fun getDurationUs(): Long = durationUs
override fun getSeekPoints(timeUs: Long): SeekMap.SeekPoints {
val length = inputLength
if (length == C.LENGTH_UNSET.toLong() || durationUs <= 0) {
return SeekMap.SeekPoints(SeekPoint(0, 0))
}
val clampedTimeUs = timeUs.coerceIn(0, durationUs)
val position = (clampedTimeUs.toDouble() / durationUs * length).toLong().coerceIn(0, length)
return SeekMap.SeekPoints(SeekPoint(clampedTimeUs, position))
}
override fun getSeekPoints(timeUs: Long): SeekMap.SeekPoints {
val length = inputLength
if (length == C.LENGTH_UNSET.toLong() || durationUs <= 0) {
return SeekMap.SeekPoints(SeekPoint(0, 0))
}
val clampedTimeUs = timeUs.coerceIn(0, durationUs)
val position = (clampedTimeUs.toDouble() / durationUs * length).toLong().coerceIn(0, length)
return SeekMap.SeekPoints(SeekPoint(clampedTimeUs, position))
}
}
}
@@ -1,85 +1,378 @@
package com.edde746.plezy.exoplayer
import android.content.Context
import android.media.MediaCodecInfo
import android.media.MediaCodecList
import android.os.Build
import android.util.Log
import android.view.Display
import android.view.WindowManager
enum class DvConversionMode { DISABLED, DV81, HEVC_STRIP }
object DoviBridge {
private const val TAG = "DoviBridge"
private const val TAG = "DoviBridge"
private val nativeLoaded: Boolean by lazy {
try {
System.loadLibrary("dovi_bridge")
true
} catch (_: UnsatisfiedLinkError) {
Log.w(TAG, "Native lib not found")
false
data class DvAutoDecision(
val mode: DvConversionMode,
val reason: String,
val bridgeReady: Boolean,
val displayDv: Boolean,
val nativeDecoder: Boolean,
val advertisedP7: Boolean,
val advertisedP8: Boolean,
val decoders: String,
val displayHdr: String
) {
fun logMessage(): String = "AUTO P7 DV decision: mode=$mode; reason=$reason; bridgeReady=$bridgeReady, " +
"displayDV=$displayDv, nativeDecoder=$nativeDecoder, advertisedP7=$advertisedP7, " +
"advertisedP8=$advertisedP8, decoders=$decoders, displayHdr=$displayHdr"
}
data class Dv7FallbackDecision(
val mode: DvConversionMode,
val reason: String,
val bridgeReady: Boolean,
val displayDv: Boolean,
val advertisedP8: Boolean,
val displayHdr: String
) {
fun logMessage(): String = "DV7 fallback decision: mode=$mode; reason=$reason; bridgeReady=$bridgeReady, " +
"displayDV=$displayDv, advertisedP8=$advertisedP8, displayHdr=$displayHdr"
}
private val DOLBY_VISION_MIME_TYPES = setOf(
"video/dolby-vision",
"video/hevcdv",
"video/dv_hevc"
)
const val CONVERT_FAILED = -1
const val DESTINATION_TOO_SMALL = -2
private data class DvProfileLevel(val profile: Int, val level: Int)
private data class DvDecoderCapability(
val name: String,
val mimeType: String,
val profileLevels: List<DvProfileLevel>
)
private val nativeLoaded: Boolean by lazy {
try {
System.loadLibrary("dovi_bridge")
true
} catch (_: UnsatisfiedLinkError) {
Log.w(TAG, "Native lib not found")
false
}
}
private val conversionPathReady: Boolean by lazy {
nativeLoaded && runCatching { nativeIsConversionPathReady() }.getOrDefault(false)
}
fun isAvailable(): Boolean = conversionPathReady
private val dolbyVisionDecoders: List<DvDecoderCapability> by lazy {
try {
val codecList = MediaCodecList(MediaCodecList.REGULAR_CODECS)
codecList.codecInfos.flatMap { info ->
if (info.isEncoder) {
emptyList()
} else {
info.supportedTypes.mapNotNull { type ->
if (!DOLBY_VISION_MIME_TYPES.contains(type.lowercase())) return@mapNotNull null
val capabilities = runCatching { info.getCapabilitiesForType(type) }
.onFailure { Log.w(TAG, "Failed to query ${info.name} capabilities for $type", it) }
.getOrNull()
?: return@mapNotNull null
DvDecoderCapability(
name = info.name,
mimeType = type,
profileLevels = capabilities.profileLevels.map { DvProfileLevel(it.profile, it.level) }
)
}
}
}
} catch (e: Exception) {
Log.w(TAG, "Failed to query native Dolby Vision decoder support", e)
emptyList()
}
}
val hasNativeDolbyVisionDecoder: Boolean by lazy {
dolbyVisionDecoders.isNotEmpty().also {
Log.i(TAG, "Native Dolby Vision decoder available: $it; decoders=${describeDolbyVisionDecoders()}")
}
}
private fun deviceAdvertisesDvProfile(profile: Int, minApi: Int = 0): Boolean {
if (Build.VERSION.SDK_INT < minApi) return false
return dolbyVisionDecoders.any { decoder ->
decoder.profileLevels.any { it.profile == profile }
}
}
val deviceSupportsDvProfile7: Boolean by lazy {
deviceAdvertisesDvProfile(MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheDtb)
.also { Log.i(TAG, "Device advertises exact DV Profile 7 (DvheDtb): $it") }
}
val deviceSupportsDvProfile8: Boolean by lazy {
deviceAdvertisesDvProfile(MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheSt, minApi = 27)
.also { Log.i(TAG, "Device advertises DV Profile 8 (DvheSt): $it") }
}
fun displaySupportsDolbyVision(context: Context): Boolean {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
Log.i(TAG, "Display Dolby Vision support: false (HDR capabilities require API 24, device API=${Build.VERSION.SDK_INT})")
return false
}
fun isAvailable(): Boolean = nativeLoaded &&
runCatching { nativeIsConversionPathReady() }.getOrDefault(false)
val display = getCurrentDisplay(context)
if (display == null) {
Log.i(TAG, "Display Dolby Vision support: false (no active display)")
return false
}
private fun deviceSupportsDvProfile(profile: Int, minApi: Int = 0): Boolean {
try {
if (Build.VERSION.SDK_INT < minApi) return false
val codecList = MediaCodecList(MediaCodecList.REGULAR_CODECS)
return codecList.codecInfos.any { info ->
!info.isEncoder && info.supportedTypes.any { type ->
type.equals("video/dolby-vision", ignoreCase = true) &&
info.getCapabilitiesForType(type).profileLevels.any { it.profile == profile }
}
}
} catch (e: Exception) {
Log.w(TAG, "Failed to query DV profile $profile support", e)
return false
val hdrTypes = runCatching { getDisplayHdrTypes(display) }.getOrElse { error ->
Log.w(TAG, "Display Dolby Vision support: false (failed to query HDR types)", error)
return false
}
val supported = hdrTypes.contains(Display.HdrCapabilities.HDR_TYPE_DOLBY_VISION)
Log.i(TAG, "Display Dolby Vision support: $supported; ${describeDisplayHdrCapabilities(display)}")
return supported
}
fun describeDisplayHdrCapabilities(context: Context): String {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) return "HDR capabilities unavailable (API=${Build.VERSION.SDK_INT})"
val display = getCurrentDisplay(context) ?: return "HDR capabilities unavailable (no active display)"
return describeDisplayHdrCapabilities(display)
}
fun logSupportSummary(context: Context) {
Log.i(
TAG,
"DV support summary: bridgeReady=${isAvailable()}, displayDV=${displaySupportsDolbyVision(context)}, " +
"nativeDecoder=$hasNativeDolbyVisionDecoder, advertisedP7=$deviceSupportsDvProfile7, " +
"advertisedP8=$deviceSupportsDvProfile8, decoders=${describeDolbyVisionDecoders()}, " +
"displayHdr=${describeDisplayHdrCapabilities(context)}"
)
}
fun getConversionDecision(context: Context): DvAutoDecision {
val bridgeReady = isAvailable()
val displayDv = displaySupportsDolbyVision(context)
val nativeDecoder = hasNativeDolbyVisionDecoder
val advertisedP7 = deviceSupportsDvProfile7
val advertisedP8 = deviceSupportsDvProfile8
val mode = when {
!displayDv -> DvConversionMode.HEVC_STRIP
advertisedP7 -> DvConversionMode.DISABLED
advertisedP8 && bridgeReady -> DvConversionMode.DV81
else -> DvConversionMode.HEVC_STRIP
}
val reason = when {
!displayDv -> "active display does not support Dolby Vision; stripping DV metadata for HEVC fallback"
advertisedP7 -> "active display supports Dolby Vision and decoder advertises exact Profile 7; trying native DV first"
advertisedP8 && bridgeReady -> "active display supports Dolby Vision and decoder advertises Profile 8; converting to Profile 8.1"
!bridgeReady -> "conversion bridge unavailable; stripping DV metadata for HEVC fallback"
else -> "Dolby Vision output path is unavailable; stripping DV metadata for HEVC fallback"
}
val decision = DvAutoDecision(
mode = mode,
reason = reason,
bridgeReady = bridgeReady,
displayDv = displayDv,
nativeDecoder = nativeDecoder,
advertisedP7 = advertisedP7,
advertisedP8 = advertisedP8,
decoders = describeDolbyVisionDecoders(),
displayHdr = describeDisplayHdrCapabilities(context)
)
Log.i(TAG, decision.logMessage())
return decision
}
fun getConversionMode(context: Context): DvConversionMode = getConversionDecision(context).mode
/** Get the fallback mode when native DV7 decoding fails. */
fun getDv7FallbackDecision(context: Context): Dv7FallbackDecision {
val bridgeReady = isAvailable()
val displayDv = displaySupportsDolbyVision(context)
val advertisedP8 = deviceSupportsDvProfile8
val mode = if (displayDv && advertisedP8 && bridgeReady) DvConversionMode.DV81 else DvConversionMode.HEVC_STRIP
val reason = when {
mode == DvConversionMode.DV81 -> "display supports Dolby Vision and decoder advertises Profile 8"
!bridgeReady -> "conversion bridge unavailable; stripping DV metadata for HEVC fallback"
else -> "Dolby Vision output or Profile 8 support is unavailable"
}
val decision = Dv7FallbackDecision(
mode = mode,
reason = reason,
bridgeReady = bridgeReady,
displayDv = displayDv,
advertisedP8 = advertisedP8,
displayHdr = describeDisplayHdrCapabilities(context)
)
Log.i(TAG, decision.logMessage())
return decision
}
fun getDv7FallbackMode(context: Context): DvConversionMode = getDv7FallbackDecision(context).mode
private fun getCurrentDisplay(context: Context): Display? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
context.display
} else {
@Suppress("DEPRECATION")
(context.getSystemService(Context.WINDOW_SERVICE) as? WindowManager)?.defaultDisplay
}
private fun describeDolbyVisionDecoders(): String {
if (dolbyVisionDecoders.isEmpty()) return "none"
return dolbyVisionDecoders.joinToString { decoder ->
val profiles = if (decoder.profileLevels.isEmpty()) {
"none"
} else {
decoder.profileLevels.joinToString(prefix = "[", postfix = "]") {
"${describeDvProfile(it.profile)}/${describeDvLevel(it.level)}"
}
}
"${decoder.name}(${decoder.mimeType}, profiles=$profiles)"
}
}
private fun describeHdrTypes(hdrTypes: IntArray): String {
if (hdrTypes.isEmpty()) return "none"
return hdrTypes.joinToString(prefix = "[", postfix = "]") { type ->
when (type) {
Display.HdrCapabilities.HDR_TYPE_DOLBY_VISION -> "DOLBY_VISION"
Display.HdrCapabilities.HDR_TYPE_HDR10 -> "HDR10"
Display.HdrCapabilities.HDR_TYPE_HLG -> "HLG"
Display.HdrCapabilities.HDR_TYPE_HDR10_PLUS -> "HDR10_PLUS"
else -> "unknown(${hex(type)})"
}
}
}
private fun describeDisplayHdrCapabilities(display: Display): String {
val hdrCapabilities = getDisplayHdrCapabilities(display)
val parts = mutableListOf(
"display=${display.displayId}:${display.name}",
"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 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
}
}
val deviceSupportsDvProfile7: Boolean by lazy {
deviceSupportsDvProfile(MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheDtr)
.also { Log.i(TAG, "Device DV Profile 7 support: $it") }
@Suppress("DEPRECATION")
return hdrCapabilities.supportedHdrTypes
}
private fun describeDisplayMode(mode: Display.Mode): String {
val hdr = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
", hdr=${describeHdrTypes(mode.supportedHdrTypes)}"
} else {
""
}
return "#${mode.modeId} ${mode.physicalWidth}x${mode.physicalHeight}@${mode.refreshRate}Hz$hdr"
}
val deviceSupportsDvProfile8: Boolean by lazy {
deviceSupportsDvProfile(MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheSt, minApi = 27)
.also { Log.i(TAG, "Device DV Profile 8 support: $it") }
private fun formatLuminance(value: Float): String = if (value.isNaN() || value <= 0f) "unknown" else "${value}nits"
private fun describeDvProfile(profile: Int): String = when (profile) {
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvavPer -> "P0/DvavPer"
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvavPen -> "P1/DvavPen"
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheDer -> "P2/DvheDer"
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheDen -> "P3/DvheDen"
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheDtr -> "P4/DvheDtr"
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheStn -> "P5/DvheStn"
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheDth -> "P6/DvheDth"
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheDtb -> "P7/DvheDtb"
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvheSt -> "P8/DvheSt"
MediaCodecInfo.CodecProfileLevel.DolbyVisionProfileDvavSe -> "P9/DvavSe"
else -> "unknown(${hex(profile)})"
}
private fun describeDvLevel(level: Int): String = when (level) {
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelHd24 -> "L1/Hd24"
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelHd30 -> "L2/Hd30"
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelFhd24 -> "L3/Fhd24"
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelFhd30 -> "L4/Fhd30"
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelFhd60 -> "L5/Fhd60"
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelUhd24 -> "L6/Uhd24"
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelUhd30 -> "L7/Uhd30"
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelUhd48 -> "L8/Uhd48"
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelUhd60 -> "L9/Uhd60"
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevelUhd120 -> "L10/Uhd120"
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevel8k30 -> "L11/8k30"
MediaCodecInfo.CodecProfileLevel.DolbyVisionLevel8k60 -> "L12/8k60"
else -> "unknown(${hex(level)})"
}
private fun hex(value: Int): String = "0x${value.toString(16)}"
fun convertRpuNalu(
payload: ByteArray,
payloadOffset: Int,
payloadLength: Int,
output: ByteArray,
outputOffset: Int,
outputCapacity: Int,
mode: Int = 2
): Int {
if (!conversionPathReady || payloadLength <= 0) return CONVERT_FAILED
return runCatching {
nativeConvertDv7RpuToDv81(payload, payloadOffset, payloadLength, output, outputOffset, outputCapacity, mode)
}
.onFailure { Log.w(TAG, "RPU conversion failed: ${it.message}") }
.getOrDefault(CONVERT_FAILED)
}
fun getConversionMode(): DvConversionMode = when {
!isAvailable() -> DvConversionMode.DISABLED
deviceSupportsDvProfile7 -> DvConversionMode.DISABLED // try native first; ExoPlayerCore retries with conversion on failure
deviceSupportsDvProfile8 -> DvConversionMode.DV81
else -> DvConversionMode.HEVC_STRIP
}
fun getVersion(): String? {
if (!nativeLoaded) return null
return runCatching { nativeGetBridgeVersion() }.getOrNull()
}
/** Get the fallback mode when native DV7 decoding fails. */
fun getDv7FallbackMode(): DvConversionMode = when {
deviceSupportsDvProfile8 -> DvConversionMode.DV81
else -> DvConversionMode.HEVC_STRIP
}
@JvmStatic
private external fun nativeConvertDv7RpuToDv81(
payload: ByteArray,
payloadOffset: Int,
payloadLength: Int,
output: ByteArray,
outputOffset: Int,
outputCapacity: Int,
mode: Int
): Int
fun convertRpuNalu(payload: ByteArray, mode: Int = 2): ByteArray? {
if (!isAvailable() || payload.isEmpty()) return null
return runCatching { nativeConvertDv7RpuToDv81(payload, mode) }
.onFailure { Log.w(TAG, "RPU conversion failed: ${it.message}") }
.getOrNull()
}
@JvmStatic
private external fun nativeIsConversionPathReady(): Boolean
fun getVersion(): String? {
if (!nativeLoaded) return null
return runCatching { nativeGetBridgeVersion() }.getOrNull()
}
@JvmStatic
private external fun nativeConvertDv7RpuToDv81(payload: ByteArray, mode: Int): ByteArray?
@JvmStatic
private external fun nativeIsConversionPathReady(): Boolean
@JvmStatic
private external fun nativeGetBridgeVersion(): String
@JvmStatic
private external fun nativeGetBridgeVersion(): String
}
File diff suppressed because it is too large Load Diff
@@ -14,22 +14,23 @@ import androidx.media3.extractor.TrackOutput
* Shared by DoviExtractorWrapper for both MP4 and MKV containers.
*/
class DoviExtractorOutputWrapper(
private val delegate: ExtractorOutput,
private val dvMode: DvConversionMode,
private val onVideoTrackWrapped: (DoviConvertingTrackOutput) -> Unit,
private val delegate: ExtractorOutput,
private val dvMode: DvConversionMode,
private val emitLog: ((String, String, String) -> Unit)?,
private val onVideoTrackWrapped: (DoviConvertingTrackOutput) -> Unit
) : ExtractorOutput {
override fun track(id: Int, type: Int): TrackOutput {
val original = delegate.track(id, type)
if (type == C.TRACK_TYPE_VIDEO) {
val wrapper = DoviConvertingTrackOutput(original, dvMode)
onVideoTrackWrapped(wrapper)
return wrapper
}
return original
override fun track(id: Int, type: Int): TrackOutput {
val original = delegate.track(id, type)
if (type == C.TRACK_TYPE_VIDEO) {
val wrapper = DoviConvertingTrackOutput(original, dvMode, emitLog)
onVideoTrackWrapped(wrapper)
return wrapper
}
return original
}
override fun endTracks() = delegate.endTracks()
override fun seekMap(seekMap: SeekMap) = delegate.seekMap(seekMap)
override fun endTracks() = delegate.endTracks()
override fun seekMap(seekMap: SeekMap) = delegate.seekMap(seekMap)
}
/**
@@ -38,23 +39,23 @@ class DoviExtractorOutputWrapper(
* DV Profile 7 → 8.1 conversion via inline NAL processing.
*/
class DoviExtractorWrapper(
private val delegate: Extractor,
private val dvMode: DvConversionMode = DvConversionMode.HEVC_STRIP,
private val delegate: Extractor,
private val dvMode: DvConversionMode = DvConversionMode.HEVC_STRIP,
private val emitLog: ((String, String, String) -> Unit)? = null
) : Extractor {
@Volatile var doviTrackOutput: DoviConvertingTrackOutput? = null
private set
@Volatile var doviTrackOutput: DoviConvertingTrackOutput? = null
private set
override fun sniff(input: ExtractorInput): Boolean = delegate.sniff(input)
override fun sniff(input: ExtractorInput): Boolean = delegate.sniff(input)
override fun init(output: ExtractorOutput) {
delegate.init(DoviExtractorOutputWrapper(output, dvMode) { doviTrackOutput = it })
}
override fun init(output: ExtractorOutput) {
delegate.init(DoviExtractorOutputWrapper(output, dvMode, emitLog) { doviTrackOutput = it })
}
override fun read(input: ExtractorInput, seekPosition: PositionHolder): Int =
delegate.read(input, seekPosition)
override fun read(input: ExtractorInput, seekPosition: PositionHolder): Int = delegate.read(input, seekPosition)
override fun seek(position: Long, timeUs: Long) = delegate.seek(position, timeUs)
override fun seek(position: Long, timeUs: Long) = delegate.seek(position, timeUs)
override fun release() = delegate.release()
override fun release() = delegate.release()
}
@@ -0,0 +1,172 @@
package com.edde746.plezy.exoplayer
import java.nio.ByteBuffer
/**
* In-place sanitizer for HEVC Annex B buffers carrying both Dolby Vision and HDR10+
* dynamic metadata. Buggy chipsets (Fire TV 4K Max, MediaTek-based Google TV, ...)
* crash or black-screen when a native DV codec also receives in-band HDR10+ SEI, so
* only the metadata the active decode path consumes may be kept:
*
* - Native DV codec: strip HDR10+ SEI NALs (types 39/40 with ST 2094-40 payload),
* the decoder follows the DV RPU. Port of androidx/media#3085 / Kodi xbmc#24584.
* - HEVC fallback for a DV format: strip DV RPU/EL NALs (types 62/63) instead,
* leaving HDR10+ for the display.
*
* Runs on the playback thread against MediaCodec's direct input buffers, where
* per-byte ByteBuffer accessor calls are far too slow for high-bitrate UHD remuxes
* (#1313). Each sample is therefore staged through a reusable heap array with a
* single bulk get, scanned and compacted with array ops, and only the modified tail
* is written back. Instances are not thread-safe: use one per renderer.
*
* Pure JVM (no android/media3 imports) so it stays unit-testable on the host.
*/
class DvBitstreamSanitizer {
private companion object {
const val NAL_TYPE_PREFIX_SEI = 39
const val NAL_TYPE_SUFFIX_SEI = 40
const val NAL_TYPE_UNSPEC62 = 62 // DV RPU
const val NAL_TYPE_UNSPEC63 = 63 // DV Enhancement Layer
const val SEI_PAYLOAD_TYPE_ITU_T_T35 = 4
const val INITIAL_SCRATCH_SIZE = 256 * 1024
}
/** Reusable staging buffer — grown as needed, never shrunk. */
private var scratch = ByteArray(INITIAL_SCRATCH_SIZE)
/**
* Scans `[position, limit)` of [data] for Annex B NAL units and removes the selected
* metadata NALs by compacting the buffer in place and reducing its limit. The position
* is left unchanged. Returns the number of NAL units stripped.
*
* A sample with no start codes at all is left untouched: it cannot contain the
* targeted NALs, and emptying it would only confuse the decoder.
*/
fun sanitize(data: ByteBuffer, stripHdr10PlusSei: Boolean, stripDvRpu: Boolean): Int {
val startPos = data.position()
val len = data.limit() - startPos
if (len == 0) return 0
if (scratch.size < len) scratch = ByteArray(maxOf(len, scratch.size * 2))
val buf = scratch
data.get(buf, 0, len)
data.position(startPos)
var writeLen = 0
var firstModified = -1
var strippedCount = 0
var nalStartIndex = -1
var startCodeLen = 0
var i = 0
while (i <= len) {
// Find next start code or end of buffer.
val atEnd = i == len
var foundStartCode = false
var nextStartCodeLen = 0
if (!atEnd && i + 2 < len && buf[i].toInt() == 0 && buf[i + 1].toInt() == 0) {
if (buf[i + 2].toInt() == 1) {
foundStartCode = true
nextStartCodeLen = 3
} else if (buf[i + 2].toInt() == 0 && i + 3 < len && buf[i + 3].toInt() == 1) {
foundStartCode = true
nextStartCodeLen = 4
}
}
if (foundStartCode || atEnd) {
if (nalStartIndex >= 0) {
// Complete NAL unit (including its start code) from nalStartIndex to i.
val nalDataStart = nalStartIndex + startCodeLen
val nalEnd = i
var strip = false
if (nalEnd - nalDataStart >= 2) {
// HEVC NAL header: forbidden_zero_bit(1) + nal_unit_type(6) + nuh_layer_id MSB(1).
val nalUnitType = (buf[nalDataStart].toInt() and 0x7E) shr 1
strip = when (nalUnitType) {
NAL_TYPE_UNSPEC62, NAL_TYPE_UNSPEC63 -> stripDvRpu
NAL_TYPE_PREFIX_SEI, NAL_TYPE_SUFFIX_SEI ->
stripHdr10PlusSei && isHdr10PlusSeiNalUnit(buf, nalDataStart + 2, nalEnd)
else -> false
}
}
if (strip) {
strippedCount++
if (firstModified < 0) firstModified = writeLen
} else {
if (writeLen != nalStartIndex) {
// Also reached with zero strips when bytes precede the first start code.
if (firstModified < 0) firstModified = writeLen
System.arraycopy(buf, nalStartIndex, buf, writeLen, nalEnd - nalStartIndex)
}
writeLen += nalEnd - nalStartIndex
}
}
nalStartIndex = i
startCodeLen = nextStartCodeLen
i += if (nextStartCodeLen > 0) nextStartCodeLen else 1
} else {
i++
}
}
if (writeLen == len || firstModified < 0) return 0
// Bytes before firstModified are byte-identical to the buffer; write back only the tail.
data.position(startPos + firstModified)
data.put(buf, firstModified, writeLen - firstModified)
data.limit(startPos + writeLen)
data.position(startPos)
return strippedCount
}
/**
* Returns whether the SEI RBSP (starting after the 2-byte HEVC NAL header) begins with an
* HDR10+ message: user_data_registered_itu_t_t35 with country code 0xB5 (United States),
* provider code 0x003C (Samsung), provider oriented code 0x0001, application identifier 4
* (ST 2094-40), application version 0 or 1. Malformed/truncated data returns false so the
* NAL is kept.
*/
private fun isHdr10PlusSeiNalUnit(buf: ByteArray, rbspStart: Int, nalEnd: Int): Boolean {
var pos = rbspStart
if (pos >= nalEnd) return false
// SEI payload type: accumulated 0xFF bytes plus the final byte.
var payloadType = 0
while (pos < nalEnd) {
val b = buf[pos++].toInt() and 0xFF
payloadType += b
if (b != 0xFF) break
}
// SEI payload size, same encoding.
var payloadSize = 0
while (pos < nalEnd) {
val b = buf[pos++].toInt() and 0xFF
payloadSize += b
if (b != 0xFF) break
}
if (payloadType != SEI_PAYLOAD_TYPE_ITU_T_T35 || payloadSize < 7 || pos + 7 > nalEnd) {
return false
}
// The identifier bytes (B5 00 3C 00 01 04 00/01) cannot contain the 0x000003 emulation
// prevention pattern, so they can be read without RBSP unescaping.
val countryCode = buf[pos].toInt() and 0xFF
val providerCode = ((buf[pos + 1].toInt() and 0xFF) shl 8) or (buf[pos + 2].toInt() and 0xFF)
val orientedCode = ((buf[pos + 3].toInt() and 0xFF) shl 8) or (buf[pos + 4].toInt() and 0xFF)
val appIdentifier = buf[pos + 5].toInt() and 0xFF
val appVersion = buf[pos + 6].toInt() and 0xFF
return countryCode == 0xB5 &&
providerCode == 0x003C &&
orientedCode == 0x0001 &&
appIdentifier == 4 &&
(appVersion == 0 || appVersion == 1)
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -3,11 +3,16 @@ package com.edde746.plezy.exoplayer
import android.content.Context
import android.media.AudioDeviceInfo
import android.os.Build
import android.os.Handler
import androidx.annotation.OptIn
import androidx.media3.common.Format
import androidx.media3.common.MimeTypes
import androidx.media3.common.PlaybackParameters
import androidx.media3.common.util.Clock
import androidx.media3.common.util.UnstableApi
import androidx.media3.decoder.DecoderInputBuffer
import androidx.media3.exoplayer.DefaultRenderersFactory
import androidx.media3.exoplayer.Renderer
import androidx.media3.exoplayer.analytics.PlayerId
import androidx.media3.exoplayer.audio.AudioOutput
import androidx.media3.exoplayer.audio.AudioOutputProvider
@@ -16,41 +21,104 @@ import androidx.media3.exoplayer.audio.AudioTrackAudioOutputProvider
import androidx.media3.exoplayer.audio.DefaultAudioSink
import androidx.media3.exoplayer.audio.DefaultAudioTrackBufferSizeProvider
import androidx.media3.exoplayer.audio.ForwardingAudioSink
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 java.nio.ByteBuffer
import java.util.concurrent.atomic.AtomicLong
import kotlin.math.abs
@OptIn(UnstableApi::class)
class PlezyRenderersFactory(context: Context) : DefaultRenderersFactory(context) {
override fun buildAudioSink(
context: Context,
enableFloatOutput: Boolean,
enableAudioOutputPlaybackParams: Boolean
): AudioSink {
AudioTrackAudioOutputProvider.failOnSpuriousAudioTimestamp = false
/** Audio delay in microseconds. Shared with PositionFixAudioSink for live updates. */
val audioDelayUs = AtomicLong(0L)
val bufferSizeProvider = DefaultAudioTrackBufferSizeProvider.Builder()
.setMinPcmBufferDurationUs(500_000)
.setMaxPcmBufferDurationUs(1_000_000)
.setPcmBufferMultiplicationFactor(4)
.build()
/** Returns whether direct encoded output should be hidden so decoded PCM output can be selected. */
var shouldBlockDirectAudioOutput: ((Format) -> Boolean)? = null
val realProvider = AudioTrackAudioOutputProvider.Builder(context)
.setAudioTrackBufferSizeProvider(bufferSizeProvider)
.build()
/** Called before Media3 reacts to an audio route/capability change. */
var onAudioCapabilitiesChanged: (() -> Unit)? = null
// Shared position: RawPositionAudioOutput writes the raw AudioTrack position,
// PositionFixAudioSink reads it to bypass DefaultAudioSink's writtenDuration clamp.
val rawPositionUs = AtomicLong(Long.MIN_VALUE)
var audioDiagnosticsLogger: ((String, String, String) -> Unit)? = null
val defaultSink = DefaultAudioSink.Builder(context)
.setEnableFloatOutput(enableFloatOutput)
.setEnableAudioOutputPlaybackParameters(enableAudioOutputPlaybackParams)
.setAudioOutputProvider(RawPositionOutputProvider(realProvider, rawPositionUs))
.build()
var videoDiagnosticsLogger: ((String, String, String) -> Unit)? = null
return PositionFixAudioSink(defaultSink, rawPositionUs)
}
override fun buildVideoRenderers(
context: Context,
extensionRendererMode: Int,
mediaCodecSelector: MediaCodecSelector,
enableDecoderFallback: Boolean,
eventHandler: Handler,
eventListener: VideoRendererEventListener,
allowedVideoJoiningTimeMs: Long,
out: ArrayList<Renderer>
) {
// Let super build the full list (it also appends extension renderers reflectively,
// e.g. the jellyfin ffmpeg artifact's video renderer), then swap the stock
// MediaCodecVideoRenderer for the DV-sanitizing variant at the same index.
super.buildVideoRenderers(
context,
extensionRendererMode,
mediaCodecSelector,
enableDecoderFallback,
eventHandler,
eventListener,
allowedVideoJoiningTimeMs,
out
)
val index = out.indexOfFirst { it.javaClass == MediaCodecVideoRenderer::class.java }
if (index < 0) return
out[index] = DvSanitizingVideoRenderer(
MediaCodecVideoRenderer.Builder(context)
.setCodecAdapterFactory(codecAdapterFactory)
.setMediaCodecSelector(mediaCodecSelector)
.setAllowedJoiningTimeMs(allowedVideoJoiningTimeMs)
.setEnableDecoderFallback(enableDecoderFallback)
.setEventHandler(eventHandler)
.setEventListener(eventListener)
.setMaxDroppedFramesToNotify(MAX_DROPPED_VIDEO_FRAME_COUNT_TO_NOTIFY),
videoDiagnosticsLogger
)
}
override fun buildAudioSink(
context: Context,
enableFloatOutput: Boolean,
enableAudioOutputPlaybackParams: Boolean
): AudioSink {
AudioTrackAudioOutputProvider.failOnSpuriousAudioTimestamp = false
val bufferSizeProvider = DefaultAudioTrackBufferSizeProvider.Builder()
.setMinPcmBufferDurationUs(500_000)
.setMaxPcmBufferDurationUs(1_000_000)
.setPcmBufferMultiplicationFactor(4)
.build()
val realProvider = AudioTrackAudioOutputProvider.Builder(context)
.setAudioTrackBufferSizeProvider(bufferSizeProvider)
.build()
// Shared position: RawPositionAudioOutput writes the raw AudioTrack position,
// PositionFixAudioSink reads it to bypass DefaultAudioSink's writtenDuration clamp.
val rawPositionUs = AtomicLong(Long.MIN_VALUE)
val defaultSink = DefaultAudioSink.Builder(context)
.setEnableFloatOutput(enableFloatOutput)
.setEnableAudioOutputPlaybackParameters(enableAudioOutputPlaybackParams)
.setAudioOutputProvider(RawPositionOutputProvider(realProvider, rawPositionUs, audioDiagnosticsLogger))
.build()
return PositionFixAudioSink(
defaultSink,
rawPositionUs,
audioDelayUs,
shouldBlockDirectAudioOutput,
onAudioCapabilitiesChanged,
audioDiagnosticsLogger
)
}
}
/**
@@ -76,106 +144,277 @@ class PlezyRenderersFactory(context: Context) : DefaultRenderersFactory(context)
*/
@OptIn(UnstableApi::class)
private class PositionFixAudioSink(
sink: AudioSink,
private val rawPositionUs: AtomicLong
sink: AudioSink,
private val rawPositionUs: AtomicLong,
private val audioDelayUs: AtomicLong,
private val shouldBlockDirectAudioOutput: ((Format) -> Boolean)?,
private val onAudioCapabilitiesChanged: (() -> Unit)?,
private val log: ((String, String, String) -> Unit)?
) : ForwardingAudioSink(sink) {
private var startMediaTimeUs = Long.MIN_VALUE
private var suppressedErrorCount = 0
private var startMediaTimeUs = Long.MIN_VALUE
private var suppressedErrorCount = 0
// Speed tracking for position bypass
private var currentSpeed = 1.0f
private var refMediaTimeUs = Long.MIN_VALUE
private var refRawPositionUs = 0L
// Speed tracking for position bypass
private var currentSpeed = 1.0f
private var refMediaTimeUs = Long.MIN_VALUE
private var refRawPositionUs = 0L
override fun handleBuffer(
buffer: ByteBuffer,
presentationTimeUs: Long,
encodedAccessUnitCount: Int
): Boolean {
if (startMediaTimeUs == Long.MIN_VALUE) {
startMediaTimeUs = presentationTimeUs
refMediaTimeUs = presentationTimeUs
refRawPositionUs = 0
// Transient counter-offset: after seek/flush, ramp offset from 0 to full
// over recoveryDurationUs to prevent video frame drops.
private var recoveryDurationUs = 0L
private val loggedDirectBlockMimeTypes = mutableSetOf<String>()
private var loggedFirstBuffer = false
override fun supportsFormat(format: Format): Boolean {
if (blocksDirectAudioOutput(format)) return false
return super.supportsFormat(format)
}
override fun getFormatSupport(format: Format): Int {
if (blocksDirectAudioOutput(format)) return AudioSink.SINK_FORMAT_UNSUPPORTED
return super.getFormatSupport(format)
}
private fun blocksDirectAudioOutput(format: Format): Boolean {
if (shouldBlockDirectAudioOutput?.invoke(format) != true) return false
val mimeType = format.sampleMimeType ?: "unknown"
if (loggedDirectBlockMimeTypes.add(mimeType)) {
log?.invoke(
"info",
"audio",
"Blocking direct $mimeType output; decoded PCM output will be preferred"
)
}
return true
}
override fun handleBuffer(
buffer: ByteBuffer,
presentationTimeUs: Long,
encodedAccessUnitCount: Int
): Boolean {
if (!loggedFirstBuffer && buffer.hasRemaining()) {
loggedFirstBuffer = true
log?.invoke(
"debug",
"audio-sink",
"First buffer: size=${buffer.remaining()}B, pts=${presentationTimeUs}us, accessUnits=$encodedAccessUnitCount"
)
}
if (startMediaTimeUs == Long.MIN_VALUE) {
startMediaTimeUs = presentationTimeUs
refMediaTimeUs = presentationTimeUs
refRawPositionUs = 0
val delayUs = audioDelayUs.get()
recoveryDurationUs = if (delayUs == 0L) 0L else maxOf(200_000L, 2L * abs(delayUs))
}
return super.handleBuffer(buffer, presentationTimeUs, encodedAccessUnitCount)
}
override fun setPlaybackParameters(playbackParameters: PlaybackParameters) {
// Capture reference point before speed changes
val rawPos = rawPositionUs.get()
if (rawPos > 0 && refMediaTimeUs != Long.MIN_VALUE) {
refMediaTimeUs = refMediaTimeUs + ((rawPos - refRawPositionUs) * currentSpeed).toLong()
refRawPositionUs = rawPos
}
currentSpeed = playbackParameters.speed
super.setPlaybackParameters(playbackParameters)
}
override fun getCurrentPositionUs(sourceEnded: Boolean): Long {
val delegatePos = super.getCurrentPositionUs(sourceEnded)
if (delegatePos == Long.MIN_VALUE || refMediaTimeUs == Long.MIN_VALUE) {
return delegatePos
}
val rawPos = rawPositionUs.get()
val basePos = if (rawPos <= 0) {
delegatePos
} else {
val expectedPos = refMediaTimeUs + ((rawPos - refRawPositionUs) * currentSpeed).toLong()
if (expectedPos > delegatePos + 30_000) expectedPos else delegatePos
}
// Audio delay with transient counter-offset to prevent frame drops after seeks.
// After flush, offset ramps linearly from 0 to full over recoveryDurationUs.
val delayUs = audioDelayUs.get()
if (delayUs == 0L) return basePos
val elapsedUs = basePos - startMediaTimeUs
val netOffsetUs = if (recoveryDurationUs <= 0L || elapsedUs >= recoveryDurationUs) {
delayUs
} else {
(delayUs * elapsedUs) / recoveryDurationUs
}
return basePos + netOffsetUs
}
// --- Suppress timestamp discontinuity errors ---
override fun setListener(listener: AudioSink.Listener) {
super.setListener(
@OptIn(UnstableApi::class) object : AudioSink.Listener {
override fun onPositionDiscontinuity() = listener.onPositionDiscontinuity()
override fun onPositionAdvancing(playoutStartSystemTimeUs: Long) = listener.onPositionAdvancing(playoutStartSystemTimeUs)
override fun onUnderrun(bufferSize: Int, bufferSizeMs: Long, elapsedSinceLastFeedMs: Long) = listener.onUnderrun(bufferSize, bufferSizeMs, elapsedSinceLastFeedMs)
override fun onSkipSilenceEnabledChanged(skipSilenceEnabled: Boolean) = listener.onSkipSilenceEnabledChanged(skipSilenceEnabled)
override fun onOffloadBufferEmptying() = listener.onOffloadBufferEmptying()
override fun onOffloadBufferFull() = listener.onOffloadBufferFull()
override fun onAudioCapabilitiesChanged() {
onAudioCapabilitiesChanged?.invoke()
listener.onAudioCapabilitiesChanged()
}
return super.handleBuffer(buffer, presentationTimeUs, encodedAccessUnitCount)
}
override fun onAudioTrackInitialized(audioTrackConfig: AudioSink.AudioTrackConfig) = listener.onAudioTrackInitialized(audioTrackConfig)
override fun onAudioTrackReleased(audioTrackConfig: AudioSink.AudioTrackConfig) = listener.onAudioTrackReleased(audioTrackConfig)
override fun onSilenceSkipped() = listener.onSilenceSkipped()
override fun onAudioSessionIdChanged(audioSessionId: Int) = listener.onAudioSessionIdChanged(audioSessionId)
override fun setPlaybackParameters(playbackParameters: PlaybackParameters) {
// Capture reference point before speed changes
val rawPos = rawPositionUs.get()
if (rawPos > 0 && refMediaTimeUs != Long.MIN_VALUE) {
refMediaTimeUs = refMediaTimeUs + ((rawPos - refRawPositionUs) * currentSpeed).toLong()
refRawPositionUs = rawPos
override fun onAudioSinkError(audioSinkError: Exception) {
if (isTimestampDiscontinuity(audioSinkError)) {
suppressedErrorCount++
return
}
listener.onAudioSinkError(audioSinkError)
}
currentSpeed = playbackParameters.speed
super.setPlaybackParameters(playbackParameters)
}
}
)
}
override fun getCurrentPositionUs(sourceEnded: Boolean): Long {
val delegatePos = super.getCurrentPositionUs(sourceEnded)
if (delegatePos == Long.MIN_VALUE || refMediaTimeUs == Long.MIN_VALUE) {
return delegatePos
override fun flush() {
startMediaTimeUs = Long.MIN_VALUE
refMediaTimeUs = Long.MIN_VALUE
refRawPositionUs = 0
recoveryDurationUs = 0L
rawPositionUs.set(Long.MIN_VALUE)
super.flush()
}
override fun reset() {
startMediaTimeUs = Long.MIN_VALUE
refMediaTimeUs = Long.MIN_VALUE
refRawPositionUs = 0
recoveryDurationUs = 0L
currentSpeed = 1.0f
rawPositionUs.set(Long.MIN_VALUE)
suppressedErrorCount = 0
super.reset()
}
private fun isTimestampDiscontinuity(e: Exception): Boolean {
val name = e.javaClass.simpleName
val msg = e.message ?: ""
return name == "InvalidAudioTrackTimestampException" ||
name == "UnexpectedDiscontinuityException" ||
msg.contains("timestamp discontinuity", ignoreCase = true)
}
}
/**
* Wraps a text renderer to shift subtitle timing by [delayUs] microseconds.
* Positive delay → subtitles appear later, negative → earlier.
* Only render() needs the offset — the text renderer uses positionUs to decide
* which cues are active; other Renderer methods are timing-independent.
*/
@OptIn(UnstableApi::class)
internal class SubtitleDelayRenderer(
private val delegate: Renderer,
private val delayUs: AtomicLong
) : Renderer by delegate {
override fun render(positionUs: Long, elapsedRealtimeUs: Long) {
delegate.render(positionUs - delayUs.get(), elapsedRealtimeUs)
}
}
/**
* MediaCodecVideoRenderer that resolves the DV / HDR10+ dual-dynamic-metadata conflict
* per decode path (#1296, generalizes androidx/media#3085):
* - native DV codec selected (media3 only selects one when decoder AND display support DV):
* strip in-band HDR10+ SEI — conflicting dynamic metadata crashes Fire TV-class chipsets
* - HEVC fallback for an HEVC-based DV format: strip DV RPU/EL NALs (profiles 7/8, where the
* base layer remains valid HDR10/HLG), keeping HDR10+ for the display
*
* Flags are reassigned on every codec init: tunneling toggles and DV retries re-init the
* codec without recreating renderers, and decoder fallback can switch the codec MIME.
*/
@OptIn(UnstableApi::class)
internal class DvSanitizingVideoRenderer(
builder: Builder,
private val log: ((String, String, String) -> Unit)?
) : MediaCodecVideoRenderer(builder) {
private val sanitizer = DvBitstreamSanitizer()
private var stripHdr10PlusSei = false
private var stripDvRpu = false
// Sanitize diagnostics — playback-thread only, cumulative for the renderer's lifetime.
private var sanitizedSampleCount = 0L
private var totalSanitizeTimeUs = 0L
private var maxSanitizeTimeUs = 0L
private var totalStrippedNals = 0L
private var totalStrippedBytes = 0L
override fun onCodecInitialized(
name: String,
configuration: MediaCodecAdapter.Configuration,
initializedTimestampMs: Long,
initializationDurationMs: Long
) {
super.onCodecInitialized(name, configuration, initializedTimestampMs, initializationDurationMs)
val codecs = configuration.format.codecs?.lowercase() ?: ""
val dvHevcFormat = configuration.format.sampleMimeType == MimeTypes.VIDEO_DOLBY_VISION &&
(codecs.startsWith("dvhe.") || codecs.startsWith("dvh1."))
val codecMimeType = configuration.codecInfo.codecMimeType
val newStripHdr10PlusSei = dvHevcFormat && codecMimeType == MimeTypes.VIDEO_DOLBY_VISION
val newStripDvRpu = dvHevcFormat &&
codecMimeType == MimeTypes.VIDEO_H265 &&
isBlCompatibleDvProfile(codecs)
if (newStripHdr10PlusSei != stripHdr10PlusSei || newStripDvRpu != stripDvRpu) {
log?.invoke(
"info",
"video",
"DV bitstream sanitizing: stripHdr10PlusSei=$newStripHdr10PlusSei, " +
"stripDvRpu=$newStripDvRpu (codec=$name, codecs=${configuration.format.codecs})"
)
}
stripHdr10PlusSei = newStripHdr10PlusSei
stripDvRpu = newStripDvRpu
}
override fun onQueueInputBuffer(buffer: DecoderInputBuffer) {
if (stripHdr10PlusSei || stripDvRpu) {
val data = buffer.data
if (data != null && data.hasRemaining() && !buffer.isEncrypted) {
val sizeBefore = data.remaining()
val startNs = System.nanoTime()
val stripped = sanitizer.sanitize(data, stripHdr10PlusSei, stripDvRpu)
val elapsedUs = (System.nanoTime() - startNs) / 1_000
sanitizedSampleCount++
totalSanitizeTimeUs += elapsedUs
if (elapsedUs > maxSanitizeTimeUs) maxSanitizeTimeUs = elapsedUs
totalStrippedNals += stripped
totalStrippedBytes += sizeBefore - data.remaining()
if (sanitizedSampleCount <= 3 || sanitizedSampleCount % 500 == 0L) {
log?.invoke(
"debug",
"dv-sanitize",
"Sample #$sanitizedSampleCount: ${sizeBefore}B -> ${data.remaining()}B, " +
"stripped=$stripped, took=${elapsedUs}us " +
"(avg=${totalSanitizeTimeUs / sanitizedSampleCount}us, max=${maxSanitizeTimeUs}us, " +
"totalNals=$totalStrippedNals, totalBytes=${totalStrippedBytes}B)"
)
}
val rawPos = rawPositionUs.get()
if (rawPos <= 0) return delegatePos
val expectedPos = refMediaTimeUs + ((rawPos - refRawPositionUs) * currentSpeed).toLong()
return if (expectedPos > delegatePos + 30_000) expectedPos else delegatePos
}
}
super.onQueueInputBuffer(buffer)
}
// --- Suppress timestamp discontinuity errors ---
override fun setListener(listener: AudioSink.Listener) {
super.setListener(@OptIn(UnstableApi::class) object : AudioSink.Listener {
override fun onPositionDiscontinuity() = listener.onPositionDiscontinuity()
override fun onPositionAdvancing(playoutStartSystemTimeUs: Long) = listener.onPositionAdvancing(playoutStartSystemTimeUs)
override fun onUnderrun(bufferSize: Int, bufferSizeMs: Long, elapsedSinceLastFeedMs: Long) = listener.onUnderrun(bufferSize, bufferSizeMs, elapsedSinceLastFeedMs)
override fun onSkipSilenceEnabledChanged(skipSilenceEnabled: Boolean) = listener.onSkipSilenceEnabledChanged(skipSilenceEnabled)
override fun onOffloadBufferEmptying() = listener.onOffloadBufferEmptying()
override fun onOffloadBufferFull() = listener.onOffloadBufferFull()
override fun onAudioCapabilitiesChanged() = listener.onAudioCapabilitiesChanged()
override fun onAudioTrackInitialized(audioTrackConfig: AudioSink.AudioTrackConfig) = listener.onAudioTrackInitialized(audioTrackConfig)
override fun onAudioTrackReleased(audioTrackConfig: AudioSink.AudioTrackConfig) = listener.onAudioTrackReleased(audioTrackConfig)
override fun onSilenceSkipped() = listener.onSilenceSkipped()
override fun onAudioSessionIdChanged(audioSessionId: Int) = listener.onAudioSessionIdChanged(audioSessionId)
override fun onAudioSinkError(audioSinkError: Exception) {
if (isTimestampDiscontinuity(audioSinkError)) {
suppressedErrorCount++
return
}
listener.onAudioSinkError(audioSinkError)
}
})
}
override fun flush() {
startMediaTimeUs = Long.MIN_VALUE
refMediaTimeUs = Long.MIN_VALUE
refRawPositionUs = 0
rawPositionUs.set(Long.MIN_VALUE)
super.flush()
}
override fun reset() {
startMediaTimeUs = Long.MIN_VALUE
refMediaTimeUs = Long.MIN_VALUE
refRawPositionUs = 0
currentSpeed = 1.0f
rawPositionUs.set(Long.MIN_VALUE)
suppressedErrorCount = 0
super.reset()
}
private fun isTimestampDiscontinuity(e: Exception): Boolean {
val name = e.javaClass.simpleName
val msg = e.message ?: ""
return name == "InvalidAudioTrackTimestampException" ||
name == "UnexpectedDiscontinuityException" ||
msg.contains("timestamp discontinuity", ignoreCase = true)
}
private fun isBlCompatibleDvProfile(codecs: String): Boolean = codecs.startsWith("dvhe.07") ||
codecs.startsWith("dvh1.07") ||
codecs.startsWith("dvhe.08") ||
codecs.startsWith("dvh1.08")
}
// --- AudioOutput wrapping: shares raw position with PositionFixAudioSink ---
@@ -187,117 +426,147 @@ private class PositionFixAudioSink(
@OptIn(UnstableApi::class)
private class RawPositionOutputProvider(
private val delegate: AudioOutputProvider,
private val rawPositionUs: AtomicLong
private val delegate: AudioOutputProvider,
private val rawPositionUs: AtomicLong,
private val log: ((String, String, String) -> Unit)?
) : AudioOutputProvider {
private var cachedOutput: RawPositionAudioOutput? = null
private var cachedConfig: AudioOutputProvider.OutputConfig? = null
private var cachedOutput: RawPositionAudioOutput? = null
private var cachedConfig: AudioOutputProvider.OutputConfig? = null
override fun getFormatSupport(config: AudioOutputProvider.FormatConfig) =
delegate.getFormatSupport(config)
override fun getFormatSupport(config: AudioOutputProvider.FormatConfig) = delegate.getFormatSupport(config)
override fun getOutputConfig(config: AudioOutputProvider.FormatConfig) =
delegate.getOutputConfig(config)
override fun getOutputConfig(config: AudioOutputProvider.FormatConfig) = delegate.getOutputConfig(config)
override fun getAudioOutput(config: AudioOutputProvider.OutputConfig): AudioOutput {
val cached = cachedOutput
if (cached != null && cachedConfig == config) {
cachedOutput = null
return cached
}
cached?.forceRelease()
cachedOutput = null
val realOutput = delegate.getAudioOutput(config)
cachedConfig = config
return RawPositionAudioOutput(realOutput, rawPositionUs, this)
override fun getAudioOutput(config: AudioOutputProvider.OutputConfig): AudioOutput {
val cached = cachedOutput
if (cached != null && cachedConfig == config) {
cachedOutput = null
return cached
}
cached?.forceRelease()
cachedOutput = null
fun returnToCache(output: RawPositionAudioOutput) {
val existing = cachedOutput
if (existing != null && existing !== output) {
existing.forceRelease()
}
cachedOutput = output
val realOutput = delegate.getAudioOutput(config)
cachedConfig = config
return RawPositionAudioOutput(realOutput, rawPositionUs, this, log)
}
fun returnToCache(output: RawPositionAudioOutput) {
val existing = cachedOutput
if (existing != null && existing !== output) {
existing.forceRelease()
}
cachedOutput = output
}
override fun addListener(listener: AudioOutputProvider.Listener) =
delegate.addListener(listener)
override fun addListener(listener: AudioOutputProvider.Listener) = delegate.addListener(listener)
override fun removeListener(listener: AudioOutputProvider.Listener) =
delegate.removeListener(listener)
override fun removeListener(listener: AudioOutputProvider.Listener) = delegate.removeListener(listener)
override fun setClock(clock: Clock) = delegate.setClock(clock)
override fun setClock(clock: Clock) = delegate.setClock(clock)
override fun release() {
cachedOutput?.forceRelease()
cachedOutput = null
cachedConfig = null
delegate.release()
}
override fun release() {
cachedOutput?.forceRelease()
cachedOutput = null
cachedConfig = null
delegate.release()
}
}
@OptIn(UnstableApi::class)
private class RawPositionAudioOutput(
private val delegate: AudioOutput,
private val rawPositionUs: AtomicLong,
private val provider: RawPositionOutputProvider
private val delegate: AudioOutput,
private val rawPositionUs: AtomicLong,
private val provider: RawPositionOutputProvider,
private val log: ((String, String, String) -> Unit)?
) : AudioOutput {
override fun getPositionUs(): Long {
val pos = delegate.getPositionUs()
rawPositionUs.set(pos)
return pos
private var loggedFirstWrite = false
private var writeCount = 0L
private var writtenBytes = 0L
private var failed = false
override fun getPositionUs(): Long {
val pos = delegate.getPositionUs()
rawPositionUs.set(pos)
return pos
}
override fun play() = delegate.play()
override fun pause() = delegate.pause()
@Throws(AudioOutput.WriteException::class)
override fun write(buffer: ByteBuffer, size: Int, presentationTimeUs: Long): Boolean {
val before = buffer.position()
val handled = try {
delegate.write(buffer, size, presentationTimeUs)
} catch (e: AudioOutput.WriteException) {
failed = true
rawPositionUs.set(Long.MIN_VALUE)
log?.invoke("warn", "audio-output", "Write failed; AudioTrack will not be reused: ${e.message}")
throw e
}
override fun play() = delegate.play()
override fun pause() = delegate.pause()
@Throws(AudioOutput.WriteException::class)
override fun write(buffer: ByteBuffer, size: Int, presentationTimeUs: Long) =
delegate.write(buffer, size, presentationTimeUs)
override fun flush() {
rawPositionUs.set(Long.MIN_VALUE)
delegate.flush()
val written = buffer.position() - before
if (written > 0) {
writeCount++
writtenBytes += written.toLong()
if (!loggedFirstWrite) {
loggedFirstWrite = true
log?.invoke(
"debug",
"audio-output",
"First write: wrote=${written}B, handled=$handled, pts=${presentationTimeUs}us, writes=$writeCount, total=${writtenBytes}B"
)
}
}
return handled
}
override fun stop() = delegate.stop()
override fun flush() {
rawPositionUs.set(Long.MIN_VALUE)
loggedFirstWrite = false
writeCount = 0
writtenBytes = 0
delegate.flush()
}
override fun release() {
rawPositionUs.set(Long.MIN_VALUE)
if (Build.VERSION.SDK_INT >= 25) {
delegate.stop()
delegate.flush()
provider.returnToCache(this)
} else {
delegate.release()
}
override fun stop() = delegate.stop()
override fun release() {
rawPositionUs.set(Long.MIN_VALUE)
if (failed) {
delegate.release()
return
}
fun forceRelease() {
rawPositionUs.set(Long.MIN_VALUE)
delegate.release()
if (Build.VERSION.SDK_INT >= 25) {
delegate.stop()
delegate.flush()
provider.returnToCache(this)
} else {
delegate.release()
}
}
override fun setVolume(volume: Float) = delegate.setVolume(volume)
override fun isOffloadedPlayback() = delegate.isOffloadedPlayback()
override fun getAudioSessionId() = delegate.getAudioSessionId()
override fun getSampleRate() = delegate.getSampleRate()
override fun getBufferSizeInFrames() = delegate.getBufferSizeInFrames()
override fun getPlaybackParameters() = delegate.getPlaybackParameters()
override fun isStalled() = delegate.isStalled()
override fun addListener(listener: AudioOutput.Listener) = delegate.addListener(listener)
override fun removeListener(listener: AudioOutput.Listener) = delegate.removeListener(listener)
override fun setPlaybackParameters(playbackParameters: PlaybackParameters) =
delegate.setPlaybackParameters(playbackParameters)
override fun setOffloadDelayPadding(delayInFrames: Int, paddingInFrames: Int) =
delegate.setOffloadDelayPadding(delayInFrames, paddingInFrames)
override fun setOffloadEndOfStream() = delegate.setOffloadEndOfStream()
override fun setPlayerId(playerId: PlayerId) = delegate.setPlayerId(playerId)
override fun attachAuxEffect(effectId: Int) = delegate.attachAuxEffect(effectId)
override fun setAuxEffectSendLevel(level: Float) = delegate.setAuxEffectSendLevel(level)
override fun setPreferredDevice(preferredDevice: AudioDeviceInfo?) =
delegate.setPreferredDevice(preferredDevice)
fun forceRelease() {
rawPositionUs.set(Long.MIN_VALUE)
delegate.release()
}
override fun setVolume(volume: Float) = delegate.setVolume(volume)
override fun isOffloadedPlayback() = delegate.isOffloadedPlayback()
override fun getAudioSessionId() = delegate.getAudioSessionId()
override fun getSampleRate() = delegate.getSampleRate()
override fun getBufferSizeInFrames() = delegate.getBufferSizeInFrames()
override fun getPlaybackParameters() = delegate.getPlaybackParameters()
override fun isStalled() = delegate.isStalled()
override fun addListener(listener: AudioOutput.Listener) = delegate.addListener(listener)
override fun removeListener(listener: AudioOutput.Listener) = delegate.removeListener(listener)
override fun setPlaybackParameters(playbackParameters: PlaybackParameters) = delegate.setPlaybackParameters(playbackParameters)
override fun setOffloadDelayPadding(delayInFrames: Int, paddingInFrames: Int) = delegate.setOffloadDelayPadding(delayInFrames, paddingInFrames)
override fun setOffloadEndOfStream() = delegate.setOffloadEndOfStream()
override fun setPlayerId(playerId: PlayerId) = delegate.setPlayerId(playerId)
override fun attachAuxEffect(effectId: Int) = delegate.attachAuxEffect(effectId)
override fun setAuxEffectSendLevel(level: Float) = delegate.setAuxEffectSendLevel(level)
override fun setPreferredDevice(preferredDevice: AudioDeviceInfo?) = delegate.setPreferredDevice(preferredDevice)
}
@@ -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)
}
}
@@ -16,108 +16,115 @@ 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,
private val delegate: TrackOutput
) : TrackOutput {
companion object {
private const val TAG = "ZlibTrackOutput"
private const val INITIAL_BUFFER_SIZE = 256 * 1024
private const val INFLATE_CHUNK = 64 * 1024
companion object {
private const val TAG = "ZlibTrackOutput"
private const val INITIAL_BUFFER_SIZE = 256 * 1024
private const val INFLATE_CHUNK = 64 * 1024
}
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 fun sampleData(
input: DataReader,
length: Int,
allowEndOfInput: Boolean,
sampleDataPart: Int
): Int {
if (!active) return delegate.sampleData(input, length, allowEndOfInput, sampleDataPart)
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
}
var active = false
buffering = true
ensureCompressedCapacity(compressedLen + length)
data.readBytes(compressedBuf, compressedLen, length)
compressedLen += length
}
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 fun sampleData(
input: DataReader, length: Int, allowEndOfInput: Boolean, sampleDataPart: Int
): Int {
if (!active) return delegate.sampleData(input, length, allowEndOfInput, sampleDataPart)
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 sampleMetadata(
timeUs: Long,
flags: Int,
size: Int,
offset: Int,
cryptoData: TrackOutput.CryptoData?
) {
if (!active || !buffering) {
delegate.sampleMetadata(timeUs, flags, size, offset, cryptoData)
return
}
override fun sampleData(data: ParsableByteArray, length: Int, sampleDataPart: Int) {
if (!active) {
delegate.sampleData(data, length, sampleDataPart)
return
}
buffering = false
val srcLen = compressedLen
compressedLen = 0
buffering = true
ensureCompressedCapacity(compressedLen + length)
data.readBytes(compressedBuf, compressedLen, length)
compressedLen += length
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
}
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
}
outputParsable.reset(inflateBuf, inflatedLen)
delegate.sampleData(outputParsable, inflatedLen, TrackOutput.SAMPLE_DATA_PART_MAIN)
delegate.sampleMetadata(timeUs, flags, inflatedLen, 0, cryptoData)
}
buffering = false
val srcLen = compressedLen
compressedLen = 0
private fun appendCompressed(src: ByteArray, offset: Int, length: Int) {
ensureCompressedCapacity(compressedLen + length)
System.arraycopy(src, offset, compressedBuf, compressedLen, length)
compressedLen += length
}
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 ensureCompressedCapacity(needed: Int) {
if (compressedBuf.size < needed) {
compressedBuf = compressedBuf.copyOf(maxOf(needed, compressedBuf.size * 2))
}
}
private fun appendCompressed(src: ByteArray, offset: Int, length: Int) {
ensureCompressedCapacity(compressedLen + length)
System.arraycopy(src, offset, compressedBuf, compressedLen, length)
compressedLen += length
private fun ensureInflateCapacity(needed: Int) {
if (inflateBuf.size < needed) {
inflateBuf = ByteArray(maxOf(needed, inflateBuf.size * 2))
}
}
private fun ensureCompressedCapacity(needed: Int) {
if (compressedBuf.size < needed) {
compressedBuf = compressedBuf.copyOf(maxOf(needed, compressedBuf.size * 2))
}
}
private fun ensureInflateCapacity(needed: Int) {
if (inflateBuf.size < needed) {
inflateBuf = ByteArray(maxOf(needed, inflateBuf.size * 2))
}
}
private fun growInflateBuf() {
inflateBuf = inflateBuf.copyOf(inflateBuf.size * 2)
}
private fun growInflateBuf() {
inflateBuf = inflateBuf.copyOf(inflateBuf.size * 2)
}
}
@@ -6,9 +6,9 @@ import androidx.media3.extractor.ExtractorOutput
import androidx.media3.extractor.SeekMap
import androidx.media3.extractor.TrackOutput
import androidx.media3.extractor.mkv.MatroskaExtractor
import io.github.peerless2012.ass.media.AssHandler
import io.github.peerless2012.ass.media.extractor.AssMatroskaExtractor
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).
@@ -20,97 +20,97 @@ import androidx.media3.extractor.text.SubtitleParser
* - Skips ContentCompSettings for zlib tracks (not applicable)
*/
class ZlibMatroskaExtractor(
subtitleParserFactory: SubtitleParser.Factory,
assHandler: AssHandler,
subtitleParserFactory: SubtitleParser.Factory,
assHandler: AssHandler
) : AssMatroskaExtractor(subtitleParserFactory, assHandler) {
companion object {
private const val TAG = "ZlibMkvExtractor"
companion object {
private const val TAG = "ZlibMkvExtractor"
// Matroska EBML element IDs
private const val ID_SEGMENT = 0x18538067
private const val ID_TRACK_ENTRY = 0xAE
private const val ID_CONTENT_COMPRESSION_ALGORITHM = 0x4254
private const val ID_CONTENT_COMPRESSION_SETTINGS = 0x4255
// Matroska EBML element IDs
private const val ID_SEGMENT = 0x18538067
private const val ID_TRACK_ENTRY = 0xAE
private const val ID_CONTENT_COMPRESSION_ALGORITHM = 0x4254
private const val ID_CONTENT_COMPRESSION_SETTINGS = 0x4255
private val extractorOutputField by lazy {
MatroskaExtractor::class.java.getDeclaredField("extractorOutput").apply {
isAccessible = true
}
}
private val extractorOutputField by lazy {
MatroskaExtractor::class.java.getDeclaredField("extractorOutput").apply {
isAccessible = true
}
}
}
private var zlibOutput: ZlibExtractorOutputWrapper? = 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
if (id == ID_SEGMENT && zlibOutput == null) {
val currentOutput = extractorOutputField.get(this) as ExtractorOutput
val wrapper = ZlibExtractorOutputWrapper(currentOutput)
zlibOutput = wrapper
extractorOutputField.set(this, wrapper)
Log.d(TAG, "Installed zlib ExtractorOutput wrapper")
}
}
override fun integerElement(id: Int, value: Long) {
if (id == ID_CONTENT_COMPRESSION_ALGORITHM && value == 0L) {
currentTrackUsesZlib = true
Log.i(TAG, "Track uses ContentCompAlgo 0 (zlib), will inflate samples")
// Tell parent it's header stripping (algo 3) to avoid ParserException
super.integerElement(id, 3)
return
}
super.integerElement(id, value)
}
override fun binaryElement(id: Int, contentSize: Int, input: ExtractorInput) {
if (id == ID_CONTENT_COMPRESSION_SETTINGS && currentTrackUsesZlib) {
// Skip ContentCompSettings for zlib tracks — parent would store these as
// sampleStrippedBytes and prepend them to every sample, corrupting output.
input.skipFully(contentSize)
return
}
super.binaryElement(id, contentSize, input)
}
override fun endMasterElement(id: Int) {
val wasZlib = currentTrackUsesZlib
super.endMasterElement(id)
if (id == ID_TRACK_ENTRY && wasZlib) {
zlibOutput?.activateLast()
currentTrackUsesZlib = false
Log.i(TAG, "Activated zlib inflation for track")
}
}
/**
* ExtractorOutput wrapper that wraps all TrackOutputs with ZlibInflatingTrackOutput.
* Tracks are created inactive; activateLast() enables inflation for the most recently
* created track (called when we know a track uses zlib compression).
*/
private class ZlibExtractorOutputWrapper(
private val delegate: ExtractorOutput
) : ExtractorOutput {
private var lastCreatedWrapper: ZlibInflatingTrackOutput? = null
override fun track(id: Int, type: Int): TrackOutput {
val original = delegate.track(id, type)
val wrapper = ZlibInflatingTrackOutput(original)
lastCreatedWrapper = wrapper
return wrapper
}
private var zlibOutput: ZlibExtractorOutputWrapper? = 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
if (id == ID_SEGMENT && zlibOutput == null) {
val currentOutput = extractorOutputField.get(this) as ExtractorOutput
val wrapper = ZlibExtractorOutputWrapper(currentOutput)
zlibOutput = wrapper
extractorOutputField.set(this, wrapper)
Log.d(TAG, "Installed zlib ExtractorOutput wrapper")
}
fun activateLast() {
lastCreatedWrapper?.active = true
}
override fun integerElement(id: Int, value: Long) {
if (id == ID_CONTENT_COMPRESSION_ALGORITHM && value == 0L) {
currentTrackUsesZlib = true
Log.i(TAG, "Track uses ContentCompAlgo 0 (zlib), will inflate samples")
// Tell parent it's header stripping (algo 3) to avoid ParserException
super.integerElement(id, 3)
return
}
super.integerElement(id, value)
}
override fun binaryElement(id: Int, contentSize: Int, input: ExtractorInput) {
if (id == ID_CONTENT_COMPRESSION_SETTINGS && currentTrackUsesZlib) {
// Skip ContentCompSettings for zlib tracks — parent would store these as
// sampleStrippedBytes and prepend them to every sample, corrupting output.
input.skipFully(contentSize)
return
}
super.binaryElement(id, contentSize, input)
}
override fun endMasterElement(id: Int) {
val wasZlib = currentTrackUsesZlib
super.endMasterElement(id)
if (id == ID_TRACK_ENTRY && wasZlib) {
zlibOutput?.activateLast()
currentTrackUsesZlib = false
Log.i(TAG, "Activated zlib inflation for track")
}
}
/**
* ExtractorOutput wrapper that wraps all TrackOutputs with ZlibInflatingTrackOutput.
* Tracks are created inactive; activateLast() enables inflation for the most recently
* created track (called when we know a track uses zlib compression).
*/
private class ZlibExtractorOutputWrapper(
private val delegate: ExtractorOutput,
) : ExtractorOutput {
private var lastCreatedWrapper: ZlibInflatingTrackOutput? = null
override fun track(id: Int, type: Int): TrackOutput {
val original = delegate.track(id, type)
val wrapper = ZlibInflatingTrackOutput(original)
lastCreatedWrapper = wrapper
return wrapper
}
fun activateLast() {
lastCreatedWrapper?.active = true
}
override fun endTracks() = delegate.endTracks()
override fun seekMap(seekMap: SeekMap) = delegate.seekMap(seekMap)
}
override fun endTracks() = delegate.endTracks()
override fun seekMap(seekMap: SeekMap) = delegate.seekMap(seekMap)
}
}
File diff suppressed because it is too large Load Diff
@@ -10,307 +10,419 @@ import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
class MpvPlayerPlugin : FlutterPlugin, MethodChannel.MethodCallHandler,
EventChannel.StreamHandler, ActivityAware, com.edde746.plezy.shared.PlayerDelegate {
class MpvPlayerPlugin :
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"
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 lateinit var methodChannel: MethodChannel
private lateinit var eventChannel: EventChannel
private var eventSink: EventChannel.EventSink? = null
private var playerCore: MpvPlayerCore? = null
private var activity: Activity? = null
private var activityBinding: ActivityPluginBinding? = null
private val nameToId = mutableMapOf<String, Int>()
private var sessionGeneration = 0
// 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
// was the root cause of #930.
private val pendingInitResults = mutableListOf<MethodChannel.Result>()
@Volatile private var isInitializing = false
// 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")
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
methodChannel.setMethodCallHandler(null)
eventChannel.setStreamHandler(null)
Log.d(TAG, "Detached from engine")
}
// ActivityAware
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
activity = binding.activity
activityBinding = binding
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)
activity = null
activityBinding = null
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")
}
override fun onDetachedFromActivityForConfigChanges() {
activity = null
activityBinding = null
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")
}
override fun onCancel(arguments: Any?) {
eventSink = null
Log.d(TAG, "Event stream disconnected")
}
// MethodChannel.MethodCallHandler
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
when (call.method) {
"initialize" -> handleInitialize(result)
"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)
"updateFrame" -> handleUpdateFrame(result)
"setVideoFrameRate" -> handleSetVideoFrameRate(call, result)
"clearVideoFrameRate" -> handleClearVideoFrameRate(result)
"requestAudioFocus" -> handleRequestAudioFocus(result)
"abandonAudioFocus" -> handleAbandonAudioFocus(result)
"openContentFd" -> handleOpenContentFd(call, result)
"isInitialized" -> result.success(playerCore?.isInitialized ?: false)
"setLogLevel" -> result.success(null)
else -> result.notImplemented()
}
}
private fun handleInitialize(result: MethodChannel.Result) {
val currentActivity = activity
if (currentActivity == null) {
result.error("NO_ACTIVITY", "Activity not available", null)
return
}
private lateinit var methodChannel: MethodChannel
private lateinit var eventChannel: EventChannel
private var eventSink: EventChannel.EventSink? = null
private var playerCore: MpvPlayerCore? = null
private var activity: Activity? = null
private var activityBinding: ActivityPluginBinding? = null
private val nameToId = mutableMapOf<String, Int>()
private var sessionGeneration = 0
// 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")
if (playerCore?.isInitialized == true) {
Log.d(TAG, "Already initialized")
result.success(true)
return
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
methodChannel.setMethodCallHandler(null)
eventChannel.setStreamHandler(null)
Log.d(TAG, "Detached from engine")
// Coalesce concurrent inits: the second caller waits for the first
// call's outcome instead of disposing the in-flight core. The Dart
// side memoizes too, but this is defense in depth for any direct
// `invoke('initialize')` that bypasses _ensureInitialized.
synchronized(pendingInitResults) {
pendingInitResults += result
if (isInitializing) {
Log.d(TAG, "Init already in flight, queuing caller")
return
}
isInitializing = true
}
// ActivityAware
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
activity = binding.activity
activityBinding = binding
Log.d(TAG, "Attached to activity")
}
override fun onDetachedFromActivity() {
++sessionGeneration
playerCore?.dispose()
playerCore = null
activity = null
activityBinding = null
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")
}
override fun onDetachedFromActivityForConfigChanges() {
activity = null
activityBinding = null
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")
}
override fun onCancel(arguments: Any?) {
eventSink = null
Log.d(TAG, "Event stream disconnected")
}
// MethodChannel.MethodCallHandler
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
when (call.method) {
"initialize" -> handleInitialize(result)
"dispose" -> handleDispose(result)
"setProperty" -> handleSetProperty(call, result)
"getProperty" -> handleGetProperty(call, result)
"observeProperty" -> handleObserveProperty(call, result)
"command" -> handleCommand(call, result)
"setVisible" -> handleSetVisible(call, result)
"updateFrame" -> handleUpdateFrame(result)
"setVideoFrameRate" -> handleSetVideoFrameRate(call, result)
"clearVideoFrameRate" -> handleClearVideoFrameRate(result)
"requestAudioFocus" -> handleRequestAudioFocus(result)
"abandonAudioFocus" -> handleAbandonAudioFocus(result)
"openContentFd" -> handleOpenContentFd(call, result)
"isInitialized" -> result.success(playerCore?.isInitialized ?: false)
"setLogLevel" -> result.success(null)
else -> result.notImplemented()
}
}
private fun handleInitialize(result: MethodChannel.Result) {
val currentActivity = activity
if (currentActivity == null) {
result.error("NO_ACTIVITY", "Activity not available", null)
return
currentActivity.runOnUiThread {
val gen: Int
val core: MpvPlayerCore
try {
// Caller invariant: dispose() was already called explicitly,
// 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")
playerCore?.dispose()
playerCore = null
}
if (playerCore?.isInitialized == true) {
Log.d(TAG, "Already initialized")
result.success(true)
return
gen = ++sessionGeneration
core = MpvPlayerCore(currentActivity).apply {
delegate = this@MpvPlayerPlugin
}
playerCore = core
} catch (e: Exception) {
Log.e(TAG, "Failed to initialize: ${e.message}", e)
completePendingInits(success = false, errorMessage = e.message)
return@runOnUiThread
}
currentActivity.runOnUiThread {
try {
// Dispose stale core idempotently
playerCore?.dispose()
playerCore = null
val gen = ++sessionGeneration
val core = MpvPlayerCore(currentActivity).apply {
delegate = this@MpvPlayerPlugin
}
playerCore = core
core.initialize { success ->
if (gen != sessionGeneration || playerCore !== core) {
Log.d(TAG, "Stale init callback (gen=$gen, current=$sessionGeneration)")
result.success(false)
return@initialize
}
// Start hidden - now safe because setVisible operates on the container,
// not the SurfaceView directly (matching ExoPlayer's approach)
core.setVisible(false)
Log.d(TAG, "Initialized: $success")
result.success(success)
}
} catch (e: Exception) {
Log.e(TAG, "Failed to initialize: ${e.message}", e)
result.error("INIT_FAILED", e.message, null)
}
core.initialize { success ->
val stale = gen != sessionGeneration || playerCore !== core
if (stale) {
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)
core.setVisible(false)
Log.d(TAG, "Initialized: $success")
}
completePendingInits(success = !stale && success)
}
}
}
private fun handleDispose(result: MethodChannel.Result) {
activity?.runOnUiThread {
val core = playerCore
++sessionGeneration
playerCore = null
core?.dispose {
Log.d(TAG, "Disposed")
result.success(null)
} ?: result.success(null)
} ?: result.success(null)
private fun completePendingInits(success: Boolean, errorMessage: String? = null) {
val pending = synchronized(pendingInitResults) {
isInitializing = false
val copy = pendingInitResults.toList()
pendingInitResults.clear()
copy
}
for (r in pending) {
if (errorMessage != null) {
r.error("INIT_FAILED", errorMessage, null)
} else {
r.success(success)
}
}
}
private fun handleSetProperty(call: MethodCall, result: MethodChannel.Result) {
val name = call.argument<String>("name")
val value = call.argument<String>("value")
private fun handleDispose(result: MethodChannel.Result) {
activity?.runOnUiThread {
val core = playerCore
++sessionGeneration
playerCore = null
if (name == null || value == null) {
result.error("INVALID_ARGS", "Missing 'name' or 'value'", null)
return
}
// Any in-flight init callback is cancelled with the scope, so
// close out queued callers here instead of leaking them.
completePendingInits(success = false)
playerCore?.setProperty(name, value)
core?.dispose {
Log.d(TAG, "Disposed")
result.success(null)
} ?: result.success(null)
} ?: result.success(null)
}
private fun handleSetProperty(call: MethodCall, result: MethodChannel.Result) {
val name = call.argument<String>("name")
val value = call.argument<String>("value")
if (name == null || value == null) {
result.error("INVALID_ARGS", "Missing 'name' or 'value'", null)
return
}
private fun handleGetProperty(call: MethodCall, result: MethodChannel.Result) {
val name = call.argument<String>("name")
val core = playerCore
if (core == null) {
result.success(null)
return
}
if (name == null) {
result.error("INVALID_ARGS", "Missing 'name'", null)
return
}
core.setProperty(name, value) {
result.success(null)
}
}
val value = playerCore?.getProperty(name)
private fun handleGetProperty(call: MethodCall, result: MethodChannel.Result) {
val name = call.argument<String>("name")
if (name == null) {
result.error("INVALID_ARGS", "Missing 'name'", null)
return
}
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 currentActivity = activity
val core = playerCore
if (currentActivity == null || core == null) {
result.success(mapOf("playerType" to "mpv"))
return
}
private fun handleObserveProperty(call: MethodCall, result: MethodChannel.Result) {
val name = call.argument<String>("name")
val format = call.argument<String>("format")
val id = call.argument<Int>("id")
val gen = sessionGeneration
Thread {
val stats = core.getStats()
currentActivity.runOnUiThread {
if (gen != sessionGeneration || playerCore !== core) {
result.success(mapOf("playerType" to "mpv"))
} else {
result.success(stats)
}
}
}.start()
}
if (name == null || format == null || id == null) {
result.error("INVALID_ARGS", "Missing 'name', 'format', or 'id'", null)
return
private fun handleObserveProperty(call: MethodCall, result: MethodChannel.Result) {
val name = call.argument<String>("name")
val format = call.argument<String>("format")
val id = call.argument<Int>("id")
if (name == null || format == null || id == null) {
result.error("INVALID_ARGS", "Missing 'name', 'format', or 'id'", null)
return
}
nameToId[name] = id
playerCore?.observeProperty(name, format)
result.success(null)
}
private fun handleCommand(call: MethodCall, result: MethodChannel.Result) {
val args = call.argument<List<String>>("args")
if (args == null) {
result.error("INVALID_ARGS", "Missing 'args'", null)
return
}
val core = playerCore
if (core == null) {
result.success(null)
return
}
core.command(args.toTypedArray()) {
result.success(null)
}
}
private fun handleSetVisible(call: MethodCall, result: MethodChannel.Result) {
val visible = call.argument<Boolean>("visible")
if (visible == null) {
result.error("INVALID_ARGS", "Missing 'visible'", null)
return
}
playerCore?.setVisible(visible)
result.success(null)
}
private fun handleUpdateFrame(result: MethodChannel.Result) {
playerCore?.updateFrame()
result.success(null)
}
private fun handleSetVideoFrameRate(call: MethodCall, result: MethodChannel.Result) {
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, video=${videoWidth}x$videoHeight")
val core = playerCore
if (core == null) {
result.success(false)
return
}
core.setVideoFrameRate(fps, duration, extraDelayMs, videoWidth, videoHeight) { switched ->
result.success(switched)
}
}
private fun handleClearVideoFrameRate(result: MethodChannel.Result) {
Log.d(TAG, "clearVideoFrameRate")
playerCore?.clearVideoFrameRate()
result.success(null)
}
private fun handleRequestAudioFocus(result: MethodChannel.Result) {
Log.d(TAG, "requestAudioFocus")
val granted = playerCore?.requestAudioFocus() ?: false
result.success(granted)
}
private fun handleAbandonAudioFocus(result: MethodChannel.Result) {
Log.d(TAG, "abandonAudioFocus")
playerCore?.abandonAudioFocus()
result.success(null)
}
private fun handleOpenContentFd(call: MethodCall, result: MethodChannel.Result) {
val uriString = call.argument<String>("uri")
if (uriString == null) {
result.error("INVALID_ARGS", "Missing 'uri'", null)
return
}
val contentResolver = activity?.contentResolver
if (contentResolver == null) {
result.error("NO_ACTIVITY", "Activity not available", null)
return
}
// Open file descriptor off UI thread to prevent ANR on slow storage
Thread {
try {
val uri = Uri.parse(uriString)
val pfd = contentResolver.openFileDescriptor(uri, "r")
if (pfd == null) {
activity?.runOnUiThread {
result.error("OPEN_FAILED", "Failed to open file descriptor for $uriString", null)
}
return@Thread
}
nameToId[name] = id
playerCore?.observeProperty(name, format)
result.success(null)
}
val fd = pfd.detachFd()
Log.d(TAG, "Opened content FD $fd for $uriString")
activity?.runOnUiThread { 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) }
}
}.start()
}
private fun handleCommand(call: MethodCall, result: MethodChannel.Result) {
val args = call.argument<List<String>>("args")
// PlayerDelegate
if (args == null) {
result.error("INVALID_ARGS", "Missing 'args'", null)
return
}
override fun onPropertyChange(name: String, value: Any?) {
val propId = nameToId[name] ?: return
eventSink?.success(listOf(propId, value))
}
playerCore?.command(args.toTypedArray())
result.success(null)
}
private fun handleSetVisible(call: MethodCall, result: MethodChannel.Result) {
val visible = call.argument<Boolean>("visible")
if (visible == null) {
result.error("INVALID_ARGS", "Missing 'visible'", null)
return
}
playerCore?.setVisible(visible)
result.success(null)
}
private fun handleUpdateFrame(result: MethodChannel.Result) {
playerCore?.updateFrame()
result.success(null)
}
private fun handleSetVideoFrameRate(call: MethodCall, result: MethodChannel.Result) {
val fps = call.argument<Double>("fps")?.toFloat() ?: 0f
val duration = call.argument<Number>("duration")?.toLong() ?: 0L
Log.d(TAG, "setVideoFrameRate: fps=$fps, duration=$duration")
playerCore?.setVideoFrameRate(fps, duration)
result.success(null)
}
private fun handleClearVideoFrameRate(result: MethodChannel.Result) {
Log.d(TAG, "clearVideoFrameRate")
playerCore?.clearVideoFrameRate()
result.success(null)
}
private fun handleRequestAudioFocus(result: MethodChannel.Result) {
Log.d(TAG, "requestAudioFocus")
val granted = playerCore?.requestAudioFocus() ?: false
result.success(granted)
}
private fun handleAbandonAudioFocus(result: MethodChannel.Result) {
Log.d(TAG, "abandonAudioFocus")
playerCore?.abandonAudioFocus()
result.success(null)
}
private fun handleOpenContentFd(call: MethodCall, result: MethodChannel.Result) {
val uriString = call.argument<String>("uri")
if (uriString == null) {
result.error("INVALID_ARGS", "Missing 'uri'", null)
return
}
val contentResolver = activity?.contentResolver
if (contentResolver == null) {
result.error("NO_ACTIVITY", "Activity not available", null)
return
}
// Open file descriptor off UI thread to prevent ANR on slow storage
Thread {
try {
val uri = Uri.parse(uriString)
val pfd = contentResolver.openFileDescriptor(uri, "r")
if (pfd == null) {
activity?.runOnUiThread {
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) }
} catch (e: Exception) {
Log.e(TAG, "Failed to open content FD: ${e.message}", e)
activity?.runOnUiThread { result.error("OPEN_FAILED", e.message, null) }
}
}.start()
}
// PlayerDelegate
override fun onPropertyChange(name: String, value: Any?) {
val propId = nameToId[name] ?: return
eventSink?.success(listOf(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)
}
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)
}
}
@@ -9,97 +9,97 @@ import android.os.Handler
import android.util.Log
class AudioFocusManager(
context: Context,
private val handler: Handler,
private val onPause: () -> Unit,
private val onResume: () -> Unit,
private val isPaused: () -> Boolean,
private val log: (String) -> Unit = { Log.d(TAG, it) }
context: Context,
private val handler: Handler,
private val onPause: () -> Unit,
private val onResume: () -> Unit,
private val isPaused: () -> Boolean,
private val log: (String) -> Unit = { Log.d(TAG, it) }
) {
companion object {
private const val TAG = "AudioFocusManager"
}
companion object {
private const val TAG = "AudioFocusManager"
}
private val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
private var audioFocusRequest: AudioFocusRequest? = null
private var hasAudioFocus: Boolean = false
var wasPlayingBeforeFocusLoss: Boolean = false
private set
private val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
private var audioFocusRequest: AudioFocusRequest? = null
private var hasAudioFocus: Boolean = false
var wasPlayingBeforeFocusLoss: Boolean = false
private set
private val audioFocusChangeListener = AudioManager.OnAudioFocusChangeListener { focusChange ->
when (focusChange) {
AudioManager.AUDIOFOCUS_GAIN -> {
log("Focus gained")
hasAudioFocus = true
if (wasPlayingBeforeFocusLoss) {
onResume()
wasPlayingBeforeFocusLoss = false
}
}
AudioManager.AUDIOFOCUS_LOSS -> {
log("Focus lost permanently")
hasAudioFocus = false
wasPlayingBeforeFocusLoss = !isPaused()
onPause()
}
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> {
log("Focus lost transiently")
hasAudioFocus = false
wasPlayingBeforeFocusLoss = !isPaused()
onPause()
}
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> {
log("Focus lost transiently (can duck)")
}
private val audioFocusChangeListener = AudioManager.OnAudioFocusChangeListener { focusChange ->
when (focusChange) {
AudioManager.AUDIOFOCUS_GAIN -> {
log("Focus gained")
hasAudioFocus = true
if (wasPlayingBeforeFocusLoss) {
onResume()
wasPlayingBeforeFocusLoss = false
}
}
fun requestAudioFocus(): Boolean {
Log.d(TAG, "Requesting audio focus")
val result = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val focusRequest = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
.setAudioAttributes(
AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MOVIE)
.build()
)
.setOnAudioFocusChangeListener(audioFocusChangeListener, handler)
.build()
audioFocusRequest = focusRequest
audioManager.requestAudioFocus(focusRequest)
} else {
@Suppress("DEPRECATION")
audioManager.requestAudioFocus(
audioFocusChangeListener,
AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN
)
}
hasAudioFocus = (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED)
Log.d(TAG, "Audio focus request result: $result, granted: $hasAudioFocus")
return hasAudioFocus
}
fun abandonAudioFocus() {
Log.d(TAG, "Abandoning audio focus")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
audioFocusRequest?.let { audioManager.abandonAudioFocusRequest(it) }
audioFocusRequest = null
} else {
@Suppress("DEPRECATION")
audioManager.abandonAudioFocus(audioFocusChangeListener)
}
}
AudioManager.AUDIOFOCUS_LOSS -> {
log("Focus lost permanently")
hasAudioFocus = false
wasPlayingBeforeFocusLoss = false
wasPlayingBeforeFocusLoss = !isPaused()
onPause()
}
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> {
log("Focus lost transiently")
hasAudioFocus = false
wasPlayingBeforeFocusLoss = !isPaused()
onPause()
}
AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> {
log("Focus lost transiently (can duck)")
}
}
}
fun requestAudioFocus(): Boolean {
Log.d(TAG, "Requesting audio focus")
val result = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val focusRequest = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
.setAudioAttributes(
AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MOVIE)
.build()
)
.setOnAudioFocusChangeListener(audioFocusChangeListener, handler)
.build()
audioFocusRequest = focusRequest
audioManager.requestAudioFocus(focusRequest)
} else {
@Suppress("DEPRECATION")
audioManager.requestAudioFocus(
audioFocusChangeListener,
AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN
)
}
fun release() {
abandonAudioFocus()
hasAudioFocus = (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED)
Log.d(TAG, "Audio focus request result: $result, granted: $hasAudioFocus")
return hasAudioFocus
}
fun abandonAudioFocus() {
Log.d(TAG, "Abandoning audio focus")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
audioFocusRequest?.let { audioManager.abandonAudioFocusRequest(it) }
audioFocusRequest = null
} else {
@Suppress("DEPRECATION")
audioManager.abandonAudioFocus(audioFocusChangeListener)
}
hasAudioFocus = false
wasPlayingBeforeFocusLoss = false
}
fun release() {
abandonAudioFocus()
}
}
@@ -0,0 +1,23 @@
package com.edde746.plezy.shared
import android.os.Build
object DeviceQuirks {
val isEWaste: Boolean
get() = isGooglePixelDevice || isGoogleTensorDevice
private val isGooglePixelDevice: Boolean
get() = (
Build.MANUFACTURER.equals("Google", ignoreCase = true) ||
Build.BRAND.equals("google", ignoreCase = true)
) &&
Build.MODEL.contains("Pixel", ignoreCase = true)
private val isGoogleTensorDevice: Boolean
get() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return false
val soc = Build.SOC_MODEL
return soc.startsWith("Tensor", ignoreCase = true) ||
soc.startsWith("GS", ignoreCase = true)
}
}
@@ -1,6 +1,7 @@
package com.edde746.plezy.shared
import android.graphics.PixelFormat
import android.os.Build
import android.view.SurfaceView
import android.view.TextureView
import android.view.View
@@ -8,52 +9,84 @@ import android.view.ViewGroup
object FlutterOverlayHelper {
/**
* Find the FlutterView container in the content view hierarchy.
* First tries to match by class name (works in debug builds),
* then falls back to picking the last ViewGroup with children
* (needed for release builds where FlutterView may be obfuscated).
*/
fun findFlutterContainer(contentView: ViewGroup, excludeView: View? = null): ViewGroup? {
// First pass: look for FlutterView by name (debug builds)
for (i in 0 until contentView.childCount) {
val child = contentView.getChildAt(i)
if (child is ViewGroup && child.javaClass.name.contains("FlutterView")) {
return child
}
}
// Fallback for release (FlutterView may be obfuscated): pick the last ViewGroup
// that is not our video container and has children.
for (i in contentView.childCount - 1 downTo 0) {
val child = contentView.getChildAt(i)
if (child is ViewGroup && child != excludeView && child.childCount > 0) {
return child
}
}
return null
/**
* Find the top-level container holding the Flutter render surface. Returns the
* direct child of [contentView] that contains a FlutterSurfaceView/FlutterTextureView
* at any depth — `bringChildToFront` only works for direct children, so this is the
* node to pass to [configureFlutterZOrder].
*
* Searches any depth because an app may wrap Flutter (e.g. for key-event dispatch)
* and push it below the direct-child level.
*/
fun findFlutterContainer(contentView: ViewGroup, excludeView: View? = null): ViewGroup? {
for (i in contentView.childCount - 1 downTo 0) {
val child = contentView.getChildAt(i)
if (child === excludeView || child !is ViewGroup) continue
if (findRenderSurface(child) != null) return child
}
return null
}
/**
* Configure z-ordering so the Flutter UI renders above the video surface.
*
* @param zOrderOnTop true for MPV (Flutter needs to be fully on top),
* false for ExoPlayer (subtitle layer sits between video and Flutter)
*/
fun configureFlutterZOrder(contentView: ViewGroup, container: ViewGroup, zOrderOnTop: Boolean) {
contentView.bringChildToFront(container)
for (j in 0 until container.childCount) {
val flutterChild = container.getChildAt(j)
if (flutterChild is SurfaceView) {
flutterChild.setZOrderOnTop(zOrderOnTop)
flutterChild.setZOrderMediaOverlay(true)
flutterChild.holder.setFormat(PixelFormat.TRANSLUCENT)
break
} else if (flutterChild is TextureView) {
flutterChild.isOpaque = false
break
}
}
private fun findRenderSurface(root: ViewGroup): View? {
for (i in 0 until root.childCount) {
val child = root.getChildAt(i)
if (child is SurfaceView || child is TextureView) return child
if (child is ViewGroup) findRenderSurface(child)?.let { return it }
}
return null
}
/**
* Apply [SurfaceView.setCompositionOrder] on API 36+; no-op on older APIs where
* the legacy [SurfaceView.setZOrderOnTop]/[SurfaceView.setZOrderMediaOverlay]
* bucket settings govern Z-order instead.
*
* The value maps directly to the SurfaceView's `mSubLayer`. Per AOSP semantics:
* `mSubLayer >= 0` (non-negative `order`) is composited above the parent window
* and skips the hole-punch in `draw()`; `mSubLayer < 0` (negative `order`) is
* behind the parent window and the SurfaceView is made visible by punching a
* transparent hole in the parent canvas. Valid range is `[-2, 2]`. Picking the
* right sign matters: any view that draws on the parent canvas (e.g. Media3's
* `CanvasSubtitleOutput` for SRT/VTT/SDH) is hidden by SurfaceViews with
* non-negative orders that sit on top of the same area.
*/
fun applyCompositionOrder(view: SurfaceView, order: Int) {
if (Build.VERSION.SDK_INT >= 36) view.compositionOrder = order
}
/**
* Configure z-ordering so the Flutter UI renders above the video/subtitle surfaces.
*
* On API 36+ the value is applied via [SurfaceView.setCompositionOrder] and maps
* directly to `mSubLayer` (see [applyCompositionOrder] for the sign semantics).
* On pre-36 SurfaceView builds the value is mapped to the legacy on-top bucket
* when positive. On TextureView builds the value is unused (view hierarchy order
* handles it).
*
* Pass a non-negative value (e.g. `1`) so Flutter renders above the parent canvas
* and lets the legacy transparent-mode `setZOrderOnTop(true)` semantics carry over.
*/
fun configureFlutterZOrder(contentView: ViewGroup, container: ViewGroup, compositionOrder: Int) {
contentView.bringChildToFront(container)
when (val surface = findRenderSurface(container)) {
is SurfaceView -> {
if (Build.VERSION.SDK_INT >= 36) {
// Clear legacy bucket hints so compositionOrder is authoritative.
// Flutter's FlutterSurfaceView sets setZOrderOnTop(true) in its
// transparent-mode constructor, which otherwise pins it to z=1.
surface.setZOrderOnTop(false)
surface.setZOrderMediaOverlay(false)
surface.compositionOrder = compositionOrder
} else {
// Pre-36 has 3 coarse sublayer buckets. Put Flutter in the on-top
// bucket so it renders above the video (default) and libass subtitle
// (media overlay) SurfaceViews. NB: setZOrderMediaOverlay overwrites
// mSubLayer internally, so don't call it here or it cancels setZOrderOnTop.
surface.setZOrderOnTop(compositionOrder > 0)
}
surface.holder.setFormat(PixelFormat.TRANSLUCENT)
}
is TextureView -> surface.isOpaque = false
}
}
}
@@ -6,179 +6,298 @@ import android.hardware.display.DisplayManager
import android.os.Build
import android.os.Handler
import android.util.Log
import android.view.Surface
import android.view.Display
import android.view.WindowManager
import androidx.annotation.RequiresApi
import java.math.BigDecimal
import java.math.RoundingMode
import kotlin.math.abs
import kotlin.math.roundToInt
class FrameRateManager(
private val activity: Activity,
private val handler: Handler,
private val onDisplayChanged: () -> Unit,
private val log: (String) -> Unit = { Log.d(TAG, it) }
private val activity: Activity,
private val handler: Handler,
private val log: (String) -> Unit = { Log.d(TAG, it) }
) {
companion object {
private const val TAG = "FrameRateManager"
private const val SHORT_VIDEO_LENGTH_MS = 300000L // 5 minutes
companion object {
private const val TAG = "FrameRateManager"
private const val DISPLAY_SETTLE_MS = 2000L
private const val WATCHDOG_MARGIN_MS = 3000L
private const val RATE_TOLERANCE = 0.1f
}
private data class RefreshRateMatch(
val reason: String,
val priority: Int,
val error: Float
)
@RequiresApi(Build.VERSION_CODES.M)
private data class DisplayModeCandidate(
val mode: Display.Mode,
val match: RefreshRateMatch
)
private var currentVideoFps: Float = 0f
private var currentVideoWidth: Int = 0
private var currentVideoHeight: Int = 0
private var displayListener: DisplayManager.DisplayListener? = null
private var pendingSettleRunnable: Runnable? = null
private var watchdogRunnable: Runnable? = null
private var pendingCompletion: ((switched: Boolean) -> Unit)? = null
private fun getDisplayManager(): DisplayManager = activity.getSystemService(Context.DISPLAY_SERVICE) as DisplayManager
// Request a display frame-rate switch. Invokes [onComplete] once, either:
// - immediately with `switched=false` when no switch is needed (invalid fps,
// no matching mode, or already matching); or
// - after the real DisplayListener event + [DISPLAY_SETTLE_MS] + the caller's
// [extraDelayMs], with `switched=true`; or
// - via a watchdog if the real event never arrives, so the caller doesn't hang.
//
// The caller is responsible for pausing playback before calling and resuming
// it after [onComplete] fires.
fun setVideoFrameRate(
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)
return
}
private var currentVideoFps: Float = 0f
private var displayListener: DisplayManager.DisplayListener? = null
log(
"request fps=$fps, duration=${videoDurationMs}ms, extraDelayMs=$extraDelayMs, " +
"video=${videoWidth}x$videoHeight, API=${Build.VERSION.SDK_INT}, currentMode=${currentModeDescription()}"
)
private fun getDisplayManager(): DisplayManager {
return activity.getSystemService(Context.DISPLAY_SERVICE) as DisplayManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
setDisplayMode(fps, extraDelayMs, onComplete)
} else {
onComplete(false)
}
}
fun clearVideoFrameRate() {
Log.d(TAG, "clearVideoFrameRate")
currentVideoFps = 0f
// Resolve any pending setVideoFrameRate future as "not switched" so
// the Dart caller's await doesn't hang on player dispose.
firePendingCompletion("clear", switched = false)
// Restore default display mode on API M (preferredDisplayModeId persists)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
activity.window?.attributes?.let { attrs ->
attrs.preferredDisplayModeId = 0
activity.window?.attributes = attrs
}
}
}
// Release pending callbacks/listener without restoring the display mode.
// Used by player-core dispose paths so a backend handoff (e.g. ExoPlayer→MPV
// audio fallback) doesn't clobber the just-applied refresh-rate switch —
// window-scoped preferredDisplayModeId persists across the SurfaceView swap,
// letting MPV inherit the rate without a second HDMI renegotiation.
fun releasePending() {
Log.d(TAG, "releasePending")
currentVideoFps = 0f
firePendingCompletion("release", switched = false)
}
private fun cancelPendingCallbacks() {
pendingSettleRunnable?.let { handler.removeCallbacks(it) }
watchdogRunnable?.let { handler.removeCallbacks(it) }
pendingSettleRunnable = null
watchdogRunnable = null
}
private fun firePendingCompletion(reason: String, switched: Boolean) {
cancelPendingCallbacks()
displayListener?.let {
getDisplayManager().unregisterDisplayListener(it)
displayListener = null
}
val cb = pendingCompletion ?: return
pendingCompletion = null
log("complete reason=$reason, switched=$switched, currentMode=${currentModeDescription()}")
cb(switched)
}
private fun registerDisplayListener(fps: Float, extraDelayMs: Long, onComplete: (switched: Boolean) -> Unit) {
// Resolve any previous pending op before starting a new one.
firePendingCompletion("superseded", switched = false)
pendingCompletion = onComplete
displayListener = object : DisplayManager.DisplayListener {
override fun onDisplayAdded(displayId: Int) = Unit
override fun onDisplayRemoved(displayId: Int) = Unit
override fun onDisplayChanged(displayId: Int) {
// Unregister immediately so a chatty display (e.g. several
// onDisplayChanged events during HDMI renegotiation) doesn't
// queue multiple settle callbacks.
getDisplayManager().unregisterDisplayListener(this)
displayListener = null
val settle = Runnable { firePendingCompletion("display settled", switched = currentRateMatch(fps) != null) }
pendingSettleRunnable = settle
handler.postDelayed(settle, DISPLAY_SETTLE_MS + extraDelayMs)
}
}
getDisplayManager().registerDisplayListener(displayListener, handler)
// Watchdog: if the TV never signals a display change (silently ignoring
// the mode request), still complete after a bounded wait so the caller
// doesn't hang.
val watchdog = Runnable { firePendingCompletion("watchdog", switched = currentRateMatch(fps) != null) }
watchdogRunnable = watchdog
handler.postDelayed(watchdog, DISPLAY_SETTLE_MS + extraDelayMs + WATCHDOG_MARGIN_MS)
}
private fun matchRefreshRate(refreshRate: Float, fps: Float): RefreshRateMatch? {
if (refreshRate <= 0f || fps <= 0f) return null
val exactError = abs(refreshRate - fps)
if (exactError < RATE_TOLERANCE) {
return RefreshRateMatch(reason = "exact", priority = 0, error = exactError)
}
fun setVideoFrameRate(fps: Float, videoDurationMs: Long, surface: Surface?) {
currentVideoFps = fps
if (fps <= 0f) {
Log.d(TAG, "setVideoFrameRate: Invalid fps ($fps), skipping")
return
}
log("fps=$fps, duration=${videoDurationMs}ms, API=${Build.VERSION.SDK_INT}")
when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
if (surface == null) {
Log.d(TAG, "setVideoFrameRate: Surface not available")
return
}
setFrameRateS(fps, surface, videoDurationMs)
}
// API R's Surface.setFrameRate() only supports seamless switching (no
// CHANGE_FRAME_RATE_ALWAYS), so 60→24Hz won't switch. Fall through to
// preferredDisplayModeId which directly sets the display mode.
Build.VERSION.SDK_INT >= Build.VERSION_CODES.M -> setFrameRateM(fps)
}
val multiple = (refreshRate / fps).roundToInt()
if (multiple > 1) {
val multipleError = abs(refreshRate - (fps * multiple))
if (multipleError < RATE_TOLERANCE) {
return RefreshRateMatch(reason = "${multiple}x", priority = 1, error = multipleError)
}
}
fun clearVideoFrameRate() {
Log.d(TAG, "clearVideoFrameRate")
currentVideoFps = 0f
displayListener?.let {
getDisplayManager().unregisterDisplayListener(it)
displayListener = null
}
// Restore default display mode on API M (preferredDisplayModeId persists)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
activity.window?.attributes?.let { attrs ->
attrs.preferredDisplayModeId = 0
activity.window?.attributes = attrs
}
}
return null
}
private fun currentRateMatch(fps: Float): RefreshRateMatch? {
val current = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
currentDisplayMode()?.refreshRate
} else {
null
} ?: return null
return matchRefreshRate(current, fps)
}
private fun currentModeDescription(): String = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
describeMode(currentDisplayMode())
} else {
"unavailable"
}
@RequiresApi(Build.VERSION_CODES.M)
private fun currentDisplay(): Display? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
activity.display
} else {
@Suppress("DEPRECATION")
(activity.getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay
}
@RequiresApi(Build.VERSION_CODES.M)
private fun currentDisplayMode(): Display.Mode? = currentDisplay()?.mode
@RequiresApi(Build.VERSION_CODES.M)
private fun describeMode(mode: Display.Mode?): String {
if (mode == null) return "unknown"
return "#${mode.modeId} ${mode.physicalWidth}x${mode.physicalHeight}@${mode.refreshRate}Hz"
}
@RequiresApi(Build.VERSION_CODES.M)
private fun describeSupportedModes(modes: Array<Display.Mode>): String = modes.joinToString(prefix = "[", postfix = "]") { describeMode(it) }
@RequiresApi(Build.VERSION_CODES.M)
private fun findBestModeMatch(
fps: Float,
currentMode: Display.Mode,
supportedModes: Array<Display.Mode>,
videoWidth: Int,
videoHeight: Int
): DisplayModeCandidate? {
// Tier 1 — a matching-refresh mode at the CURRENT resolution: a refresh-only
// switch, the least disruptive (no resolution/HDMI renegotiation).
supportedModes.asSequence()
.filter { it.physicalHeight == currentMode.physicalHeight && it.physicalWidth == currentMode.physicalWidth }
.mapNotNull { mode -> matchRefreshRate(mode.refreshRate, fps)?.let { DisplayModeCandidate(mode, it) } }
.minWithOrNull(
compareBy<DisplayModeCandidate> { it.match.priority }
.thenBy { it.match.error }
.thenBy { abs(it.mode.refreshRate - currentMode.refreshRate) }
)
?.let { return it }
// Tier 2 — no same-resolution match (e.g. a 4K panel with no 4K@24 mode, but a
// 1080p@23.976 mode for 1080p content). Allow a resolution change, but never one
// that downscales the video below its native size (trading detail for cadence).
// Requires known video dimensions; without them keep Tier-1-only behaviour.
if (videoWidth <= 0 || videoHeight <= 0) return null
val currentArea = currentMode.physicalWidth.toLong() * currentMode.physicalHeight
return supportedModes.asSequence()
.filter { it.physicalWidth >= videoWidth && it.physicalHeight >= videoHeight }
.mapNotNull { mode -> matchRefreshRate(mode.refreshRate, fps)?.let { DisplayModeCandidate(mode, it) } }
.minWithOrNull(
// Prefer the resolution closest to the panel's current one (least change,
// keeps panel-native res when a high-res match exists), then refresh match.
compareBy<DisplayModeCandidate> { abs(it.mode.physicalWidth.toLong() * it.mode.physicalHeight - currentArea) }
.thenBy { it.match.priority }
.thenBy { it.match.error }
)
}
@RequiresApi(Build.VERSION_CODES.M)
private fun setDisplayMode(fps: Float, extraDelayMs: Long, onComplete: (switched: Boolean) -> Unit) {
log("setDisplayMode fps=$fps")
val display = currentDisplay()
if (display == null) {
log("display unavailable")
onComplete(false)
return
}
private fun registerDisplayListener() {
displayListener?.let {
getDisplayManager().unregisterDisplayListener(it)
}
val supportedModes = display.supportedModes
if (supportedModes == null) {
log("supported display modes unavailable")
onComplete(false)
return
}
val currentMode = display.mode
log("supported modes=${describeSupportedModes(supportedModes)}")
displayListener = object : DisplayManager.DisplayListener {
override fun onDisplayAdded(displayId: Int) = Unit
override fun onDisplayRemoved(displayId: Int) = Unit
override fun onDisplayChanged(displayId: Int) {
handler.postDelayed({
onDisplayChanged()
}, 2000L)
getDisplayManager().unregisterDisplayListener(this)
displayListener = null
}
}
getDisplayManager().registerDisplayListener(displayListener, handler)
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} " +
"(video=${currentVideoWidth}x$currentVideoHeight)"
)
onComplete(false)
return
}
@RequiresApi(Build.VERSION_CODES.S)
private fun setFrameRateS(fps: Float, surface: Surface, videoDurationMs: Long) {
Log.d(TAG, "setFrameRateS: fps=$fps, duration=${videoDurationMs}ms")
if (videoDurationMs < SHORT_VIDEO_LENGTH_MS) {
Log.d(TAG, "Short video, using seamless-only switching")
surface.setFrameRate(
fps,
Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE,
Surface.CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS
)
return
}
var seamless = false
activity.display?.mode?.alternativeRefreshRates?.let { refreshRates ->
for (rate in refreshRates) {
if (fps.toString().startsWith(rate.toString()) ||
rate.toString().startsWith(fps.toString()) ||
rate % fps == 0f) {
seamless = true
break
}
}
}
if (seamless) {
log("Seamless switch available for ${fps}fps")
surface.setFrameRate(
fps,
Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE,
Surface.CHANGE_FRAME_RATE_ALWAYS
)
registerDisplayListener()
} else {
val userPreference = getDisplayManager().matchContentFrameRateUserPreference
if (userPreference == DisplayManager.MATCH_CONTENT_FRAMERATE_ALWAYS) {
Log.d(TAG, "User preference allows non-seamless switch")
surface.setFrameRate(
fps,
Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE,
Surface.CHANGE_FRAME_RATE_ALWAYS
)
registerDisplayListener()
} else {
Log.d(TAG, "Non-seamless switch not allowed, using seamless-only")
surface.setFrameRate(
fps,
Surface.FRAME_RATE_COMPATIBILITY_FIXED_SOURCE,
Surface.CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS
)
}
}
val modeToUse = modeMatch.mode
if (modeToUse.modeId == currentMode.modeId) {
log("current mode already matches ${fps}fps (${modeMatch.match.reason}), no switch needed")
onComplete(false)
return
}
@RequiresApi(Build.VERSION_CODES.M)
private fun setFrameRateM(fps: Float) {
Log.d(TAG, "setFrameRateM: fps=$fps")
val wm = activity.getSystemService(Context.WINDOW_SERVICE) as WindowManager
@Suppress("DEPRECATION")
val display = wm.defaultDisplay ?: return
display.supportedModes?.let { supportedModes ->
val currentMode = display.mode
var modeToUse = currentMode
for (mode in supportedModes) {
if (mode.physicalHeight != currentMode.physicalHeight ||
mode.physicalWidth != currentMode.physicalWidth) {
continue
}
if (BigDecimal(fps.toString()).setScale(1, RoundingMode.FLOOR) ==
BigDecimal(mode.refreshRate.toString()).setScale(1, RoundingMode.FLOOR)) {
modeToUse = mode
break
} else if ((mode.refreshRate % fps).let { it < 0.1f || (fps - it) < 0.1f }) {
modeToUse = mode
break
}
}
if (modeToUse != currentMode) {
Log.d(TAG, "Switching to mode ${modeToUse.modeId} (${modeToUse.refreshRate}Hz)")
activity.window?.attributes?.let { attrs ->
attrs.preferredDisplayModeId = modeToUse.modeId
activity.window?.attributes = attrs
}
registerDisplayListener()
}
}
log(
"switching to ${describeMode(modeToUse)} for ${fps}fps " +
"(${modeMatch.match.reason}, error=${modeMatch.match.error})"
)
val window = activity.window
if (window == null) {
log("window unavailable")
onComplete(false)
return
}
registerDisplayListener(fps, extraDelayMs, onComplete)
window.attributes = window.attributes.apply { preferredDisplayModeId = modeToUse.modeId }
}
}
@@ -1,6 +1,6 @@
package com.edde746.plezy.shared
interface PlayerDelegate {
fun onPropertyChange(name: String, value: Any?)
fun onEvent(name: String, data: Map<String, Any>?)
fun onPropertyChange(name: String, value: Any?)
fun onEvent(name: String, data: Map<String, Any>?)
}
@@ -3,10 +3,10 @@ package com.edde746.plezy.shared
import android.graphics.Color
object ThemeHelper {
fun themeColor(mode: String?): Int? = when (mode) {
"oled" -> Color.BLACK
"dark" -> Color.parseColor("#0E0F12")
"light" -> Color.parseColor("#F7F7F8")
else -> null
}
fun themeColor(mode: String?): Int? = when (mode) {
"oled" -> Color.BLACK
"dark" -> Color.parseColor("#0E0F12")
"light" -> Color.parseColor("#F7F7F8")
else -> null
}
}
@@ -16,167 +16,169 @@ import java.util.concurrent.Executors
* Flutter plugin for Android TV Watch Next integration.
* Syncs Plex "On Deck" content to the Android TV launcher's Watch Next row.
*/
class WatchNextPlugin : FlutterPlugin, MethodChannel.MethodCallHandler {
class WatchNextPlugin :
FlutterPlugin,
MethodChannel.MethodCallHandler {
companion object {
private const val TAG = "WatchNextPlugin"
private const val METHOD_CHANNEL = "com.plezy/watch_next"
companion object {
private const val TAG = "WatchNextPlugin"
private const val METHOD_CHANNEL = "com.plezy/watch_next"
private var pendingDeepLink: String? = null
/**
* Parse a Watch Next deep link intent.
* Returns the content ID if this was a Watch Next intent, null otherwise.
*/
fun handleIntent(intent: Intent?): String? {
val data = intent?.data ?: return null
if (data.scheme == "plezy" && data.authority == "play") {
return data.getQueryParameter("content_id")
}
return null
}
}
private lateinit var methodChannel: MethodChannel
private var applicationContext: Context? = null
private var watchNextProvider: WatchNextProvider? = null
private val ioExecutor by lazy { Executors.newSingleThreadExecutor() }
private val mainHandler = Handler(Looper.getMainLooper())
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
applicationContext = binding.applicationContext
watchNextProvider = WatchNextProvider(binding.applicationContext)
methodChannel = MethodChannel(binding.binaryMessenger, METHOD_CHANNEL)
methodChannel.setMethodCallHandler(this)
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
methodChannel.setMethodCallHandler(null)
applicationContext = null
watchNextProvider = null
ioExecutor.shutdown()
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
when (call.method) {
"isSupported" -> handleIsSupported(result)
"sync" -> handleSync(call, result)
"clear" -> handleClear(result)
"remove" -> handleRemove(call, result)
"getInitialDeepLink" -> handleGetInitialDeepLink(result)
else -> result.notImplemented()
}
}
private fun handleIsSupported(result: MethodChannel.Result) {
val context = applicationContext
if (context == null) {
result.success(false)
return
}
result.success(context.packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK))
}
private fun handleSync(call: MethodCall, result: MethodChannel.Result) {
val provider = watchNextProvider
if (provider == null) {
result.error("NOT_INITIALIZED", "WatchNextProvider not initialized", null)
return
}
val itemsData = call.argument<List<Map<String, Any?>>>("items")
if (itemsData == null) {
result.error("INVALID_ARGS", "Missing 'items' argument", null)
return
}
val items = itemsData.mapNotNull { parseWatchNextItem(it) }
executeOnIo(result) { provider.syncWatchNextPrograms(items) }
}
private fun handleClear(result: MethodChannel.Result) {
val provider = watchNextProvider
if (provider == null) {
result.error("NOT_INITIALIZED", "WatchNextProvider not initialized", null)
return
}
executeOnIo(result) { provider.clearAll() }
}
private fun handleRemove(call: MethodCall, result: MethodChannel.Result) {
val provider = watchNextProvider
if (provider == null) {
result.error("NOT_INITIALIZED", "WatchNextProvider not initialized", null)
return
}
val contentId = call.argument<String>("contentId")
if (contentId == null) {
result.error("INVALID_ARGS", "Missing 'contentId' argument", null)
return
}
executeOnIo(result) { provider.removeItem(contentId) }
}
private fun executeOnIo(result: MethodChannel.Result, block: () -> Any?) {
try {
ioExecutor.execute {
try {
val value = block()
mainHandler.post { result.success(value) }
} catch (e: Exception) {
Log.e(TAG, "IO operation failed: ${e.message}", e)
mainHandler.post { result.error("IO_ERROR", e.message, null) }
}
}
} catch (e: java.util.concurrent.RejectedExecutionException) {
result.error("SHUTDOWN", "Plugin is shutting down", null)
}
}
private fun handleGetInitialDeepLink(result: MethodChannel.Result) {
val contentId = pendingDeepLink
pendingDeepLink = null
result.success(contentId)
}
private fun parseWatchNextItem(data: Map<String, Any?>): WatchNextProvider.WatchNextItem? {
val contentId = data["contentId"] as? String ?: return null
val title = data["title"] as? String ?: return null
val typeString = data["type"] as? String ?: "movie"
val type = when (typeString.lowercase()) {
"episode" -> TvContractCompat.WatchNextPrograms.TYPE_TV_EPISODE
"movie" -> TvContractCompat.WatchNextPrograms.TYPE_MOVIE
else -> TvContractCompat.WatchNextPrograms.TYPE_MOVIE
}
return WatchNextProvider.WatchNextItem(
contentId = contentId,
title = title,
episodeTitle = data["episodeTitle"] as? String,
description = data["description"] as? String,
posterUri = data["posterUri"] as? String,
type = type,
duration = (data["duration"] as? Number)?.toLong() ?: 0L,
lastPlaybackPosition = (data["lastPlaybackPosition"] as? Number)?.toLong() ?: 0L,
lastEngagementTime = (data["lastEngagementTime"] as? Number)?.toLong() ?: System.currentTimeMillis(),
seriesTitle = data["seriesTitle"] as? String,
seasonNumber = (data["seasonNumber"] as? Number)?.toInt(),
episodeNumber = (data["episodeNumber"] as? Number)?.toInt()
)
}
private var pendingDeepLink: String? = null
/**
* Store a deep link content ID for delivery to Flutter.
* Called from MainActivity on intent receipt.
* Parse a Watch Next deep link intent.
* Returns the content ID if this was a Watch Next intent, null otherwise.
*/
fun notifyDeepLink(contentId: String) {
pendingDeepLink = contentId
try {
methodChannel.invokeMethod("onWatchNextTap", mapOf("contentId" to contentId))
} catch (e: Exception) {
Log.d(TAG, "Method channel not ready, stored as pending deep link")
}
fun handleIntent(intent: Intent?): String? {
val data = intent?.data ?: return null
if (data.scheme == "plezy" && data.authority == "play") {
return data.getQueryParameter("content_id")
}
return null
}
}
private lateinit var methodChannel: MethodChannel
private var applicationContext: Context? = null
private var watchNextProvider: WatchNextProvider? = null
private val ioExecutor by lazy { Executors.newSingleThreadExecutor() }
private val mainHandler = Handler(Looper.getMainLooper())
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
applicationContext = binding.applicationContext
watchNextProvider = WatchNextProvider(binding.applicationContext)
methodChannel = MethodChannel(binding.binaryMessenger, METHOD_CHANNEL)
methodChannel.setMethodCallHandler(this)
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
methodChannel.setMethodCallHandler(null)
applicationContext = null
watchNextProvider = null
ioExecutor.shutdown()
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
when (call.method) {
"isSupported" -> handleIsSupported(result)
"sync" -> handleSync(call, result)
"clear" -> handleClear(result)
"remove" -> handleRemove(call, result)
"getInitialDeepLink" -> handleGetInitialDeepLink(result)
else -> result.notImplemented()
}
}
private fun handleIsSupported(result: MethodChannel.Result) {
val context = applicationContext
if (context == null) {
result.success(false)
return
}
result.success(context.packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK))
}
private fun handleSync(call: MethodCall, result: MethodChannel.Result) {
val provider = watchNextProvider
if (provider == null) {
result.error("NOT_INITIALIZED", "WatchNextProvider not initialized", null)
return
}
val itemsData = call.argument<List<Map<String, Any?>>>("items")
if (itemsData == null) {
result.error("INVALID_ARGS", "Missing 'items' argument", null)
return
}
val items = itemsData.mapNotNull { parseWatchNextItem(it) }
executeOnIo(result) { provider.syncWatchNextPrograms(items) }
}
private fun handleClear(result: MethodChannel.Result) {
val provider = watchNextProvider
if (provider == null) {
result.error("NOT_INITIALIZED", "WatchNextProvider not initialized", null)
return
}
executeOnIo(result) { provider.clearAll() }
}
private fun handleRemove(call: MethodCall, result: MethodChannel.Result) {
val provider = watchNextProvider
if (provider == null) {
result.error("NOT_INITIALIZED", "WatchNextProvider not initialized", null)
return
}
val contentId = call.argument<String>("contentId")
if (contentId == null) {
result.error("INVALID_ARGS", "Missing 'contentId' argument", null)
return
}
executeOnIo(result) { provider.removeItem(contentId) }
}
private fun executeOnIo(result: MethodChannel.Result, block: () -> Any?) {
try {
ioExecutor.execute {
try {
val value = block()
mainHandler.post { result.success(value) }
} catch (e: Exception) {
Log.e(TAG, "IO operation failed: ${e.message}", e)
mainHandler.post { result.error("IO_ERROR", e.message, null) }
}
}
} catch (e: java.util.concurrent.RejectedExecutionException) {
result.error("SHUTDOWN", "Plugin is shutting down", null)
}
}
private fun handleGetInitialDeepLink(result: MethodChannel.Result) {
val contentId = pendingDeepLink
pendingDeepLink = null
result.success(contentId)
}
private fun parseWatchNextItem(data: Map<String, Any?>): WatchNextProvider.WatchNextItem? {
val contentId = data["contentId"] as? String ?: return null
val title = data["title"] as? String ?: return null
val typeString = data["type"] as? String ?: "movie"
val type = when (typeString.lowercase()) {
"episode" -> TvContractCompat.WatchNextPrograms.TYPE_TV_EPISODE
"movie" -> TvContractCompat.WatchNextPrograms.TYPE_MOVIE
else -> TvContractCompat.WatchNextPrograms.TYPE_MOVIE
}
return WatchNextProvider.WatchNextItem(
contentId = contentId,
title = title,
episodeTitle = data["episodeTitle"] as? String,
description = data["description"] as? String,
posterUri = data["posterUri"] as? String,
type = type,
duration = (data["duration"] as? Number)?.toLong() ?: 0L,
lastPlaybackPosition = (data["lastPlaybackPosition"] as? Number)?.toLong() ?: 0L,
lastEngagementTime = (data["lastEngagementTime"] as? Number)?.toLong() ?: System.currentTimeMillis(),
seriesTitle = data["seriesTitle"] as? String,
seasonNumber = (data["seasonNumber"] as? Number)?.toInt(),
episodeNumber = (data["episodeNumber"] as? Number)?.toInt()
)
}
/**
* Store a deep link content ID for delivery to Flutter.
* Called from MainActivity on intent receipt.
*/
fun notifyDeepLink(contentId: String) {
pendingDeepLink = contentId
try {
methodChannel.invokeMethod("onWatchNextTap", mapOf("contentId" to contentId))
} catch (e: Exception) {
Log.d(TAG, "Method channel not ready, stored as pending deep link")
}
}
}
@@ -14,154 +14,151 @@ import androidx.tvprovider.media.tv.WatchNextProgram
*/
class WatchNextProvider(private val context: Context) {
companion object {
private const val TAG = "WatchNextProvider"
}
companion object {
private const val TAG = "WatchNextProvider"
}
data class WatchNextItem(
val contentId: String,
val title: String,
val episodeTitle: String?,
val description: String?,
val posterUri: String?,
val type: Int,
val duration: Long,
val lastPlaybackPosition: Long,
val lastEngagementTime: Long,
val seriesTitle: String?,
val seasonNumber: Int?,
val episodeNumber: Int?
data class WatchNextItem(
val contentId: String,
val title: String,
val episodeTitle: String?,
val description: String?,
val posterUri: String?,
val type: Int,
val duration: Long,
val lastPlaybackPosition: Long,
val lastEngagementTime: Long,
val seriesTitle: String?,
val seasonNumber: Int?,
val episodeNumber: Int?
)
/**
* Sync items to Watch Next row.
* Uses applyBatch to delete + insert in a single transaction so the
* launcher receives one content-change notification with the full set.
*/
fun syncWatchNextPrograms(items: List<WatchNextItem>): Boolean = try {
val ops = ArrayList<ContentProviderOperation>()
ops.add(
ContentProviderOperation.newDelete(
TvContractCompat.WatchNextPrograms.CONTENT_URI
).build()
)
/**
* Sync items to Watch Next row.
* Uses applyBatch to delete + insert in a single transaction so the
* launcher receives one content-change notification with the full set.
*/
fun syncWatchNextPrograms(items: List<WatchNextItem>): Boolean {
return try {
val ops = ArrayList<ContentProviderOperation>()
for (item in items) {
val program = buildProgram(item)
ops.add(
ContentProviderOperation.newInsert(
TvContractCompat.WatchNextPrograms.CONTENT_URI
).withValues(program.toContentValues()).build()
)
}
ops.add(
ContentProviderOperation.newDelete(
TvContractCompat.WatchNextPrograms.CONTENT_URI
).build()
context.contentResolver.applyBatch(TvContractCompat.AUTHORITY, ops)
Log.d(TAG, "Synced ${items.size} Watch Next entries")
true
} catch (e: Exception) {
Log.e(TAG, "Failed to sync Watch Next programs", e)
false
}
fun clearAll(): Boolean = try {
context.contentResolver.delete(
TvContractCompat.WatchNextPrograms.CONTENT_URI,
null,
null
)
true
} catch (e: Exception) {
Log.e(TAG, "Failed to clear Watch Next entries", e)
false
}
fun removeItem(contentId: String): Boolean {
return try {
val cursor = context.contentResolver.query(
TvContractCompat.WatchNextPrograms.CONTENT_URI,
arrayOf(
TvContractCompat.WatchNextPrograms._ID,
TvContractCompat.WatchNextPrograms.COLUMN_INTERNAL_PROVIDER_ID
),
null,
null,
null
)
cursor?.use {
val idIndex = it.getColumnIndex(TvContractCompat.WatchNextPrograms._ID)
val providerIdIndex = it.getColumnIndex(TvContractCompat.WatchNextPrograms.COLUMN_INTERNAL_PROVIDER_ID)
if (idIndex < 0 || providerIdIndex < 0) return false
while (it.moveToNext()) {
if (it.getString(providerIdIndex) == contentId) {
val id = it.getLong(idIndex)
val deleteUri = ContentUris.withAppendedId(
TvContractCompat.WatchNextPrograms.CONTENT_URI,
id
)
for (item in items) {
val program = buildProgram(item)
ops.add(
ContentProviderOperation.newInsert(
TvContractCompat.WatchNextPrograms.CONTENT_URI
).withValues(program.toContentValues()).build()
)
}
context.contentResolver.applyBatch(TvContractCompat.AUTHORITY, ops)
Log.d(TAG, "Synced ${items.size} Watch Next entries")
true
} catch (e: Exception) {
Log.e(TAG, "Failed to sync Watch Next programs", e)
false
context.contentResolver.delete(deleteUri, null, null)
return true
}
}
}
false
} catch (e: Exception) {
Log.e(TAG, "Failed to remove Watch Next item: $contentId", e)
false
}
}
private fun buildProgram(item: WatchNextItem): WatchNextProgram {
val watchNextType = if (item.lastPlaybackPosition > 0) {
TvContractCompat.WatchNextPrograms.WATCH_NEXT_TYPE_CONTINUE
} else {
TvContractCompat.WatchNextPrograms.WATCH_NEXT_TYPE_NEXT
}
fun clearAll(): Boolean {
return try {
context.contentResolver.delete(
TvContractCompat.WatchNextPrograms.CONTENT_URI,
null,
null
)
true
} catch (e: Exception) {
Log.e(TAG, "Failed to clear Watch Next entries", e)
false
}
val builder = WatchNextProgram.Builder()
.setType(item.type)
.setWatchNextType(watchNextType)
.setTitle(item.title)
.setInternalProviderId(item.contentId)
.setLastEngagementTimeUtcMillis(item.lastEngagementTime)
item.description?.let { builder.setDescription(it) }
item.posterUri?.let { uri ->
try {
builder.setPosterArtUri(Uri.parse(uri))
builder.setPosterArtAspectRatio(TvContractCompat.PreviewPrograms.ASPECT_RATIO_16_9)
} catch (e: Exception) {
Log.w(TAG, "Failed to parse poster URI: $uri", e)
}
}
fun removeItem(contentId: String): Boolean {
return try {
val cursor = context.contentResolver.query(
TvContractCompat.WatchNextPrograms.CONTENT_URI,
arrayOf(
TvContractCompat.WatchNextPrograms._ID,
TvContractCompat.WatchNextPrograms.COLUMN_INTERNAL_PROVIDER_ID
),
null,
null,
null
)
cursor?.use {
val idIndex = it.getColumnIndex(TvContractCompat.WatchNextPrograms._ID)
val providerIdIndex = it.getColumnIndex(TvContractCompat.WatchNextPrograms.COLUMN_INTERNAL_PROVIDER_ID)
if (idIndex < 0 || providerIdIndex < 0) return false
while (it.moveToNext()) {
if (it.getString(providerIdIndex) == contentId) {
val id = it.getLong(idIndex)
val deleteUri = ContentUris.withAppendedId(
TvContractCompat.WatchNextPrograms.CONTENT_URI,
id
)
context.contentResolver.delete(deleteUri, null, null)
return true
}
}
}
false
} catch (e: Exception) {
Log.e(TAG, "Failed to remove Watch Next item: $contentId", e)
false
}
if (item.duration > 0) {
builder.setDurationMillis(item.duration.toInt())
if (item.lastPlaybackPosition > 0) {
builder.setLastPlaybackPositionMillis(item.lastPlaybackPosition.toInt())
}
}
private fun buildProgram(item: WatchNextItem): WatchNextProgram {
val watchNextType = if (item.lastPlaybackPosition > 0)
TvContractCompat.WatchNextPrograms.WATCH_NEXT_TYPE_CONTINUE
else
TvContractCompat.WatchNextPrograms.WATCH_NEXT_TYPE_NEXT
val builder = WatchNextProgram.Builder()
.setType(item.type)
.setWatchNextType(watchNextType)
.setTitle(item.title)
.setInternalProviderId(item.contentId)
.setLastEngagementTimeUtcMillis(item.lastEngagementTime)
item.description?.let { builder.setDescription(it) }
item.posterUri?.let { uri ->
try {
builder.setPosterArtUri(Uri.parse(uri))
builder.setPosterArtAspectRatio(TvContractCompat.PreviewPrograms.ASPECT_RATIO_16_9)
} catch (e: Exception) {
Log.w(TAG, "Failed to parse poster URI: $uri", e)
}
}
if (item.duration > 0) {
builder.setDurationMillis(item.duration.toInt())
if (item.lastPlaybackPosition > 0) {
builder.setLastPlaybackPositionMillis(item.lastPlaybackPosition.toInt())
}
}
if (item.type == TvContractCompat.WatchNextPrograms.TYPE_TV_EPISODE) {
item.episodeTitle?.let { builder.setEpisodeTitle(it) }
item.seasonNumber?.let { builder.setSeasonNumber(it) }
item.episodeNumber?.let { builder.setEpisodeNumber(it) }
}
val intentUri = Uri.Builder()
.scheme("plezy")
.authority("play")
.appendQueryParameter("content_id", item.contentId)
.build()
builder.setIntentUri(intentUri)
return builder.build()
if (item.type == TvContractCompat.WatchNextPrograms.TYPE_TV_EPISODE) {
item.episodeTitle?.let { builder.setEpisodeTitle(it) }
item.seasonNumber?.let { builder.setSeasonNumber(it) }
item.episodeNumber?.let { builder.setEpisodeNumber(it) }
}
val intentUri = Uri.Builder()
.scheme("plezy")
.authority("play")
.appendQueryParameter("content_id", item.contentId)
.build()
builder.setIntentUri(intentUri)
return builder.build()
}
}
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/white" />
<item android:drawable="@color/splash_background" />
<!-- You can insert your own image assets here -->
<!-- <item>
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- TV (Android TV / Google TV / Fire TV) launch + window background.
The television UI-mode qualifier outranks night/notnight, so this wins
even on TVs that report notnight (most do) where values/ would resolve
the near-white #F7F7F8. Black matches the OLED default theme on TV. -->
<color name="splash_background">#000000</color>
</resources>
@@ -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,313 @@
package com.edde746.plezy.exoplayer
import java.nio.ByteBuffer
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class DvBitstreamSanitizerTest {
private val sanitizer = DvBitstreamSanitizer()
// --- HDR10+ SEI stripping (native DV codec path) ---
@Test
fun stripsHdr10PlusPrefixSeiBetweenVclNals() {
val vcl1 = annexBNal(1, byteArrayOf(0x01, 0x02))
val vcl2 = annexBNal(1, byteArrayOf(0x03, 0x04))
val buffer = bufferOf(vcl1, hdr10PlusSei(), vcl2)
val originalLimit = buffer.limit()
sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
assertTrue(buffer.limit() < originalLimit)
assertEquals(0, buffer.position())
}
@Test
fun stripsSuffixSei() {
val vcl = annexBNal(1, byteArrayOf(0x01))
val suffixSei = annexBNal(40, hdr10PlusSeiPayload())
val buffer = bufferOf(vcl, suffixSei)
sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
assertArrayEquals(vcl, remainingBytes(buffer))
}
@Test
fun handles3ByteStartCodes() {
val vcl1 = annexBNal(1, byteArrayOf(0x01, 0x02), startCodeLen = 3)
val sei = annexBNal(39, hdr10PlusSeiPayload(), startCodeLen = 3)
val vcl2 = annexBNal(1, byteArrayOf(0x03), startCodeLen = 3)
val buffer = bufferOf(vcl1, sei, vcl2)
sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
}
@Test
fun preservesNonHdr10PlusT35Sei() {
// Same T.35 layout but wrong country code (0x00 instead of 0xB5).
val sei = annexBNal(
39,
byteArrayOf(0x04, 0x07, 0x00, 0x00, 0x3C, 0x00, 0x01, 0x04, 0x00)
)
val buffer = bufferOf(annexBNal(1, byteArrayOf(0x01)), sei, annexBNal(1, byteArrayOf(0x02)))
val original = remainingBytes(buffer)
sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
assertArrayEquals(original, remainingBytes(buffer))
}
@Test
fun noOpWithoutSeiNals() {
val buffer = bufferOf(annexBNal(1, byteArrayOf(0x01, 0x02)), annexBNal(1, byteArrayOf(0x03)))
val original = remainingBytes(buffer)
sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = true)
assertArrayEquals(original, remainingBytes(buffer))
}
@Test
fun keepsTruncatedSei() {
// Declares payload size 7 but the identifier bytes are cut short.
val truncated = annexBNal(39, byteArrayOf(0x04, 0x07, 0xB5.toByte(), 0x00, 0x3C))
val buffer = bufferOf(annexBNal(1, byteArrayOf(0x01)), truncated)
val original = remainingBytes(buffer)
sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
assertArrayEquals(original, remainingBytes(buffer))
}
@Test
fun keepsHdr10PlusSeiWhenFlagOff() {
val buffer = bufferOf(annexBNal(1, byteArrayOf(0x01)), hdr10PlusSei())
val original = remainingBytes(buffer)
sanitizer.sanitize(buffer, stripHdr10PlusSei = false, stripDvRpu = false)
assertArrayEquals(original, remainingBytes(buffer))
}
// --- DV RPU/EL stripping (HEVC fallback path) ---
@Test
fun rpuModeStripsRpuAndElButKeepsHdr10PlusSei() {
val vcl = annexBNal(1, byteArrayOf(0x01))
val rpu = annexBNal(62, byteArrayOf(0x19, 0x08))
val el = annexBNal(63, byteArrayOf(0x42))
val sei = hdr10PlusSei()
val buffer = bufferOf(vcl, rpu, sei, el)
sanitizer.sanitize(buffer, stripHdr10PlusSei = false, stripDvRpu = true)
assertArrayEquals(concat(vcl, sei), remainingBytes(buffer))
}
@Test
fun bothFlagsStripBothMetadataKinds() {
val vcl1 = annexBNal(19, byteArrayOf(0x00)) // IDR_W_RADL
val vcl2 = annexBNal(1, byteArrayOf(0x05))
val buffer = bufferOf(vcl1, annexBNal(62, byteArrayOf(0x19)), hdr10PlusSei(), vcl2)
sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = true)
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
}
// --- Buffer handling ---
@Test
fun respectsPositionAndRestoresIt() {
val prefix = byteArrayOf(0xAA.toByte(), 0xBB.toByte())
val vcl = annexBNal(1, byteArrayOf(0x01))
val content = concat(prefix, vcl, hdr10PlusSei())
val buffer = ByteBuffer.wrap(content.copyOf())
buffer.position(prefix.size)
sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
assertEquals(prefix.size, buffer.position())
assertArrayEquals(vcl, remainingBytes(buffer))
// Bytes before the position are untouched.
assertEquals(0xAA.toByte(), buffer.get(0))
assertEquals(0xBB.toByte(), buffer.get(1))
}
@Test
fun worksOnDirectBuffers() {
val vcl = annexBNal(1, byteArrayOf(0x01, 0x02))
val buffer = directBufferOf(vcl, hdr10PlusSei())
sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
assertArrayEquals(vcl, remainingBytes(buffer))
}
@Test
fun emptyBufferIsNoOp() {
val buffer = ByteBuffer.allocate(0)
sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = true)
assertEquals(0, buffer.position())
assertEquals(0, buffer.limit())
}
@Test
fun stripsOnDirectBufferWithNonZeroPosition() {
val vcl1 = annexBNal(1, byteArrayOf(0x01, 0x02))
val vcl2 = annexBNal(1, byteArrayOf(0x03))
val buffer = directBufferOf(byteArrayOf(0xAA.toByte(), 0xBB.toByte()), vcl1, hdr10PlusSei(), vcl2)
buffer.position(2)
val stripped = sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
assertEquals(1, stripped)
assertEquals(2, buffer.position())
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
// Bytes before the position are untouched.
assertEquals(0xAA.toByte(), buffer.get(0))
assertEquals(0xBB.toByte(), buffer.get(1))
}
@Test
fun noStripLeavesDirectBufferStateUntouched() {
val vcl1 = annexBNal(1, byteArrayOf(0x01, 0x02))
val vcl2 = annexBNal(1, byteArrayOf(0x03))
val buffer = directBufferOf(vcl1, vcl2)
val originalLimit = buffer.limit()
val stripped = sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = true)
assertEquals(0, stripped)
assertEquals(0, buffer.position())
assertEquals(originalLimit, buffer.limit())
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
}
@Test
fun stripsTrailingRpuWithZeroByteTailWriteBack() {
val vcl1 = annexBNal(1, byteArrayOf(0x01, 0x02))
val vcl2 = annexBNal(1, byteArrayOf(0x03))
val rpu = annexBNal(62, byteArrayOf(0x19, 0x08))
val buffer = directBufferOf(vcl1, vcl2, rpu)
val originalLimit = buffer.limit()
val stripped = sanitizer.sanitize(buffer, stripHdr10PlusSei = false, stripDvRpu = true)
assertEquals(1, stripped)
assertEquals(originalLimit - rpu.size, buffer.limit())
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
}
@Test
fun growsScratchForLargeSamples() {
// Exceeds the initial 256KB scratch and one doubling; non-zero filler so no
// accidental start codes appear in the payloads.
val vcl1 = annexBNal(1, ByteArray(800_000) { 0xAB.toByte() })
val vcl2 = annexBNal(1, ByteArray(700_000) { 0xCD.toByte() })
val buffer = bufferOf(vcl1, hdr10PlusSei(), vcl2)
val stripped = sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
assertEquals(1, stripped)
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
}
@Test
fun reusesSanitizerAcrossSequentialBuffers() {
val vcl1 = annexBNal(1, byteArrayOf(0x01, 0x02))
val vcl2 = annexBNal(1, byteArrayOf(0x03, 0x04))
val first = bufferOf(vcl1, hdr10PlusSei(), vcl2)
assertEquals(1, sanitizer.sanitize(first, stripHdr10PlusSei = true, stripDvRpu = false))
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(first))
val second = bufferOf(vcl1, vcl2)
assertEquals(0, sanitizer.sanitize(second, stripHdr10PlusSei = true, stripDvRpu = false))
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(second))
val third = bufferOf(hdr10PlusSei(), vcl1, annexBNal(62, byteArrayOf(0x19)), vcl2, hdr10PlusSei())
assertEquals(3, sanitizer.sanitize(third, stripHdr10PlusSei = true, stripDvRpu = true))
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(third))
}
@Test
fun keepsBufferWithoutStartCodes() {
val content = byteArrayOf(0x12, 0x34, 0x56, 0x78)
val buffer = ByteBuffer.wrap(content.copyOf())
val stripped = sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = true)
assertEquals(0, stripped)
assertEquals(0, buffer.position())
assertEquals(content.size, buffer.limit())
assertArrayEquals(content, remainingBytes(buffer))
}
@Test
fun stripsMultipleSeisInOneAccessUnit() {
val vcl1 = annexBNal(1, byteArrayOf(0x01, 0x02))
val vcl2 = annexBNal(1, byteArrayOf(0x03))
val suffixSei = annexBNal(40, hdr10PlusSeiPayload())
val buffer = bufferOf(vcl1, hdr10PlusSei(), vcl2, suffixSei)
val stripped = sanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
assertEquals(2, stripped)
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
}
// --- Helpers ---
/** Builds an HEVC NAL unit: start code + 2-byte NAL header encoding [nalUnitType] + payload. */
private fun annexBNal(nalUnitType: Int, payload: ByteArray, startCodeLen: Int = 4): ByteArray {
val startCode = if (startCodeLen == 3) byteArrayOf(0, 0, 1) else byteArrayOf(0, 0, 0, 1)
val header = byteArrayOf(((nalUnitType shl 1) and 0x7E).toByte(), 0x01)
return concat(startCode, header, payload)
}
/**
* SEI payload: type 4 (user_data_registered_itu_t_t35), size 7, then the HDR10+
* identifiers — country 0xB5, provider 0x003C, oriented code 0x0001, app id 4, version 0 —
* closed by the rbsp_trailing_bits stop byte real SEI NALs always end with (a trailing 0x00
* would otherwise be ambiguous against a following 3-byte start code).
*/
private fun hdr10PlusSeiPayload(): ByteArray = byteArrayOf(0x04, 0x07, 0xB5.toByte(), 0x00, 0x3C, 0x00, 0x01, 0x04, 0x00, 0x80.toByte())
private fun hdr10PlusSei(): ByteArray = annexBNal(39, hdr10PlusSeiPayload())
private fun concat(vararg parts: ByteArray): ByteArray {
val result = ByteArray(parts.sumOf { it.size })
var offset = 0
for (part in parts) {
part.copyInto(result, offset)
offset += part.size
}
return result
}
private fun bufferOf(vararg parts: ByteArray): ByteBuffer = ByteBuffer.wrap(concat(*parts))
private fun directBufferOf(vararg parts: ByteArray): ByteBuffer {
val content = concat(*parts)
val buffer = ByteBuffer.allocateDirect(content.size)
buffer.put(content)
buffer.flip()
return buffer
}
private fun remainingBytes(buffer: ByteBuffer): ByteArray {
val copy = ByteArray(buffer.remaining())
buffer.duplicate().get(copy)
return copy
}
}
+12 -6
View File
@@ -1,5 +1,10 @@
require 'dotenv/load'
Dotenv.load("../../.env")
require 'shellwords'
PROJECT_ROOT = File.expand_path("../..", __dir__)
PROJECT_ROOT_ARG = Shellwords.escape(PROJECT_ROOT)
Dotenv.load(File.join(PROJECT_ROOT, ".env"))
default_platform(:android)
@@ -7,7 +12,7 @@ platform :android do
desc "Build and deploy to Google Play Store"
lane :release do
# Get version from pubspec.yaml
pubspec_path = "#{ENV['PWD']}/../pubspec.yaml"
pubspec_path = File.join(PROJECT_ROOT, "pubspec.yaml")
pubspec_content = File.read(pubspec_path)
version_match = pubspec_content.match(/version:\s*(.+)\+(\d+)/)
@@ -19,11 +24,11 @@ platform :android do
UI.user_error!("Could not extract version from pubspec.yaml")
end
debug_info_dir = "./debug-info/#{version_name}+#{version_code}"
git_commit = `git rev-parse --short HEAD`.strip
git_commit = `git -C #{PROJECT_ROOT_ARG} rev-parse --short HEAD`.strip
# Build the Flutter app
sh("cd #{ENV['PWD']}/.. && flutter build appbundle --dart-define=ENABLE_IN_APP_REVIEW=true --dart-define=ENABLE_SENTRY=true --dart-define=GIT_COMMIT=#{git_commit} --obfuscate --split-debug-info=#{debug_info_dir}/aab")
sh("cd #{PROJECT_ROOT_ARG} && flutter build appbundle --dart-define=ENABLE_SENTRY=true --dart-define=GIT_COMMIT=#{git_commit} --dart-define=SENTRY_ENVIRONMENT=play-store --dart-define=SENTRY_DIST=play-store --obfuscate --split-debug-info=debug-info/android-aab --extra-gen-snapshot-options=--save-obfuscation-map=debug-info/android-aab/obfuscation.map.json")
sh("cd #{PROJECT_ROOT_ARG} && SENTRY_DIST=play-store ./scripts/upload-symbols.sh android-aab")
upload_to_play_store(
track: "production",
@@ -33,7 +38,8 @@ platform :android do
)
# Build universal APK for Amazon Appstore (doesn't accept AABs, excludes x86 via env var)
sh("cd #{ENV['PWD']}/.. && AMAZON=1 flutter build apk --release --dart-define=ENABLE_SENTRY=true --dart-define=GIT_COMMIT=#{git_commit} --obfuscate --split-debug-info=#{debug_info_dir}/apk")
sh("cd #{PROJECT_ROOT_ARG} && AMAZON=1 flutter build apk --release --dart-define=ENABLE_SENTRY=true --dart-define=GIT_COMMIT=#{git_commit} --dart-define=SENTRY_ENVIRONMENT=amazon --dart-define=SENTRY_DIST=amazon --obfuscate --split-debug-info=debug-info/android-apk --extra-gen-snapshot-options=--save-obfuscation-map=debug-info/android-apk/obfuscation.map.json")
sh("cd #{PROJECT_ROOT_ARG} && SENTRY_DIST=amazon ./scripts/upload-symbols.sh android-apk")
upload_to_amazon_appstore(
apk_paths: [
+4
View File
@@ -1,3 +1,7 @@
org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
android.useAndroidX=true
android.enableJetifier=true
# This builtInKotlin flag was added automatically by Flutter migrator
android.builtInKotlin=false
# This newDsl flag was added automatically by Flutter migrator
android.newDsl=false
+58
View File
@@ -0,0 +1,58 @@
// 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")
}
android {
namespace = "com.edde746.plezy.libass"
compileSdk = 36
// Matches flutter.ndkVersion so only one NDK is provisioned. This module's
// CMake build (-DANDROID_STL=c++_shared) contributes NDK 28.2's
// libc++_shared.so to packaging, but that copy is NOT what ships: the app
// packages the libmpv AAR's newer copy with top merge priority (see
// app/build.gradle.kts packaging { jniLibs } + sourceSets).
ndkVersion = "28.2.13676358"
defaultConfig {
minSdk = 21
consumerProguardFiles("consumer-rules.pro")
externalNativeBuild {
cmake {
// 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"
)
}
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
kotlinOptions {
jvmTarget = JavaVersion.VERSION_11.toString()
}
externalNativeBuild {
cmake {
path = file("src/main/cpp/CMakeLists.txt")
version = "3.22.1"
}
}
}
dependencies {
implementation("androidx.annotation:annotation:1.9.1")
implementation("androidx.annotation:annotation-experimental:1.5.1")
implementation("androidx.media3:media3-exoplayer:1.9.2")
implementation("androidx.media3:media3-ui:1.9.2")
testImplementation("junit:junit:4.13.2")
}
+6
View File
@@ -0,0 +1,6 @@
# 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>;
}
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
</manifest>
+643
View File
@@ -0,0 +1,643 @@
// 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) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (long long)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
}
#include "ass/ass.h"
#define LOG_TAG "SubtitleRenderer"
static void assMessageCallback(int level, const char* fmt, va_list args, void* data) {
if (level > 4) return;
if (level >= 2) {
__android_log_vprint(ANDROID_LOG_WARN, LOG_TAG, fmt, args);
} else {
__android_log_vprint(ANDROID_LOG_ERROR, LOG_TAG, fmt, args);
}
}
// --- Ass (library) ---
JNIEXPORT jlong JNICALL Java_com_edde746_plezy_libass_Ass_nativeAssInit(JNIEnv* env, jclass clazz) {
ASS_Library* assLibrary = ass_library_init();
ass_set_message_cb(assLibrary, assMessageCallback, NULL);
ass_set_extract_fonts(assLibrary, 1);
return (jlong)assLibrary;
}
JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_Ass_nativeAssAddFont(
JNIEnv* env, jclass clazz, jlong ass, jstring name, jbyteArray byteArray) {
jsize length = (*env)->GetArrayLength(env, byteArray);
jbyte* bytePtr = (*env)->GetByteArrayElements(env, byteArray, NULL);
if (bytePtr == NULL) {
return;
}
const char* cName = (*env)->GetStringUTFChars(env, name, NULL);
ass_add_font(((ASS_Library*)ass), cName, (char*)bytePtr, length);
(*env)->ReleaseByteArrayElements(env, byteArray, bytePtr, 0);
if (cName != NULL) {
(*env)->ReleaseStringUTFChars(env, name, cName);
}
}
JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_Ass_nativeAssDeinit(JNIEnv* env, jclass clazz, jlong ass) {
if (ass) {
ass_library_done((ASS_Library*)ass);
}
}
// --- AssTrack ---
JNIEXPORT jlong JNICALL
Java_com_edde746_plezy_libass_AssTrack_nativeAssTrackInit(JNIEnv* env, jclass clazz, jlong 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.
// chunked != 0 routes to ass_process_chunk (timed dialogue), else ass_process_data.
static void processTrackBytes(
JNIEnv* env, jlong track, jbyteArray buffer, jint offset, jint length, jlong start, jlong duration, int chunked) {
if (!track) return;
jbyte* elements = (*env)->GetByteArrayElements(env, buffer, NULL);
if (elements == NULL) {
return;
}
if (chunked) {
ass_process_chunk((ASS_Track*)track, (char*)(elements + offset), length, start, duration);
} else {
ass_process_data((ASS_Track*)track, (char*)(elements + offset), length);
}
(*env)->ReleaseByteArrayElements(env, buffer, elements, 0);
}
JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_AssTrack_nativeAssTrackReadBuffer(
JNIEnv* env, jclass clazz, jlong track, jbyteArray buffer, jint offset, jint length) {
processTrackBytes(env, track, buffer, offset, length, 0, 0, 0);
}
JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_AssTrack_nativeAssTrackReadChunk(
JNIEnv* env, jclass clazz, jlong track, jlong start, jlong duration, jbyteArray buffer, jint offset, jint length) {
processTrackBytes(env, track, buffer, offset, length, start, duration, 1);
}
JNIEXPORT void JNICALL
Java_com_edde746_plezy_libass_AssTrack_nativeAssTrackDeinit(JNIEnv* env, jclass clazz, jlong track) {
if (!track) return;
ass_free_track((ASS_Track*)track);
}
// Earliest event Start strictly after afterMs, or -1. Lets the render pipeline
// pre-render (cache-warm) the next upcoming event during idle stretches so
// heavy typesetting doesn't pay its cache-cold rasterization at appearance.
JNIEXPORT jlong JNICALL Java_com_edde746_plezy_libass_AssTrack_nativeAssTrackNextEventStart(
JNIEnv* env, jclass clazz, jlong track, jlong afterMs) {
if (!track) return -1;
ASS_Track* t = (ASS_Track*)track;
long long best = -1;
for (int i = 0; i < t->n_events; i++) {
const long long start = t->events[i].Start;
if (start > afterMs && (best < 0 || start < best)) best = start;
}
return (jlong)best;
}
// Earliest visible-content boundary (event Start OR End) strictly after afterMs,
// or -1. A cache-warming prefetch is only invisible while no boundary passes:
// the render pipeline uses this to ensure nothing on screen is due to change
// before the event it is about to warm.
JNIEXPORT jlong JNICALL Java_com_edde746_plezy_libass_AssTrack_nativeAssTrackNextEventChange(
JNIEnv* env, jclass clazz, jlong track, jlong afterMs) {
if (!track) return -1;
ASS_Track* t = (ASS_Track*)track;
long long best = -1;
for (int i = 0; i < t->n_events; i++) {
const long long start = t->events[i].Start;
const long long end = start + t->events[i].Duration;
if (start > afterMs && (best < 0 || start < best)) best = start;
if (end > afterMs && (best < 0 || end < best)) best = end;
}
return (jlong)best;
}
// --- 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);
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;
}
JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRenderSetFontScale(
JNIEnv* env, jclass clazz, jlong render, jfloat scale) {
if (!render) return;
ass_set_font_scale((ASS_Renderer*)render, scale);
}
JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRenderSetCacheLimit(
JNIEnv* env, jclass clazz, jlong render, jint glyphMax, jint bitmapMaxSize) {
if (!render) return;
ass_set_cache_limits((ASS_Renderer*)render, glyphMax, bitmapMaxSize);
}
JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRenderSetFrameSize(
JNIEnv* env, jclass clazz, jlong render, jint width, jint height) {
if (!render) return;
ass_set_frame_size((ASS_Renderer*)render, width, height);
}
JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRenderSetStorageSize(
JNIEnv* env, jclass clazz, jlong render, jint width, jint height) {
if (!render) return;
ass_set_storage_size((ASS_Renderer*)render, width, height);
}
JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRenderSetMargins(
JNIEnv* env, jclass clazz, jlong render, jint top, jint bottom, jint left, jint right) {
if (!render) return;
ass_set_margins((ASS_Renderer*)render, top, bottom, left, right);
}
JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRenderSetUseMargins(
JNIEnv* env, jclass clazz, jlong render, jboolean use) {
if (!render) return;
ass_set_use_margins((ASS_Renderer*)render, use ? 1 : 0);
}
JNIEXPORT void JNICALL
Java_com_edde746_plezy_libass_AssRender_nativeAssRenderDeinit(JNIEnv* env, jclass clazz, jlong render) {
if (render) {
ass_renderer_done((ASS_Renderer*)render);
}
}
// (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;
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;
}
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;
// 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.
// - 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.
//
// 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, hasOutput) without touching the
// buffers. hasOutput lets Kotlin distinguish "reuse the previous atlas" from
// "the current frame is blank and the GL surface must be cleared."
JNIEXPORT jobject 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>", "(IIIIIZ)V");
if (!ctor) return NULL;
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) {
const jboolean hasOutput = imageListHasOutput(image) ? JNI_TRUE : JNI_FALSE;
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 == JNI_TRUE);
}
return (*env)->NewObject(env, atlasFrameClass, ctor, 0, 0, 0, changed, 0, hasOutput);
}
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, JNI_FALSE);
}
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 ((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;
}
// 48 floats per quad × 4 bytes = 192 bytes/quad
const int maxQuads = (int)(vertexCap / 192);
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, JNI_FALSE);
}
// 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++;
}
}
qsort(items, (size_t)n, sizeof(PackItem), comparePackItemsByHeightDesc);
int cursorX = 0, cursorY = 0, rowH = 0;
int truncated = 0;
int packedH = 0;
int accepted = 0;
long long srcPixels = 0;
for (int i = 0; i < n; i++) {
ASS_Image* img = items[i].img;
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) {
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 (sx < 0) truncated++;
slotX[items[i].idx] = sx;
slotY[items[i].idx] = sy;
}
if (truncated > 0 && (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);
}
if (accepted == 0) {
free(items);
free(slotX);
free(slotY);
return (*env)->NewObject(env, atlasFrameClass, ctor, 0, 0, 0, changed, truncated, JNI_TRUE);
}
memset(atlasPixels, 0, (size_t)atlasMaxW * packedH);
// Pass 2: walk the original list (= libass's painter/blend order), copying each
// accepted image into its assigned slot and emitting its quad.
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 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);
}
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 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 unsigned int c = img->color;
const float r = (float)((c >> 24) & 0xFFu) / 255.0f;
const float g = (float)((c >> 16) & 0xFFu) / 255.0f;
const float b = (float)((c >> 8) & 0xFFu) / 255.0f;
const float a = (float)(0xFFu - (c & 0xFFu)) / 255.0f;
float* vx = vertices + (size_t)qi * 48;
// 8 floats per vertex: x, y, u, v, r, g, b, a.
// Triangle 1: (x0,y0) (x1,y0) (x0,y1)
vx[0] = x0;
vx[1] = y0;
vx[2] = u0;
vx[3] = v0;
vx[4] = r;
vx[5] = g;
vx[6] = b;
vx[7] = a;
vx[8] = x1;
vx[9] = y0;
vx[10] = u1;
vx[11] = v0;
vx[12] = r;
vx[13] = g;
vx[14] = b;
vx[15] = a;
vx[16] = x0;
vx[17] = y1;
vx[18] = u0;
vx[19] = v1;
vx[20] = r;
vx[21] = g;
vx[22] = b;
vx[23] = a;
// Triangle 2: (x1,y0) (x1,y1) (x0,y1)
vx[24] = x1;
vx[25] = y0;
vx[26] = u1;
vx[27] = v0;
vx[28] = r;
vx[29] = g;
vx[30] = b;
vx[31] = a;
vx[32] = x1;
vx[33] = y1;
vx[34] = u1;
vx[35] = v1;
vx[36] = r;
vx[37] = g;
vx[38] = b;
vx[39] = a;
vx[40] = x0;
vx[41] = y1;
vx[42] = u0;
vx[43] = v1;
vx[44] = r;
vx[45] = g;
vx[46] = b;
vx[47] = a;
qi++;
}
free(items);
free(slotX);
free(slotY);
// Slow-render breakdown: separates libass's own cost (rasterize/blur/shape)
// from this function's packing + memcpy, so device logs attribute the time.
const long long tEnd = nowMs();
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);
}
// 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, JNI_TRUE);
}
// --- 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];
}
@@ -0,0 +1,55 @@
cmake_minimum_required(VERSION 3.22.1)
project("asskt")
# 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.1")
set(LIBASS_SHA256 "56088619d3907fabbede978d053eca842c1acdda2fea8f11a1e4e1c5722f0624")
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
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);
}
@@ -0,0 +1,62 @@
package com.edde746.plezy.libass
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
class Ass {
companion object {
init {
System.loadLibrary("asskt")
}
@JvmStatic
external fun nativeAssInit(): Long
@JvmStatic
external fun nativeAssAddFont(ptr: Long, name: String, buffer: ByteArray)
@JvmStatic
external fun nativeAssDeinit(ptr: Long)
}
/** Single lock for all libass calls on this library instance. */
val lock = ReentrantLock()
private var nativeAss: Long = nativeAssInit()
@Volatile
var released = false
private set
private fun <T> create(block: (Long) -> T): T = lock.withLock {
check(!released && nativeAss != 0L) { "Ass already released" }
block(nativeAss)
}
fun createTrack(): AssTrack = create { AssTrack(it, lock) }
fun createRender(): AssRender = create { AssRender(it, lock) }
fun addFont(name: String, buffer: ByteArray) {
lock.withLock {
if (!released && nativeAss != 0L) nativeAssAddFont(nativeAss, name, buffer)
}
}
fun release() {
lock.withLock {
if (released) return
released = true
if (nativeAss != 0L) {
nativeAssDeinit(nativeAss)
nativeAss = 0
}
}
}
protected fun finalize() {
release()
}
}
@@ -0,0 +1,33 @@
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)
* @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 quadCount: Int,
val changed: Int,
val truncated: Int,
val hasOutput: Boolean
) {
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
}
@@ -0,0 +1,164 @@
package com.edde746.plezy.libass
import java.nio.ByteBuffer
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
class AssRender(nativeAss: Long, private val lock: ReentrantLock) {
companion object {
@JvmStatic
external fun nativeAssRenderInit(ass: Long): Long
@JvmStatic
external fun nativeAssRenderSetFontScale(render: Long, scale: Float)
@JvmStatic
external fun nativeAssRenderSetCacheLimit(render: Long, glyphMax: Int, bitmapMaxSize: Int)
@JvmStatic
external fun nativeAssRenderSetStorageSize(render: Long, width: Int, height: Int)
@JvmStatic
external fun nativeAssRenderSetFrameSize(render: Long, width: Int, height: Int)
@JvmStatic
external fun nativeAssRenderSetMargins(render: Long, top: Int, bottom: Int, left: Int, right: Int)
@JvmStatic
external fun nativeAssRenderSetUseMargins(render: Long, use: Boolean)
@JvmStatic
external fun nativeAssRenderFrameAtlas(
render: Long,
track: Long,
time: Long,
atlasBuf: ByteBuffer,
atlasMaxWidth: Int,
atlasMaxHeight: Int,
vertexBuf: ByteBuffer
): AssAtlasFrame?
@JvmStatic
external fun nativeAssRenderDeinit(render: Long)
}
private var nativeRender: Long = nativeAssRenderInit(nativeAss)
@Volatile
var released = false
private set
private var track: AssTrack? = null
/**
* Bumped on every renderer-state mutation (track, sizes, margins, font scale).
* Lets the render-ahead pipeline detect that a speculatively rendered frame was
* produced against stale state and must not be presented.
*/
private val generation = java.util.concurrent.atomic.AtomicInteger(0)
/** Current renderer-state generation; see [generation]. */
val stateGeneration: Int get() = generation.get()
/** Runs [block] with the native handle under the shared libass lock; no-op once released. */
private inline fun withNative(block: (Long) -> Unit) {
lock.withLock {
if (!released && nativeRender != 0L) block(nativeRender)
}
}
fun setTrack(track: AssTrack?) {
generation.incrementAndGet()
lock.withLock { this.track = track }
}
fun setFontScale(scale: Float) {
generation.incrementAndGet()
withNative { nativeAssRenderSetFontScale(it, scale) }
}
fun setCacheLimit(glyphMax: Int, bitmapMaxSize: Int) = withNative { nativeAssRenderSetCacheLimit(it, glyphMax, bitmapMaxSize) }
fun setStorageSize(width: Int, height: Int) {
generation.incrementAndGet()
withNative { nativeAssRenderSetStorageSize(it, width, height) }
}
fun setFrameSize(width: Int, height: Int) {
generation.incrementAndGet()
withNative { nativeAssRenderSetFrameSize(it, width, height) }
}
/**
* mpv-style frame margins: offsets of the video dst rect within the frame set by
* [setFrameSize]. Negative when the video extends beyond the frame (zoomed in / cover).
*/
fun setMargins(top: Int, bottom: Int, left: Int, right: Int) {
generation.incrementAndGet()
withNative { nativeAssRenderSetMargins(it, top, bottom, left, right) }
}
/**
* mpv's sub-ass-force-margins: lay out non-positioned events against the full frame
* (kept on the visible screen) instead of the video rect between the margins.
*/
fun setUseMargins(use: Boolean) {
generation.incrementAndGet()
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
fun renderFrameAtlas(
time: Long,
atlasBuf: ByteBuffer,
atlasMaxW: Int,
atlasMaxH: Int,
vertexBuf: ByteBuffer
): AssAtlasFrame? {
val tQueue = System.nanoTime()
lock.withLock {
lastLockWaitMs = (System.nanoTime() - tQueue) / 1_000_000
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)
}
}
fun release() {
lock.withLock {
if (released) return
released = true
track = null
if (nativeRender != 0L) {
nativeAssRenderDeinit(nativeRender)
nativeRender = 0
}
}
}
protected fun finalize() {
release()
}
}
@@ -0,0 +1,77 @@
package com.edde746.plezy.libass
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
class AssTrack(private val ass: Long, private val lock: ReentrantLock) {
companion object {
@JvmStatic
external fun nativeAssTrackInit(track: Long): Long
@JvmStatic
external fun nativeAssTrackReadBuffer(track: Long, byteArray: ByteArray, offset: Int, length: Int)
@JvmStatic
external fun nativeAssTrackReadChunk(track: Long, start: Long, duration: Long, byteArray: ByteArray, offset: Int, length: Int)
@JvmStatic
external fun nativeAssTrackDeinit(track: Long)
@JvmStatic
external fun nativeAssTrackNextEventStart(track: Long, afterMs: Long): Long
@JvmStatic
external fun nativeAssTrackNextEventChange(track: Long, afterMs: Long): Long
}
var nativeAssTrack = nativeAssTrackInit(ass)
private set
@Volatile
var released = false
private set
/** Runs [block] with the native handle under the shared libass lock; no-op once released. */
private inline fun withNative(block: (Long) -> Unit) {
lock.withLock {
if (!released && nativeAssTrack != 0L) block(nativeAssTrack)
}
}
fun readBuffer(array: ByteArray, offset: Int = 0, length: Int = array.size) = withNative { nativeAssTrackReadBuffer(it, array, offset, length) }
fun readChunk(start: Long, duration: Long, array: ByteArray, offset: Int = 0, length: Int = array.size) = withNative { nativeAssTrackReadChunk(it, start, duration, array, offset, length) }
/** Earliest event start strictly after [afterMs], or -1 if none (yet). */
fun nextEventStartMs(afterMs: Long): Long {
lock.withLock {
if (released || nativeAssTrack == 0L) return -1
return nativeAssTrackNextEventStart(nativeAssTrack, afterMs)
}
}
/** Earliest event start OR end strictly after [afterMs], or -1 if none (yet). */
fun nextEventChangeMs(afterMs: Long): Long {
lock.withLock {
if (released || nativeAssTrack == 0L) return -1
return nativeAssTrackNextEventChange(nativeAssTrack, afterMs)
}
}
fun release() {
lock.withLock {
if (released) return
released = true
if (nativeAssTrack != 0L) {
nativeAssTrackDeinit(nativeAssTrack)
nativeAssTrack = 0
}
}
}
protected fun finalize() {
release()
}
}
@@ -0,0 +1,405 @@
package com.edde746.plezy.libass.media
import android.util.Log
import androidx.annotation.OptIn
import androidx.media3.common.Format
import androidx.media3.common.MediaItem
import androidx.media3.common.MimeTypes
import androidx.media3.common.MimeTypes.TEXT_SSA
import androidx.media3.common.Player.Listener
import androidx.media3.common.Tracks
import androidx.media3.common.VideoSize
import androidx.media3.common.util.Size
import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.video.VideoFrameMetadataListener
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.
*
* This class listens to ExoPlayer events and manages the creation, selection, and rendering of ASS
* subtitle tracks. Rendering always happens on a GL overlay surface (atlas pipeline) — the
* libass frame is the overlay surface, not the video.
*/
@OptIn(UnstableApi::class)
class AssHandler(
val config: AssHandlerConfig = AssHandlerConfig()
) : Listener {
/** The ASS instance used for creating tracks and renderers. This is lazy to avoid loading
* libass if the played media does not have ASS tracks. */
private val assDelegate = lazy { Ass() }
val ass by assDelegate
/** The current ASS renderer. It's created as soon as a ASS track is detected. */
var render: AssRender? = null
private set
/**
* AssRender changed callback
*/
var renderCallback: ((AssRender?) -> Unit)? = null
/** The currently selected ASS track. */
var track: AssTrack? = null
private set
/** The available ASS tracks in the current media. */
private val availableTracks = mutableMapOf<String, AssTrack>()
/** Fonts encountered before any ASS track was created. Flushed in [createTrack]. */
private val pendingFonts = mutableListOf<Pair<String, ByteArray>>()
/** The size of the video track. */
var videoSize = Size.ZERO
private set
/** The size of the surface on which subtitles are rendered. */
var surfaceSize = Size.ZERO
private set
/**
* True once an overlay widget reported its surface size via [setOverlaySurfaceSize].
* From then on the Player.Listener surface size (= the video output surface, which
* may differ from the subtitle overlay once the overlay is parented elsewhere) is
* ignored as a frame-size source.
*/
private var overlaySizeFromWidget = false
/** mpv-style margins of the video rect within the frame: top, bottom, left, right. */
private var margins: IntArray? = null
/** mpv's sub-ass-force-margins: anchor non-positioned events to the visible frame. */
private var useMargins = false
/**
* Per-video-frame callback. Fired by ExoPlayer just before MediaCodec releases the frame
* to the output surface. Carries the exact PTS of the frame and the System.nanoTime()
* domain target release time, so subtitle renderers can align composition to the same
* display vsync as the video.
*
* - [presentationTimeUs] is track-relative microseconds matching the subtitle track's PTS.
* - [releaseTimeNs] may be [androidx.media3.common.C.TIME_UNSET] in rare paths.
*
* Invoked on the playback thread.
*/
var videoFrameCallback: ((presentationTimeUs: Long, releaseTimeNs: Long) -> Unit)? = null
private val videoFrameMetadataListener = VideoFrameMetadataListener { pts, releaseNs, _, _ ->
videoFrameCallback?.invoke(pts, releaseNs)
}
private var player: ExoPlayer? = null
/** The current selected ass format. */
private var format: Format? = null
/**
* Initializes the handler with the provided ExoPlayer instance.
* @param player The ExoPlayer instance to attach to.
*/
fun init(player: ExoPlayer) {
this.player = player
player.addListener(this)
player.setVideoFrameMetadataListener(videoFrameMetadataListener)
}
/**
* Handles transitions between media items in the player and resets everything to the initial
* state.
*/
override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
super.onMediaItemTransition(mediaItem, reason)
Log.i("AssHandler", "onMediaItemTransition: item = $mediaItem, reason = $reason")
resetMediaState(releaseNative = true)
}
private fun resetMediaState(releaseNative: Boolean) {
val oldRender = render
val oldTracks = availableTracks.values.toList()
render = null
track = null
format = null
availableTracks.clear()
pendingFonts.clear()
videoSize = Size.ZERO
renderCallback?.invoke(null)
if (releaseNative) {
oldRender?.release()
oldTracks.forEach { it.release() }
}
}
/**
* Handles changes to the tracks available in the current media.
* Configures the selected ASS track if available.
* @param tracks The selected tracks.
*/
override fun onTracksChanged(tracks: Tracks) {
Log.i("AssHandler", "onTracksChanged $tracks")
val selectedVideoTrack = getSelectedVideoTrack(tracks)
if (selectedVideoTrack != null) {
setVideoSize(selectedVideoTrack.width, selectedVideoTrack.height)
}
format = getSelectedAssTrack(tracks)
if (format == null) {
Log.i("AssHandler", "subtitle track disabled")
track = null
render?.setTrack(null)
return
}
updateTrack()
}
private fun updateTrack() {
val track = availableTracks.firstNotNullOfOrNull {
// When media without external subtitles, format id will not change.
// When media with external subtitles, format will become like 1:1 .
// So to compat both situation, we extract the actual id after the colon.
if (format?.id?.substringAfter(":") == it.key) {
it.value
} else {
null
}
}
if (track == null || this.track == track) return
Log.i("AssHandler", "subtitle track changed to $format")
this.track = track
val render = requireNotNull(render)
applyRenderState(render)
render.setTrack(track)
}
/**
* (Re)applies sizing and margin state to [render]. Called whenever a render is
* (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(scaledForRender(surfaceSize.width), scaledForRender(surfaceSize.height))
// Fallback frame until the overlay surface reports its size.
videoSize.isValid -> render.setFrameSize(scaledForRender(videoSize.width), scaledForRender(videoSize.height))
}
margins?.let { m -> render.setMargins(scaledForRender(m[0]), scaledForRender(m[1]), scaledForRender(m[2]), scaledForRender(m[3])) }
render.setUseMargins(useMargins)
}
/**
* Handles changes to the surface size for video playback.
* Notifies the callback if the size has changed.
* @param width The new width of the surface.
* @param height The new height of the surface.
*/
override fun onSurfaceSizeChanged(width: Int, height: Int) {
super.onSurfaceSizeChanged(width, height)
Log.i("AssHandler", "onSurfaceSizeChanged: width = $width, height = $height")
// The video output surface is only a frame-size proxy until an overlay widget
// reports its own size — they diverge when the overlay isn't video-rect-sized.
if (overlaySizeFromWidget) return
if (surfaceSize.width == width && surfaceSize.height == height) return
surfaceSize = Size(width, height)
}
/**
* Reports the subtitle overlay widget's actual surface size — the authoritative
* libass frame size for OVERLAY render types.
*/
fun setOverlaySurfaceSize(width: Int, height: Int) {
overlaySizeFromWidget = true
if (surfaceSize.width == width && surfaceSize.height == height) return
Log.i("AssHandler", "setOverlaySurfaceSize: width = $width, height = $height")
surfaceSize = Size(width, height)
render?.setFrameSize(scaledForRender(width), scaledForRender(height))
}
/**
* Sets mpv-style frame margins: the offsets of the video dst rect within the libass
* frame ([setOverlaySurfaceSize]); negative when the video extends beyond the frame.
* Applied to the current render and re-applied whenever a render is (re)created.
*/
fun setMargins(top: Int, bottom: Int, left: Int, right: Int) {
margins = intArrayOf(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
render?.setUseMargins(use)
}
override fun onVideoSizeChanged(videoSize: VideoSize) {
super.onVideoSizeChanged(videoSize)
this.videoSize = Size(videoSize.width, videoSize.height)
Log.i("AssHandler", "onVideoSizeChanged: width = ${videoSize.width}, height = ${videoSize.height}")
}
/**
* Updates the video size for the ASS renderer. Called as soon as the video size is known in
* order to properly render subtitles.
* @param width The width of the video.
* @param height The height of the video.
*/
fun setVideoSize(width: Int, height: Int) {
Log.i("AssHandler", "setVideoSize: width = $width, height = $height")
videoSize = Size(width, height)
}
/**
* Returns true if the current media has ASS tracks, false otherwise.
*/
fun hasTracks(): Boolean = availableTracks.isNotEmpty()
/**
* Adds a font to the ASS library. If no tracks have been created yet, the font is buffered
* and will be added when the first track is created via [createTrack].
*/
@Synchronized
fun addFont(name: String, data: ByteArray) {
if (hasTracks()) {
ass.addFont(name, data)
} else {
pendingFonts.add(name to data)
}
}
/**
* Creates a new ASS track from the given format and saves it in the [availableTracks].
* The renderer and libass are also created if needed.
* @param format The format of the ASS track.
* @return The created ASS track.
*/
@Synchronized
fun createTrack(format: Format): AssTrack {
Log.i("AssHandler", "createTrack: format = $format")
// Ensure the renderer is created before creating tracks.
createRenderIfNeeded()
// Flush any fonts that were buffered before the first track was created.
if (pendingFonts.isNotEmpty()) {
for ((name, data) in pendingFonts) {
ass.addFont(name, data)
}
pendingFonts.clear()
}
val track = ass.createTrack()
if (format.initializationData.size > 0) {
val header = AssHeaderParser.parse(format)
track.readBuffer(header)
}
availableTracks[format.id!!] = track
updateTrack()
return track
}
/**
* Ensures the ASS renderer is created if it does not already exist.
*/
private fun createRenderIfNeeded() {
if (render != null) return
Log.i("AssHandler", "createRender (cacheSize: ${config.cacheSize}MB, glyphSize: ${config.glyphSize})")
render = ass.createRender().also { render ->
render.setCacheLimit(config.glyphSize, config.cacheSize)
applyRenderState(render)
}
renderCallback?.invoke(render)
}
/**
* Reads a dialogue into the track of the given [trackId].
* Thread-safe: AssTrack.readChunk internally acquires the shared libass lock.
*/
fun readTrackDialogue(
trackId: String?,
start: Long,
duration: Long,
data: ByteArray,
offset: Int = 0,
length: Int = data.size
) {
val t = availableTracks[trackId] ?: return
t.readChunk(start, duration, data, offset, length)
}
/**
* Retrieves the selected video track, if any.
*/
private fun getSelectedVideoTrack(tracks: Tracks): Format? = tracks.groups.find { group ->
if (group.isSelected) {
(0 until group.length).any { index ->
val track = group.getTrackFormat(index)
MimeTypes.isVideo(track.sampleMimeType)
}
} else {
false
}
}?.getTrackFormat(0)
/**
* Retrieves the ID of the selected ASS track, if any.
* @param tracks The selected tracks.
* @return The ID of the selected ASS track, or null if none.
*/
private fun getSelectedAssTrack(tracks: Tracks): Format? = tracks.groups.find { group ->
if (group.isSelected) {
(0 until group.length).any { index ->
val track = group.getTrackFormat(index)
track.sampleMimeType == TEXT_SSA || track.codecs == TEXT_SSA
}
} else {
false
}
}?.getTrackFormat(0)
/**
* Releases all native resources held by this handler.
*/
fun release() {
videoFrameCallback = null
player?.clearVideoFrameMetadataListener(videoFrameMetadataListener)
player = null
resetMediaState(releaseNative = true)
if (assDelegate.isInitialized()) {
ass.release()
}
}
/**
* Checks if the size is valid (both width and height are greater than 0).
*/
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)
}
}
}
@@ -0,0 +1,6 @@
package com.edde746.plezy.libass.media
data class AssHandlerConfig(
val glyphSize: Int = 10000,
val cacheSize: Int = 128
)
@@ -0,0 +1,127 @@
package com.edde746.plezy.libass.media.extractor
import androidx.annotation.OptIn
import androidx.media3.common.util.ParsableByteArray
import androidx.media3.common.util.UnstableApi
import androidx.media3.extractor.ExtractorInput
import androidx.media3.extractor.ExtractorOutput
import androidx.media3.extractor.mkv.EbmlProcessor
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.text.AssSubtitleExtractorOutput
@OptIn(UnstableApi::class)
open class AssMatroskaExtractor(
subtitleParserFactory: SubtitleParser.Factory,
private val assHandler: AssHandler,
flags: Int = 0
) : MatroskaExtractor(subtitleParserFactory, flags) {
private var currentAttachmentName: String? = null
private var currentAttachmentMime: String? = null
internal val subtitleSample = subtitleSampleField.get(this) as ParsableByteArray
override fun getElementType(id: Int): Int = when (id) {
ID_ATTACHMENTS -> EbmlProcessor.ELEMENT_TYPE_MASTER
ID_ATTACHED_FILE -> EbmlProcessor.ELEMENT_TYPE_MASTER
ID_FILE_NAME -> EbmlProcessor.ELEMENT_TYPE_STRING
ID_FILE_MIME_TYPE -> EbmlProcessor.ELEMENT_TYPE_STRING
ID_FILE_DATA -> EbmlProcessor.ELEMENT_TYPE_BINARY
else -> super.getElementType(id)
}
override fun isLevel1Element(id: Int): Boolean = super.isLevel1Element(id) || id == ID_ATTACHMENTS
override fun startMasterElement(id: Int, contentPosition: Long, contentSize: Long) {
when (id) {
ID_EBML -> {
val currentExtractor = extractorOutput.get(this) as ExtractorOutput
if (currentExtractor !is AssSubtitleExtractorOutput) {
extractorOutput.set(
this,
AssSubtitleExtractorOutput(currentExtractor, assHandler, this)
)
}
super.startMasterElement(id, contentPosition, contentSize)
}
ID_ATTACHED_FILE -> clearAttachment()
else -> super.startMasterElement(id, contentPosition, contentSize)
}
}
override fun endMasterElement(id: Int) {
when (id) {
ID_VIDEO -> {
// We need to get the video dimensions very early
val track = getCurrentTrack(id)
assHandler.setVideoSize(track.width, track.height)
super.endMasterElement(id)
}
ID_ATTACHED_FILE -> clearAttachment()
else -> super.endMasterElement(id)
}
}
override fun stringElement(id: Int, value: String) {
when (id) {
ID_FILE_NAME -> currentAttachmentName = value
ID_FILE_MIME_TYPE -> currentAttachmentMime = value
else -> super.stringElement(id, value)
}
}
override fun binaryElement(id: Int, contentSize: Int, input: ExtractorInput) {
when (id) {
ID_FILE_DATA -> {
val attachmentName = requireNotNull(currentAttachmentName)
val attachmentMime = requireNotNull(currentAttachmentMime)
if (attachmentMime in fontMimeTypes) {
val data = ByteArray(contentSize)
input.readFully(data, 0, contentSize)
assHandler.addFont(attachmentName, data)
} else {
input.skipFully(contentSize)
}
}
else -> super.binaryElement(id, contentSize, input)
}
}
private fun clearAttachment() {
currentAttachmentName = null
currentAttachmentMime = null
}
companion object {
const val ID_EBML = 0x1A45DFA3
const val ID_VIDEO = 0xE0
const val ID_ATTACHMENTS = 0x1941A469
const val ID_ATTACHED_FILE = 0x61A7
const val ID_FILE_NAME = 0x466E
const val ID_FILE_MIME_TYPE = 0x4660
const val ID_FILE_DATA = 0x465C
val fontMimeTypes = listOf(
"font/ttf",
"font/otf",
"font/sfnt",
"font/woff",
"font/woff2",
"application/font-sfnt",
"application/font-woff",
"application/x-truetype-font",
"application/vnd.ms-opentype",
"application/x-font-ttf"
)
val extractorOutput = MatroskaExtractor::class.java.getDeclaredField("extractorOutput").apply {
isAccessible = true
}
val subtitleSampleField = MatroskaExtractor::class.java.getDeclaredField("subtitleSample").apply {
isAccessible = true
}
}
}
@@ -0,0 +1,29 @@
package com.edde746.plezy.libass.media.parser
import androidx.media3.common.Format
import androidx.media3.common.util.Consumer
import androidx.media3.common.util.UnstableApi
import androidx.media3.extractor.text.CuesWithTiming
import androidx.media3.extractor.text.SubtitleParser
import com.edde746.plezy.libass.AssTrack
/**
* Parser for full (non-embedded) ASS documents, e.g. external sidecar files.
* Feeds the whole document into the libass track; rendering happens on the
* overlay surface, so no Media3 cues are emitted.
*/
@UnstableApi
class AssFullSubtitleParser(private val track: AssTrack) : SubtitleParser {
override fun parse(
data: ByteArray,
offset: Int,
length: Int,
outputOptions: SubtitleParser.OutputOptions,
output: Consumer<CuesWithTiming>
) {
track.readBuffer(data, offset, length)
}
override fun getCueReplacementBehavior(): Int = Format.CUE_REPLACEMENT_BEHAVIOR_REPLACE
}
@@ -0,0 +1,30 @@
package com.edde746.plezy.libass.media.parser
import androidx.annotation.OptIn
import androidx.media3.common.Format
import androidx.media3.common.util.UnstableApi
@OptIn(UnstableApi::class)
object AssHeaderParser {
private const val ASS_EVENTS = "[Events]\n" +
"Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text"
/**
* Fix some ass header with error end.
* https://github.com/jellyfin/jellyfin-ffmpeg/issues/506
*/
private fun fixAssHeaderIfNeed(buffer: ByteArray): ByteArray = if (buffer[buffer.size - 1] != 0.toByte()) {
// validate ass header
buffer
} else {
// remote the last null character and append the events tag
(String(buffer, 0, buffer.size - 1) + "\n" + ASS_EVENTS).toByteArray()
}
/**
* Parses the headers from the initialization data of the given [format]. The original
* headers are preserved (duplication checks are handled by libass).
*/
fun parse(format: Format): ByteArray = fixAssHeaderIfNeed(format.initializationData[1])
}
@@ -0,0 +1,24 @@
package com.edde746.plezy.libass.media.parser
import androidx.media3.common.Format
import androidx.media3.common.util.Consumer
import androidx.media3.common.util.UnstableApi
import androidx.media3.extractor.text.CuesWithTiming
import androidx.media3.extractor.text.SubtitleParser
/**
* No operation subtitle parser.
*/
@UnstableApi
class AssNoOpSubtitleParser : SubtitleParser {
override fun parse(
p0: ByteArray,
p1: Int,
p2: Int,
p3: SubtitleParser.OutputOptions,
p4: Consumer<CuesWithTiming>
) {
}
override fun getCueReplacementBehavior(): Int = Format.CUE_REPLACEMENT_BEHAVIOR_REPLACE
}
@@ -0,0 +1,32 @@
package com.edde746.plezy.libass.media.parser
import androidx.media3.common.Format
import androidx.media3.common.MimeTypes
import androidx.media3.common.util.UnstableApi
import androidx.media3.extractor.text.DefaultSubtitleParserFactory
import androidx.media3.extractor.text.SubtitleParser
import com.edde746.plezy.libass.media.AssHandler
@UnstableApi
class AssSubtitleParserFactory(private val assHandler: AssHandler) : SubtitleParser.Factory {
private val defaultSubtitleParserFactory = DefaultSubtitleParserFactory()
override fun supportsFormat(format: Format): Boolean = defaultSubtitleParserFactory.supportsFormat(format)
override fun getCueReplacementBehavior(format: Format): Int = defaultSubtitleParserFactory.getCueReplacementBehavior(format)
override fun create(format: Format): SubtitleParser = if (format.sampleMimeType == MimeTypes.TEXT_SSA) {
val embeddedSubtitles = MimeTypes.VIDEO_MATROSKA
.contentEquals(format.containerMimeType)
val track = assHandler.createTrack(format)
if (embeddedSubtitles) {
// Embedded dialogue lines reach libass via AssTrackOutput; nothing to parse here.
AssNoOpSubtitleParser()
} else {
AssFullSubtitleParser(track)
}
} else {
defaultSubtitleParserFactory.create(format)
}
}
@@ -0,0 +1,26 @@
package com.edde746.plezy.libass.media.text
import androidx.media3.common.C
import androidx.media3.common.util.UnstableApi
import androidx.media3.extractor.ExtractorOutput
import androidx.media3.extractor.TrackOutput
import com.edde746.plezy.libass.media.AssHandler
import com.edde746.plezy.libass.media.extractor.AssMatroskaExtractor
/**
* This class is only used by the overlay renderer. It's needed to get the start time of the subtitles.
*/
@UnstableApi
class AssSubtitleExtractorOutput(
private val delegate: ExtractorOutput,
private val assHandler: AssHandler,
private val extractor: AssMatroskaExtractor
) : ExtractorOutput by delegate {
override fun track(id: Int, type: Int): TrackOutput = if (type == C.TRACK_TYPE_TEXT) {
// We can't know at this time if the subtitle track is ASS or other format, so we wrap
// every subtitle track
AssTrackOutput(delegate.track(id, type), assHandler, extractor)
} else {
delegate.track(id, type)
}
}
@@ -0,0 +1,95 @@
package com.edde746.plezy.libass.media.text
import androidx.media3.common.C
import androidx.media3.common.Format
import androidx.media3.common.MimeTypes
import androidx.media3.common.util.UnstableApi
import androidx.media3.common.util.Util
import androidx.media3.extractor.TrackOutput
import com.edde746.plezy.libass.media.AssHandler
import com.edde746.plezy.libass.media.extractor.AssMatroskaExtractor
import java.util.regex.Pattern
/**
* This class is only used by the overlay renderer. It's needed to get the start time of the subtitles.
*/
@UnstableApi
class AssTrackOutput(
private val delegate: TrackOutput,
private val assHandler: AssHandler,
private val extractor: AssMatroskaExtractor
) : TrackOutput by delegate {
private var isAss = false
private var trackId: String? = null
override fun format(format: Format) {
if (format.sampleMimeType == MimeTypes.TEXT_SSA || format.codecs == MimeTypes.TEXT_SSA) {
isAss = true
trackId = format.id
}
delegate.format(format)
}
override fun sampleMetadata(
timeUs: Long,
flags: Int,
size: Int,
offset: Int,
cryptoData: TrackOutput.CryptoData?
) {
if (isAss && timeUs.isValidTs) {
val sample = extractor.subtitleSample
val endIndex = findTokenIndex(sample.data, 1)
val lineIndex = findTokenIndex(sample.data, 2)
val rawDuration = sample.data.decodeToString(endIndex, lineIndex - 1)
val durationUs = parseTimecodeUs(rawDuration)
assHandler.readTrackDialogue(
trackId = trackId,
start = timeUs / 1000,
duration = durationUs / 1000,
data = sample.data,
offset = lineIndex,
length = sample.limit() - lineIndex
)
}
delegate.sampleMetadata(timeUs, flags, size, offset, cryptoData)
}
private fun parseTimecodeUs(timeString: String): Long {
val matcher = SSA_TIMECODE_PATTERN.matcher(timeString.trim { it <= ' ' })
if (!matcher.matches()) {
return C.TIME_UNSET
}
var timestampUs =
Util.castNonNull(matcher.group(1)).toLong() * 60 * 60 * C.MICROS_PER_SECOND
timestampUs += Util.castNonNull(matcher.group(2)).toLong() * 60 * C.MICROS_PER_SECOND
timestampUs += Util.castNonNull(matcher.group(3)).toLong() * C.MICROS_PER_SECOND
timestampUs += Util.castNonNull(matcher.group(4)).toLong() * 10000
return timestampUs
}
private fun findTokenIndex(array: ByteArray, tokenNumber: Int): Int {
if (tokenNumber == 0) return 0
var tokensFound = 0
array.forEachIndexed { index, byte ->
if (byte == COMMA && ++tokensFound == tokenNumber) {
return index + 1
}
}
return 0
}
private val Long.isValidTs
get() = this != C.TIME_UNSET
private companion object {
val SSA_TIMECODE_PATTERN: Pattern =
Pattern.compile("""(?:(\d+):)?(\d+):(\d+)[:.](\d+)""")
const val COMMA = ','.code.toByte()
}
}
@@ -0,0 +1,177 @@
package com.edde746.plezy.libass.media.widget
import android.app.ActivityManager
import android.content.Context
import android.graphics.PixelFormat
import android.view.SurfaceHolder
import android.view.SurfaceView
import androidx.media3.common.util.UnstableApi
import com.edde746.plezy.libass.media.AssHandler
/**
* Subtitle overlay rendered through a dedicated [SurfaceView] layer.
*
* Uses a SurfaceFlinger layer directly, which lets the atlas-based pipeline
* vsync-align its swap with the corresponding video frame via
* `eglPresentationTimeANDROID`.
*/
@UnstableApi
class AssSubtitleSurfaceView(
context: Context,
private val assHandler: AssHandler
) : SurfaceView(context),
SurfaceHolder.Callback {
private var pipeline: AssAtlasPipeline? = null
private var preSwapProbe: ((Long) -> Unit)? = null
init {
setZOrderMediaOverlay(true)
holder.setFormat(PixelFormat.TRANSLUCENT)
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)
}
/** Re-renders the last position, e.g. after margin changes while paused. */
fun invalidateSubtitles() {
pipeline?.invalidate()
}
/** Vsync-pinned swaps performed by the current pipeline. */
val swapCount: Long get() = pipeline?.swapCount ?: 0L
/** Pinned swaps that finished past the swap-time budget (possible missed vsync). */
val lateSwapCount: Long get() = pipeline?.lateSwapCount ?: 0L
/** Worst observed swap lateness past the target release time, in milliseconds. */
val maxLateMs: Long get() = pipeline?.maxLateMs ?: 0L
/** Total libass renders performed by the current pipeline. */
val renderCount: Long get() = pipeline?.renderCount ?: 0L
/** Renders where libass reported changed content. */
val changedRenderCount: Long get() = pipeline?.changedRenderCount ?: 0L
/** Renders that overflowed the atlas/vertex capacity. */
val overflowCount: Long get() = pipeline?.overflowCount ?: 0L
/** Duration of the most recent libass render, in milliseconds. */
val lastLibassMs: Long get() = pipeline?.lastLibassMs ?: 0L
/** Worst observed libass render duration, in milliseconds. */
val maxLibassMs: Long get() = pipeline?.maxLibassMs ?: 0L
/** Changed-render duration histogram: [≤10ms, ≤25ms, ≤42ms, ≤84ms, >84ms]. */
val libassMsHistogram: List<Long> get() = pipeline?.libassMsHistogram ?: emptyList()
/** Requests served from a pre-rendered (speculative) frame. */
val specHits: Long get() = pipeline?.specHits ?: 0L
/** Requests where speculation existed but didn't match (seek, state change). */
val specMisses: Long get() = pipeline?.specMisses ?: 0L
/** 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
// 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) {
assHandler.setOverlaySurfaceSize(width, height)
pipeline?.onSurfaceSizeChanged(width, height)
}
override fun surfaceDestroyed(holder: SurfaceHolder) {
pipeline?.releaseAndWait()
pipeline = null
}
}
@@ -0,0 +1,287 @@
package com.edde746.plezy.libass.media.widget
import com.edde746.plezy.libass.AssAtlasFrame
/**
* Decision core of the speculative render-ahead pipeline.
*
* The problem it solves: ExoPlayer's frame-metadata callback gives only ~40 ms
* between "video frame scheduled" and that frame's vsync, while a changed-content
* libass render can take longer — so a render started at the callback lands a
* frame (or more) late. The engine renders the *predicted next* PTS right after
* servicing the current one, in the dead time between frames; when the next
* request matches the prediction, only the GL upload+swap (~6–11 ms) sits inside
* the deadline.
*
* Pure logic, single-threaded (the libass worker) — rendering, buffers and GL
* are behind injected closures, so the state machine is unit-testable. Only the
* stat fields are read from other threads.
*
* Slot ownership invariant: a slot handed to GL ([lastPostedSlot]) or currently
* read by GL ([glTakenSlot]) is never chosen as a render target. With 3 slots and
* at most 2 exclusions a target always exists; with 2 slots (low-RAM devices)
* speculation must be disabled and the legacy alternation behavior falls out.
*
* Key subtlety inherited from libass: `ass_render_frame`'s `changed` flag compares
* against libass's *previous render* — which, with speculation, may be content
* that never reached the screen. The engine therefore tracks [libassLastSlot]
* (the slot holding libass's most recent render output) rather than the last
* *posted* slot, and prefers it as the render target: on `changed == 0` the
* buffers were untouched and that slot already holds exactly the right content.
*/
internal class SpecRenderEngine(
private val slotCount: Int,
private val speculationEnabled: Boolean,
/**
* Renders the current track at [timeMs] into the slot's buffers. Returns null
* when the renderer/track is gone. The closure owns timing/stat accounting.
*/
private val renderAt: (timeMs: Long, slot: Int) -> AssAtlasFrame?,
/**
* Renderer identity + state generation as one comparable value. Must change
* whenever a speculatively rendered frame could be stale: margins, sizes,
* track switches, renderer recreation.
*/
private val stateGeneration: () -> Long,
/** Slot the GL thread most recently took for drawing, or -1. Never write it. */
private val glTakenSlot: () -> Int,
/** Diagnostic sink for hit/miss/skip decisions; null disables (no string cost). */
private val debugLog: ((String) -> Unit)? = null
) {
/** What the caller should do after [service]. */
sealed class Outcome {
/** Nothing to post (no renderer, or no rendered content exists yet). */
object Skip : Outcome()
/**
* Post [slot] to GL. [newContent] means this call wrote fresh content into
* the slot (the caller bumps the payload's content seq). [specHit] means the
* content was pre-rendered — no libass render ran inside the deadline.
*/
class Post(val slot: Int, val frame: AssAtlasFrame, val newContent: Boolean, val specHit: Boolean) : Outcome()
}
/** A speculative render that wrote new content into [slot] (bump its seq). */
class SpecWrite(val slot: Int, val frame: AssAtlasFrame)
// Speculation state: content for specPtsUs is pre-rendered and lives either in
// specSlot, or — when the spec render returned changed == 0 — is identical to
// libassLastSlot's content (specIsLibassLast).
private var specPtsUs = UNSET
private var specSlot = -1
private var specIsLibassLast = false
private var specGen = 0L
// The slot holding libass's most recent render output and its frame.
private var libassLastSlot = -1
private var libassLastFrame: AssAtlasFrame? = null
private var lastPostedSlot = -1
// Request-cadence estimator over pinned (playing) requests: median of the last
// 8 PTS deltas, valid after 4, reset on any non-monotonic or > 250 ms jump.
private val deltas = LongArray(DELTA_SAMPLES)
private var deltaCount = 0
private var deltaIndex = 0
private var lastPinnedPtsUs = UNSET
// Stats; single-writer (the libass thread), read from the stats path.
@Volatile
var specHits = 0L
private set
@Volatile
var specMisses = 0L
private set
@Volatile
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
* estimator and never count as speculation misses against playback.
*/
fun service(ptsUs: Long, pinned: Boolean): Outcome {
if (pinned) updateDeltaEstimator(ptsUs)
val ptsMs = toLibassMs(ptsUs)
if (specPtsUs != UNSET) {
val specPtsMs = toLibassMs(specPtsUs)
val genNow = stateGeneration()
val hit = genNow == specGen && ptsMs == specPtsMs
val slot = if (specIsLibassLast) libassLastSlot else specSlot
val frame = libassLastFrame
val specPts = specPtsUs
specPtsUs = UNSET
if (hit && slot >= 0 && frame != null) {
specHits++
lastPostedSlot = 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=${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=${ptsMs}ms")
}
// 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(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
lastPostedSlot = lastSlot
return Outcome.Post(lastSlot, lastFrame, newContent = false, specHit = false)
}
libassLastSlot = target
libassLastFrame = frame
lastPostedSlot = target
return Outcome.Post(target, frame, newContent = true, specHit = false)
}
/**
* Speculatively renders the predicted next request ([servicedPtsUs] + median
* delta) into a free slot. Call after posting the current frame; skipped while
* paused ([pinned] false), when a newer request is already waiting, or while
* the cadence estimator has no confident delta.
*/
fun speculateAfter(servicedPtsUs: Long, pinned: Boolean, hasPending: Boolean): SpecWrite? {
if (!speculationEnabled) return null
if (!pinned || hasPending || !deltaValid()) {
specSkips++
debugLog?.invoke(
"spec-skip after=${servicedPtsUs / 1000}ms pinned=$pinned pending=$hasPending cadence=${deltaValid()}"
)
return null
}
val target = renderTargetSlot() ?: run {
specSkips++
debugLog?.invoke("spec-skip after=${servicedPtsUs / 1000}ms no-free-slot")
return null
}
val gen = stateGeneration()
val specPts = servicedPtsUs + medianDeltaUs()
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
specSlot = -1
return null
}
libassLastSlot = target
libassLastFrame = frame
specIsLibassLast = false
specSlot = target
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 —
* heavy typesetting otherwise pays its cache-cold rasterization (measured
* 0.8–2.6 s on weak devices) exactly when the sign appears. The result is
* never posted; like any render it becomes libass's last-rendered content,
* so any pending speculation is invalidated first (its slot/content
* references would go stale).
*
* Returns the slot written (caller bumps its content seq) or null when
* nothing was rendered.
*/
fun prefetch(ptsUs: Long): SpecWrite? {
specPtsUs = UNSET
val target = renderTargetSlot() ?: return null
val frame = renderAt(toLibassMs(ptsUs), target) ?: return null
prefetchCount++
if (frame.changed == 0) return null
libassLastSlot = target
libassLastFrame = frame
return SpecWrite(target, frame)
}
/** Cache-warming prefetch renders performed; single-writer, read cross-thread. */
@Volatile
var prefetchCount = 0L
private set
private fun renderTargetSlot(): Int? {
// The GL exclusion only exists in ≥3-slot mode; with 2 slots this reduces to
// the legacy "don't write the posted slot" alternation.
val taken = if (slotCount > 2) glTakenSlot() else -1
val last = libassLastSlot
if (last >= 0 && last != lastPostedSlot && last != taken) return last
for (s in 0 until slotCount) {
if (s != lastPostedSlot && s != taken) return s
}
return null
}
private fun updateDeltaEstimator(ptsUs: Long) {
val prev = lastPinnedPtsUs
lastPinnedPtsUs = ptsUs
if (prev == UNSET) return
val d = ptsUs - prev
if (d <= 0 || d > MAX_DELTA_US) {
// Seek/discontinuity (or duplicate PTS): forget the cadence.
deltaCount = 0
deltaIndex = 0
return
}
deltas[deltaIndex] = d
deltaIndex = (deltaIndex + 1) % DELTA_SAMPLES
if (deltaCount < DELTA_SAMPLES) deltaCount++
}
private fun deltaValid() = deltaCount >= MIN_DELTA_SAMPLES
private fun medianDeltaUs(): Long {
val copy = deltas.copyOfRange(0, deltaCount)
copy.sort()
return copy[deltaCount / 2]
}
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
}
}
@@ -0,0 +1,405 @@
package com.edde746.plezy.libass.media.widget
import com.edde746.plezy.libass.AssAtlasFrame
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* Tests for the speculative render-ahead state machine. The render function is
* scripted: each call records (timeMs, slot) and returns the next queued frame.
*/
class SpecRenderEngineTest {
private class RenderCall(val timeMs: Long, val slot: Int)
private class Harness(
slotCount: Int = 3,
speculationEnabled: Boolean = true
) {
val calls = mutableListOf<RenderCall>()
val script = ArrayDeque<AssAtlasFrame?>()
var generation = 0L
var glTaken = -1
val engine = SpecRenderEngine(
slotCount = slotCount,
speculationEnabled = speculationEnabled,
renderAt = { timeMs, slot ->
calls.add(RenderCall(timeMs, slot))
if (script.isEmpty()) changed() else script.removeFirst()
},
stateGeneration = { generation },
glTakenSlot = { glTaken }
)
/** Primes the cadence estimator with [n] steady requests; returns last pts. */
fun prime(n: Int = 5, startUs: Long = 0L, deltaUs: Long = 42_000L): Long {
var pts = startUs
repeat(n) {
engine.service(pts, pinned = true)
engine.speculateAfter(pts, pinned = true, hasPending = false)
pts += deltaUs
}
return pts - deltaUs
}
}
private companion object {
const val DELTA = 42_000L
fun changed(quads: Int = 5) = AssAtlasFrame(2048, 100, quads, 2, 0)
fun unchanged() = AssAtlasFrame(0, 0, 0, 0, 0, hasOutput = true)
fun blankUnchanged() = AssAtlasFrame(0, 0, 0, 0, 0, hasOutput = false)
}
@Test
fun `steady state hits serve without rendering`() {
val h = Harness()
val last = h.prime()
// Cadence is confident by now: the last speculateAfter pre-rendered last+Δ.
val before = h.calls.size
val outcome = h.engine.service(last + DELTA, pinned = true)
assertTrue(outcome is SpecRenderEngine.Outcome.Post)
outcome as SpecRenderEngine.Outcome.Post
assertTrue(outcome.specHit)
assertFalse(outcome.newContent) // content was written (and seq-bumped) at spec time
assertEquals("service must not render on a hit", before, h.calls.size)
assertEquals(1L, h.engine.specHits)
}
@Test
fun `hit tolerates jitter only within the same libass millisecond`() {
val h = Harness()
val last = h.prime()
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()
val last = h.prime()
val specSlot = h.calls.last().slot // where the speculative content went
val before = h.calls.size
h.script.add(changed())
val outcome = h.engine.service(last + 1_000_000, pinned = true)
assertTrue(outcome is SpecRenderEngine.Outcome.Post)
outcome as SpecRenderEngine.Outcome.Post
assertFalse(outcome.specHit)
assertTrue(outcome.newContent)
assertEquals(before + 1, h.calls.size)
assertEquals("miss must render into the slot holding libass's last content", specSlot, h.calls.last().slot)
assertEquals(1L, h.engine.specMisses)
}
@Test
fun `miss with changed 0 posts the spec slot not stale screen content`() {
// The trap: spec rendered NEW content (never posted); a mismatched request
// then returns changed == 0 (identical to libass's LAST render = the spec
// content). Posting "last posted" content would be stale — the engine must
// post the slot libass last wrote.
val h = Harness()
val last = h.prime()
val specSlot = h.calls.last().slot
h.script.add(unchanged())
val outcome = h.engine.service(last + 200_000, pinned = true) // > ε, miss; estimator resets too
assertTrue(outcome is SpecRenderEngine.Outcome.Post)
outcome as SpecRenderEngine.Outcome.Post
assertFalse(outcome.specHit)
assertFalse(outcome.newContent)
assertEquals("changed==0 must repost libass's last-rendered slot", specSlot, outcome.slot)
}
@Test
fun `state generation change invalidates speculation`() {
val h = Harness()
val last = h.prime()
h.generation++ // margins/zoom/track switch between spec render and the request
h.script.add(changed())
val before = h.calls.size
val outcome = h.engine.service(last + DELTA, pinned = true)
assertTrue(outcome is SpecRenderEngine.Outcome.Post)
assertFalse((outcome as SpecRenderEngine.Outcome.Post).specHit)
assertEquals("stale spec must be re-rendered", before + 1, h.calls.size)
assertEquals(1L, h.engine.specMisses)
}
@Test
fun `unpinned requests never feed the estimator or speculate`() {
val h = Harness()
val last = h.prime()
// Paused invalidate-repaint at an arbitrary position.
h.script.add(changed())
h.engine.service(last, pinned = false)
val specBefore = h.calls.size
assertNull(h.engine.speculateAfter(last, pinned = false, hasPending = false))
assertEquals("unpinned must not speculate", specBefore, h.calls.size)
// Cadence survives the unpinned request: the next pinned pair still hits.
h.engine.service(last + DELTA, pinned = true)
h.engine.speculateAfter(last + DELTA, pinned = true, hasPending = false)
val outcome = h.engine.service(last + 2 * DELTA, pinned = true)
assertTrue((outcome as SpecRenderEngine.Outcome.Post).specHit)
}
@Test
fun `speculation skipped while a request is pending`() {
val h = Harness()
val last = h.prime()
val before = h.calls.size
assertNull(h.engine.speculateAfter(last, pinned = true, hasPending = true))
assertEquals(before, h.calls.size)
assertTrue(h.engine.specSkips > 0)
}
@Test
fun `no speculation until cadence is confident`() {
val h = Harness()
h.engine.service(0, pinned = true)
// Only one delta sample so far (needs 4).
h.engine.service(DELTA, pinned = true)
val before = h.calls.size
assertNull(h.engine.speculateAfter(DELTA, pinned = true, hasPending = false))
assertEquals(before, h.calls.size)
}
@Test
fun `render target avoids posted and gl taken slots`() {
val h = Harness()
h.script.add(changed())
val first = h.engine.service(0, pinned = true) as SpecRenderEngine.Outcome.Post
val posted = first.slot
h.glTaken = (posted + 1) % 3
h.script.add(changed())
val second = h.engine.service(1_000_000, pinned = true) as SpecRenderEngine.Outcome.Post
val expected = (0 until 3).first { it != posted && it != h.glTaken }
assertEquals(expected, second.slot)
}
@Test
fun `changed 0 before any content skips`() {
val h = Harness()
h.script.add(unchanged())
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()
h.script.add(null)
assertEquals(SpecRenderEngine.Outcome.Skip, h.engine.service(0, pinned = true))
}
@Test
fun `two slot mode alternates and never speculates`() {
val h = Harness(slotCount = 2, speculationEnabled = false)
h.script.add(changed())
val a = h.engine.service(0, pinned = true) as SpecRenderEngine.Outcome.Post
assertNull(h.engine.speculateAfter(0, pinned = true, hasPending = false))
h.script.add(changed())
val b = h.engine.service(DELTA, pinned = true) as SpecRenderEngine.Outcome.Post
assertTrue(a.slot != b.slot)
assertTrue(a.slot in 0..1 && b.slot in 0..1)
assertEquals(0, h.calls.count { it.slot >= 2 })
}
@Test
fun `static dialogue hit reposts the same slot without new content`() {
// Spec render returns changed == 0 (nothing moves): a hit must repost the
// last-rendered slot so GL skips the upload entirely.
val h = Harness()
h.script.add(changed())
val first = h.engine.service(0, pinned = true) as SpecRenderEngine.Outcome.Post
var pts = 0L
repeat(4) {
// build cadence; renders return changed for simplicity
pts += DELTA
h.engine.service(pts, pinned = true)
}
h.script.add(unchanged()) // speculative render: nothing changes at pts+Δ
assertNull(h.engine.speculateAfter(pts, pinned = true, hasPending = false))
val before = h.calls.size
val outcome = h.engine.service(pts + DELTA, pinned = true) as SpecRenderEngine.Outcome.Post
assertTrue(outcome.specHit)
assertFalse(outcome.newContent)
assertEquals(before, h.calls.size)
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()
val last = h.prime()
h.script.add(changed())
val write = h.engine.speculateAfter(last, pinned = true, hasPending = false)
assertNotNull(write)
assertEquals(h.calls.last().slot, write!!.slot)
}
@Test
fun `spec predicts pts plus median delta`() {
val h = Harness()
val last = h.prime()
h.script.add(changed())
h.engine.speculateAfter(last, pinned = true, hasPending = false)
assertEquals((last + DELTA) / 1000, h.calls.last().timeMs)
}
@Test
fun `prefetch renders the requested future pts and reports its slot`() {
val h = Harness()
h.script.add(changed())
h.engine.service(0, pinned = true) // some content on screen
h.script.add(changed())
val write = h.engine.prefetch(5_000_000)
assertNotNull(write)
assertEquals(5_000L, h.calls.last().timeMs)
assertEquals(h.calls.last().slot, write!!.slot)
assertEquals(1L, h.engine.prefetchCount)
}
@Test
fun `prefetch invalidates pending speculation`() {
// Prefetch rewrites libass's last-rendered content (and possibly the spec
// slot itself); a stale spec hit would post future-event content.
val h = Harness()
val last = h.prime() // leaves a valid spec for last+Δ
h.script.add(changed())
h.engine.prefetch(last + 5_000_000)
val before = h.calls.size
h.script.add(changed())
val outcome = h.engine.service(last + DELTA, pinned = true)
assertTrue(outcome is SpecRenderEngine.Outcome.Post)
assertFalse((outcome as SpecRenderEngine.Outcome.Post).specHit)
assertEquals("post-prefetch request must render on demand", before + 1, h.calls.size)
}
@Test
fun `render after prefetch with changed 0 posts the prefetched slot`() {
// changed==0 after a prefetch means "identical to libass's last render" =
// the prefetched content — correct exactly when playback reached the
// prefetched event. The engine must post that slot, not older content.
val h = Harness()
h.script.add(changed())
h.engine.service(0, pinned = true)
h.script.add(changed())
val write = h.engine.prefetch(5_000_000)!!
h.script.add(unchanged())
val outcome = h.engine.service(5_000_000, pinned = true) as SpecRenderEngine.Outcome.Post
assertEquals(write.slot, outcome.slot)
assertFalse(outcome.newContent)
}
@Test
fun `prefetch avoids posted and gl taken slots`() {
val h = Harness()
h.script.add(changed())
val posted = (h.engine.service(0, pinned = true) as SpecRenderEngine.Outcome.Post).slot
h.glTaken = (posted + 1) % 3
h.script.add(changed())
val write = h.engine.prefetch(5_000_000)
val expected = (0 until 3).first { it != posted && it != h.glTaken }
assertEquals(expected, write!!.slot)
}
}
+2
View File
@@ -19,7 +19,9 @@ pluginManagement {
plugins {
id("dev.flutter.flutter-plugin-loader") version "1.0.0"
id("com.android.application") version "8.9.1" apply false
id("com.android.library") version "8.9.1" apply false
id("org.jetbrains.kotlin.android") version "2.1.0" apply false
}
include(":app")
include(":libass")
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="75 75 363 363"><path fill="#02a9ff" d="M321.92 323.27V136.6c0-10.698-5.887-16.602-16.558-16.602h-36.433c-10.672 0-16.561 5.904-16.561 16.602v88.651c0 2.497 23.996 14.089 24.623 16.541 18.282 71.61 3.972 128.92-13.359 131.6 28.337 1.405 31.455 15.064 10.348 5.731 3.229-38.209 15.828-38.134 52.049-1.406.31.317 7.427 15.282 7.87 15.282h85.545c10.672 0 16.558-5.9 16.558-16.6v-36.524c0-10.698-5.886-16.602-16.558-16.602z"/><path fill="currentColor" d="M170.68 120 74.999 393h74.338l16.192-47.222h80.96L262.315 393h73.968l-95.314-273zm11.776 165.28 23.183-75.629 25.393 75.629z"/></svg>

After

Width:  |  Height:  |  Size: 633 B

+4
View File
@@ -0,0 +1,4 @@
<svg viewBox="0 0 72 72" xmlns="http://www.w3.org/2000/svg" fill="currentColor">
<path d="M24.2116 49.1581C22.6599 46.0424 32.8378 27.5879 35.9999 27.5879C39.1666 27.5895 49.3228 46.0764 47.7882 49.1581C46.2536 52.2398 25.7632 52.2738 24.2116 49.1581Z"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M0.481861 64.9951C-4.19479 55.6047 26.4765 0 36 0C45.5328 0 76.153 55.713 71.5274 64.9951C66.9018 74.2773 5.15852 74.3856 0.481861 64.9951ZM12.7358 56.847C15.8005 62.9995 56.2536 62.9314 59.2843 56.847C62.3149 50.761 42.2515 14.2605 36.0093 14.2605C29.767 14.2605 9.67118 50.6944 12.7358 56.847Z"/>
</svg>

After

Width:  |  Height:  |  Size: 614 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="25 37 900 900"><path fill="currentColor" d="M360.18,640.05h-93.37v-215.38h-.85l-71.97,95.92-70.16-95.92h-.96v215.38H29.5v-356.23h88.57l75.91,104.66,77.61-104.66h88.58v356.23Z"/><path fill="currentColor" d="M667.97,640.05h-93.37v-112.96h-101.99c.5,36.48,12.42,74.14,35.77,112.96l-75.8,50.14c-11.5-17.25-21.42-35.61-29.76-55.09-8.34-19.48-14.71-39.57-19.11-60.26-4.4-20.69-6.6-41.26-6.6-61.7s2.31-42.21,6.92-62.76c4.61-20.55,11.71-40.12,21.29-58.72,9.58-18.59,21.58-35.1,35.98-49.51,15.83-15.97,32.77-28.19,50.84-36.68,18.06-8.48,36.89-14.21,56.48-17.19,19.59-2.98,42.09-4.47,67.5-4.47h45.78l21.83,80.27h-73.25c-30.38,0-54.35,4.36-71.92,13.08-17.57,8.72-29.85,18.47-36.84,29.24-6.99,10.77-13.65,24.24-19.96,40.4h92.84v-71.76h93.37v264.99Z"/><path fill="currentColor" d="M797.69,559.78h122.54l-21.83,80.28h-194.08v-356.23h93.37v275.96Z"/></svg>

After

Width:  |  Height:  |  Size: 891 B

+3
View File
@@ -0,0 +1,3 @@
<svg viewBox="636.71 89.58 269.72 269.72" xmlns="http://www.w3.org/2000/svg" fill="currentColor">
<path d="M774.47 359.3H677.74L768.67 224.5L677.74 89.58H774.47L865.4 224.5L774.47 359.3Z"/>
</svg>

After

Width:  |  Height:  |  Size: 199 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><defs><linearGradient id="g" x1="0" y1="24" x2="24" y2="0" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#ab543a"/><stop offset="1" stop-color="#ff7e57"/></linearGradient></defs><path fill="url(#g)" d="M12 10.9c-.61 0-1.1.49-1.1 1.1s.49 1.1 1.1 1.1c.61 0 1.1-.49 1.1-1.1s-.49-1.1-1.1-1.1zM12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm2.19 12.19L6 18l3.81-8.19L18 6l-3.81 8.19z"/></svg>

After

Width:  |  Height:  |  Size: 481 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><defs><linearGradient id="g" x1="0" y1="24" x2="24" y2="0" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#ab543a"/><stop offset="1" stop-color="#ff7e57"/></linearGradient></defs><path fill="url(#g)" d="M3 17v2h6v-2H3zM3 5v2h10V5H3zm10 16v-2h8v-2h-8v-2h-2v6h2zM7 9v2H3v2h4v2h2V9H7zm14 4v-2H11v2h10zm-6-4h2V7h4V5h-4V3h-2v6z"/></svg>

After

Width:  |  Height:  |  Size: 405 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><defs><linearGradient id="g" x1="0" y1="24" x2="24" y2="0" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#ab543a"/><stop offset="1" stop-color="#ff7e57"/></linearGradient></defs><path fill="url(#g)" d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"/></svg>

After

Width:  |  Height:  |  Size: 327 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><defs><linearGradient id="g" x1="0" y1="24" x2="24" y2="0" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#ab543a"/><stop offset="1" stop-color="#ff7e57"/></linearGradient></defs><path fill="url(#g)" d="M20.5 11H19V7c0-1.1-.9-2-2-2h-4V3.5C13 2.12 11.88 1 10.5 1S8 2.12 8 3.5V5H4c-1.1 0-1.99.9-1.99 2v3.8H3.5c1.49 0 2.7 1.21 2.7 2.7s-1.21 2.7-2.7 2.7H2V20c0 1.1.9 2 2 2h3.8v-1.5c0-1.49 1.21-2.7 2.7-2.7 1.49 0 2.7 1.21 2.7 2.7V22H17c1.1 0 2-.9 2-2v-4h1.5c1.38 0 2.5-1.12 2.5-2.5S21.88 11 20.5 11z"/></svg>

After

Width:  |  Height:  |  Size: 578 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><defs><linearGradient id="g" x1="0" y1="24" x2="24" y2="0" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#ab543a"/><stop offset="1" stop-color="#ff7e57"/></linearGradient></defs><path fill="url(#g)" d="M21 6h-7.59l3.29-3.29L16 2l-4 4-4-4-.71.71L10.59 6H3c-1.1 0-2 .89-2 2v12c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V8c0-1.11-.9-2-2-2zm0 14H3V8h18v12zM9 10v8l7-4z"/></svg>

After

Width:  |  Height:  |  Size: 437 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><defs><linearGradient id="g" x1="0" y1="24" x2="24" y2="0" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#ab543a"/><stop offset="1" stop-color="#ff7e57"/></linearGradient></defs><path fill="url(#g)" d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 14.5v-9l6 4.5-6 4.5z"/></svg>

After

Width:  |  Height:  |  Size: 376 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><defs><linearGradient id="g" x1="0" y1="24" x2="24" y2="0" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#ab543a"/><stop offset="1" stop-color="#ff7e57"/></linearGradient></defs><path fill="url(#g)" d="M12 12.75c1.63 0 3.07.39 4.24.9 1.08.48 1.76 1.56 1.76 2.73V18H6v-1.61c0-1.18.68-2.26 1.76-2.73 1.17-.52 2.61-.91 4.24-.91zM4 13c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm1.13 1.1c-.37-.06-.74-.1-1.13-.1-.99 0-1.93.21-2.78.58C.48 14.9 0 15.62 0 16.43V18h4.5v-1.61c0-.83.23-1.61.63-2.29zM20 13c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm4 3.43c0-.81-.48-1.53-1.22-1.85-.85-.37-1.79-.58-2.78-.58-.39 0-.76.04-1.13.1.4.68.63 1.46.63 2.29V18H24v-1.57zM12 6c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3z"/></svg>

After

Width:  |  Height:  |  Size: 794 B

-15
View File
@@ -1,15 +0,0 @@
## iOS
| Home | Library | Media Card | Season |
|------|---------|------------|--------|
| ![iOS Home - Content discovery and recommendations](ios-home.png) | ![iOS Library - Media collection view](ios-library.png) | ![iOS Media Card](ios-media-card.png) | ![iOS Season View](ios-season.png) |
## macOS
![macOS Home - Content discovery and recommendations](macos-home.png)
![macOS Library - Media collection view](macos-library.png)
![macOS Media Card](macos-media-card.png)
![macOS Season View](macos-season.png)
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.4 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 MiB

File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff

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