Compare commits

..
70 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
284 changed files with 10925 additions and 2753 deletions
+2 -2
View File
@@ -1,6 +1,6 @@
cask "plezy" do
version "2.6.0"
sha256 "e408fe84c07e0ff4a2f1a78e8dcfc418233c66ca98c79028a7b099499307a59e"
version "2.7.1"
sha256 "b649195b030add21f3901dabfc90e3f893e08171c51928a7327f19b4ac9150c5"
url "https://github.com/edde746/plezy/releases/download/#{version}/plezy-macos.dmg"
name "Plezy"
+9 -24
View File
@@ -152,26 +152,17 @@ android {
packaging {
jniLibs {
// Three copies of libc++_shared.so reach the merge: the libmpv AAR's
// (NDK r29 — exports std::from_chars<float> that libmpv.so needs), the
// :libass module's CMake-contributed copy (NDK 28.2 — lacks it), and
// peerless2012:ass's bundled copy (also old). pickFirst keeps the merge
// from erroring on the duplicates; WHICH copy wins is pinned by the
// sourceSets block below: extractMpvLibcxx unpacks the libmpv AAR's copy
// into an app jniLibs dir, and PROJECT-scope sources beat sub-projects
// and external AARs. libc++ is backward ABI-compatible, so the older-NDK
// consumers (libass.so, libasskt.so, ffmpeg decoder, cronet) run fine
// against the newer copy.
// pickFirst only suppresses the duplicate libc++ merge error; the
// sourceSets rule below makes libmpv's newer runtime win for
// std::from_chars<float>, while older native consumers remain ABI-compatible.
pickFirsts.add("lib/*/libc++_shared.so")
}
}
sourceSets {
getByName("main") {
// libc++_shared.so extracted from the libmpv AAR by extractMpvLibcxx.
// App source-set jniLibs sit in the PROJECT scope, merged ahead of
// subprojects (:libass) and external AARs, so with the pickFirst rule
// above this copy deterministically wins regardless of dependency order.
// PROJECT-scope jniLibs merge ahead of subprojects/AARs, so dependency
// order cannot accidentally select the older libc++ copy.
jniLibs.srcDir(File(mpvDir, "libcxx/jni"))
}
}
@@ -181,17 +172,15 @@ flutter {
source = "../.."
}
// Download libdovi before any CMake/native build task
tasks.matching { it.name.contains("CMake") || it.name.contains("externalNative") }.configureEach {
dependsOn(downloadLibdovi)
}
// Download the libmpv AAR before compilation
tasks.matching { it.name.startsWith("pre") && it.name.endsWith("Build") }.configureEach {
dependsOn(downloadLibmpv, extractMpvLibcxx)
}
// merge{Debug,Profile,Release}JniLibFolders snapshot jniLibs source dirs as inputs;
// Gradle 8 requires an explicit dependency on the producing task.
// Gradle snapshots jniLibs source dirs before task execution; this keeps the
// extracted libmpv libc++ directory present during input discovery.
tasks.matching { it.name.startsWith("merge") && it.name.endsWith("JniLibFolders") }.configureEach {
dependsOn(extractMpvLibcxx)
}
@@ -216,12 +205,8 @@ dependencies {
// FFmpeg audio decoder for unsupported codecs (ALAC, DTS, TrueHD, etc.)
implementation("org.jellyfin.media3:media3-ffmpeg-decoder:1.9.0+1")
// libass ASS/SSA subtitle rendering: optimized native core (libass.so +
// prefab headers) from the edde746/libass-android fork's releases; Kotlin/JNI
// bindings + Media3 glue live in the android/libass module. -PlocalAssCore
// swaps in a mavenLocal()-published core (0.4.0-local) for native A/B tests.
val assCoreVersion = if (project.hasProperty("localAssCore")) "0.4.0-local" else "0.4.1-plezy.1"
implementation("io.github.peerless2012:ass:$assCoreVersion@aar")
// Keeping libass in-project lets its static core share the app's native
// packaging rules.
implementation(project(":libass"))
testImplementation("junit:junit:4.13.2")
@@ -0,0 +1,202 @@
package com.edde746.plezy.exoplayer
import android.os.Build
import android.view.SurfaceControl
import android.view.SurfaceView
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import kotlin.math.abs
import kotlin.math.roundToInt
/**
* Auto-calibrates [ExoPlayerCore]'s subtitle/video layer offset by measuring, per device, how much
* later the codec VIDEO plane reaches the display than the GL subtitle OVERLAY plane — the
* inter-plane latency (a deep video VPP on TV boxes) that otherwise makes subtitles a frame ahead.
*
* Both planes are pinned to the same video-frame target (releaseTimeNs). Measuring BOTH with the
* same mechanism — [SurfaceTxProbe] + the API-34 previous-release fence — the per-SoC buffer-recycle
* bias cancels in the difference, leaving the pure offset:
*
* offsetFrames = round( (median(videoReleaseVsTarget) − median(overlayReleaseVsTarget)) / frameMs )
*
* This is a MEDIAN-of-each-plane model, NOT a per-frame paired difference: every sample is
* self-paired to its own frame's target, and the per-plane release-vs-target is a steady hardware
* constant, so the two medians need not come from the same frames — only from the same (stable)
* device. Both medians use a recent-sample window so they stay roughly contemporaneous, and a
* confidence gate refuses to converge on an ambiguous (~half-frame) result.
*
* Video samples arrive every few frames from the metadata listener (codec thread); overlay samples
* from the libass GL thread's pre-swap hook (sparse — only when subtitles swap). Once both planes
* have enough samples and the result is confident it converges ONCE, applies + persists, and stops
* all probing (zero steady-state overhead). Re-runs each play to re-confirm.
*
* Threads: probeVideo (codec), probeOverlay (libass GL), onResult (probe reader). The lock guards
* only counter/sample state and is NEVER held across the binder/JNI `applyTransactionToFrame` call
* (so the GL swap path is never stalled by it). The native slot ring is allocated atomically.
*/
internal class AssLatencyCalibrator(
private val videoSurface: SurfaceView,
private val overlaySurface: SurfaceView,
private val onCalibrated: (Int) -> Unit,
private val onDone: () -> Unit,
private val log: (String) -> Unit
) {
private val lock = Any()
private val finished = AtomicBoolean(false)
private val applyFail = AtomicInteger(0)
@Volatile private var frameIntervalNs: Long = 0L
@Volatile private var converged = false
@Volatile private var stopped = false
private var videoFrames = 0
private var videoAttempts = 0
private var overlaySwaps = 0
private var overlayAttempts = 0
private val videoRel = ArrayDeque<Double>()
private val overlayRel = ArrayDeque<Double>()
fun start() {
SurfaceTxProbe.sink = { tag, latch, release, count, state, source, cb ->
onResult(tag, latch, release, count, state, source, cb)
}
log("calibration started (API ${Build.VERSION.SDK_INT})")
}
fun probeVideo(releaseTimeNs: Long, fps: Float) {
if (stopped || converged || Build.VERSION.SDK_INT < 34) return
if (fps > 1f) frameIntervalNs = (1_000_000_000.0 / fps).toLong()
var doAttach = false
var giveUp = false
synchronized(lock) {
videoFrames++
if (videoFrames > GIVEUP_FRAMES) {
giveUp = true
} else if (videoAttempts < VIDEO_ATTEMPT_CAP && videoFrames % VIDEO_EVERY == 0) {
videoAttempts++
doAttach = true
}
}
if (giveUp) {
finishIncomplete()
} else if (doAttach) {
attach(videoSurface, releaseTimeNs, SurfaceTxProbe.SOURCE_VIDEO)
}
}
fun probeOverlay(releaseTimeNs: Long) {
if (stopped || converged || Build.VERSION.SDK_INT < 34) return
var doAttach = false
synchronized(lock) {
overlaySwaps++
if (overlayAttempts < OVERLAY_ATTEMPT_CAP && overlaySwaps % OVERLAY_EVERY == 0) {
overlayAttempts++
doAttach = true
}
}
if (doAttach) attach(overlaySurface, releaseTimeNs, SurfaceTxProbe.SOURCE_OVERLAY)
}
/** Never called while holding [lock]: applyTransactionToFrame is a binder call and runs on the
* GL swap path. The native slot allocation is atomic, so concurrent callers are safe. */
private fun attach(surface: SurfaceView, releaseTimeNs: Long, source: Int) {
try {
val tx = SurfaceControl.Transaction()
SurfaceTxProbe.nativeAttach(tx, releaseTimeNs, source)
surface.applyTransactionToFrame(tx)
} catch (t: Throwable) {
if (applyFail.incrementAndGet() == 1) {
log("applyTransactionToFrame failed: ${t.javaClass.simpleName}: ${t.message}")
}
}
}
private fun onResult(
tag: Long,
latchNs: Long,
releaseNs: Long,
surfaceCount: Int,
fenceState: Int,
source: Int,
callbackNs: Long
) {
if (surfaceCount <= 0 || fenceState != FENCE_OK || releaseNs <= 0) return
val relMs = (releaseNs - tag) / 1_000_000.0
var result: Int? = null
synchronized(lock) {
if (converged || stopped) return
val list = if (source == SurfaceTxProbe.SOURCE_OVERLAY) overlayRel else videoRel
val window = if (source == SurfaceTxProbe.SOURCE_OVERLAY) OVERLAY_WINDOW else VIDEO_WINDOW
list.addLast(relMs)
while (list.size > window) list.removeFirst() // keep a recent window so medians stay fresh
result = tryComputeOffset()
}
result?.let {
onCalibrated(it)
finish()
}
}
private fun tryComputeOffset(): Int? {
val frameMs = frameIntervalNs / 1_000_000.0
if (frameMs <= 0.5) return null
if (videoRel.size < VIDEO_MIN || overlayRel.size < OVERLAY_MIN) return null
val medV = median(videoRel)
val medO = median(overlayRel)
val offsetMs = medV - medO
val raw = offsetMs / frameMs
val frames = raw.roundToInt()
// Confidence gate: only trust a measurement that points clearly at an integer frame count.
// An ambiguous ~half-frame result (corruption / drift / wrong fps) keeps collecting instead.
if (abs(raw - frames) > CONFIDENCE_TOL) return null
val clamped = frames.coerceIn(-2, 2)
converged = true
log(
"CALIBRATED offsetFrames=$clamped raw=${"%.2f".format(raw)} " +
"(video=${"%.1f".format(medV)}ms − overlay=${"%.1f".format(medO)}ms = ${"%.1f".format(offsetMs)}ms " +
"/ frameMs=${"%.2f".format(frameMs)}) samples video=${videoRel.size} overlay=${overlayRel.size} " +
"applyFail=${applyFail.get()}"
)
return clamped
}
private fun finishIncomplete() {
if (converged || stopped) return
log(
"calibration incomplete after $videoFrames frames " +
"(video=${videoRel.size} overlay=${overlayRel.size}); keeping seed"
)
finish()
}
fun stop() = finish()
private fun finish() {
if (!finished.compareAndSet(false, true)) return
stopped = true
SurfaceTxProbe.sink = null
onDone()
}
private fun median(xs: Collection<Double>): Double {
val s = xs.sorted()
val n = s.size
return if (n % 2 == 1) s[n / 2] else (s[n / 2 - 1] + s[n / 2]) / 2.0
}
companion object {
private const val FENCE_OK = 3
private const val VIDEO_EVERY = 2
private const val OVERLAY_EVERY = 1 // overlay swaps are already sparse
private const val VIDEO_MIN = 40
private const val OVERLAY_MIN = 12
private const val VIDEO_WINDOW = 60 // recent-sample window for the median
private const val OVERLAY_WINDOW = 40
private const val VIDEO_ATTEMPT_CAP = 200 // ~16s @24fps/2 of video probing, then the window freezes
private const val OVERLAY_ATTEMPT_CAP = 60
private const val CONFIDENCE_TOL = 0.33 // |raw − round(raw)| must be within ⅓ frame to converge
private const val GIVEUP_FRAMES = 1800 // ~75s @24fps without enough confident overlay samples
}
}
@@ -0,0 +1,17 @@
package com.edde746.plezy.exoplayer
import androidx.media3.common.MimeTypes
internal fun isPassthroughAudioMimeType(mimeType: String): Boolean = when (mimeType) {
"audio/ac3",
"audio/eac3",
"audio/eac3-joc",
"audio/ac4",
"audio/vnd.dts",
"audio/vnd.dts.hd",
"audio/vnd.dts.uhd",
MimeTypes.AUDIO_TRUEHD -> true
else -> false
}
internal fun shouldBlockDirectOutputForPassthrough(mimeType: String, audioPassthroughEnabled: Boolean): Boolean = !audioPassthroughEnabled && isPassthroughAudioMimeType(mimeType)
@@ -258,24 +258,40 @@ object DoviBridge {
}
private fun describeDisplayHdrCapabilities(display: Display): String {
val hdrCapabilities = display.hdrCapabilities
val hdrCapabilities = getDisplayHdrCapabilities(display)
val parts = mutableListOf(
"display=${display.displayId}:${display.name}",
"activeMode=${describeDisplayMode(display.mode)}",
"hdrCapabilities=${describeHdrTypes(hdrCapabilities.supportedHdrTypes)}",
"desiredLuminance=max=${formatLuminance(hdrCapabilities.desiredMaxLuminance)}, " +
"activeMode=${describeDisplayMode(display.mode)}"
)
if (hdrCapabilities == null) {
parts += "hdrCapabilities=unavailable"
} else {
@Suppress("DEPRECATION")
parts += "hdrCapabilities=${describeHdrTypes(hdrCapabilities.supportedHdrTypes)}"
parts += "desiredLuminance=max=${formatLuminance(hdrCapabilities.desiredMaxLuminance)}, " +
"maxAvg=${formatLuminance(hdrCapabilities.desiredMaxAverageLuminance)}, " +
"min=${formatLuminance(hdrCapabilities.desiredMinLuminance)}"
)
}
parts += "supportedModes=${display.supportedModes.joinToString(prefix = "[", postfix = "]") { describeDisplayMode(it) }}"
return parts.joinToString(prefix = "{", postfix = "}")
}
private fun getDisplayHdrTypes(display: Display): IntArray = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
display.mode.supportedHdrTypes
} else {
private fun getDisplayHdrCapabilities(display: Display): Display.HdrCapabilities? = runCatching {
display.hdrCapabilities
}.onFailure { Log.w(TAG, "Failed to query display HDR capabilities", it) }.getOrNull()
private fun getDisplayHdrTypes(display: Display): IntArray {
val hdrCapabilities = getDisplayHdrCapabilities(display) ?: return IntArray(0)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
return runCatching { display.mode.supportedHdrTypes }.getOrElse { error ->
Log.w(TAG, "Failed to query mode HDR types; falling back to display HDR capabilities", error)
@Suppress("DEPRECATION")
hdrCapabilities.supportedHdrTypes
}
}
@Suppress("DEPRECATION")
display.hdrCapabilities.supportedHdrTypes
return hdrCapabilities.supportedHdrTypes
}
private fun describeDisplayMode(mode: Display.Mode): String {
@@ -103,6 +103,16 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
/** Per-frame "video is at X" logcat stream (tag AssFrameCb) for diagnosing
* ASS subtitle lag against the libass pipeline's render/swap lines. */
private const val ASS_FRAME_LOGS = false
private const val ASS_SYNC_LOG_INTERVAL_FRAMES = 120L
/** Auto-calibrate the subtitle/video layer offset per device (API 34+) by measuring the
* video vs overlay plane present timing. See [AssLatencyCalibrator]. Falls back to the
* seeded value (persisted calibration or the Dart perf-tier proxy) when off/unsupported. */
private const val ASS_LATENCY_AUTOCAL = true
/** SharedPreferences store for the per-device subtitle/video latency calibration. */
private const val ASS_CAL_PREFS = "plezy_ass_calibration"
private const val ASS_CAL_KEY_FRAMES = "video_latency_frames"
private const val TS_TIMESTAMP_SEARCH_PACKETS = 1800
private val DV_CODEC_PROFILE_REGEX = Regex("""(?:^|,)\s*dvh[1e]\.(\d{2})""")
@@ -158,6 +168,10 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
private var videoZoomScale: Float = 1.0f
private var assHandler: AssHandler? = null
private var assSubtitleView: AssSubtitleSurfaceView? = null
// Touched from the codec metadata listener, the GL-thread overlay hook, and the main-thread
// media-item-transition/dispose paths — keep visibility across threads.
@Volatile private var latencyCalibrator: AssLatencyCalibrator? = null
private var assForceMargins = false
private var lastAssMargins: IntArray? = null
private var overlayLayoutListener: ViewTreeObserver.OnGlobalLayoutListener? = null
@@ -165,9 +179,24 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
private var exoPlayer: ExoPlayer? = null
private var renderersFactory: PlezyRenderersFactory? = null
private val subtitleDelayUs = AtomicLong(0L)
/**
* Frames the hardware codec→display path lags a GL subtitle overlay pinned to the
* same release time (the overlay otherwise shows a frame ahead of the picture).
* The subtitle is rendered this many frames earlier to match the later video — a
* content-time shift, so it never delays the overlay's present (delaying the
* present freezes the single-slot latest-wins pipeline). Device-specific: ~1 on
* low-end TV boxes (longer video pipeline), 0 on phones. Set from Dart at init
* from the device performance tier ([com.plezy/device] auto low-end signal).
*/
@Volatile private var assVideoLatencyFrames = 0
private var subtitlePositionPercent: Int = 100
private var subtitleFontSize: Float = 55f
private var lastSubtitleCues: List<Cue> = emptyList()
// Tracks whether a text track was selected on the previous onTracksChanged so we
// can detect the transition to "no subtitle" and clear the painted overlays (#1387).
private var hadSelectedTextTrack: Boolean = false
private var httpDataSourceFactory: HttpDataSource.Factory? = null
private var dataSourceFactory: DefaultDataSource.Factory? = null
private var trackSelector: DefaultTrackSelector? = null
@@ -188,11 +217,13 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
// Loudness normalization (#1289): audiofx effects only process non-tunneled
// PCM mixer streams, so while enabled we block direct/bitstream output and
// disable tunneling.
private var audioPassthroughEnabled: Boolean = false
private var audioNormalizationEnabled: Boolean = false
private val audioNormalization = AudioNormalizationEffect(::emitLog)
private var pendingAudioRendererBounce: Boolean = false
private val audioBounceTimeout = Runnable { completeAudioRendererBounce("audio-normalization bounce timeout") }
private val audioBounceTimeout = Runnable { completeAudioRendererBounce("audio renderer bounce timeout") }
private var lastSeekable: Boolean? = null
private var forceSeekable: Boolean = false
@Volatile private var disposing: Boolean = false
private var pendingStartPositionMs: Long = 0L
@@ -231,6 +262,7 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
private val fpsTimestamps = LongArray(FPS_SAMPLE_COUNT)
@Volatile private var fpsTimestampCount = 0
private var assSyncFrameCount = 0L
// Audio focus
private var audioFocusManager: AudioFocusManager? = null
@@ -369,13 +401,18 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
return decision.mode
}
fun initialize(bufferSizeBytes: Int? = null, tunnelingEnabled: Boolean = true): Boolean {
fun initialize(
bufferSizeBytes: Int? = null,
tunnelingEnabled: Boolean = true,
audioPassthroughEnabled: Boolean = false
): Boolean {
if (isInitialized) {
Log.d(TAG, "Already initialized")
return true
}
tunnelingUserEnabled = tunnelingEnabled
this.audioPassthroughEnabled = audioPassthroughEnabled
this.dvMode = getConfiguredDvMode()
DoviBridge.logSupportSummary(activity)
Log.i(
@@ -686,7 +723,61 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
exoPlayer!!.addAnalyticsListener(decoderHangListener)
exoPlayer!!.setVideoFrameMetadataListener { presentationTimeUs, releaseTimeNs, _, _ ->
// ASS bypasses Media3's text renderer, so apply sub-delay before libass renders.
assSubtitleView?.requestRender(presentationTimeUs - subtitleDelayUs.get(), releaseTimeNs)
// Also render the subtitle one video-frame earlier than the picture: the
// hardware codec→display path lags a GL overlay pinned to the same release
// time, so without this the overlay shows a frame ahead of the video. Done
// as a content-time shift (not a present delay, which would freeze the
// single-slot latest-wins pipeline by superseding every frame).
val assView = assSubtitleView
val latencyFrames = assVideoLatencyFrames
val fps = detectedFrameRate.takeIf { it > 1f } ?: currentVideoFormat?.frameRate?.takeIf { it > 1f } ?: 0f
val videoLatencyUs = if (latencyFrames != 0 && fps > 1f) {
(latencyFrames * 1_000_000.0 / fps).toLong()
} else {
0L
}
assView?.requestRender(presentationTimeUs - subtitleDelayUs.get() - videoLatencyUs, releaseTimeNs)
if (ASS_LATENCY_AUTOCAL && assView != null && Build.VERSION.SDK_INT >= 34) {
val calibrator = latencyCalibrator ?: surfaceView?.let { sv ->
AssLatencyCalibrator(
videoSurface = sv,
overlaySurface = assView,
onCalibrated = { frames -> onAssLatencyCalibrated(frames) },
onDone = { assSubtitleView?.setPreSwapProbe(null) },
log = { msg -> emitLog("info", "ass-latency-cal", msg) }
).also {
it.start()
// Bind the hook to THIS instance, not the volatile field, so a concurrent transition
// reset can't redirect it to a different/null calibrator mid-swap.
assView.setPreSwapProbe { rt -> it.probeOverlay(rt) }
latencyCalibrator = it
}
}
calibrator?.probeVideo(releaseTimeNs, fps)
}
assSyncFrameCount++
if (assView != null && assSyncFrameCount % ASS_SYNC_LOG_INTERVAL_FRAMES == 0L) {
emitLog(
"info",
"ass-sync",
"frames=$assSyncFrameCount swaps=${assView.swapCount} late=${assView.lateSwapCount} " +
"phaseLeadMs=${assView.phaseLeadMs} swapLeadMs=${assView.swapLeadMs} frameOffMs=${videoLatencyUs / 1000} sleepMs=${assView.lastScheduledSleepMs} " +
"headroomMs=${assView.lastSwapHeadroomMs} leadMs=${assView.lastSwapLeadMs} " +
"minLeadMs=${assView.minLeadChangedMs?.toString() ?: "n/a"} " +
"present=${assView.presentSource} " +
"presentErrMs=${assView.lastPresentErrorMs?.toString() ?: "n/a"} " +
"worstPresentMs=${assView.worstPresentErrorMs?.toString() ?: "n/a"} " +
"presentHist=${assView.presentErrorHistogram.joinToString(",")} " +
"presentMeasured=${assView.presentMeasuredCount} " +
"presentInvalid=${assView.presentInvalidCount} presentDropped=${assView.presentDroppedCount} " +
"render=${assView.changedRenderCount}/${assView.renderCount} " +
"libassMs=${assView.lastLibassMs}/${assView.maxLibassMs} libassHist=${assView.libassMsHistogram.joinToString(",")} " +
"spec=${assView.specHits}/${assView.specMisses}/${assView.specSkips} " +
"prefetch=${assView.prefetchCount} blankClears=${assView.blankClearCount} " +
"coalesced=${assView.coalescedRequestCount} stale=${assView.staleGenerationCount}/${assView.staleBeforeSwapCount} " +
"superseded=${assView.supersededBeforeSwapCount}"
)
}
if (ASS_FRAME_LOGS) {
// Reference stream for subtitle-lag diagnosis: the video frame ExoPlayer
// is releasing right now and how far ahead of its vsync we are. Subtitle
@@ -791,9 +882,8 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
lastPosition = startPositionMs
lastDuration = 0L
lastBufferedPosition = 0L
delegate?.onPropertyChange("time-pos", startPositionMs / 1000.0)
delegate?.onPropertyChange("duration", 0.0)
delegate?.onPropertyChange("demuxer-cache-time", 0.0)
// Dart already seeds the visible timeline before open. Emitting native
// zeroes here races server-offset Plex transcode restarts back to 0:00.
delegate?.onPropertyChange("eof-reached", false)
}
@@ -805,10 +895,19 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
private fun emitCurrentSeekable(force: Boolean = false) {
val player = exoPlayer
val seekable = player?.isCurrentMediaItemSeekable == true && !currentMediaIsLive
val hasMedia = player?.currentMediaItem != null
val seekable = hasMedia &&
!currentMediaIsLive &&
(forceSeekable || player?.isCurrentMediaItemSeekable == true)
emitSeekable(seekable, force)
}
fun setForceSeekable(force: Boolean) {
if (forceSeekable == force) return
forceSeekable = force
emitCurrentSeekable(force = true)
}
// Player.Listener
override fun onCues(cueGroup: CueGroup) {
@@ -1000,6 +1099,20 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
}
}
// Disabling the text track produces no trailing empty CueGroup, and no new
// video frame re-renders the libass overlay while paused, so the last SRT/VTT
// line stays painted on the SubtitleView and the last ASS frame stays on the
// overlay. AssHandler (registered before this listener) has already nulled the
// libass track by now, so re-rendering the last position clears it. Gate on the
// transition to avoid redundant clears on every track change. (#1387)
val hasSelectedText = hasSelectedTextTrack(tracks)
if (!hasSelectedText && hadSelectedTextTrack) {
lastSubtitleCues = emptyList()
subtitleView?.setCues(emptyList())
assSubtitleView?.invalidateSubtitles()
}
hadSelectedTextTrack = hasSelectedText
evaluateAudioCodecForTunneling()
evaluateVideoCodecForTunneling()
evaluateAssSubtitlesForTunneling(tracks)
@@ -1298,6 +1411,12 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
delegate?.onEvent("file-loaded", null)
delegate?.onPropertyChange("eof-reached", false)
emitCurrentSeekable(force = true)
// Re-calibrate the subtitle/video layer offset each play: tear down the converged calibrator
// so the metadata listener lazily spins up a fresh one. The seeded (persisted) value stays
// applied meanwhile, so subtitles are right from the first frame.
latencyCalibrator?.stop()
latencyCalibrator = null
assSubtitleView?.setPreSwapProbe(null)
}
override fun onVideoSizeChanged(videoSize: VideoSize) {
@@ -1665,6 +1784,8 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
selectionFlags = format.selectionFlags
)
private fun hasSelectedTextTrack(tracks: Tracks): Boolean = tracks.groups.any { it.type == C.TRACK_TYPE_TEXT && it.isSelected }
private fun restorePendingDvTrackSelection(tracks: Tracks): Boolean {
val pending = pendingDvTrackRestore ?: return false
if (trackSelector == null) return false
@@ -1673,7 +1794,7 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
val audioMatch = pending.audio?.let { findTrackRestoreMatch(tracks, it) }
val subtitleMatch = pending.subtitle?.let { findTrackRestoreMatch(tracks, it) }
val hasSelectedText = tracks.groups.any { it.type == C.TRACK_TYPE_TEXT && it.isSelected }
val hasSelectedText = hasSelectedTextTrack(tracks)
var selectionWillChange = false
var appliedRestore = false
var audioOverride: TrackSelectionOverride? = null
@@ -1831,6 +1952,7 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
val mimeType = format.sampleMimeType ?: return false
// Loudness normalization needs decoded PCM for the audiofx chain to act on.
if (audioNormalizationEnabled && isEncodedAudioMimeType(mimeType)) return true
if (shouldBlockDirectOutputForPassthrough(mimeType, audioPassthroughEnabled)) return true
if (directAudioOutputBlockedAfterFailure.contains(mimeType)) {
if (loggedDirectAudioRecoveryBlocks.add("$mimeType|$reason")) {
emitLog(
@@ -2563,6 +2685,7 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
// Reset FPS detection for new content
detectedFrameRate = -1f
fpsTimestampCount = 0
assSyncFrameCount = 0
// Reset DV7 retry flag when opening a different file
if (uri != currentMediaUri) {
@@ -2598,6 +2721,7 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
externalSubtitles.clear()
externalSubtitleUris.clear()
lastSubtitleCues = emptyList()
hadSelectedTextTrack = false
audioTrackGroupMap.clear()
subtitleTrackGroupMap.clear()
selectedAudioTrackId = null
@@ -2711,6 +2835,25 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
}
}
fun setAudioPassthrough(enabled: Boolean) {
if (audioPassthroughEnabled == enabled) return
audioPassthroughEnabled = enabled
emitLog("info", "audio", "Audio passthrough ${if (enabled) "enabled" else "disabled"}")
if (exoPlayer == null) return
val outputEncoding = lastAudioTrackConfig?.encoding
val selectedMime = selectedAudioFormat()?.sampleMimeType
val needsBounce = outputEncoding != null &&
selectedMime != null &&
isPassthroughAudioMimeType(selectedMime) &&
(if (enabled) isPcmEncoding(outputEncoding) else !isPcmEncoding(outputEncoding))
if (needsBounce) {
startAudioRendererBounce("audio-passthrough")
} else {
updateTunnelingState("audio-passthrough")
}
}
private fun attachNormalizationEffect() {
val sessionId = exoPlayer?.audioSessionId ?: C.AUDIO_SESSION_ID_UNSET
if (sessionId == C.AUDIO_SESSION_ID_UNSET) {
@@ -2728,7 +2871,7 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
private fun startAudioRendererBounce(reason: String) {
if (pendingAudioRendererBounce) return
pendingAudioRendererBounce = true
emitLog("info", "audio-normalization", "Bouncing audio renderer to re-evaluate output path (reason=$reason)")
emitLog("info", "audio", "Bouncing audio renderer to re-evaluate output path (reason=$reason)")
applyTrackSelectorPolicy(reason = "$reason (audio renderer off)", audioDisabled = true)
handler.postDelayed(audioBounceTimeout, AUDIO_BOUNCE_TIMEOUT_MS)
}
@@ -2744,6 +2887,35 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
subtitleDelayUs.set((seconds * 1_000_000).toLong())
}
fun setAssVideoLatencyFrames(frames: Int) {
assVideoLatencyFrames = frames.coerceIn(-2, 2)
}
/**
* Seed the subtitle/video layer offset at init: prefer this device's persisted measured
* calibration, falling back to [proxyDefault] (the Dart perf-tier guess) on first-ever play.
* The live [AssLatencyCalibrator] re-confirms and updates it each play.
*/
fun seedAssVideoLatencyFrames(proxyDefault: Int) {
val stored = activity.getSharedPreferences(ASS_CAL_PREFS, Context.MODE_PRIVATE)
.getInt(ASS_CAL_KEY_FRAMES, Int.MIN_VALUE)
val seed = if (stored != Int.MIN_VALUE) stored else proxyDefault
setAssVideoLatencyFrames(seed)
Log.d(TAG, "ass latency seed=$seed (stored=${if (stored == Int.MIN_VALUE) "none" else stored}, proxy=$proxyDefault)")
}
/** Apply + persist a freshly measured calibration (called by [AssLatencyCalibrator]). */
private fun onAssLatencyCalibrated(frames: Int) {
val clamped = frames.coerceIn(-2, 2)
val previous = assVideoLatencyFrames
setAssVideoLatencyFrames(clamped)
activity.getSharedPreferences(ASS_CAL_PREFS, Context.MODE_PRIVATE)
.edit().putInt(ASS_CAL_KEY_FRAMES, clamped).apply()
if (clamped != previous) {
emitLog("info", "ass-latency-cal", "applied offsetFrames=$clamped (was $previous), persisted")
}
}
fun setDebugDvConversionMode(mode: String): Boolean {
val override = when (mode.trim().lowercase()) {
"auto" -> null
@@ -2785,6 +2957,7 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
audioDecoderInitName = null
detectedFrameRate = -1f
fpsTimestampCount = 0
assSyncFrameCount = 0
firstFrameRendered = false
currentVideoFormat = null
loggedNativeDvSelectionKey = null
@@ -3121,6 +3294,8 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
fps: Float,
videoDurationMs: Long,
extraDelayMs: Long,
videoWidth: Int,
videoHeight: Int,
onComplete: (switched: Boolean) -> Unit
) {
val mgr = frameRateManager
@@ -3128,7 +3303,7 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
onComplete(false)
return
}
mgr.setVideoFrameRate(fps, videoDurationMs, extraDelayMs, onComplete)
mgr.setVideoFrameRate(fps, videoDurationMs, extraDelayMs, videoWidth, videoHeight, onComplete)
}
fun clearVideoFrameRate() {
@@ -3192,7 +3367,26 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
"subSpecMisses" to assSubtitleView?.specMisses,
"subSpecSkips" to assSubtitleView?.specSkips,
"subPrefetches" to assSubtitleView?.prefetchCount,
"subBlankClears" to assSubtitleView?.blankClearCount,
"subCoalesced" to assSubtitleView?.coalescedRequestCount,
"subStaleGeneration" to assSubtitleView?.staleGenerationCount,
"subSupersededBeforeSwap" to assSubtitleView?.supersededBeforeSwapCount,
"subStaleBeforeSwap" to assSubtitleView?.staleBeforeSwapCount,
"subMinLeadMs" to assSubtitleView?.minLeadChangedMs,
"subPhaseLeadMs" to assSubtitleView?.phaseLeadMs,
"subLastLeadMs" to assSubtitleView?.lastSwapLeadMs,
"subLastHeadroomMs" to assSubtitleView?.lastSwapHeadroomMs,
"subLastSleepMs" to assSubtitleView?.lastScheduledSleepMs,
// Actual on-screen present time vs the video frame's release target (ground
// truth for frame-perfection; null/false on emulator + pre-29 devices).
"subPresentTimingEnabled" to assSubtitleView?.presentTimingEnabled,
"subPresentSource" to assSubtitleView?.presentSource,
"subPresentErrMs" to assSubtitleView?.lastPresentErrorMs,
"subWorstPresentErrMs" to assSubtitleView?.worstPresentErrorMs,
"subPresentMeasured" to assSubtitleView?.presentMeasuredCount,
"subPresentInvalid" to assSubtitleView?.presentInvalidCount,
"subPresentDropped" to assSubtitleView?.presentDroppedCount,
"subPresentErrHist" to assSubtitleView?.presentErrorHistogram,
// Color info
"colorSpace" to videoFormat?.colorInfo?.colorSpace,
"colorRange" to videoFormat?.colorInfo?.colorRange,
@@ -3374,6 +3568,9 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
// Synchronous ownership invalidation — stale code can no longer
// reach surface state through instance fields.
latencyCalibrator?.stop()
latencyCalibrator = null
assSubtitleView?.setPreSwapProbe(null)
surfaceContainer = null
videoAspectContainer = null
surfaceView = null
@@ -8,6 +8,7 @@ import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.util.Log
import com.edde746.plezy.libass.media.AssHandler
import com.edde746.plezy.mpv.MpvPlayerCore
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
@@ -27,7 +28,6 @@ class ExoPlayerPlugin :
private const val TAG = "ExoPlayerPlugin"
private const val METHOD_CHANNEL = "com.plezy/exo_player"
private const val EVENT_CHANNEL = "com.plezy/exo_player/events"
private const val MPV_FALLBACK_SWITCH_TIMEOUT_MS = 15_000L
}
private lateinit var methodChannel: MethodChannel
@@ -37,7 +37,6 @@ class ExoPlayerPlugin :
private var mpvCore: MpvPlayerCore? = null // MPV fallback player
private var usingMpvFallback: Boolean = false
private var fallbackInProgress: Boolean = false
private var pendingMpvFallbackSwitchGeneration: Int? = null
private var activity: Activity? = null
private var activityBinding: ActivityPluginBinding? = null
@@ -60,6 +59,7 @@ class ExoPlayerPlugin :
// fallback is already active) so one playback's properties never leak into
// the next session's fallback.
private val pendingMpvProperties = LinkedHashMap<String, String>()
private var currentExternalSubtitles: List<Map<String, Any?>>? = null
// FlutterPlugin
@@ -95,7 +95,7 @@ class ExoPlayerPlugin :
mpvCore = null
usingMpvFallback = false
fallbackInProgress = false
clearPendingMpvFallbackSwitch()
currentExternalSubtitles = null
pendingMpvProperties.clear()
activity = null
activityBinding = null
@@ -111,7 +111,6 @@ class ExoPlayerPlugin :
override fun onDetachedFromActivityForConfigChanges() {
sessionGeneration++
fallbackInProgress = false
clearPendingMpvFallbackSwitch()
activity = null
activityBinding = null
Log.d(TAG, "Detached from activity for config changes")
@@ -169,6 +168,7 @@ class ExoPlayerPlugin :
"setVideoZoom" -> handleSetVideoZoom(call, result)
"setDvConversionMode" -> handleSetDvConversionMode(call, result)
"setAudioNormalization" -> handleSetAudioNormalization(call, result)
"setAudioPassthrough" -> handleSetAudioPassthrough(call, result)
"observeProperty" -> handleObserveProperty(call, result)
"setMpvProperty" -> handleSetMpvProperty(call, result)
"setLogLevel" -> {
@@ -201,7 +201,13 @@ class ExoPlayerPlugin :
val bufferSizeBytes = call.argument<Int>("bufferSizeBytes")
val tunnelingEnabled = call.argument<Boolean>("tunnelingEnabled") ?: true
val dvConversionMode = call.argument<String>("dvConversionMode") ?: "auto"
val audioPassthroughEnabled = call.argument<Boolean>("audioPassthroughEnabled") ?: false
val assVideoLatencyFrames = call.argument<Int>("assVideoLatencyFrames") ?: 0
val subtitleRenderScale = call.argument<Double>("subtitleRenderScale")?.toFloat() ?: 1.0f
configuredBufferSizeBytes = bufferSizeBytes
// Global libass overlay render scale — set before the player/handler is built below so the
// first frame-size apply already uses it.
AssHandler.setRenderScale(subtitleRenderScale)
currentActivity.runOnUiThread {
sessionGeneration++
@@ -214,7 +220,6 @@ class ExoPlayerPlugin :
mpvCore = null
usingMpvFallback = false
fallbackInProgress = false
clearPendingMpvFallbackSwitch()
}
try {
@@ -224,11 +229,14 @@ class ExoPlayerPlugin :
}
val success = playerCore?.initialize(
bufferSizeBytes = bufferSizeBytes,
tunnelingEnabled = tunnelingEnabled
tunnelingEnabled = tunnelingEnabled,
audioPassthroughEnabled = audioPassthroughEnabled
) ?: false
if (success && playerCore?.setDebugDvConversionMode(dvConversionMode) != true) {
Log.w(TAG, "Invalid DV conversion mode during initialize: $dvConversionMode")
}
// Seed from this device's persisted calibration, falling back to the Dart perf-tier proxy.
playerCore?.seedAssVideoLatencyFrames(assVideoLatencyFrames)
// Start hidden
playerCore?.setVisible(false)
@@ -251,7 +259,7 @@ class ExoPlayerPlugin :
mpvCore = null
usingMpvFallback = false
fallbackInProgress = false
clearPendingMpvFallbackSwitch()
currentExternalSubtitles = null
pendingMpvProperties.clear()
Log.d(TAG, "Disposed")
result.success(null)
@@ -263,6 +271,7 @@ class ExoPlayerPlugin :
val uri = call.argument<String>("uri")
val headers = call.argument<Map<String, String>>("headers")
val startPositionMs = call.argument<Number>("startPositionMs")?.toLong() ?: 0L
val hasStartPosition = call.argument<Boolean>("hasStartPosition") ?: (startPositionMs > 0L)
val autoPlay = call.argument<Boolean>("autoPlay") ?: true
val isLive = call.argument<Boolean>("isLive") ?: false
val externalSubtitles = call.argument<List<Map<String, Any?>>>("externalSubtitles")
@@ -271,13 +280,14 @@ class ExoPlayerPlugin :
result.error("INVALID_ARGS", "Missing 'uri'", null)
return
}
val externalSubtitleSnapshot = externalSubtitles?.map { it.toMap() }
currentExternalSubtitles = externalSubtitleSnapshot
// Only clear pending MPV state when MPV is the active backend. A same-core
// MPV reload must not inherit a fallback switch that was armed for the
// previous load. When ExoPlayer is active, keep queued properties for a
// potential ExoPlayer→MPV fallback.
if (usingMpvFallback) {
clearPendingMpvFallbackSwitch()
pendingMpvProperties.clear()
}
@@ -286,19 +296,24 @@ class ExoPlayerPlugin :
// MPV: Build loadfile command with options
val startSeconds = startPositionMs / 1000.0
val options = mutableListOf<String>()
options.add("start=$startSeconds")
options.add(if (hasStartPosition && startPositionMs > 0L) "start=$startSeconds" else "start=none")
if (!autoPlay) options.add("pause=yes")
options.add("sid=no")
options.add("secondary-sid=no")
appendExternalSubtitleOptions(options, externalSubtitleSnapshot)
headers?.forEach { (key, value) ->
options.add("http-header-fields-append=$key: $value")
}
val optionsStr = options.joinToString(",")
// Convert content:// URIs to fdclose:// for MPV (SAF SD card downloads)
val mpvUri = openContentFd(uri)?.let { "fdclose://$it" } ?: uri
mpvCore?.command(arrayOf("loadfile", mpvUri, "replace", "-1", optionsStr))
mpvCore?.command(arrayOf("loadfile", mpvUri, "replace", "-1", optionsStr)) { success ->
if (success && autoPlay) {
mpvCore?.setProperty("pause", "no")
}
}
} else {
playerCore?.open(uri, headers, startPositionMs, autoPlay, isLive, externalSubtitles)
playerCore?.open(uri, headers, startPositionMs, autoPlay, isLive, externalSubtitleSnapshot)
}
result.success(null)
} ?: result.error("NO_ACTIVITY", "Activity not available", null)
@@ -441,11 +456,18 @@ class ExoPlayerPlugin :
activity?.runOnUiThread {
if (usingMpvFallback) {
val selectFlag = if (select) "select" else "auto"
mpvCore?.command(arrayOf("sub-add", uri, selectFlag, title ?: "External"))
val core = mpvCore
if (core == null) {
result.success(null)
} else {
core.command(arrayOf("sub-add", uri, selectFlag, title ?: "External")) {
result.success(null)
}
}
} else {
playerCore?.addSubtitleTrack(uri, title, language, mimeType, select)
result.success(null)
}
result.success(null)
} ?: result.success(null)
}
@@ -478,22 +500,24 @@ class ExoPlayerPlugin :
val fps = call.argument<Double>("fps")?.toFloat() ?: 0f
val duration = call.argument<Number>("duration")?.toLong() ?: 0L
val extraDelayMs = call.argument<Number>("extraDelayMs")?.toLong() ?: 0L
val videoWidth = call.argument<Number>("videoWidth")?.toInt() ?: 0
val videoHeight = call.argument<Number>("videoHeight")?.toInt() ?: 0
Log.d(TAG, "setVideoFrameRate: fps=$fps, duration=$duration, extraDelayMs=$extraDelayMs")
Log.d(TAG, "setVideoFrameRate: fps=$fps, duration=$duration, extraDelayMs=$extraDelayMs, video=${videoWidth}x$videoHeight")
val onComplete: (Boolean) -> Unit = { switched -> result.success(switched) }
if (usingMpvFallback) {
val core = mpvCore
if (core == null) {
result.success(false)
} else {
core.setVideoFrameRate(fps, duration, extraDelayMs, onComplete)
core.setVideoFrameRate(fps, duration, extraDelayMs, videoWidth, videoHeight, onComplete)
}
} else {
val core = playerCore
if (core == null) {
result.success(false)
} else {
core.setVideoFrameRate(fps, duration, extraDelayMs, onComplete)
core.setVideoFrameRate(fps, duration, extraDelayMs, videoWidth, videoHeight, onComplete)
}
}
}
@@ -635,6 +659,25 @@ class ExoPlayerPlugin :
} ?: result.error("NO_ACTIVITY", "Activity not available", null)
}
private fun handleSetAudioPassthrough(call: MethodCall, result: MethodChannel.Result) {
val enabled = call.argument<Boolean>("enabled")
if (enabled == null) {
result.error("INVALID_ARGS", "Missing 'enabled'", null)
return
}
val audioSpdif = if (enabled) "ac3,eac3,dts,dts-hd,truehd" else ""
pendingMpvProperties["audio-spdif"] = audioSpdif
if (usingMpvFallback) {
mpvCore?.setProperty("audio-spdif", audioSpdif)
result.success(true)
return
}
activity?.runOnUiThread {
playerCore?.setAudioPassthrough(enabled)
result.success(true)
} ?: result.error("NO_ACTIVITY", "Activity not available", null)
}
private fun handleSetMpvProperty(call: MethodCall, result: MethodChannel.Result) {
val name = call.argument<String>("name")
val value = call.argument<String>("value")
@@ -652,6 +695,7 @@ class ExoPlayerPlugin :
// mpv semantics mirrored on the libass overlay: anchor non-positioned ASS
// events to the visible screen (Dart sets 'yes' for cover mode / zoom > 1)
"sub-ass-force-margins" -> playerCore?.setAssForceMargins(value == "yes")
"force-seekable" -> playerCore?.setForceSeekable(value == "yes")
}
}
@@ -683,59 +727,7 @@ class ExoPlayerPlugin :
* Queries relevant MPV properties and returns them in a map format
* compatible with the performance overlay.
*/
private fun getMpvStats(): Map<String, Any?> {
val mpv = mpvCore ?: return mapOf("playerType" to "mpv")
val hasVideo = mpv.getProperty("video-params/w") != null
val stats = mutableMapOf<String, Any?>(
"playerType" to "mpv",
// Video metrics
"video-codec" to mpv.getProperty("video-codec"),
"video-params/w" to mpv.getProperty("video-params/w"),
"video-params/h" to mpv.getProperty("video-params/h"),
"videoWidth" to mpv.getProperty("dwidth"),
"videoHeight" to mpv.getProperty("dheight"),
"container-fps" to mpv.getProperty("container-fps"),
"estimated-vf-fps" to mpv.getProperty("estimated-vf-fps"),
"video-bitrate" to mpv.getProperty("video-bitrate"),
"hwdec-current" to mpv.getProperty("hwdec-current"),
// Audio metrics
"audio-codec-name" to mpv.getProperty("audio-codec-name"),
"audio-params/samplerate" to mpv.getProperty("audio-params/samplerate"),
"audio-params/hr-channels" to mpv.getProperty("audio-params/hr-channels"),
"audio-bitrate" to mpv.getProperty("audio-bitrate"),
// Performance metrics
"total-avsync-change" to mpv.getProperty("total-avsync-change"),
"cache-used" to mpv.getProperty("cache-used"),
"demuxer-max-bytes" to mpv.getProperty("demuxer-max-bytes"),
"cache-speed" to mpv.getProperty("cache-speed"),
"frame-drop-count" to mpv.getProperty("frame-drop-count"),
"decoder-frame-drop-count" to mpv.getProperty("decoder-frame-drop-count"),
"demuxer-cache-duration" to mpv.getProperty("demuxer-cache-duration")
)
// Only query properties that require an active video track
if (hasVideo) {
stats["display-fps"] = mpv.getProperty("display-fps")
// Color/Format properties
stats["video-params/pixelformat"] = mpv.getProperty("video-params/pixelformat")
stats["video-params/hw-pixelformat"] = mpv.getProperty("video-params/hw-pixelformat")
stats["video-params/colormatrix"] = mpv.getProperty("video-params/colormatrix")
stats["video-params/primaries"] = mpv.getProperty("video-params/primaries")
stats["video-params/gamma"] = mpv.getProperty("video-params/gamma")
// HDR metadata
stats["video-params/max-luma"] = mpv.getProperty("video-params/max-luma")
stats["video-params/min-luma"] = mpv.getProperty("video-params/min-luma")
stats["video-params/max-cll"] = mpv.getProperty("video-params/max-cll")
stats["video-params/max-fall"] = mpv.getProperty("video-params/max-fall")
// Other
stats["video-params/aspect-name"] = mpv.getProperty("video-params/aspect-name")
stats["video-params/rotate"] = mpv.getProperty("video-params/rotate")
}
return stats
}
private fun getMpvStats(): Map<String, Any?> = mpvCore?.getStats() ?: mapOf("playerType" to "mpv")
// PiP Mode handling
@@ -766,34 +758,12 @@ class ExoPlayerPlugin :
}
override fun onEvent(name: String, data: Map<String, Any>?) {
val pendingFallbackSwitch =
name == "file-loaded" && pendingMpvFallbackSwitchGeneration == sessionGeneration && usingMpvFallback
if (pendingFallbackSwitch) {
clearPendingMpvFallbackSwitch()
}
val event = eventPayload(name, data)
mainHandler.post {
eventSink?.success(event)
if (pendingFallbackSwitch) {
eventSink?.success(eventPayload("backend-switched"))
}
}
mainHandler.post { eventSink?.success(event) }
}
private fun armPendingMpvFallbackSwitch(generation: Int) {
pendingMpvFallbackSwitchGeneration = generation
mainHandler.postDelayed({
if (pendingMpvFallbackSwitchGeneration == generation && sessionGeneration == generation && usingMpvFallback) {
Log.w(TAG, "Timed out waiting for MPV fallback file-loaded before backend-switched")
clearPendingMpvFallbackSwitch()
onEvent("backend-switched", null)
}
}, MPV_FALLBACK_SWITCH_TIMEOUT_MS)
}
private fun clearPendingMpvFallbackSwitch() {
pendingMpvFallbackSwitchGeneration = null
private fun notifyBackendSwitched() {
mainHandler.post { eventSink?.success(eventPayload("backend-switched")) }
}
/**
@@ -818,6 +788,24 @@ class ExoPlayerPlugin :
}
}
private fun appendExternalSubtitleOptions(
options: MutableList<String>,
externalSubtitles: List<Map<String, Any?>>?
) {
val escapedUris = externalSubtitles.orEmpty()
.mapNotNull { it["uri"] as? String }
.filter { it.isNotEmpty() }
.map(::escapeMpvPathListEntry)
.toList()
if (escapedUris.isEmpty()) return
val pathList = escapedUris.joinToString(":")
options.add("sub-files=%${pathList.toByteArray(Charsets.UTF_8).size}%$pathList")
}
private fun escapeMpvPathListEntry(value: String): String = value.replace("\\", "\\\\").replace(":", "\\:")
/**
* Configure a freshly initialized MPV fallback core: replay the properties
* and observers Dart registered against the ExoPlayer session, then resume
@@ -829,7 +817,8 @@ class ExoPlayerPlugin :
act: Activity,
uri: String,
headers: Map<String, String>?,
positionMs: Long
positionMs: Long,
externalSubtitles: List<Map<String, Any?>>?
) {
// Snapshot Dart-registered state on main thread before clearing
val pendingProps = pendingMpvProperties.toList()
@@ -846,7 +835,6 @@ class ExoPlayerPlugin :
if (mpvCore !== core) {
core.dispose()
fallbackInProgress = false
clearPendingMpvFallbackSwitch()
return
}
// Configure basic MPV properties for Plex playback
@@ -876,12 +864,15 @@ class ExoPlayerPlugin :
// Load media at the same position
val startSeconds = positionMs / 1000.0
val options = mutableListOf<String>()
options.add("start=$startSeconds")
options.add(if (positionMs > 0L) "start=$startSeconds" else "start=none")
options.add("sid=no")
options.add("secondary-sid=no")
appendExternalSubtitleOptions(options, externalSubtitles)
headers?.forEach { (key, value) ->
options.add("http-header-fields-append=$key: $value")
}
val optionsStr = options.joinToString(",")
armPendingMpvFallbackSwitch(sessionGeneration)
notifyBackendSwitched()
core.command(arrayOf("loadfile", mpvUri, "replace", "-1", optionsStr))
// On GPUs without compute shaders, MPV can't do dynamic peak detection
@@ -915,6 +906,7 @@ class ExoPlayerPlugin :
}
val currentActivity = activity ?: return false
val fallbackExternalSubtitles = currentExternalSubtitles?.map { it.toMap() }
fallbackInProgress = true
Log.i(TAG, "ExoPlayer error, switching to MPV fallback at ${positionMs}ms: $errorMessage")
@@ -937,20 +929,17 @@ class ExoPlayerPlugin :
mpvCore?.dispose()
mpvCore = null
usingMpvFallback = false // Clear before handoff
clearPendingMpvFallbackSwitch()
val generation = sessionGeneration
Handler(Looper.getMainLooper()).post {
if (generation != sessionGeneration) {
fallbackInProgress = false
clearPendingMpvFallbackSwitch()
return@post
}
val act = activity
if (act == null) {
fallbackInProgress = false
clearPendingMpvFallbackSwitch()
return@post
}
@@ -967,7 +956,6 @@ class ExoPlayerPlugin :
mpvCore = null
}
fallbackInProgress = false
clearPendingMpvFallbackSwitch()
return@initialize
}
if (!success) {
@@ -976,7 +964,6 @@ class ExoPlayerPlugin :
mpvCore = null
}
fallbackInProgress = false
clearPendingMpvFallbackSwitch()
Log.e(TAG, "Failed to initialize MPV fallback")
onEvent("end-file", mapOf("reason" to "error", "message" to "Fallback failed: $errorMessage"))
return@initialize
@@ -985,18 +972,16 @@ class ExoPlayerPlugin :
usingMpvFallback = true
fallbackInProgress = false
setupMpvFallback(core, act, uri, headers, positionMs)
setupMpvFallback(core, act, uri, headers, positionMs, fallbackExternalSubtitles)
}
} catch (e: Exception) {
fallbackInProgress = false
clearPendingMpvFallbackSwitch()
Log.e(TAG, "Failed to switch to MPV fallback", e)
onEvent("end-file", mapOf("reason" to "error", "message" to "Fallback failed: ${e.message}"))
}
}
} catch (e: Exception) {
fallbackInProgress = false
clearPendingMpvFallbackSwitch()
Log.e(TAG, "Failed to switch to MPV fallback", e)
onEvent("end-file", mapOf("reason" to "error", "message" to "Fallback failed: ${e.message}"))
}
@@ -0,0 +1,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)
}
}
@@ -76,6 +76,7 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
@Volatile private var videoOutputEpoch: Long = 0L
private val videoOutputMutex = Mutex()
private val commandMutex = Mutex()
private var pendingVideoOutputDisableJob: Job? = null
private var pendingVideoOutputRefreshJob: Job? = null
@@ -111,20 +112,29 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
return refreshRate.toString()
}
private fun updateDisplayFpsOverride(p: MpvPlayer, reason: String) {
private fun updateDisplayFpsOverride(p: MpvPlayer, reason: String, onComplete: () -> Unit = {}) {
val fps = currentDisplayFpsOverride()
if (fps == null) {
Log.d(TAG, "Skipping display-fps-override update ($reason): no display rate")
onComplete()
return
}
if (!scope.isActive) {
onComplete()
return
}
try {
runBlocking(Dispatchers.IO) {
scope.launch(Dispatchers.IO) {
try {
p.setProperty("display-fps-override", fps)
Log.d(TAG, "Updated display-fps-override=$fps ($reason)")
} catch (e: Exception) {
Log.w(TAG, "Failed to update display-fps-override ($reason)", e)
} finally {
withContext(NonCancellable + Dispatchers.Main) {
onComplete()
}
}
Log.d(TAG, "Updated display-fps-override=$fps ($reason)")
} catch (e: Exception) {
Log.w(TAG, "Failed to update display-fps-override ($reason)", e)
}
}
@@ -649,8 +659,11 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
// Public API
fun setProperty(name: String, value: String) {
if (!isInitialized || disposing) return
fun setProperty(name: String, value: String, onComplete: ((Boolean) -> Unit)? = null) {
if (!isInitialized || disposing || !scope.isActive) {
onComplete?.invoke(false)
return
}
if (name == "pause") {
val paused = normalizePauseValue(value)
if (paused == true) {
@@ -664,6 +677,7 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
if (!hasReadyVideoOutput()) {
deferredResumeRequested = true
Log.d(TAG, "Deferring public resume until video output is ready")
onComplete?.invoke(true)
return
}
cachedPaused = false
@@ -671,16 +685,30 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
Log.d(TAG, "Public pause state updated: paused=false")
}
}
scope.launch {
scope.launch(Dispatchers.IO) {
var success = false
try {
player?.setProperty(name, value)
success = true
} catch (e: Exception) {
Log.w(TAG, "setProperty($name) failed", e)
} finally {
withContext(NonCancellable + Dispatchers.Main) {
onComplete?.invoke(success)
}
}
}
}
fun getProperty(name: String): String? {
if (Looper.myLooper() == Looper.getMainLooper()) {
Log.w(TAG, "Refusing synchronous getProperty($name) on the main thread")
return null
}
return getPropertyBlocking(name)
}
private fun getPropertyBlocking(name: String): String? {
if (!isInitialized || disposing) return null
return try {
runBlocking(Dispatchers.IO) { player?.getString(name) }
@@ -689,6 +717,75 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
}
}
fun getPropertyAsync(name: String, onResult: (String?) -> Unit) {
if (!isInitialized || disposing) {
onResult(null)
return
}
Thread {
val value = getPropertyBlocking(name)
activity.runOnUiThread {
onResult(if (!disposing && isInitialized) value else null)
}
}.start()
}
/**
* Returns MPV stats in the same key format used by the performance overlay.
* This method performs synchronous native property reads and must not be
* called on Android's main thread.
*/
fun getStats(): Map<String, Any?> {
if (Looper.myLooper() == Looper.getMainLooper()) {
Log.w(TAG, "Refusing synchronous getStats() on the main thread")
return mapOf("playerType" to "mpv")
}
val hasVideo = getProperty("video-params/w") != null
val stats = mutableMapOf<String, Any?>(
"playerType" to "mpv",
"video-codec" to getProperty("video-codec"),
"video-params/w" to getProperty("video-params/w"),
"video-params/h" to getProperty("video-params/h"),
"videoWidth" to getProperty("dwidth"),
"videoHeight" to getProperty("dheight"),
"container-fps" to getProperty("container-fps"),
"estimated-vf-fps" to getProperty("estimated-vf-fps"),
"video-bitrate" to getProperty("video-bitrate"),
"hwdec-current" to getProperty("hwdec-current"),
"audio-codec-name" to getProperty("audio-codec-name"),
"audio-params/samplerate" to getProperty("audio-params/samplerate"),
"audio-params/hr-channels" to getProperty("audio-params/hr-channels"),
"audio-bitrate" to getProperty("audio-bitrate"),
"total-avsync-change" to getProperty("total-avsync-change"),
"cache-used" to getProperty("cache-used"),
"demuxer-max-bytes" to getProperty("demuxer-max-bytes"),
"cache-speed" to getProperty("cache-speed"),
"frame-drop-count" to getProperty("frame-drop-count"),
"decoder-frame-drop-count" to getProperty("decoder-frame-drop-count"),
"demuxer-cache-duration" to getProperty("demuxer-cache-duration")
)
if (hasVideo) {
stats["display-fps"] = getProperty("display-fps")
stats["video-params/pixelformat"] = getProperty("video-params/pixelformat")
stats["video-params/hw-pixelformat"] = getProperty("video-params/hw-pixelformat")
stats["video-params/colormatrix"] = getProperty("video-params/colormatrix")
stats["video-params/primaries"] = getProperty("video-params/primaries")
stats["video-params/gamma"] = getProperty("video-params/gamma")
stats["video-params/max-luma"] = getProperty("video-params/max-luma")
stats["video-params/min-luma"] = getProperty("video-params/min-luma")
stats["video-params/max-cll"] = getProperty("video-params/max-cll")
stats["video-params/max-fall"] = getProperty("video-params/max-fall")
stats["video-params/aspect-name"] = getProperty("video-params/aspect-name")
stats["video-params/rotate"] = getProperty("video-params/rotate")
}
return stats
}
fun observeProperty(name: String, format: String) {
val p = player ?: return
if (!isInitialized) return
@@ -706,15 +803,19 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
onComplete?.invoke(false)
return
}
scope.launch {
scope.launch(Dispatchers.IO) {
var success = false
try {
player?.command(*args)
success = true
commandMutex.withLock {
player?.command(*args)
success = true
}
} catch (e: Exception) {
Log.w(TAG, "command failed", e)
} finally {
onComplete?.invoke(success)
withContext(NonCancellable + Dispatchers.Main) {
onComplete?.invoke(success)
}
}
}
}
@@ -785,6 +886,8 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
fps: Float,
videoDurationMs: Long,
extraDelayMs: Long,
videoWidth: Int,
videoHeight: Int,
onComplete: (switched: Boolean) -> Unit
) {
val mgr = frameRateManager
@@ -792,9 +895,12 @@ class MpvPlayerCore(private val activity: Activity) : SurfaceHolder.Callback {
onComplete(false)
return
}
mgr.setVideoFrameRate(fps, videoDurationMs, extraDelayMs) { switched ->
player?.let { updateDisplayFpsOverride(it, "frame rate switch, switched=$switched") }
onComplete(switched)
mgr.setVideoFrameRate(fps, videoDurationMs, extraDelayMs, videoWidth, videoHeight) { switched ->
player?.let {
updateDisplayFpsOverride(it, "frame rate switch, switched=$switched") {
onComplete(switched)
}
} ?: onComplete(switched)
}
}
@@ -110,6 +110,7 @@ class MpvPlayerPlugin :
"dispose" -> handleDispose(result)
"setProperty" -> handleSetProperty(call, result)
"getProperty" -> handleGetProperty(call, result)
"getStats" -> handleGetStats(result)
"observeProperty" -> handleObserveProperty(call, result)
"command" -> handleCommand(call, result)
"setVisible" -> handleSetVisible(call, result)
@@ -232,8 +233,15 @@ class MpvPlayerPlugin :
return
}
playerCore?.setProperty(name, value)
result.success(null)
val core = playerCore
if (core == null) {
result.success(null)
return
}
core.setProperty(name, value) {
result.success(null)
}
}
private fun handleGetProperty(call: MethodCall, result: MethodChannel.Result) {
@@ -244,8 +252,41 @@ class MpvPlayerPlugin :
return
}
val value = playerCore?.getProperty(name)
result.success(value)
val core = playerCore
if (core == null) {
result.success(null)
return
}
val gen = sessionGeneration
core.getPropertyAsync(name) { value ->
if (gen != sessionGeneration || playerCore !== core) {
result.success(null)
} else {
result.success(value)
}
}
}
private fun handleGetStats(result: MethodChannel.Result) {
val currentActivity = activity
val core = playerCore
if (currentActivity == null || core == null) {
result.success(mapOf("playerType" to "mpv"))
return
}
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()
}
private fun handleObserveProperty(call: MethodCall, result: MethodChannel.Result) {
@@ -302,14 +343,16 @@ class MpvPlayerPlugin :
val fps = call.argument<Double>("fps")?.toFloat() ?: 0f
val duration = call.argument<Number>("duration")?.toLong() ?: 0L
val extraDelayMs = call.argument<Number>("extraDelayMs")?.toLong() ?: 0L
val videoWidth = call.argument<Number>("videoWidth")?.toInt() ?: 0
val videoHeight = call.argument<Number>("videoHeight")?.toInt() ?: 0
Log.d(TAG, "setVideoFrameRate: fps=$fps, duration=$duration, extraDelayMs=$extraDelayMs")
Log.d(TAG, "setVideoFrameRate: fps=$fps, duration=$duration, extraDelayMs=$extraDelayMs, video=${videoWidth}x$videoHeight")
val core = playerCore
if (core == null) {
result.success(false)
return
}
core.setVideoFrameRate(fps, duration, extraDelayMs) { switched ->
core.setVideoFrameRate(fps, duration, extraDelayMs, videoWidth, videoHeight) { switched ->
result.success(switched)
}
}
@@ -37,6 +37,8 @@ class FrameRateManager(
)
private var currentVideoFps: Float = 0f
private var currentVideoWidth: Int = 0
private var currentVideoHeight: Int = 0
private var displayListener: DisplayManager.DisplayListener? = null
private var pendingSettleRunnable: Runnable? = null
private var watchdogRunnable: Runnable? = null
@@ -57,9 +59,13 @@ class FrameRateManager(
fps: Float,
videoDurationMs: Long,
extraDelayMs: Long,
videoWidth: Int = 0,
videoHeight: Int = 0,
onComplete: (switched: Boolean) -> Unit
) {
currentVideoFps = fps
currentVideoWidth = videoWidth
currentVideoHeight = videoHeight
if (fps <= 0f) {
Log.d(TAG, "setVideoFrameRate: Invalid fps ($fps), skipping")
onComplete(false)
@@ -68,7 +74,7 @@ class FrameRateManager(
log(
"request fps=$fps, duration=${videoDurationMs}ms, extraDelayMs=$extraDelayMs, " +
"API=${Build.VERSION.SDK_INT}, currentMode=${currentModeDescription()}"
"video=${videoWidth}x$videoHeight, API=${Build.VERSION.SDK_INT}, currentMode=${currentModeDescription()}"
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
@@ -208,17 +214,42 @@ class FrameRateManager(
private fun describeSupportedModes(modes: Array<Display.Mode>): String = modes.joinToString(prefix = "[", postfix = "]") { describeMode(it) }
@RequiresApi(Build.VERSION_CODES.M)
private fun findBestModeMatch(fps: Float, currentMode: Display.Mode, supportedModes: Array<Display.Mode>): DisplayModeCandidate? = supportedModes.asSequence()
.filter { mode ->
mode.physicalHeight == currentMode.physicalHeight &&
mode.physicalWidth == currentMode.physicalWidth
}
.mapNotNull { mode -> matchRefreshRate(mode.refreshRate, fps)?.let { DisplayModeCandidate(mode, it) } }
.minWithOrNull(
compareBy<DisplayModeCandidate> { it.match.priority }
.thenBy { it.match.error }
.thenBy { abs(it.mode.refreshRate - currentMode.refreshRate) }
)
private fun findBestModeMatch(
fps: Float,
currentMode: Display.Mode,
supportedModes: Array<Display.Mode>,
videoWidth: Int,
videoHeight: Int
): DisplayModeCandidate? {
// Tier 1 — a matching-refresh mode at the CURRENT resolution: a refresh-only
// switch, the least disruptive (no resolution/HDMI renegotiation).
supportedModes.asSequence()
.filter { it.physicalHeight == currentMode.physicalHeight && it.physicalWidth == currentMode.physicalWidth }
.mapNotNull { mode -> matchRefreshRate(mode.refreshRate, fps)?.let { DisplayModeCandidate(mode, it) } }
.minWithOrNull(
compareBy<DisplayModeCandidate> { it.match.priority }
.thenBy { it.match.error }
.thenBy { abs(it.mode.refreshRate - currentMode.refreshRate) }
)
?.let { return it }
// Tier 2 — no same-resolution match (e.g. a 4K panel with no 4K@24 mode, but a
// 1080p@23.976 mode for 1080p content). Allow a resolution change, but never one
// that downscales the video below its native size (trading detail for cadence).
// Requires known video dimensions; without them keep Tier-1-only behaviour.
if (videoWidth <= 0 || videoHeight <= 0) return null
val currentArea = currentMode.physicalWidth.toLong() * currentMode.physicalHeight
return supportedModes.asSequence()
.filter { it.physicalWidth >= videoWidth && it.physicalHeight >= videoHeight }
.mapNotNull { mode -> matchRefreshRate(mode.refreshRate, fps)?.let { DisplayModeCandidate(mode, it) } }
.minWithOrNull(
// Prefer the resolution closest to the panel's current one (least change,
// keeps panel-native res when a high-res match exists), then refresh match.
compareBy<DisplayModeCandidate> { abs(it.mode.physicalWidth.toLong() * it.mode.physicalHeight - currentArea) }
.thenBy { it.match.priority }
.thenBy { it.match.error }
)
}
@RequiresApi(Build.VERSION_CODES.M)
private fun setDisplayMode(fps: Float, extraDelayMs: Long, onComplete: (switched: Boolean) -> Unit) {
@@ -239,9 +270,12 @@ class FrameRateManager(
val currentMode = display.mode
log("supported modes=${describeSupportedModes(supportedModes)}")
val modeMatch = findBestModeMatch(fps, currentMode, supportedModes)
val modeMatch = findBestModeMatch(fps, currentMode, supportedModes, currentVideoWidth, currentVideoHeight)
if (modeMatch == null) {
log("no matching display mode for ${fps}fps at ${currentMode.physicalWidth}x${currentMode.physicalHeight}")
log(
"no matching display mode for ${fps}fps at ${currentMode.physicalWidth}x${currentMode.physicalHeight} " +
"(video=${currentVideoWidth}x$currentVideoHeight)"
)
onComplete(false)
return
}
@@ -0,0 +1,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))
}
}
}
-22
View File
@@ -2,28 +2,6 @@ allprojects {
repositories {
google()
mavenCentral()
if (providers.gradleProperty("localAssCore").isPresent) {
// Opt-in A/B of a locally built libass native core: build it in the
// libass-android fork with `./gradlew :lib_ass:publishToMavenLocal
// -PVERSION_NAME=0.4.0-local`, then build this app with -PlocalAssCore.
mavenLocal()
} else {
// Production libass native core: the -O3/NEON/asm AAR published on
// the edde746/libass-android fork's releases (the upstream Maven
// artifact io.github.peerless2012:ass ships un-optimized natives —
// see the fork's pinned libass-cmake fix). Resolved as
// <tag>/ass-<tag>.aar with no metadata probing.
exclusiveContent {
forRepository {
ivy {
url = uri("https://github.com/edde746/libass-android/releases/download")
patternLayout { artifact("[revision]/[artifact]-[revision].[ext]") }
metadataSources { artifact() }
}
}
filter { includeModule("io.github.peerless2012", "ass") }
}
}
}
}
+9 -33
View File
@@ -1,7 +1,5 @@
// libass ASS subtitle rendering: Kotlin/JNI bindings + Media3 integration
// (extractor, parsers, AssHandler, GL atlas overlay). The native libass core
// (libass.so + prefab headers) comes from the Maven artifact
// io.github.peerless2012:ass; this module compiles its JNI against it.
// Static-linking the native core here avoids shipping a separate libass.so with
// different merge rules from the app.
plugins {
id("com.android.library")
id("org.jetbrains.kotlin.android")
@@ -20,34 +18,19 @@ android {
defaultConfig {
minSdk = 21
consumerProguardFiles("consumer-rules.pro")
if (project.hasProperty("localAssCore")) {
// The locally published A/B core only ships device ABIs (x86 would need
// nasm on the host); match it so prefab resolution doesn't fail.
ndk {
abiFilters += listOf("armeabi-v7a", "arm64-v8a")
}
}
externalNativeBuild {
cmake {
// libass.so in the prefab AAR is built against c++_shared (abi.json: stl=c++_shared);
// prefab validates consumer STL compatibility.
arguments += listOf("-DANDROID_STL=c++_shared")
// HarfBuzz pulls in C++, so the JNI library must use the shared STL that
// the app already pins through libmpv.
// A shared cache keeps per-ABI CMake runs from redownloading libass.
arguments += listOf(
"-DANDROID_STL=c++_shared",
"-DLIBASS_CACHE_DIR=${layout.buildDirectory.get().asFile}/libass-prebuilt"
)
}
}
}
buildFeatures {
prefab = true
}
packaging {
jniLibs {
// libass.so is a prefab IMPORTED target (linked, not owned) — the app packages
// it from the io.github.peerless2012:ass AAR; don't duplicate it here.
excludes.add("**/libass.so")
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
@@ -66,13 +49,6 @@ android {
}
dependencies {
// compileOnly: prefab headers + link-time libass.so come from the AAR; runtime
// packaging of libass.so is the app's implementation dependency.
// -PlocalAssCore swaps in a mavenLocal()-published core for A/B tests (must
// match the app module's version so one libass.so is linked and packaged).
val assCoreVersion = if (project.hasProperty("localAssCore")) "0.4.0-local" else "0.4.1-plezy.1"
compileOnly("io.github.peerless2012:ass:$assCoreVersion@aar")
implementation("androidx.annotation:annotation:1.9.1")
implementation("androidx.annotation:annotation-experimental:1.5.1")
implementation("androidx.media3:media3-exoplayer:1.9.2")
+217 -10
View File
@@ -1,10 +1,15 @@
// JNI bindings for libass. Exports use standard Java_<package>_<Class>_<method>
// naming so no RegisterNatives/JNI_OnLoad registration is needed.
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <android/log.h>
#include <jni.h>
#include <limits.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
static inline long long nowMs(void) {
@@ -61,7 +66,13 @@ JNIEXPORT void JNICALL Java_com_edde746_plezy_libass_Ass_nativeAssDeinit(JNIEnv*
JNIEXPORT jlong JNICALL
Java_com_edde746_plezy_libass_AssTrack_nativeAssTrackInit(JNIEnv* env, jclass clazz, jlong ass) {
return (jlong)ass_new_track((ASS_Library*)ass);
ASS_Track* track = ass_new_track((ASS_Library*)ass);
if (track != NULL) {
if (ass_track_set_feature(track, ASS_FEATURE_FAST_BLUR, 1) != 0) {
__android_log_print(ANDROID_LOG_WARN, LOG_TAG, "ASS_FEATURE_FAST_BLUR unavailable in libass build");
}
}
return (jlong)track;
}
// Shared body of readBuffer/readChunk: pins the byte array and feeds libass.
@@ -132,10 +143,54 @@ JNIEXPORT jlong JNICALL Java_com_edde746_plezy_libass_AssTrack_nativeAssTrackNex
// --- AssRender ---
// The fork's fontconfig build has no Android font search defaults. A tiny
// process-local config lets /system fonts resolve without adding Context/JNI plumbing.
static char* ensureFontsConf(void) {
const char* tmp = getenv("TMPDIR");
if (tmp == NULL || tmp[0] == '\0') tmp = "/data/local/tmp";
char cacheDir[PATH_MAX];
snprintf(cacheDir, sizeof(cacheDir), "%s/fontconfig", tmp);
mkdir(cacheDir, 0700);
char* confPath = (char*)malloc(PATH_MAX);
if (confPath == NULL) return NULL;
snprintf(confPath, PATH_MAX, "%s/fonts.conf", tmp);
FILE* f = fopen(confPath, "w");
if (f == NULL) {
free(confPath);
return NULL;
}
fprintf(
f,
"<?xml version=\"1.0\"?>\n"
"<!DOCTYPE fontconfig SYSTEM \"fonts.dtd\">\n"
"<fontconfig>\n"
" <dir>/system/fonts</dir>\n"
" <dir>/system/font</dir>\n"
" <dir>/product/fonts</dir>\n"
" <dir>/data/fonts</dir>\n"
" <cachedir>%s</cachedir>\n"
"</fontconfig>\n",
cacheDir);
fclose(f);
return confPath;
}
JNIEXPORT jlong JNICALL
Java_com_edde746_plezy_libass_AssRender_nativeAssRenderInit(JNIEnv* env, jclass clazz, jlong ass) {
ASS_Renderer* assRenderer = ass_renderer_init((ASS_Library*)ass);
ass_set_fonts(assRenderer, NULL, "sans-serif", ASS_FONTPROVIDER_FONTCONFIG, NULL, 1);
if (assRenderer == NULL) return 0;
unsigned threads = ass_set_threads(assRenderer, 0);
if (threads == 0) {
__android_log_print(ANDROID_LOG_WARN, LOG_TAG, "libass threading unavailable in native build");
} else {
__android_log_print(ANDROID_LOG_INFO, LOG_TAG, "libass rendering threads enabled: %u", threads);
}
char* fontsConf = ensureFontsConf();
ass_set_fonts(assRenderer, NULL, "sans-serif", ASS_FONTPROVIDER_FONTCONFIG, fontsConf, 1);
free(fontsConf);
return (jlong)assRenderer;
}
@@ -195,6 +250,13 @@ static int comparePackItemsByHeightDesc(const void* a, const void* 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;
@@ -214,8 +276,9 @@ static int truncationLogCounter = 0;
// Never fails on content size: images that don't fit the remaining atlas/vertex
// capacity are dropped and counted in AssAtlasFrame.truncated, so a heavy frame
// degrades instead of going stale. Returns NULL only for missing buffers/handles.
// On changed == 0, returns (0, 0, 0, changed, 0) without touching the buffers —
// caller reuses the atlas texture already on the GPU.
// 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) {
@@ -223,7 +286,7 @@ JNIEXPORT jobject JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRende
jclass atlasFrameClass = (*env)->FindClass(env, "com/edde746/plezy/libass/AssAtlasFrame");
if (!atlasFrameClass) return NULL;
jmethodID ctor = (*env)->GetMethodID(env, atlasFrameClass, "<init>", "(IIIII)V");
jmethodID ctor = (*env)->GetMethodID(env, atlasFrameClass, "<init>", "(IIIIIZ)V");
if (!ctor) return NULL;
const long long t0 = nowMs();
@@ -231,13 +294,23 @@ JNIEXPORT jobject JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRende
ASS_Image* image = ass_render_frame((ASS_Renderer*)render, (ASS_Track*)track, time, &changed);
const long long tAss = nowMs();
if (changed == 0 || image == NULL) {
if (changed == 0) {
const 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);
return (*env)->NewObject(env, atlasFrameClass, ctor, 0, 0, 0, changed, 0, JNI_FALSE);
}
uint8_t* atlasPixels = (uint8_t*)(*env)->GetDirectBufferAddress(env, atlasBuf);
@@ -259,7 +332,7 @@ JNIEXPORT jobject JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRende
if (img->w > 0 && img->h > 0) total++;
}
if (total == 0) {
return (*env)->NewObject(env, atlasFrameClass, ctor, 0, 0, 0, changed, 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
@@ -324,7 +397,7 @@ JNIEXPORT jobject JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRende
free(items);
free(slotX);
free(slotY);
return (*env)->NewObject(env, atlasFrameClass, ctor, 0, 0, 0, changed, truncated);
return (*env)->NewObject(env, atlasFrameClass, ctor, 0, 0, 0, changed, truncated, JNI_TRUE);
}
memset(atlasPixels, 0, (size_t)atlasMaxW * packedH);
@@ -432,5 +505,139 @@ JNIEXPORT jobject JNICALL Java_com_edde746_plezy_libass_AssRender_nativeAssRende
// 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);
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];
}
+50 -5
View File
@@ -2,9 +2,54 @@ cmake_minimum_required(VERSION 3.22.1)
project("asskt")
# libass headers + libass.so come from the io.github.peerless2012:ass AAR via prefab.
add_library(${CMAKE_PROJECT_NAME} SHARED AssKt.c)
find_package(lib_ass REQUIRED CONFIG)
# Fetching the fork release at configure time keeps per-ABI static archives out
# of git; the pinned hash makes that network step reproducible.
set(LIBASS_VERSION "0.18.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
lib_ass::ass
log)
ass
log
EGL
c++_shared)
@@ -0,0 +1,47 @@
cmake_minimum_required(VERSION 3.22.1)
foreach(_var IN ITEMS
LIBASS_VERSION
LIBASS_SHA256
LIBASS_ZIP_URL
LIBASS_CACHE_DIR
LIBASS_ROOT
LIBASS_ARCHIVE
LIBASS_HEADER
ANDROID_ABI)
if(NOT DEFINED ${_var} OR "${${_var}}" STREQUAL "")
message(FATAL_ERROR "${_var} is required")
endif()
endforeach()
get_filename_component(_cache_parent "${LIBASS_CACHE_DIR}" DIRECTORY)
file(MAKE_DIRECTORY "${_cache_parent}")
# Android Gradle can build ABI variants in parallel; serialize the shared cache.
file(LOCK "${LIBASS_CACHE_DIR}.lock" GUARD PROCESS TIMEOUT 300)
if(NOT EXISTS "${LIBASS_ARCHIVE}" OR NOT EXISTS "${LIBASS_HEADER}")
file(MAKE_DIRECTORY "${LIBASS_CACHE_DIR}")
set(_libass_zip "${LIBASS_CACHE_DIR}/libass-android-${LIBASS_VERSION}.zip")
message(STATUS "Fetching fork libass ${LIBASS_VERSION} from ${LIBASS_ZIP_URL}")
file(DOWNLOAD "${LIBASS_ZIP_URL}" "${_libass_zip}"
EXPECTED_HASH "SHA256=${LIBASS_SHA256}"
TLS_VERIFY ON
STATUS _libass_dl)
list(GET _libass_dl 0 _libass_dl_code)
if(NOT _libass_dl_code EQUAL 0)
file(REMOVE "${_libass_zip}")
message(FATAL_ERROR "Failed to download libass: ${_libass_dl}")
endif()
file(REMOVE_RECURSE "${LIBASS_ROOT}")
file(ARCHIVE_EXTRACT INPUT "${_libass_zip}" DESTINATION "${LIBASS_CACHE_DIR}")
endif()
if(NOT EXISTS "${LIBASS_ARCHIVE}")
message(FATAL_ERROR "libass archive for ${ANDROID_ABI} was not extracted: ${LIBASS_ARCHIVE}")
endif()
if(NOT EXISTS "${LIBASS_HEADER}")
message(FATAL_ERROR "libass headers were not extracted: ${LIBASS_HEADER}")
endif()
@@ -0,0 +1,317 @@
// EXPERIMENTAL SPIKE — does the codec VIDEO plane's actual present time differ from a
// GL OSD overlay's, and is that difference measurable in-app? (See the memory note
// project_libass_present_time_instrumentation.)
//
// Android exposes no present time for a codec-owned video layer. The one runtime lead is
// API 34 `SurfaceView.applyTransactionToFrame()`: it merges an otherwise-empty,
// callback-bearing transaction with the codec's *next buffer* transaction. The completion
// stats then carry, per surface, the PREVIOUS-RELEASE fence — the moment the buffer the new
// frame replaced stopped being read by the display ≈ when the new codec frame actually
// reached the video plane. Compared in Kotlin to that frame's `releaseTimeNs` target (the
// overlay's own present error is ~0), the delta is the inter-plane lag.
//
// The SurfaceControl transaction-stats / fromJava APIs are API 29/34 while this module's
// minSdk is 21; clang's __builtin_available doesn't guard the Android availability domain in
// this toolchain. So the libandroid entry points are resolved by dlsym (no
// availability-attributed declarations get compiled). Every call site is additionally
// hard-gated to API >= 34 in Kotlin (VideoLayerLatencyProbe).
//
// Fence timestamps are read with the raw SYNC_IOC_FILE_INFO ioctl rather than libsync:
// libsync.so is NOT a public NDK library, so an app's linker namespace blocks dlopen of it.
//
// Compiled into the libass "asskt" .so; called from app Kotlin SurfaceTxProbe.
#include <android/log.h>
#include <dlfcn.h>
#include <jni.h>
#include <poll.h>
#include <pthread.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <time.h>
#include <unistd.h>
#define LOG_TAG "SurfaceTxProbe"
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)
#ifndef SYNC_IOC_MAGIC
#define SYNC_IOC_MAGIC '>'
#endif
struct stp_fence_info {
char obj_name[32];
char driver_name[32];
int32_t status;
uint32_t flags;
uint64_t timestamp_ns;
};
struct stp_file_info {
char name[32];
int32_t status;
uint32_t flags;
uint32_t num_fences;
uint32_t pad;
uint64_t sync_fence_info;
};
#ifndef SYNC_IOC_FILE_INFO
#define SYNC_IOC_FILE_INFO _IOWR(SYNC_IOC_MAGIC, 4, struct stp_file_info)
#endif
// libsync is hidden from app linker namespaces, so use the kernel ioctl directly.
static int64_t readFenceTimeNs(int fd, int* outStatus) {
*outStatus = -1;
if (fd < 0) return -1;
struct stp_file_info probe;
memset(&probe, 0, sizeof(probe));
if (ioctl(fd, SYNC_IOC_FILE_INFO, &probe) < 0) return -1;
*outStatus = probe.status;
if (probe.status != 1 || probe.num_fences == 0) return -1;
struct stp_fence_info* arr = (struct stp_fence_info*)calloc(probe.num_fences, sizeof(struct stp_fence_info));
if (!arr) return -1;
struct stp_file_info req;
memset(&req, 0, sizeof(req));
req.num_fences = probe.num_fences;
req.sync_fence_info = (uint64_t)(uintptr_t)arr;
int64_t t = -1;
if (ioctl(fd, SYNC_IOC_FILE_INFO, &req) == 0) {
for (uint32_t i = 0; i < req.num_fences; i++) {
if ((int64_t)arr[i].timestamp_ns > t) t = (int64_t)arr[i].timestamp_ns;
}
}
free(arr);
return t;
}
typedef struct ASurfaceTransaction ASurfaceTransaction;
typedef struct ASurfaceControl ASurfaceControl;
typedef struct ASurfaceTransactionStats ASurfaceTransactionStats;
typedef void (*OnCompleteFn)(void* context, ASurfaceTransactionStats* stats);
typedef ASurfaceTransaction* (*pf_fromJava)(JNIEnv*, jobject);
typedef void (*pf_setOnComplete)(ASurfaceTransaction*, void*, OnCompleteFn);
typedef int64_t (*pf_latchTime)(ASurfaceTransactionStats*);
typedef void (*pf_getControls)(ASurfaceTransactionStats*, ASurfaceControl***, size_t*);
typedef int (*pf_prevRelease)(ASurfaceTransactionStats*, ASurfaceControl*);
typedef void (*pf_releaseControls)(ASurfaceControl**);
static pf_fromJava p_fromJava = NULL;
static pf_setOnComplete p_setOnComplete = NULL;
static pf_latchTime p_latchTime = NULL;
static pf_getControls p_getControls = NULL;
static pf_prevRelease p_prevRelease = NULL;
static pf_releaseControls p_releaseControls = NULL;
static int gScResolved = 0;
static int gScOk = 0;
static int gScWarningLogged = 0;
// Runtime lookup keeps this API-34 probe buildable with the module's minSdk 21.
static int resolveSc(void) {
if (gScResolved) return gScOk;
gScResolved = 1;
void* h = dlopen("libandroid.so", RTLD_NOW | RTLD_GLOBAL);
if (!h) return 0;
p_fromJava = (pf_fromJava)dlsym(h, "ASurfaceTransaction_fromJava");
p_setOnComplete = (pf_setOnComplete)dlsym(h, "ASurfaceTransaction_setOnComplete");
p_latchTime = (pf_latchTime)dlsym(h, "ASurfaceTransactionStats_getLatchTime");
p_getControls = (pf_getControls)dlsym(h, "ASurfaceTransactionStats_getASurfaceControls");
p_prevRelease = (pf_prevRelease)dlsym(h, "ASurfaceTransactionStats_getPreviousReleaseFenceFd");
p_releaseControls = (pf_releaseControls)dlsym(h, "ASurfaceTransactionStats_releaseASurfaceControls");
gScOk = (p_fromJava && p_setOnComplete && p_latchTime && p_getControls && p_prevRelease && p_releaseControls) ? 1 : 0;
return gScOk;
}
// The completion context is pointer-width, so 32-bit devices need an index side-channel.
#define TAG_RING_SIZE 256
static int64_t gTagRing[TAG_RING_SIZE];
static int gSrcRing[TAG_RING_SIZE];
static int gTagSeq = 0;
static JavaVM* gVm = NULL;
static jclass gProbeClass = NULL;
static jmethodID gOnResult = NULL;
static int gCallbackLookupAttempted = 0;
static pthread_mutex_t gInitLock = PTHREAD_MUTEX_INITIALIZER;
static int64_t nowMonoNs(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (int64_t)ts.tv_sec * 1000000000LL + ts.tv_nsec;
}
static void reportResult(
JNIEnv* env, int64_t tag, int64_t latchNs, int64_t releaseNs, int count, int fenceState, int source, int64_t cbNs) {
if (!env || !gProbeClass || !gOnResult) return;
(*env)->CallStaticVoidMethod(
env, gProbeClass, gOnResult, (jlong)tag, (jlong)latchNs, (jlong)releaseNs, (jint)count, (jint)fenceState,
(jint)source, (jlong)cbNs);
if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
}
// Previous-release fences can still be pending in the binder callback; a worker
// thread keeps SurfaceFlinger's callback dispatch unblocked.
struct fenceJob {
int fd;
int64_t tag;
int64_t latch;
int count;
int source;
};
#define JOB_RING 64
static struct fenceJob gJobs[JOB_RING];
static int gJobHead = 0, gJobTail = 0;
static int gJobDrops = 0;
static pthread_mutex_t gJobLock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t gJobCond = PTHREAD_COND_INITIALIZER;
static pthread_t gReader;
static int gReaderStarted = 0;
static void* readerMain(void* arg);
static int ensureProbeInit(JNIEnv* env, jclass clazz) {
int scOk = 0;
pthread_mutex_lock(&gInitLock);
if (!gVm && (*env)->GetJavaVM(env, &gVm) != JNI_OK) {
LOGW("GetJavaVM failed — transaction probe disabled");
pthread_mutex_unlock(&gInitLock);
return 0;
}
if (!gProbeClass) {
gProbeClass = (*env)->NewGlobalRef(env, clazz);
if (!gProbeClass) {
LOGW("NewGlobalRef(SurfaceTxProbe) failed — transaction probe disabled");
pthread_mutex_unlock(&gInitLock);
return 0;
}
}
if (!gCallbackLookupAttempted) {
gCallbackLookupAttempted = 1;
gOnResult = (*env)->GetStaticMethodID(env, clazz, "onResult", "(JJJIIIJ)V");
if (!gOnResult) {
(*env)->ExceptionClear(env);
LOGW("onResult(JJJIIIJ)V not found — JNI callback disabled (R8 stripped it?)");
}
}
if (!gOnResult) {
pthread_mutex_unlock(&gInitLock);
return 0;
}
scOk = resolveSc();
if (!scOk) {
if (!gScWarningLogged) {
gScWarningLogged = 1;
LOGW("libandroid SurfaceControl transaction-stats API unavailable");
}
pthread_mutex_unlock(&gInitLock);
return 0;
}
if (!gReaderStarted) {
const int rc = pthread_create(&gReader, NULL, readerMain, NULL);
if (rc != 0) {
LOGW("fence reader thread start failed: %d", rc);
pthread_mutex_unlock(&gInitLock);
return 0;
}
gReaderStarted = 1;
}
pthread_mutex_unlock(&gInitLock);
return scOk;
}
static void* readerMain(void* arg) {
(void)arg;
JNIEnv* env = NULL;
if ((*gVm)->AttachCurrentThread(gVm, &env, NULL) != JNI_OK) return NULL;
for (;;) {
pthread_mutex_lock(&gJobLock);
while (gJobHead == gJobTail) pthread_cond_wait(&gJobCond, &gJobLock);
struct fenceJob job = gJobs[gJobTail];
gJobTail = (gJobTail + 1) % JOB_RING;
pthread_mutex_unlock(&gJobLock);
int64_t releaseNs = -1;
int fenceState;
struct pollfd pfd = {.fd = job.fd, .events = POLLIN, .revents = 0};
int pr = poll(&pfd, 1, 250);
if (pr > 0 && (pfd.revents & POLLIN)) {
int st = -1;
releaseNs = readFenceTimeNs(job.fd, &st);
fenceState = (releaseNs > 0) ? 3 : 1;
} else {
fenceState = 2;
}
close(job.fd);
reportResult(env, job.tag, job.latch, releaseNs, job.count, fenceState, job.source, nowMonoNs());
}
return NULL;
}
static void onComplete(void* context, ASurfaceTransactionStats* stats) {
int slot = (int)(intptr_t)context;
__atomic_thread_fence(__ATOMIC_ACQUIRE);
int64_t tag = gTagRing[slot & (TAG_RING_SIZE - 1)];
int source = gSrcRing[slot & (TAG_RING_SIZE - 1)];
int64_t latchNs = p_latchTime ? p_latchTime(stats) : -1;
// Display-global present fences are abort-prone; per-surface release fences are stable here.
int chosenFd = -1;
int count = 0;
ASurfaceControl** controls = NULL;
size_t n = 0;
if (p_getControls) p_getControls(stats, &controls, &n);
count = (int)n;
for (size_t i = 0; i < n; i++) {
int rfd = p_prevRelease ? p_prevRelease(stats, controls[i]) : -1;
if (rfd < 0) continue;
if (chosenFd < 0)
chosenFd = rfd;
else
close(rfd);
}
if (controls && p_releaseControls) p_releaseControls(controls);
if (chosenFd < 0) {
JNIEnv* env = NULL;
int didAttach = 0;
if ((*gVm)->GetEnv(gVm, (void**)&env, JNI_VERSION_1_6) != JNI_OK) {
if ((*gVm)->AttachCurrentThread(gVm, &env, NULL) != JNI_OK) return;
didAttach = 1;
}
reportResult(env, tag, latchNs, -1, count, 0, source, nowMonoNs());
if (didAttach) (*gVm)->DetachCurrentThread(gVm);
return;
}
pthread_mutex_lock(&gJobLock);
int next = (gJobHead + 1) % JOB_RING;
if (next == gJobTail) {
close(chosenFd);
if (gJobDrops++ == 0) LOGW("fence job ring full — dropping samples (slow fence reader?)");
} else {
gJobs[gJobHead].fd = chosenFd;
gJobs[gJobHead].tag = tag;
gJobs[gJobHead].latch = latchNs;
gJobs[gJobHead].count = count;
gJobs[gJobHead].source = source;
gJobHead = next;
pthread_cond_signal(&gJobCond);
}
pthread_mutex_unlock(&gJobLock);
}
JNIEXPORT void JNICALL Java_com_edde746_plezy_exoplayer_SurfaceTxProbe_nativeAttach(
JNIEnv* env, jclass clazz, jobject jtransaction, jlong tag, jint source) {
if (!ensureProbeInit(env, clazz)) return;
int slot = __atomic_fetch_add(&gTagSeq, 1, __ATOMIC_RELAXED) & (TAG_RING_SIZE - 1);
gTagRing[slot] = (int64_t)tag;
gSrcRing[slot] = (int)source;
// Binder carries only the slot index, so the ring write has to win publication.
__atomic_thread_fence(__ATOMIC_RELEASE);
ASurfaceTransaction* tx = p_fromJava(env, jtransaction);
if (!tx) {
LOGW("ASurfaceTransaction_fromJava returned null");
return;
}
p_setOnComplete(tx, (void*)(intptr_t)slot, onComplete);
}
@@ -11,11 +11,23 @@ package com.edde746.plezy.libass
* @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 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
}
@@ -17,6 +17,7 @@ import com.edde746.plezy.libass.Ass
import com.edde746.plezy.libass.AssRender
import com.edde746.plezy.libass.AssTrack
import com.edde746.plezy.libass.media.parser.AssHeaderParser
import com.edde746.plezy.libass.media.widget.AssAtlasPipelineConfig
/**
* Handles ASS subtitle rendering and integration with ExoPlayer.
@@ -185,13 +186,15 @@ class AssHandler(
* (re)created or the selected track changes, so renderer state survives both.
*/
private fun applyRenderState(render: AssRender) {
// Storage (script/video authoring size) stays full-res; only the frame and
// margins follow RENDER_SCALE so the raster shrinks while layout is unchanged.
if (videoSize.isValid) render.setStorageSize(videoSize.width, videoSize.height)
when {
surfaceSize.isValid -> render.setFrameSize(surfaceSize.width, surfaceSize.height)
surfaceSize.isValid -> render.setFrameSize(scaledForRender(surfaceSize.width), scaledForRender(surfaceSize.height))
// Fallback frame until the overlay surface reports its size.
videoSize.isValid -> render.setFrameSize(videoSize.width, videoSize.height)
videoSize.isValid -> render.setFrameSize(scaledForRender(videoSize.width), scaledForRender(videoSize.height))
}
margins?.let { m -> render.setMargins(m[0], m[1], m[2], m[3]) }
margins?.let { m -> render.setMargins(scaledForRender(m[0]), scaledForRender(m[1]), scaledForRender(m[2]), scaledForRender(m[3])) }
render.setUseMargins(useMargins)
}
@@ -220,7 +223,7 @@ class AssHandler(
if (surfaceSize.width == width && surfaceSize.height == height) return
Log.i("AssHandler", "setOverlaySurfaceSize: width = $width, height = $height")
surfaceSize = Size(width, height)
render?.setFrameSize(width, height)
render?.setFrameSize(scaledForRender(width), scaledForRender(height))
}
/**
@@ -230,9 +233,13 @@ class AssHandler(
*/
fun setMargins(top: Int, bottom: Int, left: Int, right: Int) {
margins = intArrayOf(top, bottom, left, right)
render?.setMargins(top, bottom, left, right)
render?.setMargins(scaledForRender(top), scaledForRender(bottom), scaledForRender(left), scaledForRender(right))
}
/** Frame/margin extents go to libass at the overlay's render resolution; the GL
* side scales the result back up. Identity unless RENDER_SCALE < 1. */
private fun scaledForRender(px: Int): Int = AssAtlasPipelineConfig.scaledForRender(px)
/** mpv's sub-ass-force-margins: anchor non-positioned events to the visible frame. */
fun setUseMargins(use: Boolean) {
useMargins = use
@@ -383,4 +390,16 @@ class AssHandler(
*/
private val Size.isValid
get() = width > 0 && height > 0
companion object {
/**
* Sets the global libass overlay render scale (fraction of the surface resolution; 1.0 = no
* downscale). Cheaper raster for the render-bound tail on weak GPUs, at some sharpness. Set
* before/at playback init — [AssAtlasPipelineConfig.scaledForRender] reads it on the next
* frame-size apply (overlay surface create / size change), so it takes effect from playback.
*/
fun setRenderScale(scale: Float) {
AssAtlasPipelineConfig.renderScale = scale.coerceIn(0.2f, 1.0f)
}
}
}
@@ -6,6 +6,7 @@ import android.opengl.EGLDisplay
import android.opengl.EGLExt
import android.opengl.EGLSurface
import android.opengl.GLES20
import android.os.Build
import android.os.Handler
import android.os.HandlerThread
import android.os.Process
@@ -17,18 +18,20 @@ import androidx.media3.common.util.GlUtil
import androidx.media3.common.util.Size
import androidx.media3.common.util.UnstableApi
import com.edde746.plezy.libass.AssAtlasFrame
import com.edde746.plezy.libass.AssFrameTimestamps
import com.edde746.plezy.libass.media.AssHandler
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.concurrent.atomic.AtomicLong
import java.util.concurrent.atomic.AtomicReference
import java.util.concurrent.locks.LockSupport
/**
* Atlas-rendering pipeline behind [AssSubtitleSurfaceView].
* Runs libass on its own [HandlerThread] into a packed
* ALPHA_8 texture atlas plus a single vertex stream, and a GL thread that uploads
* both and issues one `glDrawArrays` per frame. Each swap is pinned to the video's
* target release time via [EGLExt.eglPresentationTimeANDROID]: SurfaceFlinger holds
* the buffer and composes it on the same vsync as the corresponding video frame.
* both and issues one `glDrawArrays` per frame. Each timed swap is pinned to the
* corresponding video frame via [EGLExt.eglPresentationTimeANDROID].
*/
@UnstableApi
internal object AssAtlasPipelineConfig {
@@ -67,9 +70,32 @@ internal object AssAtlasPipelineConfig {
* core's ~35-50ms renders it converts near-misses into on-time latches.
*/
internal const val SPECULATION_ENABLED = true
/**
* Disabled by default: queueing subtitles one predicted video frame ahead made
* Android playback often look one frame early. Keep the estimator behind a flag
* in case a device-specific compositor path later proves it needs this again.
*/
internal const val COMPOSITOR_PHASE_LEAD_ENABLED = false
/**
* Internal raster resolution for the libass overlay, as a fraction of the
* physical surface (1.0 = full, off). Lowering it shrinks the libass frame so
* heavy/animated signs rasterize over fewer pixels (raster cost ∝ area; layout
* cost unchanged) and the GL upscales the result to the full surface — a
* quality-for-throughput trade for render-bound low-end TVs. Applied
* consistently to the libass frame size, the mpv-style margins ([AssHandler])
* and the GL `u_SurfaceSize` ([AtlasRenderer]); at 1.0 it is an exact no-op.
* Runtime-settable from the user's "Render Resolution" subtitle setting (Android exposes
* Full / ¾ / ½ / ⅓ / ¼) via [AssHandler.setRenderScale]; 1.0 = exact no-op (the default).
*/
@Volatile
internal var renderScale = 1.0f
/** Scales a physical-pixel extent to the libass render resolution; identity at 1.0. */
internal fun scaledForRender(px: Int): Int = if (renderScale == 1.0f) px else Math.round(px * renderScale)
}
/** Payload handed from the libass worker to the GL thread. */
internal class AtlasPayload(
val slotIndex: Int,
val atlasBuf: ByteBuffer,
@@ -77,9 +103,38 @@ internal class AtlasPayload(
var frame: AssAtlasFrame,
var presentationTimeUs: Long,
var releaseTimeNs: Long,
/** Bumped on every content-changing render; lets the GL thread tell "same slot,
* new content" apart from "same slot, same content" when deciding to re-upload. */
var contentSeq: Long = 0L
var sourcePresentationTimeUs: Long = presentationTimeUs,
var phaseLeadUs: Long = 0L,
/** Slot identity alone is not enough because libass rewrites buffers in place. */
var contentSeq: Long = 0L,
var requestSeq: Long = 0L,
var stateGeneration: Long = 0L
)
private class AtlasDrawSnapshot(
val atlasBuf: ByteBuffer,
val vertexBuf: ByteBuffer,
val frame: AssAtlasFrame,
val sourcePresentationTimeUs: Long,
val presentationTimeUs: Long,
val releaseTimeNs: Long,
val phaseLeadUs: Long,
val contentSeq: Long,
val requestSeq: Long,
val stateGeneration: Long
)
private fun AtlasPayload.snapshot(): AtlasDrawSnapshot = AtlasDrawSnapshot(
atlasBuf = atlasBuf,
vertexBuf = vertexBuf,
frame = frame,
sourcePresentationTimeUs = sourcePresentationTimeUs,
presentationTimeUs = presentationTimeUs,
releaseTimeNs = releaseTimeNs,
phaseLeadUs = phaseLeadUs,
contentSeq = contentSeq,
requestSeq = requestSeq,
stateGeneration = stateGeneration
)
/** Payload slots plus the atlas dims their buffers were sized for. */
@@ -99,12 +154,23 @@ internal class AssAtlasPipeline(
surface: Surface,
width: Int,
height: Int,
assHandler: AssHandler,
lowRamDevice: Boolean = false
private val assHandler: AssHandler,
lowRamDevice: Boolean = false,
refreshRateHz: Float = 60f
) {
private val surfaceWidth = width
private val surfaceHeight = height
/** The calibrator needs the final pre-swap point, and this must survive surface recreation. */
var preSwapProbe: ((releaseTimeNs: Long) -> Unit)?
get() = glThread.preSwapProbe
set(value) {
glThread.preSwapProbe = value
}
// Present-error buckets need to stay meaningful across display modes.
private val vsyncNs = (1_000_000_000.0 / (if (refreshRateHz >= 1f) refreshRateHz else 60f)).toLong()
// 3 slots give the render-ahead engine a writable target while one slot is
// posted and another is in GL's hands; low-RAM devices stay at 2 slots with
// speculation off (the legacy on-demand behavior, ~19 MB less in buffers).
@@ -147,6 +213,10 @@ internal class AssAtlasPipeline(
// first actual render. Confined to the libass thread after creation.
private var slots: AtlasSlots? = null
private fun rendererStateGeneration(): Long = assHandler.render?.let {
(System.identityHashCode(it).toLong() shl 32) or (it.stateGeneration.toLong() and 0xffffffffL)
} ?: -1L
private fun acquireSlots(): AtlasSlots {
slots?.let { return it }
if (!dimsLatch.await(1, java.util.concurrent.TimeUnit.SECONDS)) {
@@ -174,14 +244,18 @@ internal class AssAtlasPipeline(
@Volatile private var glLastTakenSlot = -1
private val pendingPayload = AtomicReference<AtlasPayload?>(null)
private val latestReadyRequestSeq = AtomicLong(0L)
private val glThread = AtlasGlThread(
surface,
width,
height,
assHandler,
vsyncNs = vsyncNs,
takePending = {
pendingPayload.getAndSet(null)?.also { glLastTakenSlot = it.slotIndex }
},
latestReadyRequestSeq = { latestReadyRequestSeq.get() },
currentStateGeneration = ::rendererStateGeneration,
resolveAtlasDims = ::resolveAtlasDims
)
private val libassThread = AtlasLibassThread(
@@ -189,7 +263,9 @@ internal class AssAtlasPipeline(
acquireSlots = ::acquireSlots,
speculationEnabled = speculationEnabled,
glTakenSlot = { glLastTakenSlot },
stateGeneration = ::rendererStateGeneration,
onFrameReady = { payload ->
latestReadyRequestSeq.set(payload.requestSeq)
pendingPayload.set(payload)
glThread.triggerDraw()
}
@@ -259,14 +335,72 @@ internal class AssAtlasPipeline(
/** Speculation rounds skipped (paused, pending request, no confident cadence). */
val specSkips: Long get() = libassThread.specSkips
/** changed==0/no-output renders forced into explicit transparent swaps. */
val blankClearCount: Long get() = libassThread.blankClearCount
/** Cache-warming prefetch renders of upcoming events. */
val prefetchCount: Long get() = libassThread.prefetchCount
/** Frame requests replaced before the libass worker serviced them. */
val coalescedRequestCount: Long get() = libassThread.coalescedRequestCount
/** Completed libass results discarded because renderer state changed before handoff. */
val staleGenerationCount: Long get() = libassThread.staleGenerationCount
/** Completed overlay snapshots skipped because a newer completed request superseded them before swap. */
val supersededBeforeSwapCount: Long get() = glThread.supersededBeforeSwapCount
/** Completed overlay snapshots skipped because renderer state changed before swap. */
val staleBeforeSwapCount: Long get() = glThread.staleBeforeSwapCount
/** Worst (minimum) lead of a changed-content pinned swap vs its target release
* time, in ms; negative = the new content was queued after the video frame's
* vsync. Long.MAX_VALUE until a changed pinned swap happened. */
val minLeadChangedMs: Long get() = glThread.minLeadChangedMs
/** Current steady-state compositor phase lead, in ms. */
val phaseLeadMs: Long get() = libassThread.phaseLeadUs / 1000
/** Most recent pinned swap lead vs its target release time, in ms. */
val lastSwapLeadMs: Long get() = glThread.lastSwapLeadMs
/** Most recent pinned swap headroom when GL work started, in ms. */
val lastSwapHeadroomMs: Long get() = glThread.lastSwapHeadroomMs
/** Most recent phase-led wait before swap, in ms. */
val lastScheduledSleepMs: Long get() = glThread.lastScheduledSleepMs
/** Adaptive swap lead actually in effect (half the measured refresh), in ms. */
val swapLeadMs: Long get() = glThread.swapLeadNs / 1_000_000
/** True once the EGL frame-timestamp extension is probed and capturing. */
val presentTimingEnabled: Boolean get() = glThread.presentTimingEnabled
/** Active present-time source, or why it's off (present/comp-start/comp-latch/off:…). */
val presentSource: String get() = glThread.presentSource
/** Actual on-screen present time of the most recent measured swap minus its
* target release time, in ms (negative = presented before the video frame's
* vsync, positive = after). The frame-perfection ground truth. */
val lastPresentErrorMs: Long get() = glThread.lastPresentErrorMs
/** Largest-magnitude present error observed, in ms. */
val worstPresentErrorMs: Long get() = glThread.worstPresentErrorMs
/** Pinned swaps whose actual present time was read back from SurfaceFlinger. */
val presentMeasuredCount: Long get() = glThread.presentMeasuredCount
/** Swaps SurfaceFlinger reported as dropped/never-presented. */
val presentInvalidCount: Long get() = glThread.presentInvalidCount
/** Pending present-time reads evicted unread because the ring filled. */
val presentDroppedCount: Long get() = glThread.presentDroppedCount
/** Present-error distribution in vsync-interval units:
* [≤−1.5, (−1.5,−0.5), (−0.5,+0.5), [+0.5,+1.5), ≥+1.5]. A clean spike in the
* middle bucket = frame-perfect; a spike at [+0.5,+1.5) = a 1-vsync late latch. */
val presentErrorHistogram: List<Long> get() = glThread.presentErrorHistogram
fun releaseAndWait() {
libassThread.releaseAndWait()
glThread.releaseAndWait()
@@ -296,6 +430,92 @@ private fun postShutdownAndWait(
/** Transport for [postShutdownAndWait] — the handler callback calls [release] then notifies. */
private class Ack(val latch: Any, val release: () -> Unit)
private class PhaseAdjustedFrame(
val sourcePtsUs: Long,
val renderPtsUs: Long,
val releaseNs: Long,
val phaseLeadUs: Long,
val releaseLeadNs: Long
)
/**
* Predicts the next video frame from the callback cadence. Media3 gives us the
* frame currently being released, but a separate subtitle SurfaceView may not latch
* in the same composition phase. Once cadence is stable, callback N renders and
* timestamps the ASS layer for predicted frame N+1.
*/
private class SubtitleFramePhaseEstimator {
private val ptsDeltasUs = LongArray(DELTA_SAMPLES)
private val releaseDeltasNs = LongArray(DELTA_SAMPLES)
private var deltaCount = 0
private var deltaIndex = 0
private var lastPtsUs = UNSET
private var lastReleaseNs = C.TIME_UNSET
@Synchronized
fun adjust(ptsUs: Long, releaseNs: Long): PhaseAdjustedFrame {
if (!AssAtlasPipelineConfig.COMPOSITOR_PHASE_LEAD_ENABLED || releaseNs == C.TIME_UNSET) {
return PhaseAdjustedFrame(ptsUs, ptsUs, releaseNs, 0L, 0L)
}
observe(ptsUs, releaseNs)
if (deltaCount < MIN_DELTA_SAMPLES) {
return PhaseAdjustedFrame(ptsUs, ptsUs, releaseNs, 0L, 0L)
}
val ptsLeadUs = median(ptsDeltasUs, deltaCount)
val releaseLeadNs = median(releaseDeltasNs, deltaCount)
return PhaseAdjustedFrame(
sourcePtsUs = ptsUs,
renderPtsUs = saturatedAdd(ptsUs, ptsLeadUs),
releaseNs = saturatedAdd(releaseNs, releaseLeadNs),
phaseLeadUs = ptsLeadUs,
releaseLeadNs = releaseLeadNs
)
}
private fun observe(ptsUs: Long, releaseNs: Long) {
val prevPtsUs = lastPtsUs
val prevReleaseNs = lastReleaseNs
lastPtsUs = ptsUs
lastReleaseNs = releaseNs
if (prevPtsUs == UNSET || prevReleaseNs == C.TIME_UNSET) return
val ptsDeltaUs = ptsUs - prevPtsUs
val releaseDeltaNs = releaseNs - prevReleaseNs
if (ptsDeltaUs <= 0 ||
ptsDeltaUs > MAX_DELTA_US ||
releaseDeltaNs <= 0 ||
releaseDeltaNs > MAX_DELTA_NS
) {
deltaCount = 0
deltaIndex = 0
return
}
ptsDeltasUs[deltaIndex] = ptsDeltaUs
releaseDeltasNs[deltaIndex] = releaseDeltaNs
deltaIndex = (deltaIndex + 1) % DELTA_SAMPLES
if (deltaCount < DELTA_SAMPLES) deltaCount++
}
private fun median(values: LongArray, count: Int): Long {
val copy = values.copyOfRange(0, count)
copy.sort()
return copy[count / 2]
}
private fun saturatedAdd(value: Long, delta: Long): Long = if (delta > 0 && value > Long.MAX_VALUE - delta) Long.MAX_VALUE else value + delta
private companion object {
const val UNSET = Long.MIN_VALUE
const val DELTA_SAMPLES = 8
const val MIN_DELTA_SAMPLES = 4
const val MAX_DELTA_US = 250_000L
const val MAX_DELTA_NS = 250_000_000L
}
}
/**
* Runs libass off the GL thread into a packed atlas + vertex stream. Latest-wins:
* older pending renders are dropped when a newer one arrives. Slot choice, the
@@ -308,30 +528,54 @@ private class AtlasLibassThread(
private val acquireSlots: () -> AtlasSlots,
private val speculationEnabled: Boolean,
private val glTakenSlot: () -> Int,
private val stateGeneration: () -> Long,
private val onFrameReady: (AtlasPayload) -> Unit
) : HandlerThread(TAG, Process.THREAD_PRIORITY_DISPLAY) {
/** Immutable (pts, release) request — handed off through a single atomic so a
* concurrent enqueue can neither be lost by drain's consume nor torn in half.
* [enqueueNs] timestamps the handoff so drain can report how long the request
* sat behind an in-flight render (the queue-wait component of subtitle lag). */
private class PendingFrame(val ptsUs: Long, val releaseNs: Long, val enqueueNs: Long = System.nanoTime())
/** Immutable frame request — handed off through a single atomic so a concurrent
* enqueue can neither be lost by drain's consume nor torn in half. [ptsUs] is
* the libass render timestamp after any phase lead; [sourcePtsUs] is the video
* callback PTS after user subtitle delay but before the compositor lead.
* [sequence] is the selected-video-frame request identity, and [enqueueNs]
* timestamps the handoff so drain can report queue wait. */
private class PendingFrame(
val sourcePtsUs: Long,
val ptsUs: Long,
val releaseNs: Long,
val phaseLeadUs: Long,
val releaseLeadNs: Long,
val sequence: Long,
val enqueueNs: Long = System.nanoTime()
)
private lateinit var handler: Handler
private val pending = AtomicReference<PendingFrame?>(null)
private val phaseEstimator = SubtitleFramePhaseEstimator()
private val requestSeqCounter = AtomicLong(0L)
@Volatile private var lastRequestedPtsUs = UNSET
private var contentSeqCounter = 0L
// Thread-confined; created on first render so non-ASS playback never allocates.
private var engine: SpecRenderEngine? = null
private var engineStateGeneration = Long.MIN_VALUE
val specHits: Long get() = engine?.specHits ?: 0L
val specMisses: Long get() = engine?.specMisses ?: 0L
val specSkips: Long get() = engine?.specSkips ?: 0L
val blankClearCount: Long get() = engine?.blankClearCount ?: 0L
val prefetchCount: Long get() = engine?.prefetchCount ?: 0L
@Volatile var coalescedRequestCount = 0L
private set
@Volatile var staleGenerationCount = 0L
private set
@Volatile var phaseLeadUs = 0L
private set
// Telemetry; single-writer (this thread), read from the stats path.
@Volatile var renderCount = 0L
private set
@@ -382,15 +626,31 @@ private class AtlasLibassThread(
fun enqueue(presentationTimeUs: Long, releaseTimeNs: Long) {
if (!::handler.isInitialized) return
val dropped = pending.getAndSet(PendingFrame(presentationTimeUs, releaseTimeNs))
if (dropped != null && AssAtlasPipelineConfig.TIMING_LOGS) {
// A request was coalesced away — the renderer is behind by at least one
// frame. agedMs = how long the dropped request had been waiting.
Log.d(
TAG,
"drop pts=${dropped.ptsUs / 1000}ms agedMs=${(System.nanoTime() - dropped.enqueueNs) / 1_000_000} " +
"replacedBy=${presentationTimeUs / 1000}ms"
val adjusted = phaseEstimator.adjust(presentationTimeUs, releaseTimeNs)
phaseLeadUs = adjusted.phaseLeadUs
val sequence = requestSeqCounter.incrementAndGet()
val dropped = pending.getAndSet(
PendingFrame(
sourcePtsUs = adjusted.sourcePtsUs,
ptsUs = adjusted.renderPtsUs,
releaseNs = adjusted.releaseNs,
phaseLeadUs = adjusted.phaseLeadUs,
releaseLeadNs = adjusted.releaseLeadNs,
sequence = sequence
)
)
if (dropped != null) {
coalescedRequestCount++
if (AssAtlasPipelineConfig.TIMING_LOGS) {
// A request was coalesced away — the renderer is behind by at least one
// frame. agedMs = how long the dropped request had been waiting.
Log.d(
TAG,
"drop seq=${dropped.sequence} src=${dropped.sourcePtsUs / 1000}ms pts=${dropped.ptsUs / 1000}ms " +
"agedMs=${(System.nanoTime() - dropped.enqueueNs) / 1_000_000} " +
"replacedBySeq=$sequence replacedBySrc=${presentationTimeUs / 1000}ms replacedByPts=${adjusted.renderPtsUs / 1000}ms"
)
}
}
handler.removeMessages(MSG_RENDER)
handler.sendEmptyMessage(MSG_RENDER)
@@ -405,8 +665,10 @@ private class AtlasLibassThread(
enqueue(pts, C.TIME_UNSET)
}
private fun ensureEngine(slots: AtlasSlots): SpecRenderEngine {
engine?.let { return it }
private fun ensureEngine(slots: AtlasSlots, generation: Long): SpecRenderEngine {
engine?.takeIf { engineStateGeneration == generation }?.let { return it }
engineStateGeneration = generation
unchangedStreak = 0
return SpecRenderEngine(
slotCount = slots.payloads.size,
speculationEnabled = speculationEnabled,
@@ -414,11 +676,7 @@ private class AtlasLibassThread(
// Renderer identity in the high bits + its state generation in the low bits:
// a recreated renderer (media item transition) can never alias a stale
// speculation, even if the new generation counter happens to match.
stateGeneration = {
assHandler.render?.let {
(System.identityHashCode(it).toLong() shl 32) or (it.stateGeneration.toLong() and 0xffffffffL)
} ?: -1L
},
stateGeneration = stateGeneration,
glTakenSlot = glTakenSlot,
debugLog = if (AssAtlasPipelineConfig.TIMING_LOGS) ({ msg -> Log.d(TAG, msg) }) else null
).also { engine = it }
@@ -453,9 +711,10 @@ private class AtlasLibassThread(
private fun drainAndRender() {
val request = pending.getAndSet(null) ?: return
val sourcePts = request.sourcePtsUs
val pts = request.ptsUs
val releaseNs = request.releaseNs
lastRequestedPtsUs = pts
lastRequestedPtsUs = sourcePts
val tDrain = System.nanoTime()
// How long the request sat in the handoff (behind an in-flight on-demand or
// speculative render) — the queue-wait component of any subtitle lag.
@@ -464,27 +723,41 @@ private class AtlasLibassThread(
// keeps the slot buffers unallocated for non-ASS playback.
if (assHandler.render == null) return
val slots = acquireSlots()
val engine = ensureEngine(slots)
val generation = stateGeneration()
val engine = ensureEngine(slots, generation)
val pinned = releaseNs != C.TIME_UNSET
// Budget left until the video frame's vsync when we START servicing.
val budgetMs = if (pinned) (releaseNs - tDrain) / 1_000_000 else -1L
when (val outcome = engine.service(pts, pinned)) {
is SpecRenderEngine.Outcome.Post -> {
if (stateGeneration() != generation) {
staleGenerationCount++
engineStateGeneration = Long.MIN_VALUE
if (AssAtlasPipelineConfig.TIMING_LOGS) {
Log.d(TAG, "stale-render req=${request.sequence} pts=${pts / 1000}ms")
}
return
}
val payload = slots.payloads[outcome.slot]
if (outcome.newContent) {
payload.frame = outcome.frame
payload.contentSeq = ++contentSeqCounter
}
payload.sourcePresentationTimeUs = sourcePts
payload.presentationTimeUs = pts
payload.releaseTimeNs = releaseNs
payload.phaseLeadUs = request.phaseLeadUs
payload.requestSeq = request.sequence
payload.stateGeneration = generation
onFrameReady(payload)
if (AssAtlasPipelineConfig.TIMING_LOGS) {
Log.d(
TAG,
"render pts=${pts / 1000}ms seq=${payload.contentSeq} waitMs=$waitMs budgetMs=$budgetMs " +
"render req=${request.sequence} src=${sourcePts / 1000}ms pts=${pts / 1000}ms phaseLeadMs=${request.phaseLeadUs / 1000} " +
"releaseLeadMs=${request.releaseLeadNs / 1_000_000} seq=${payload.contentSeq} waitMs=$waitMs budgetMs=$budgetMs " +
"libassMs=$lastLibassMs lockWaitMs=${assHandler.render?.lastLockWaitMs} " +
"specHit=${outcome.specHit} changed=${payload.frame.changed} quads=${payload.frame.quadCount} " +
"specHit=${outcome.specHit} changed=${payload.frame.changed} output=${payload.frame.hasOutput} quads=${payload.frame.quadCount} " +
"atlas=${payload.frame.atlasWidth}x${payload.frame.atlasHeight} truncated=${payload.frame.truncated}"
)
}
@@ -498,6 +771,7 @@ private class AtlasLibassThread(
// Pre-render the predicted next frame in the dead time between requests so the
// next service is (usually) a GL-only hit. Never delays a waiting request.
if (stateGeneration() != generation) return
engine.speculateAfter(pts, pinned, hasPending = pending.get() != null)?.let { write ->
val payload = slots.payloads[write.slot]
payload.frame = write.frame
@@ -506,7 +780,7 @@ private class AtlasLibassThread(
Log.d(
TAG,
"spec after=${pts / 1000}ms seq=${payload.contentSeq} libassMs=$lastLibassMs " +
"lockWaitMs=${assHandler.render?.lastLockWaitMs} slot=${write.slot} quads=${write.frame.quadCount}"
"lockWaitMs=${assHandler.render?.lastLockWaitMs} slot=${write.slot} output=${write.frame.hasOutput} quads=${write.frame.quadCount}"
)
}
}
@@ -545,7 +819,7 @@ private class AtlasLibassThread(
val now = System.nanoTime()
if (now - lastPrefetchNs < PREFETCH_COOLDOWN_NS) return
val track = assHandler.track ?: return
val nowMs = ptsUs / 1000
val nowMs = Math.floorDiv(ptsUs, 1_000L)
// Events closer than MIN_AHEAD are the regular per-frame path's business;
// beyond HORIZON the warmed bitmaps may be evicted before they're needed.
val targetMs = track.nextEventStartMs(nowMs + PREFETCH_MIN_AHEAD_MS)
@@ -619,9 +893,8 @@ private class AtlasLibassThread(
/**
* Owns the EGL surface, uploads the atlas + vertex stream and issues a single
* `glDrawArrays` per frame. Swaps immediately with the swap pinned to the video's
* target release time via [EGLExt.eglPresentationTimeANDROID]; SurfaceFlinger
* holds the buffer until then, so the thread is never blocked waiting for a vsync.
* `glDrawArrays` per frame. Timed swaps are queued close to the target video
* release time and stamped via [EGLExt.eglPresentationTimeANDROID].
*/
@UnstableApi
private class AtlasGlThread(
@@ -629,10 +902,57 @@ private class AtlasGlThread(
@Volatile private var width: Int,
@Volatile private var height: Int,
private val assHandler: AssHandler,
private val vsyncNs: Long,
private val takePending: () -> AtlasPayload?,
private val latestReadyRequestSeq: () -> Long,
private val currentStateGeneration: () -> Long,
private val resolveAtlasDims: (maxTextureSize: Int) -> Pair<Int, Int>
) : HandlerThread(TAG, Process.THREAD_PRIORITY_DISPLAY) {
// Calibration hook invoked just before each pinned eglSwapBuffers (see AssAtlasPipeline).
@Volatile var preSwapProbe: ((releaseTimeNs: Long) -> Unit)? = null
// Swap lead = half the refresh interval, clamped. Measured live from the actual
// gap between video-frame release targets rather than display.refreshRate, which
// can still read the pre-switch rate when a pre-open mode change hasn't settled
// (the bug that pinned the lead at ~8 ms while the panel was really at 24 Hz).
private val releaseDeltasNs = LongArray(8)
private var releaseDeltaCount = 0
private var releaseDeltaIndex = 0
private var lastCadenceReleaseNs = C.TIME_UNSET
// Median gap between successive video-frame release targets (≈ one refresh at
// matched cadence). Drives both the swap lead and the present offset.
@Volatile private var measuredIntervalNs: Long = vsyncNs
@Volatile var swapLeadNs: Long =
(vsyncNs / 2).coerceIn(SCHEDULED_SWAP_LEAD_MIN_NS, SCHEDULED_SWAP_LEAD_MAX_NS)
private set
private fun updateSwapLead(releaseNs: Long) {
val prev = lastCadenceReleaseNs
lastCadenceReleaseNs = releaseNs
if (prev == C.TIME_UNSET) return
val d = releaseNs - prev
if (d <= 0 || d > MAX_RELEASE_DELTA_NS) {
releaseDeltaCount = 0
releaseDeltaIndex = 0
return
}
releaseDeltasNs[releaseDeltaIndex] = d
releaseDeltaIndex = (releaseDeltaIndex + 1) % releaseDeltasNs.size
if (releaseDeltaCount < releaseDeltasNs.size) releaseDeltaCount++
if (releaseDeltaCount >= 4) {
val copy = releaseDeltasNs.copyOf(releaseDeltaCount)
copy.sort()
measuredIntervalNs = copy[releaseDeltaCount / 2]
swapLeadNs = (measuredIntervalNs / 2).coerceIn(
SCHEDULED_SWAP_LEAD_MIN_NS,
SCHEDULED_SWAP_LEAD_MAX_NS
)
}
}
private lateinit var handler: Handler
private var eglDisplay: EGLDisplay = EGL14.EGL_NO_DISPLAY
private var eglContext: EGLContext = EGL14.EGL_NO_CONTEXT
@@ -658,6 +978,59 @@ private class AtlasGlThread(
@Volatile var minLeadChangedMs = Long.MAX_VALUE
private set
@Volatile var lastSwapLeadMs = 0L
private set
@Volatile var lastSwapHeadroomMs = 0L
private set
@Volatile var lastScheduledSleepMs = 0L
private set
@Volatile var supersededBeforeSwapCount = 0L
private set
@Volatile var staleBeforeSwapCount = 0L
private set
// --- Present-time ground truth (EGL_ANDROID_get_frame_timestamps) ---
// The actual on-screen present time is reported a few swaps after eglSwapBuffers,
// so swapped frame ids are recorded here and resolved lazily. Confined to this
// (single) GL thread; telemetry fields are @Volatile for the stats reader.
@Volatile var presentTimingEnabled = false
private set
/** Which timestamp source the probe settled on, or why it's off (for diagnosis). */
@Volatile var presentSource = "off:uninit"
private set
private val ptFrameId = LongArray(PRESENT_RING)
private val ptReleaseNs = LongArray(PRESENT_RING)
private var ptHead = 0
private var ptCount = 0
@Volatile var lastPresentErrorMs = 0L
private set
@Volatile var worstPresentErrorMs = 0L
private set
@Volatile var presentMeasuredCount = 0L
private set
@Volatile var presentInvalidCount = 0L
private set
@Volatile var presentDroppedCount = 0L
private set
private val ptBuckets = LongArray(PRESENT_BUCKETS)
val presentErrorHistogram: List<Long> get() = ptBuckets.toList()
// Tracks renderer-state generation so transient seek swaps don't permanently
// corrupt the worst-case lead/present signals.
private var lastGenerationSeen = Long.MIN_VALUE
override fun start() {
super.start()
handler = Handler(looper) { msg ->
@@ -717,11 +1090,34 @@ private class AtlasGlThread(
val (atlasW, atlasH) = resolveAtlasDims(maxTexture[0])
renderer.allocateAtlasTexture(atlasW, atlasH)
sizeChanged(width, height)
initPresentTiming()
} catch (e: GlUtil.GlException) {
Log.e(TAG, "Failed to initialize EGL", e)
}
}
/** Probes the EGL frame-timestamp extension on the freshly-current surface.
* EGL_ANDROID_get_frame_timestamps exists from Android 8.0 (entry points are
* resolved at runtime via eglGetProcAddress), so gate at O and let the native
* probe disable itself where the driver/emulator reports it unsupported — that
* "unsupported" result is itself the signal that present time can't be measured. */
private fun initPresentTiming() {
ptHead = 0
ptCount = 0
val status = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
AssFrameTimestamps.ERR_UNSUPPORTED
} else {
try {
AssFrameTimestamps.nativeInit()
} catch (t: Throwable) {
Log.w(TAG, "frame-timestamp init failed; present timing disabled", t)
AssFrameTimestamps.ERR_NO_PROC
}
}
presentTimingEnabled = status >= 0
presentSource = AssFrameTimestamps.sourceLabel(status)
}
private fun sizeChanged(width: Int, height: Int) {
renderer.onSurfaceChanged(width, height)
if (eglDisplay != EGL14.EGL_NO_DISPLAY) {
@@ -732,62 +1128,177 @@ private class AtlasGlThread(
private fun drawAndSwap() {
if (eglDisplay == EGL14.EGL_NO_DISPLAY) return
drainPresentTimestamps()
val payload = takePending() ?: return
// Render immediately (GL commands queue on the GPU). Re-upload only when the
// slot's content actually changed — identity alone is not enough because the
// libass side rewrites slot buffers in place (contentSeq tracks the rewrites).
val t0 = System.nanoTime()
val reuse = payload === lastUploadedPayload && payload.contentSeq == lastUploadedSeq
renderer.onDrawFrame(payload, reuseUploads = reuse)
val snapshot = payload.snapshot()
val reuse = payload === lastUploadedPayload && snapshot.contentSeq == lastUploadedSeq
renderer.onDrawFrame(snapshot, reuseUploads = reuse)
lastUploadedPayload = payload
lastUploadedSeq = payload.contentSeq
lastUploadedSeq = snapshot.contentSeq
val t1 = System.nanoTime()
// Swap immediately with the presentation time set: SurfaceFlinger holds the
// queued buffer until the video frame's target release time, so the subtitle
// can never appear early, and the GL thread is free again within a couple of
// milliseconds. Sleeping here until near the target vsync (as a removed
// TextureView path once required) made this thread blind for almost a whole
// frame interval — the single-slot latest-wins handoff would then drop an
// intermediate subtitle state (e.g. the transition to blank), showing the
// previous state one frame too long.
if (payload.releaseTimeNs != C.TIME_UNSET) {
EGLExt.eglPresentationTimeANDROID(eglDisplay, eglSurface, payload.releaseTimeNs)
// The overlay needs latch margin, but a drawn pinned payload still belongs to
// its video frame even if the next frame becomes ready while we wait.
val pinned = snapshot.releaseTimeNs != C.TIME_UNSET
val contentChanged = snapshot.contentSeq != lastSwappedSeq
if (pinned) updateSwapLead(snapshot.releaseTimeNs)
val presentTarget = snapshot.releaseTimeNs
val scheduledSleepMs = if (pinned) sleepUntilScheduledSwap(presentTarget) else 0L
val latestReadySeq = latestReadyRequestSeq()
val currentGeneration = currentStateGeneration()
if (currentGeneration != lastGenerationSeen) {
// Seek/track/size churn should not poison the worst-case lead signal.
lastGenerationSeen = currentGeneration
minLeadChangedMs = Long.MAX_VALUE
}
val stale = snapshot.stateGeneration != currentGeneration
// A newer ready request can be for the next video frame, while this buffer is
// still the only correct content for its own target frame.
val superseded = !pinned && snapshot.requestSeq < latestReadySeq
if (stale || superseded) {
if (stale) staleBeforeSwapCount++
if (superseded) supersededBeforeSwapCount++
lastScheduledSleepMs = scheduledSleepMs
if (AssAtlasPipelineConfig.TIMING_LOGS) {
Log.d(
TAG,
"skip-before-swap req=${snapshot.requestSeq} latest=$latestReadySeq " +
"stale=$stale gen=${snapshot.stateGeneration}/$currentGeneration " +
"src=${snapshot.sourcePresentationTimeUs / 1000}ms pts=${snapshot.presentationTimeUs / 1000}ms " +
"sleepMs=$scheduledSleepMs pinned=$pinned"
)
}
return
}
if (pinned) {
// Keep the empty probe transaction out from between the presentation
// timestamp and the swap it is meant to measure.
preSwapProbe?.invoke(presentTarget)
EGLExt.eglPresentationTimeANDROID(eglDisplay, eglSurface, presentTarget)
}
// SurfaceFlinger only knows the frame id before swap and the present time later.
val frameId = if (pinned && presentTimingEnabled) {
try {
AssFrameTimestamps.nativeGetNextFrameId()
} catch (t: Throwable) {
presentTimingEnabled = false
-1L
}
} else {
-1L
}
EGL14.eglSwapBuffers(eglDisplay, eglSurface)
val t2 = System.nanoTime()
if (payload.releaseTimeNs != C.TIME_UNSET) {
if (frameId >= 0) recordSwappedFrame(frameId, presentTarget)
var headroomMs = -1L
var leadMs = -1L
if (pinned) {
swapCount++
val lateNs = t2 - payload.releaseTimeNs
headroomMs = (presentTarget - t0) / 1_000_000
val lateNs = t2 - presentTarget
leadMs = -lateNs / 1_000_000
lastSwapHeadroomMs = headroomMs
lastSwapLeadMs = leadMs
lastScheduledSleepMs = scheduledSleepMs
if (lateNs > LATE_THRESHOLD_NS) {
lateSwapCount++
val lateMs = lateNs / 1_000_000
if (lateMs > maxLateMs) maxLateMs = lateMs
}
// Lead of changed-content swaps is the frame-perfection signal: ≥ 0 means
// the new subtitle content reached the queue before the video frame's vsync.
if (payload.contentSeq != lastSwappedSeq) {
val leadMs = -lateNs / 1_000_000
if (contentChanged) {
if (leadMs < minLeadChangedMs) minLeadChangedMs = leadMs
}
if (swapCount % SYNC_LOG_INTERVAL_SWAPS == 0L) {
Log.i(
TAG,
"[ASS-sync] swaps=$swapCount late=$lateSwapCount maxLateMs=$maxLateMs " +
"minLeadChangedMs=${if (minLeadChangedMs == Long.MAX_VALUE) "n/a" else minLeadChangedMs} " +
"present=$presentSource presentErrMs=$lastPresentErrorMs worstPresentMs=$worstPresentErrorMs " +
"presentHist=${ptBuckets.joinToString(",")} measured=$presentMeasuredCount " +
"presentInvalid=$presentInvalidCount presentDropped=$presentDroppedCount " +
"src=${snapshot.sourcePresentationTimeUs / 1000}ms pts=${snapshot.presentationTimeUs / 1000}ms " +
"phaseLeadMs=${snapshot.phaseLeadUs / 1000} sleepMs=$scheduledSleepMs headroomMs=$headroomMs leadMs=$leadMs " +
"req=${snapshot.requestSeq} seq=${snapshot.contentSeq} superseded=$supersededBeforeSwapCount stale=$staleBeforeSwapCount " +
"changed=$contentChanged reused=$reuse"
)
}
}
lastSwappedSeq = payload.contentSeq
lastSwappedSeq = snapshot.contentSeq
if (AssAtlasPipelineConfig.TIMING_LOGS) {
val pinned = payload.releaseTimeNs != C.TIME_UNSET
// headroomMs: slack before the target vsync when GL STARTED; leadMs: slack
// when the buffer was actually queued (negative = queued after the vsync).
val headroomMs = if (pinned) (payload.releaseTimeNs - t0) / 1_000_000 else -1L
val leadMs = if (pinned) (payload.releaseTimeNs - t2) / 1_000_000 else -1L
Log.d(
TAG,
"swap pts=${payload.presentationTimeUs / 1000}ms seq=${payload.contentSeq} " +
"quads=${payload.frame.quadCount} reused=$reuse drawMs=${(t1 - t0) / 1_000_000} " +
"swapMs=${(t2 - t1) / 1_000_000} headroomMs=$headroomMs leadMs=$leadMs pinned=$pinned"
"swap src=${snapshot.sourcePresentationTimeUs / 1000}ms pts=${snapshot.presentationTimeUs / 1000}ms " +
"phaseLeadMs=${snapshot.phaseLeadUs / 1000} req=${snapshot.requestSeq} seq=${snapshot.contentSeq} " +
"quads=${snapshot.frame.quadCount} reused=$reuse drawMs=${(t1 - t0) / 1_000_000} " +
"sleepMs=$scheduledSleepMs swapMs=${(t2 - t1) / 1_000_000} headroomMs=$headroomMs leadMs=$leadMs pinned=$pinned"
)
}
}
private fun sleepUntilScheduledSwap(releaseTimeNs: Long): Long {
val startNs = System.nanoTime()
val wakeNs = releaseTimeNs - swapLeadNs
var remainingNs = wakeNs - startNs
while (remainingNs > SCHEDULED_SWAP_SPIN_NS && !Thread.currentThread().isInterrupted) {
LockSupport.parkNanos(remainingNs)
remainingNs = wakeNs - System.nanoTime()
}
return ((System.nanoTime() - startNs).coerceAtLeast(0L)) / 1_000_000
}
private fun recordSwappedFrame(frameId: Long, releaseNs: Long) {
if (ptCount == PRESENT_RING) {
ptHead = (ptHead + 1) % PRESENT_RING
ptCount--
presentDroppedCount++
}
val tail = (ptHead + ptCount) % PRESENT_RING
ptFrameId[tail] = frameId
ptReleaseNs[tail] = releaseNs
ptCount++
}
private fun drainPresentTimestamps() {
if (!presentTimingEnabled) return
while (ptCount > 0) {
val idx = ptHead
val present = try {
AssFrameTimestamps.nativeGetDisplayPresentTime(ptFrameId[idx])
} catch (t: Throwable) {
presentTimingEnabled = false
return
}
if (present == AssFrameTimestamps.PENDING) return
ptHead = (ptHead + 1) % PRESENT_RING
ptCount--
if (present <= 0L) {
presentInvalidCount++
continue
}
recordPresentError(present - ptReleaseNs[idx])
}
}
private fun recordPresentError(errorNs: Long) {
presentMeasuredCount++
val errorMs = errorNs / 1_000_000
lastPresentErrorMs = errorMs
if (Math.abs(errorMs) > Math.abs(worstPresentErrorMs)) worstPresentErrorMs = errorMs
val frac = errorNs.toDouble() / vsyncNs.toDouble()
val bucket = when {
frac < -1.5 -> 0
frac < -0.5 -> 1
frac < 0.5 -> 2
frac < 1.5 -> 3
else -> 4
}
ptBuckets[bucket]++
}
private fun releaseEgl() {
if (eglDisplay != EGL14.EGL_NO_DISPLAY) {
try {
@@ -810,6 +1321,16 @@ private class AtlasGlThread(
private const val MSG_DRAW = 2
private const val MSG_SIZE_CHANGED = 3
private const val MSG_RELEASE = 4
private const val SYNC_LOG_INTERVAL_SWAPS = 120L
// Missing SurfaceFlinger's latch deadline costs a full refresh, so keep the
// margin proportional to the active cadence.
private const val SCHEDULED_SWAP_LEAD_MIN_NS = 6_000_000L
private const val SCHEDULED_SWAP_LEAD_MAX_NS = 18_000_000L
private const val SCHEDULED_SWAP_SPIN_NS = 200_000L
private const val MAX_RELEASE_DELTA_NS = 250_000_000L
private const val PRESENT_RING = 16
private const val PRESENT_BUCKETS = 5
/**
* Swaps finishing this far past the target release time arrived after the
@@ -850,8 +1371,9 @@ private class AtlasRenderer(private val assHandler: AssHandler) {
varying vec4 v_Color;
uniform sampler2D u_Texture;
void main() {
float alpha = texture2D(u_Texture, v_TexCoord).a;
gl_FragColor = v_Color * alpha;
float mask = texture2D(u_Texture, v_TexCoord).a;
float alpha = v_Color.a * mask;
gl_FragColor = vec4(v_Color.rgb * alpha, alpha);
}
""".trimIndent()
@@ -915,17 +1437,30 @@ private class AtlasRenderer(private val assHandler: AssHandler) {
GLES20.glPixelStorei(GLES20.GL_UNPACK_ALIGNMENT, 1)
GLES20.glEnable(GLES20.GL_BLEND)
GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA)
// Store the translucent SurfaceView buffer premultiplied, matching Android
// layer composition and avoiding a second alpha multiply on libass masks.
GLES20.glBlendFuncSeparate(
GLES20.GL_ONE,
GLES20.GL_ONE_MINUS_SRC_ALPHA,
GLES20.GL_ONE,
GLES20.GL_ONE_MINUS_SRC_ALPHA
)
}
fun onSurfaceChanged(width: Int, height: Int) {
surfaceSize = Size(width, height)
assHandler.render?.setFrameSize(width, height)
// Render libass at RENDER_SCALE of the physical surface; the viewport stays
// full-size so the GL upscales the lower-res atlas to fill the surface. The
// u_SurfaceSize denominator must match the (scaled) libass frame so vertices,
// baked in frame-space, still map across the whole surface.
val frameW = AssAtlasPipelineConfig.scaledForRender(width)
val frameH = AssAtlasPipelineConfig.scaledForRender(height)
assHandler.render?.setFrameSize(frameW, frameH)
GLES20.glViewport(0, 0, width, height)
GLES20.glUniform2f(uSurfaceSize, width.toFloat(), height.toFloat())
GLES20.glUniform2f(uSurfaceSize, frameW.toFloat(), frameH.toFloat())
}
fun onDrawFrame(payload: AtlasPayload, reuseUploads: Boolean) {
fun onDrawFrame(payload: AtlasDrawSnapshot, reuseUploads: Boolean) {
GlUtil.clearFocusedBuffers()
val frame = payload.frame
@@ -23,6 +23,7 @@ class AssSubtitleSurfaceView(
SurfaceHolder.Callback {
private var pipeline: AssAtlasPipeline? = null
private var preSwapProbe: ((Long) -> Unit)? = null
init {
setZOrderMediaOverlay(true)
@@ -30,6 +31,16 @@ class AssSubtitleSurfaceView(
holder.addCallback(this)
}
/**
* Hook invoked on the GL thread just before each pinned overlay swap, with that swap's target
* releaseTimeNs. Set by the app's latency calibrator; cleared (null) once it converges.
* Survives pipeline recreation (re-applied in [surfaceCreated]).
*/
fun setPreSwapProbe(hook: ((Long) -> Unit)?) {
preSwapProbe = hook
pipeline?.preSwapProbe = hook
}
fun requestRender(presentationTimeUs: Long, releaseTimeNs: Long) {
pipeline?.requestRender(presentationTimeUs, releaseTimeNs)
}
@@ -75,20 +86,83 @@ class AssSubtitleSurfaceView(
/** Speculation rounds skipped (paused, pending request, no confident cadence). */
val specSkips: Long get() = pipeline?.specSkips ?: 0L
/** changed==0/no-output renders forced into explicit transparent swaps. */
val blankClearCount: Long get() = pipeline?.blankClearCount ?: 0L
/** Cache-warming prefetch renders of upcoming events. */
val prefetchCount: Long get() = pipeline?.prefetchCount ?: 0L
/** Frame requests replaced before the libass worker serviced them. */
val coalescedRequestCount: Long get() = pipeline?.coalescedRequestCount ?: 0L
/** Completed libass results discarded because renderer state changed before handoff. */
val staleGenerationCount: Long get() = pipeline?.staleGenerationCount ?: 0L
/** Completed overlay snapshots skipped because newer completed content superseded them. */
val supersededBeforeSwapCount: Long get() = pipeline?.supersededBeforeSwapCount ?: 0L
/** Completed overlay snapshots skipped because renderer state changed before swap. */
val staleBeforeSwapCount: Long get() = pipeline?.staleBeforeSwapCount ?: 0L
/** Minimum lead of changed-content pinned swaps vs the video frame's release
* time, in ms (negative = late); null until one happened. */
val minLeadChangedMs: Long? get() = pipeline?.minLeadChangedMs?.takeIf { it != Long.MAX_VALUE }
/** Current compositor phase lead applied by the atlas pipeline, in ms. */
val phaseLeadMs: Long get() = pipeline?.phaseLeadMs ?: 0L
/** Most recent pinned swap lead vs its target release time, in ms. */
val lastSwapLeadMs: Long get() = pipeline?.lastSwapLeadMs ?: 0L
/** Most recent pinned swap headroom when GL work started, in ms. */
val lastSwapHeadroomMs: Long get() = pipeline?.lastSwapHeadroomMs ?: 0L
/** Most recent phase-led wait before swap, in ms. */
val lastScheduledSleepMs: Long get() = pipeline?.lastScheduledSleepMs ?: 0L
/** Adaptive swap lead actually in effect (half the measured refresh interval), in ms. */
val swapLeadMs: Long get() = pipeline?.swapLeadMs ?: 0L
/** True once the EGL frame-timestamp extension is probed and capturing present
* times (API 26+, real device). False on the emulator / pre-26 / no driver support. */
val presentTimingEnabled: Boolean get() = pipeline?.presentTimingEnabled ?: false
/** Active present-time source, or why it's off (present/comp-start/comp-latch/off:…). */
val presentSource: String get() = pipeline?.presentSource ?: "off:no-pipeline"
/** Actual on-screen present time of the most recent measured swap minus its
* target release time, in ms (negative = before the video frame's vsync). The
* frame-perfection ground truth; null until a swap has been measured. */
val lastPresentErrorMs: Long? get() = pipeline?.lastPresentErrorMs.takeIf { presentMeasuredCount > 0 }
/** Largest-magnitude present error observed, in ms; null until measured. */
val worstPresentErrorMs: Long? get() = pipeline?.worstPresentErrorMs.takeIf { presentMeasuredCount > 0 }
/** Pinned swaps whose actual present time was read back from SurfaceFlinger. */
val presentMeasuredCount: Long get() = pipeline?.presentMeasuredCount ?: 0L
/** Swaps SurfaceFlinger reported as dropped/never-presented. */
val presentInvalidCount: Long get() = pipeline?.presentInvalidCount ?: 0L
/** Pending present-time reads evicted unread because the ring filled. */
val presentDroppedCount: Long get() = pipeline?.presentDroppedCount ?: 0L
/** Present-error distribution in vsync-interval units:
* [≤−1.5, (−1.5,−0.5), (−0.5,+0.5), [+0.5,+1.5), ≥+1.5]. Middle = frame-perfect. */
val presentErrorHistogram: List<Long> get() = pipeline?.presentErrorHistogram ?: emptyList()
override fun surfaceCreated(holder: SurfaceHolder) {
val rect = holder.surfaceFrame
assHandler.setOverlaySurfaceSize(rect.width(), rect.height())
val lowRam = (context.getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager)
?.isLowRamDevice ?: false
pipeline = AssAtlasPipeline(holder.surface, rect.width(), rect.height(), assHandler, lowRam)
.also { it.start() }
// Display refresh drives the present-error histogram's vsync-relative buckets.
val refreshRate = display?.refreshRate?.takeIf { it >= 1f } ?: 60f
pipeline = AssAtlasPipeline(holder.surface, rect.width(), rect.height(), assHandler, lowRam, refreshRate)
.also {
it.preSwapProbe = preSwapProbe
it.start()
}
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
@@ -1,7 +1,6 @@
package com.edde746.plezy.libass.media.widget
import com.edde746.plezy.libass.AssAtlasFrame
import kotlin.math.abs
/**
* Decision core of the speculative render-ahead pipeline.
@@ -99,6 +98,10 @@ internal class SpecRenderEngine(
var specSkips = 0L
private set
@Volatile
var blankClearCount = 0L
private set
/**
* Services a render request for [ptsUs]. [pinned] is false for invalidate
* repaints (paused margin changes etc.), which never feed the cadence
@@ -107,10 +110,11 @@ internal class SpecRenderEngine(
fun service(ptsUs: Long, pinned: Boolean): Outcome {
if (pinned) updateDeltaEstimator(ptsUs)
val ptsMs = toLibassMs(ptsUs)
if (specPtsUs != UNSET) {
val eps = epsilonUs()
val specPtsMs = toLibassMs(specPtsUs)
val genNow = stateGeneration()
val hit = genNow == specGen && eps > 0 && abs(ptsUs - specPtsUs) <= eps
val hit = genNow == specGen && ptsMs == specPtsMs
val slot = if (specIsLibassLast) libassLastSlot else specSlot
val frame = libassLastFrame
val specPts = specPtsUs
@@ -118,23 +122,32 @@ internal class SpecRenderEngine(
if (hit && slot >= 0 && frame != null) {
specHits++
lastPostedSlot = slot
debugLog?.invoke("hit pts=${ptsUs / 1000}ms spec=${specPts / 1000}ms d=${(ptsUs - specPts) / 1000}ms slot=$slot")
debugLog?.invoke(
"hit pts=${ptsMs}ms spec=${specPtsMs}ms dUs=${ptsUs - specPts} slot=$slot"
)
return Outcome.Post(slot, frame, newContent = false, specHit = true)
}
specMisses++
debugLog?.invoke(
"miss pts=${ptsUs / 1000}ms spec=${specPts / 1000}ms d=${(ptsUs - specPts) / 1000}ms eps=${eps / 1000}ms " +
"miss pts=${ptsMs}ms spec=${specPtsMs}ms dUs=${ptsUs - specPts} " +
"gen=${if (genNow == specGen) "ok" else "CHANGED"} slot=$slot frame=${frame != null}"
)
} else {
debugLog?.invoke("no-spec pts=${ptsUs / 1000}ms")
debugLog?.invoke("no-spec pts=${ptsMs}ms")
}
// On-demand render. Preferring libassLastSlot as the target makes changed == 0
// unambiguous: the buffers were untouched and already hold the right content.
// On-demand render. For changed == 0 with visible output, the buffers were
// untouched and libassLastSlot already holds the right content.
val target = renderTargetSlot() ?: return Outcome.Skip
val frame = renderAt(ptsUs / 1000, target) ?: return Outcome.Skip
val frame = renderAt(ptsMs, target) ?: return Outcome.Skip
if (frame.changed == 0) {
if (isImplicitBlank(frame)) {
blankClearCount++
libassLastSlot = target
libassLastFrame = frame
lastPostedSlot = target
return Outcome.Post(target, frame, newContent = true, specHit = false)
}
val lastSlot = libassLastSlot
val lastFrame = libassLastFrame ?: return Outcome.Skip
if (lastSlot < 0) return Outcome.Skip
@@ -169,13 +182,21 @@ internal class SpecRenderEngine(
}
val gen = stateGeneration()
val specPts = servicedPtsUs + medianDeltaUs()
val frame = renderAt(specPts / 1000, target) ?: run {
val frame = renderAt(toLibassMs(specPts), target) ?: run {
specSkips++
return null
}
specGen = gen
specPtsUs = specPts
if (frame.changed == 0) {
if (isImplicitBlank(frame)) {
blankClearCount++
libassLastSlot = target
libassLastFrame = frame
specIsLibassLast = false
specSlot = target
return SpecWrite(target, frame)
}
// Content at specPts is identical to libass's last render — nothing was
// written; a hit will repost libassLastSlot (and GL will skip the upload).
specIsLibassLast = true
@@ -189,6 +210,8 @@ internal class SpecRenderEngine(
return SpecWrite(target, frame)
}
private fun isImplicitBlank(frame: AssAtlasFrame): Boolean = !frame.hasOutput && libassLastFrame?.hasOutput == true
/**
* Pre-renders [ptsUs] (an upcoming event's start) purely to warm the
* renderer's glyph/bitmap caches before that content is actually needed —
@@ -204,7 +227,7 @@ internal class SpecRenderEngine(
fun prefetch(ptsUs: Long): SpecWrite? {
specPtsUs = UNSET
val target = renderTargetSlot() ?: return null
val frame = renderAt(ptsUs / 1000, target) ?: return null
val frame = renderAt(toLibassMs(ptsUs), target) ?: return null
prefetchCount++
if (frame.changed == 0) return null
libassLastSlot = target
@@ -253,13 +276,12 @@ internal class SpecRenderEngine(
return copy[deltaCount / 2]
}
private fun epsilonUs(): Long = if (deltaValid()) minOf(medianDeltaUs() / 2, EPSILON_CAP_US) else 0L
private fun toLibassMs(ptsUs: Long): Long = Math.floorDiv(ptsUs, 1_000L)
private companion object {
const val UNSET = Long.MIN_VALUE
const val DELTA_SAMPLES = 8
const val MIN_DELTA_SAMPLES = 4
const val MAX_DELTA_US = 250_000L
const val EPSILON_CAP_US = 8_000L
}
}
@@ -53,7 +53,9 @@ class SpecRenderEngineTest {
fun changed(quads: Int = 5) = AssAtlasFrame(2048, 100, quads, 2, 0)
fun unchanged() = AssAtlasFrame(0, 0, 0, 0, 0)
fun unchanged() = AssAtlasFrame(0, 0, 0, 0, 0, hasOutput = true)
fun blankUnchanged() = AssAtlasFrame(0, 0, 0, 0, 0, hasOutput = false)
}
@Test
@@ -74,15 +76,40 @@ class SpecRenderEngineTest {
}
@Test
fun `hit tolerates jitter within epsilon`() {
fun `hit tolerates jitter only within the same libass millisecond`() {
val h = Harness()
val last = h.prime()
val outcome = h.engine.service(last + DELTA + 3_000, pinned = true)
val outcome = h.engine.service(last + DELTA + 999, pinned = true)
assertTrue((outcome as SpecRenderEngine.Outcome.Post).specHit)
}
@Test
fun `jitter crossing a libass millisecond boundary misses`() {
val h = Harness()
val last = h.prime()
val before = h.calls.size
h.script.add(changed())
val outcome = h.engine.service(last + DELTA + 1_000, pinned = true)
assertTrue(outcome is SpecRenderEngine.Outcome.Post)
assertFalse((outcome as SpecRenderEngine.Outcome.Post).specHit)
assertEquals(before + 1, h.calls.size)
assertEquals(1L, h.engine.specMisses)
}
@Test
fun `negative pts floors to the preceding libass millisecond`() {
val h = Harness()
h.script.add(changed())
h.engine.service(-1, pinned = true)
assertEquals(-1L, h.calls.last().timeMs)
}
@Test
fun `seek misses and renders on demand into the spec slot`() {
val h = Harness()
@@ -201,6 +228,23 @@ class SpecRenderEngineTest {
assertEquals(SpecRenderEngine.Outcome.Skip, h.engine.service(0, pinned = true))
}
@Test
fun `changed 0 without output clears previous content`() {
val h = Harness()
h.script.add(changed())
val first = h.engine.service(0, pinned = true) as SpecRenderEngine.Outcome.Post
h.script.add(blankUnchanged())
val outcome = h.engine.service(DELTA, pinned = true) as SpecRenderEngine.Outcome.Post
assertTrue(outcome.newContent)
assertFalse(outcome.specHit)
assertFalse(outcome.frame.hasOutput)
assertEquals(0, outcome.frame.quadCount)
assertTrue("blank frame should use a fresh metadata slot", outcome.slot != first.slot)
assertEquals(1L, h.engine.blankClearCount)
}
@Test
fun `renderer gone skips`() {
val h = Harness()
@@ -246,6 +290,34 @@ class SpecRenderEngineTest {
assertNotNull(first) // first slot existed; hit reposts whichever slot was last rendered
}
@Test
fun `speculative changed 0 without output clears on hit`() {
val h = Harness()
h.script.add(changed())
h.engine.service(0, pinned = true)
var pts = 0L
repeat(4) {
pts += DELTA
h.script.add(changed())
h.engine.service(pts, pinned = true)
}
h.script.add(blankUnchanged())
val write = h.engine.speculateAfter(pts, pinned = true, hasPending = false)
assertNotNull(write)
assertFalse(write!!.frame.hasOutput)
val before = h.calls.size
val outcome = h.engine.service(pts + DELTA, pinned = true) as SpecRenderEngine.Outcome.Post
assertTrue(outcome.specHit)
assertFalse(outcome.newContent)
assertFalse(outcome.frame.hasOutput)
assertEquals(0, outcome.frame.quadCount)
assertEquals(before, h.calls.size)
assertEquals(1L, h.engine.blankClearCount)
}
@Test
fun `speculative write reports slot for seq bump`() {
val h = Harness()
-2
View File
@@ -24,6 +24,4 @@ plugins {
}
include(":app")
// libass subtitle module (Kotlin/JNI bindings + Media3 glue); the native libass
// core stays the upstream Maven artifact io.github.peerless2012:ass.
include(":libass")
+2 -2
View File
@@ -788,8 +788,8 @@
isa = XCRemoteSwiftPackageReference;
repositoryURL = "https://github.com/edde746/MPVKit";
requirement = {
kind = revision;
revision = 245b69dce22156e81b79c84cfcb748358b674e47;
kind = exactVersion;
version = 1.0.6;
};
};
/* End XCRemoteSwiftPackageReference section */
@@ -40,7 +40,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/edde746/MPVKit",
"state" : {
"revision" : "245b69dce22156e81b79c84cfcb748358b674e47"
"revision" : "bed69a1cd381934c987376db1ed30b8c4725ae0c",
"version" : "1.0.6"
}
},
{
@@ -40,7 +40,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/edde746/MPVKit",
"state" : {
"revision" : "245b69dce22156e81b79c84cfcb748358b674e47"
"revision" : "bed69a1cd381934c987376db1ed30b8c4725ae0c",
"version" : "1.0.6"
}
},
{
+11 -1
View File
@@ -61,7 +61,7 @@ class AppDatabase extends _$AppDatabase {
AppDatabase.forTesting(super.e);
@override
int get schemaVersion => 15;
int get schemaVersion => 16;
@override
MigrationStrategy get migration {
@@ -214,6 +214,13 @@ class AppDatabase extends _$AppDatabase {
() => m.addColumn(downloadedMedia, downloadedMedia.mediaSourceId),
);
}
if (from < 16) {
appLogger.i('Adding includeSpecials column to SyncRules (v16 migration)');
await _ignoreAlreadyExists(
'SyncRules.includeSpecials column',
() => m.addColumn(syncRules, syncRules.includeSpecials),
);
}
},
);
}
@@ -532,6 +539,7 @@ class AppDatabase extends _$AppDatabase {
required int episodeCount,
int mediaIndex = 0,
String downloadFilter = 'unwatched',
bool includeSpecials = true,
}) async {
// [insertOnConflictUpdate] defaults the conflict target to the primary
// key (`id`), which is auto-incremented — the conflict never triggers
@@ -549,6 +557,7 @@ class AppDatabase extends _$AppDatabase {
createdAt: DateTime.now().millisecondsSinceEpoch,
mediaIndex: Value(mediaIndex),
downloadFilter: Value(downloadFilter),
includeSpecials: Value(includeSpecials),
),
onConflict: DoUpdate(
(_) => SyncRulesCompanion(
@@ -559,6 +568,7 @@ class AppDatabase extends _$AppDatabase {
episodeCount: Value(episodeCount),
mediaIndex: Value(mediaIndex),
downloadFilter: Value(downloadFilter),
includeSpecials: Value(includeSpecials),
),
target: [syncRules.globalKey],
),
+78 -3
View File
@@ -3150,6 +3150,21 @@ class $SyncRulesTable extends SyncRules
requiredDuringInsert: false,
defaultValue: const Constant('unwatched'),
);
static const VerificationMeta _includeSpecialsMeta = const VerificationMeta(
'includeSpecials',
);
@override
late final GeneratedColumn<bool> includeSpecials = GeneratedColumn<bool>(
'include_specials',
aliasedName,
false,
type: DriftSqlType.bool,
requiredDuringInsert: false,
defaultConstraints: GeneratedColumn.constraintIsAlways(
'CHECK ("include_specials" IN (0, 1))',
),
defaultValue: const Constant(true),
);
@override
List<GeneratedColumn> get $columns => [
id,
@@ -3164,6 +3179,7 @@ class $SyncRulesTable extends SyncRules
lastExecutedAt,
mediaIndex,
downloadFilter,
includeSpecials,
];
@override
String get aliasedName => _alias ?? actualTableName;
@@ -3267,6 +3283,15 @@ class $SyncRulesTable extends SyncRules
),
);
}
if (data.containsKey('include_specials')) {
context.handle(
_includeSpecialsMeta,
includeSpecials.isAcceptableOrUnknown(
data['include_specials']!,
_includeSpecialsMeta,
),
);
}
return context;
}
@@ -3324,6 +3349,10 @@ class $SyncRulesTable extends SyncRules
DriftSqlType.string,
data['${effectivePrefix}download_filter'],
)!,
includeSpecials: attachedDatabase.typeMapping.read(
DriftSqlType.bool,
data['${effectivePrefix}include_specials'],
)!,
);
}
@@ -3346,6 +3375,7 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
final int? lastExecutedAt;
final int mediaIndex;
final String downloadFilter;
final bool includeSpecials;
const SyncRuleItem({
required this.id,
required this.profileId,
@@ -3359,6 +3389,7 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
this.lastExecutedAt,
required this.mediaIndex,
required this.downloadFilter,
required this.includeSpecials,
});
@override
Map<String, Expression> toColumns(bool nullToAbsent) {
@@ -3377,6 +3408,7 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
}
map['media_index'] = Variable<int>(mediaIndex);
map['download_filter'] = Variable<String>(downloadFilter);
map['include_specials'] = Variable<bool>(includeSpecials);
return map;
}
@@ -3396,6 +3428,7 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
: Value(lastExecutedAt),
mediaIndex: Value(mediaIndex),
downloadFilter: Value(downloadFilter),
includeSpecials: Value(includeSpecials),
);
}
@@ -3417,6 +3450,7 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
lastExecutedAt: serializer.fromJson<int?>(json['lastExecutedAt']),
mediaIndex: serializer.fromJson<int>(json['mediaIndex']),
downloadFilter: serializer.fromJson<String>(json['downloadFilter']),
includeSpecials: serializer.fromJson<bool>(json['includeSpecials']),
);
}
@override
@@ -3435,6 +3469,7 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
'lastExecutedAt': serializer.toJson<int?>(lastExecutedAt),
'mediaIndex': serializer.toJson<int>(mediaIndex),
'downloadFilter': serializer.toJson<String>(downloadFilter),
'includeSpecials': serializer.toJson<bool>(includeSpecials),
};
}
@@ -3451,6 +3486,7 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
Value<int?> lastExecutedAt = const Value.absent(),
int? mediaIndex,
String? downloadFilter,
bool? includeSpecials,
}) => SyncRuleItem(
id: id ?? this.id,
profileId: profileId ?? this.profileId,
@@ -3466,6 +3502,7 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
: this.lastExecutedAt,
mediaIndex: mediaIndex ?? this.mediaIndex,
downloadFilter: downloadFilter ?? this.downloadFilter,
includeSpecials: includeSpecials ?? this.includeSpecials,
);
SyncRuleItem copyWithCompanion(SyncRulesCompanion data) {
return SyncRuleItem(
@@ -3491,6 +3528,9 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
downloadFilter: data.downloadFilter.present
? data.downloadFilter.value
: this.downloadFilter,
includeSpecials: data.includeSpecials.present
? data.includeSpecials.value
: this.includeSpecials,
);
}
@@ -3508,7 +3548,8 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
..write('createdAt: $createdAt, ')
..write('lastExecutedAt: $lastExecutedAt, ')
..write('mediaIndex: $mediaIndex, ')
..write('downloadFilter: $downloadFilter')
..write('downloadFilter: $downloadFilter, ')
..write('includeSpecials: $includeSpecials')
..write(')'))
.toString();
}
@@ -3527,6 +3568,7 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
lastExecutedAt,
mediaIndex,
downloadFilter,
includeSpecials,
);
@override
bool operator ==(Object other) =>
@@ -3543,7 +3585,8 @@ class SyncRuleItem extends DataClass implements Insertable<SyncRuleItem> {
other.createdAt == this.createdAt &&
other.lastExecutedAt == this.lastExecutedAt &&
other.mediaIndex == this.mediaIndex &&
other.downloadFilter == this.downloadFilter);
other.downloadFilter == this.downloadFilter &&
other.includeSpecials == this.includeSpecials);
}
class SyncRulesCompanion extends UpdateCompanion<SyncRuleItem> {
@@ -3559,6 +3602,7 @@ class SyncRulesCompanion extends UpdateCompanion<SyncRuleItem> {
final Value<int?> lastExecutedAt;
final Value<int> mediaIndex;
final Value<String> downloadFilter;
final Value<bool> includeSpecials;
const SyncRulesCompanion({
this.id = const Value.absent(),
this.profileId = const Value.absent(),
@@ -3572,6 +3616,7 @@ class SyncRulesCompanion extends UpdateCompanion<SyncRuleItem> {
this.lastExecutedAt = const Value.absent(),
this.mediaIndex = const Value.absent(),
this.downloadFilter = const Value.absent(),
this.includeSpecials = const Value.absent(),
});
SyncRulesCompanion.insert({
this.id = const Value.absent(),
@@ -3586,6 +3631,7 @@ class SyncRulesCompanion extends UpdateCompanion<SyncRuleItem> {
this.lastExecutedAt = const Value.absent(),
this.mediaIndex = const Value.absent(),
this.downloadFilter = const Value.absent(),
this.includeSpecials = const Value.absent(),
}) : serverId = Value(serverId),
ratingKey = Value(ratingKey),
globalKey = Value(globalKey),
@@ -3605,6 +3651,7 @@ class SyncRulesCompanion extends UpdateCompanion<SyncRuleItem> {
Expression<int>? lastExecutedAt,
Expression<int>? mediaIndex,
Expression<String>? downloadFilter,
Expression<bool>? includeSpecials,
}) {
return RawValuesInsertable({
if (id != null) 'id': id,
@@ -3619,6 +3666,7 @@ class SyncRulesCompanion extends UpdateCompanion<SyncRuleItem> {
if (lastExecutedAt != null) 'last_executed_at': lastExecutedAt,
if (mediaIndex != null) 'media_index': mediaIndex,
if (downloadFilter != null) 'download_filter': downloadFilter,
if (includeSpecials != null) 'include_specials': includeSpecials,
});
}
@@ -3635,6 +3683,7 @@ class SyncRulesCompanion extends UpdateCompanion<SyncRuleItem> {
Value<int?>? lastExecutedAt,
Value<int>? mediaIndex,
Value<String>? downloadFilter,
Value<bool>? includeSpecials,
}) {
return SyncRulesCompanion(
id: id ?? this.id,
@@ -3649,6 +3698,7 @@ class SyncRulesCompanion extends UpdateCompanion<SyncRuleItem> {
lastExecutedAt: lastExecutedAt ?? this.lastExecutedAt,
mediaIndex: mediaIndex ?? this.mediaIndex,
downloadFilter: downloadFilter ?? this.downloadFilter,
includeSpecials: includeSpecials ?? this.includeSpecials,
);
}
@@ -3691,6 +3741,9 @@ class SyncRulesCompanion extends UpdateCompanion<SyncRuleItem> {
if (downloadFilter.present) {
map['download_filter'] = Variable<String>(downloadFilter.value);
}
if (includeSpecials.present) {
map['include_specials'] = Variable<bool>(includeSpecials.value);
}
return map;
}
@@ -3708,7 +3761,8 @@ class SyncRulesCompanion extends UpdateCompanion<SyncRuleItem> {
..write('createdAt: $createdAt, ')
..write('lastExecutedAt: $lastExecutedAt, ')
..write('mediaIndex: $mediaIndex, ')
..write('downloadFilter: $downloadFilter')
..write('downloadFilter: $downloadFilter, ')
..write('includeSpecials: $includeSpecials')
..write(')'))
.toString();
}
@@ -6842,6 +6896,7 @@ typedef $$SyncRulesTableCreateCompanionBuilder =
Value<int?> lastExecutedAt,
Value<int> mediaIndex,
Value<String> downloadFilter,
Value<bool> includeSpecials,
});
typedef $$SyncRulesTableUpdateCompanionBuilder =
SyncRulesCompanion Function({
@@ -6857,6 +6912,7 @@ typedef $$SyncRulesTableUpdateCompanionBuilder =
Value<int?> lastExecutedAt,
Value<int> mediaIndex,
Value<String> downloadFilter,
Value<bool> includeSpecials,
});
class $$SyncRulesTableFilterComposer
@@ -6927,6 +6983,11 @@ class $$SyncRulesTableFilterComposer
column: $table.downloadFilter,
builder: (column) => ColumnFilters(column),
);
ColumnFilters<bool> get includeSpecials => $composableBuilder(
column: $table.includeSpecials,
builder: (column) => ColumnFilters(column),
);
}
class $$SyncRulesTableOrderingComposer
@@ -6997,6 +7058,11 @@ class $$SyncRulesTableOrderingComposer
column: $table.downloadFilter,
builder: (column) => ColumnOrderings(column),
);
ColumnOrderings<bool> get includeSpecials => $composableBuilder(
column: $table.includeSpecials,
builder: (column) => ColumnOrderings(column),
);
}
class $$SyncRulesTableAnnotationComposer
@@ -7053,6 +7119,11 @@ class $$SyncRulesTableAnnotationComposer
column: $table.downloadFilter,
builder: (column) => column,
);
GeneratedColumn<bool> get includeSpecials => $composableBuilder(
column: $table.includeSpecials,
builder: (column) => column,
);
}
class $$SyncRulesTableTableManager
@@ -7098,6 +7169,7 @@ class $$SyncRulesTableTableManager
Value<int?> lastExecutedAt = const Value.absent(),
Value<int> mediaIndex = const Value.absent(),
Value<String> downloadFilter = const Value.absent(),
Value<bool> includeSpecials = const Value.absent(),
}) => SyncRulesCompanion(
id: id,
profileId: profileId,
@@ -7111,6 +7183,7 @@ class $$SyncRulesTableTableManager
lastExecutedAt: lastExecutedAt,
mediaIndex: mediaIndex,
downloadFilter: downloadFilter,
includeSpecials: includeSpecials,
),
createCompanionCallback:
({
@@ -7126,6 +7199,7 @@ class $$SyncRulesTableTableManager
Value<int?> lastExecutedAt = const Value.absent(),
Value<int> mediaIndex = const Value.absent(),
Value<String> downloadFilter = const Value.absent(),
Value<bool> includeSpecials = const Value.absent(),
}) => SyncRulesCompanion.insert(
id: id,
profileId: profileId,
@@ -7139,6 +7213,7 @@ class $$SyncRulesTableTableManager
lastExecutedAt: lastExecutedAt,
mediaIndex: mediaIndex,
downloadFilter: downloadFilter,
includeSpecials: includeSpecials,
),
withReferenceMapper: (p0) => p0
.map((e) => (e.readTable(table), BaseReferences(db, table, e)))
+1
View File
@@ -101,6 +101,7 @@ class SyncRules extends Table {
IntColumn get lastExecutedAt => integer().nullable()();
IntColumn get mediaIndex => integer().withDefault(const Constant(0))();
TextColumn get downloadFilter => text().withDefault(const Constant('unwatched'))();
BoolColumn get includeSpecials => boolean().withDefault(const Constant(true))();
}
/// Persisted media-server connections.
+5 -4
View File
@@ -62,14 +62,15 @@ KeyEventResult handleBackKeyAction(KeyEvent event, VoidCallback onBack) {
return KeyEventResult.handled;
}
// AppleTV physical-keyboard back (Siri Remote Menu via engine-synthesized
// escape): run onBack on KeyDown only; consume KeyUp silently. The
// suppressor-based "arm-on-KeyDown, clear-on-KeyUp" pattern leaks here
// AppleTV back (Siri Remote Menu via engine-synthesized escape): run onBack
// on KeyDown only; consume KeyUp silently. Some engine paths report Menu as
// a non-keyboard device, but the same down-only handling is still required.
// The suppressor-based "arm-on-KeyDown, clear-on-KeyUp" pattern leaks here
// because onBack typically calls Navigator.pop, swapping the focus tree
// before the matching KeyUp is dispatched — the orphaned KeyUp then never
// reaches a consumeIfSuppressed call, pinning the suppressor armed and
// silently swallowing the next press's KeyDown.
if (PlatformDetector.isAppleTV() && event.isPhysicalKeyboardEvent) {
if (PlatformDetector.isAppleTV()) {
if (event is KeyDownEvent) {
BackKeyCoordinator.markHandled();
onBack();
+6 -1
View File
@@ -118,6 +118,9 @@
"continueWatchingAction": "Действие за продължаване на гледането",
"continueWatchingPlay": "Пусни",
"continueWatchingDetails": "Отвори подробности",
"episodeAction": "Действие за епизод",
"episodePlay": "Пусни",
"episodeDetails": "Отвори подробности",
"useGlobalHubs": "Използвай начално оформление",
"useGlobalHubsDescription": "Показвай обединени начални хъбове. В противен случай използвай препоръките на библиотеката.",
"showServerNameOnHubs": "Показвай името на сървъра в хъбовете",
@@ -771,7 +774,8 @@
"studio": "Студио",
"random": "Случайно",
"dateShared": "Дата на споделяне",
"latestEpisodeAirDate": "Дата на излъчване на последния епизод"
"latestEpisodeAirDate": "Дата на излъчване на последния епизод",
"lastEpisodeDateAdded": "Дата на добавяне на последния епизод"
}
},
"about": {
@@ -1027,6 +1031,7 @@
"unwatchedOnly": "Само негледани",
"nextNUnwatched": "Следващите ${count} негледани",
"customAmount": "Персонален брой...",
"includeSpecials": "Включи специалните",
"howManyEpisodes": "Колко епизода?",
"itemsQueued": "${count} елемента са добавени в опашката за изтегляне",
"keepSynced": "Поддържай синхронизирано",
+6 -1
View File
@@ -118,6 +118,9 @@
"continueWatchingAction": "Handling for Fortsæt med at se",
"continueWatchingPlay": "Afspil",
"continueWatchingDetails": "Åbn detaljer",
"episodeAction": "Handling for afsnit",
"episodePlay": "Afspil",
"episodeDetails": "Åbn detaljer",
"useGlobalHubs": "Brug startlayout",
"useGlobalHubsDescription": "Vis samlet startsideindhold. Brug ellers biblioteksanbefalinger.",
"showServerNameOnHubs": "Vis servernavn på hubbe",
@@ -771,7 +774,8 @@
"studio": "Studie",
"random": "Tilfældig",
"dateShared": "Delt dato",
"latestEpisodeAirDate": "Seneste episodes premieredato"
"latestEpisodeAirDate": "Seneste episodes premieredato",
"lastEpisodeDateAdded": "Dato for senest tilføjede episode"
}
},
"about": {
@@ -1027,6 +1031,7 @@
"unwatchedOnly": "Kun usete",
"nextNUnwatched": "Næste ${count} usete",
"customAmount": "Angiv antal...",
"includeSpecials": "Inkludér specials",
"howManyEpisodes": "Hvor mange episoder?",
"itemsQueued": "${count} elementer sat i kø til download",
"keepSynced": "Hold synkroniseret",
+6 -1
View File
@@ -118,6 +118,9 @@
"continueWatchingAction": "Aktion für Weiterschauen",
"continueWatchingPlay": "Abspielen",
"continueWatchingDetails": "Details öffnen",
"episodeAction": "Episodenaktion",
"episodePlay": "Abspielen",
"episodeDetails": "Details öffnen",
"useGlobalHubs": "Startlayout verwenden",
"useGlobalHubsDescription": "Einheitliche Start-Hubs anzeigen. Sonst Bibliotheksempfehlungen verwenden.",
"showServerNameOnHubs": "Servername bei Hubs anzeigen",
@@ -771,7 +774,8 @@
"studio": "Studio",
"random": "Zufällig",
"dateShared": "Datum geteilt",
"latestEpisodeAirDate": "Letztes Folgenausstrahlungsdatum"
"latestEpisodeAirDate": "Letztes Folgenausstrahlungsdatum",
"lastEpisodeDateAdded": "Datum der zuletzt hinzugefügten Folge"
}
},
"about": {
@@ -1027,6 +1031,7 @@
"unwatchedOnly": "Nur ungesehene",
"nextNUnwatched": "Nächste ${count} ungesehene",
"customAmount": "Eigene Anzahl...",
"includeSpecials": "Specials einschließen",
"howManyEpisodes": "Wie viele Episoden?",
"itemsQueued": "${count} Elemente zum Download eingereiht",
"keepSynced": "Synchronisiert halten",
+6 -1
View File
@@ -118,6 +118,9 @@
"continueWatchingAction": "Continue Watching Action",
"continueWatchingPlay": "Play",
"continueWatchingDetails": "Open Details",
"episodeAction": "Episode Action",
"episodePlay": "Play",
"episodeDetails": "Open Details",
"useGlobalHubs": "Use Home Layout",
"useGlobalHubsDescription": "Show unified home hubs. Otherwise use library recommendations.",
"showServerNameOnHubs": "Show Server Name on Hubs",
@@ -777,7 +780,8 @@
"studio": "Studio",
"random": "Random",
"dateShared": "Date Shared",
"latestEpisodeAirDate": "Latest Episode Air Date"
"latestEpisodeAirDate": "Latest Episode Air Date",
"lastEpisodeDateAdded": "Last Episode Date Added"
}
},
"about": {
@@ -1036,6 +1040,7 @@
"unwatchedOnly": "Unwatched only",
"nextNUnwatched": "Next ${count} unwatched",
"customAmount": "Custom amount...",
"includeSpecials": "Include Specials",
"howManyEpisodes": "How many episodes?",
"itemsQueued": "${count} items queued for download",
"keepSynced": "Keep synced",
+6 -1
View File
@@ -118,6 +118,9 @@
"continueWatchingAction": "Acción de Seguir viendo",
"continueWatchingPlay": "Reproducir",
"continueWatchingDetails": "Abrir detalles",
"episodeAction": "Acción de episodio",
"episodePlay": "Reproducir",
"episodeDetails": "Abrir detalles",
"useGlobalHubs": "Usar diseño de inicio",
"useGlobalHubsDescription": "Mostrar hubs de inicio unificados. Si no, usar recomendaciones de biblioteca.",
"showServerNameOnHubs": "Mostrar Nombre del Servidor en los Hubs",
@@ -771,7 +774,8 @@
"studio": "Estudio",
"random": "Aleatorio",
"dateShared": "Fecha de compartición",
"latestEpisodeAirDate": "Última fecha de emisión del episodio"
"latestEpisodeAirDate": "Última fecha de emisión del episodio",
"lastEpisodeDateAdded": "Fecha de adición del último episodio"
}
},
"about": {
@@ -1027,6 +1031,7 @@
"unwatchedOnly": "Solo no vistos",
"nextNUnwatched": "Próximos ${count} no vistos",
"customAmount": "Cantidad personalizada...",
"includeSpecials": "Incluir especiales",
"howManyEpisodes": "¿Cuántos episodios?",
"itemsQueued": "${count} elementos en cola de descarga",
"keepSynced": "Mantener sincronizado",
+6 -1
View File
@@ -118,6 +118,9 @@
"continueWatchingAction": "Action Continuer à regarder",
"continueWatchingPlay": "Lire",
"continueWatchingDetails": "Ouvrir les détails",
"episodeAction": "Action des épisodes",
"episodePlay": "Lire",
"episodeDetails": "Ouvrir les détails",
"useGlobalHubs": "Utiliser la mise en page d'accueil",
"useGlobalHubsDescription": "Afficher des hubs d'accueil unifiés. Sinon, utiliser les recommandations de bibliothèque.",
"showServerNameOnHubs": "Afficher le nom du serveur sur les hubs",
@@ -771,7 +774,8 @@
"studio": "Studio",
"random": "Aléatoire",
"dateShared": "Date de partage",
"latestEpisodeAirDate": "Dernière date de diffusion"
"latestEpisodeAirDate": "Dernière date de diffusion",
"lastEpisodeDateAdded": "Date d'ajout du dernier épisode"
}
},
"about": {
@@ -1027,6 +1031,7 @@
"unwatchedOnly": "Non vus uniquement",
"nextNUnwatched": "${count} prochains non vus",
"customAmount": "Quantité personnalisée...",
"includeSpecials": "Inclure les spéciaux",
"howManyEpisodes": "Combien d'épisodes ?",
"itemsQueued": "${count} éléments mis en file d'attente",
"keepSynced": "Garder synchronisé",
+6 -1
View File
@@ -118,6 +118,9 @@
"continueWatchingAction": "Azione Continua a guardare",
"continueWatchingPlay": "Riproduci",
"continueWatchingDetails": "Apri dettagli",
"episodeAction": "Azione episodio",
"episodePlay": "Riproduci",
"episodeDetails": "Apri dettagli",
"useGlobalHubs": "Usa layout home",
"useGlobalHubsDescription": "Mostra hub Home unificati. Altrimenti usa i consigli della libreria.",
"showServerNameOnHubs": "Mostra nome server sugli hub",
@@ -771,7 +774,8 @@
"studio": "Studio",
"random": "Casuale",
"dateShared": "Data di condivisione",
"latestEpisodeAirDate": "Data ultima messa in onda"
"latestEpisodeAirDate": "Data ultima messa in onda",
"lastEpisodeDateAdded": "Data aggiunta ultimo episodio"
}
},
"about": {
@@ -1027,6 +1031,7 @@
"unwatchedOnly": "Solo non visti",
"nextNUnwatched": "Prossimi ${count} non visti",
"customAmount": "Quantità personalizzata...",
"includeSpecials": "Includi gli speciali",
"howManyEpisodes": "Quanti episodi?",
"itemsQueued": "${count} elementi in coda per il download",
"keepSynced": "Mantieni sincronizzato",
+6 -1
View File
@@ -118,6 +118,9 @@
"continueWatchingAction": "視聴中の操作",
"continueWatchingPlay": "再生",
"continueWatchingDetails": "詳細を開く",
"episodeAction": "エピソードの操作",
"episodePlay": "再生",
"episodeDetails": "詳細を開く",
"useGlobalHubs": "ホームレイアウトを使用",
"useGlobalHubsDescription": "統合ホームハブを表示します。オフの場合はライブラリのおすすめを使用します。",
"showServerNameOnHubs": "ハブにサーバー名を表示",
@@ -771,7 +774,8 @@
"studio": "スタジオ",
"random": "ランダム",
"dateShared": "共有日",
"latestEpisodeAirDate": "最新エピソード放送日"
"latestEpisodeAirDate": "最新エピソード放送日",
"lastEpisodeDateAdded": "最新エピソード追加日"
}
},
"about": {
@@ -1027,6 +1031,7 @@
"unwatchedOnly": "未視聴のみ",
"nextNUnwatched": "次の${count}件の未視聴",
"customAmount": "数を指定...",
"includeSpecials": "スペシャルを含める",
"howManyEpisodes": "何エピソード?",
"itemsQueued": "${count}件をダウンロードキューに追加",
"keepSynced": "同期を維持",
+6 -1
View File
@@ -118,6 +118,9 @@
"continueWatchingAction": "계속 보기 동작",
"continueWatchingPlay": "재생",
"continueWatchingDetails": "상세 정보 열기",
"episodeAction": "에피소드 동작",
"episodePlay": "재생",
"episodeDetails": "상세 정보 열기",
"useGlobalHubs": "홈 레이아웃 사용",
"useGlobalHubsDescription": "통합 홈 허브를 표시합니다. 끄면 라이브러리 추천을 사용합니다.",
"showServerNameOnHubs": "허브에 서버 이름 표시",
@@ -771,7 +774,8 @@
"studio": "스튜디오",
"random": "무작위",
"dateShared": "공유된 날짜",
"latestEpisodeAirDate": "최신 에피소드 방영일"
"latestEpisodeAirDate": "최신 에피소드 방영일",
"lastEpisodeDateAdded": "최신 에피소드 추가일"
}
},
"about": {
@@ -1027,6 +1031,7 @@
"unwatchedOnly": "시청하지 않은 것만",
"nextNUnwatched": "다음 ${count}개 미시청",
"customAmount": "직접 입력...",
"includeSpecials": "스페셜 포함",
"howManyEpisodes": "몇 개의 에피소드?",
"itemsQueued": "${count}개 항목이 다운로드 대기열에 추가됨",
"keepSynced": "동기화 유지",
+6 -1
View File
@@ -118,6 +118,9 @@
"continueWatchingAction": "Handling for Fortsett å se",
"continueWatchingPlay": "Spill av",
"continueWatchingDetails": "Åpne detaljer",
"episodeAction": "Handling for episoder",
"episodePlay": "Spill av",
"episodeDetails": "Åpne detaljer",
"useGlobalHubs": "Bruk startoppsett",
"useGlobalHubsDescription": "Vis samlet startinnhold. Ellers brukes bibliotekanbefalinger.",
"showServerNameOnHubs": "Vis servernavn på huber",
@@ -771,7 +774,8 @@
"studio": "Studio",
"random": "Tilfeldig",
"dateShared": "Delingsdato",
"latestEpisodeAirDate": "Siste episodes sendedato"
"latestEpisodeAirDate": "Siste episodes sendedato",
"lastEpisodeDateAdded": "Dato for sist lagt til episode"
}
},
"about": {
@@ -1027,6 +1031,7 @@
"unwatchedOnly": "Kun usette",
"nextNUnwatched": "Neste ${count} usette",
"customAmount": "Egendefinert antall...",
"includeSpecials": "Inkluder spesialepisoder",
"howManyEpisodes": "Hvor mange episoder?",
"itemsQueued": "${count} elementer i nedlastingskø",
"keepSynced": "Hold synkronisert",
+6 -1
View File
@@ -118,6 +118,9 @@
"continueWatchingAction": "Actie voor Doorgaan met kijken",
"continueWatchingPlay": "Afspelen",
"continueWatchingDetails": "Details openen",
"episodeAction": "Afleveringsactie",
"episodePlay": "Afspelen",
"episodeDetails": "Details openen",
"useGlobalHubs": "Startlayout gebruiken",
"useGlobalHubsDescription": "Toon gecombineerde home-hubs. Anders bibliotheekaanbevelingen gebruiken.",
"showServerNameOnHubs": "Servernaam tonen bij hubs",
@@ -771,7 +774,8 @@
"studio": "Studio",
"random": "Willekeurig",
"dateShared": "Gedeeld op",
"latestEpisodeAirDate": "Laatste afleveringsuitzending"
"latestEpisodeAirDate": "Laatste afleveringsuitzending",
"lastEpisodeDateAdded": "Datum laatst toegevoegde aflevering"
}
},
"about": {
@@ -1027,6 +1031,7 @@
"unwatchedOnly": "Alleen onbekeken",
"nextNUnwatched": "Volgende ${count} onbekeken",
"customAmount": "Aangepast aantal...",
"includeSpecials": "Specials opnemen",
"howManyEpisodes": "Hoeveel afleveringen?",
"itemsQueued": "${count} items in downloadwachtrij",
"keepSynced": "Gesynchroniseerd houden",
+6 -1
View File
@@ -118,6 +118,9 @@
"continueWatchingAction": "Akcja Kontynuuj oglądanie",
"continueWatchingPlay": "Odtwórz",
"continueWatchingDetails": "Otwórz szczegóły",
"episodeAction": "Akcja odcinka",
"episodePlay": "Odtwórz",
"episodeDetails": "Otwórz szczegóły",
"useGlobalHubs": "Użyj układu strony głównej",
"useGlobalHubsDescription": "Pokaż ujednolicone huby ekranu głównego. W przeciwnym razie użyj rekomendacji bibliotek.",
"showServerNameOnHubs": "Pokaż nazwę serwera w hubach",
@@ -771,7 +774,8 @@
"studio": "Studio",
"random": "Losowo",
"dateShared": "Data udostępnienia",
"latestEpisodeAirDate": "Data emisji ostatniego odcinka"
"latestEpisodeAirDate": "Data emisji ostatniego odcinka",
"lastEpisodeDateAdded": "Data dodania ostatniego odcinka"
}
},
"about": {
@@ -1027,6 +1031,7 @@
"unwatchedOnly": "Tylko nieobejrzane",
"nextNUnwatched": "Następne ${count} nieobejrzanych",
"customAmount": "Własna ilość...",
"includeSpecials": "Uwzględnij odcinki specjalne",
"howManyEpisodes": "Ile odcinków?",
"itemsQueued": "${count} elementów dodanych do kolejki pobierania",
"keepSynced": "Synchronizuj na bieżąco",
+6 -1
View File
@@ -118,6 +118,9 @@
"continueWatchingAction": "Ação de Continuar Assistindo",
"continueWatchingPlay": "Reproduzir",
"continueWatchingDetails": "Abrir detalhes",
"episodeAction": "Ação de Episódio",
"episodePlay": "Reproduzir",
"episodeDetails": "Abrir detalhes",
"useGlobalHubs": "Usar layout inicial",
"useGlobalHubsDescription": "Mostrar hubs iniciais unificados. Caso contrário, usar recomendações da biblioteca.",
"showServerNameOnHubs": "Mostrar Nome do Servidor nos Hubs",
@@ -771,7 +774,8 @@
"studio": "Estúdio",
"random": "Aleatório",
"dateShared": "Data de compartilhamento",
"latestEpisodeAirDate": "Última data de exibição do episódio"
"latestEpisodeAirDate": "Última data de exibição do episódio",
"lastEpisodeDateAdded": "Data de adição do último episódio"
}
},
"about": {
@@ -1027,6 +1031,7 @@
"unwatchedOnly": "Apenas não assistidos",
"nextNUnwatched": "Próximos ${count} não assistidos",
"customAmount": "Quantidade personalizada...",
"includeSpecials": "Incluir especiais",
"howManyEpisodes": "Quantos episódios?",
"itemsQueued": "${count} itens na fila de download",
"keepSynced": "Manter sincronizado",
+6 -1
View File
@@ -118,6 +118,9 @@
"continueWatchingAction": "Действие для «Продолжить просмотр»",
"continueWatchingPlay": "Воспроизвести",
"continueWatchingDetails": "Открыть сведения",
"episodeAction": "Действие для эпизодов",
"episodePlay": "Воспроизвести",
"episodeDetails": "Открыть сведения",
"useGlobalHubs": "Использовать макет главной",
"useGlobalHubsDescription": "Показывать единые разделы главной. Иначе использовать рекомендации библиотек.",
"showServerNameOnHubs": "Показывать имя сервера в хабах",
@@ -771,7 +774,8 @@
"studio": "Студия",
"random": "Случайно",
"dateShared": "Дата открытия доступа",
"latestEpisodeAirDate": "Дата выхода последнего эпизода"
"latestEpisodeAirDate": "Дата выхода последнего эпизода",
"lastEpisodeDateAdded": "Дата добавления последнего эпизода"
}
},
"about": {
@@ -1027,6 +1031,7 @@
"unwatchedOnly": "Только непросмотренные",
"nextNUnwatched": "Следующие ${count} непросмотренных",
"customAmount": "Указать количество...",
"includeSpecials": "Включить спецвыпуски",
"howManyEpisodes": "Сколько эпизодов?",
"itemsQueued": "${count} элементов добавлено в очередь загрузки",
"keepSynced": "Синхронизировать",
+1 -1
View File
@@ -4,7 +4,7 @@
/// To regenerate, run: `dart run slang`
///
/// Locales: 16
/// Strings: 20361 (1272 per locale)
/// Strings: 20441 (1277 per locale)
// coverage:ignore-file
// ignore_for_file: type=lint, unused_import
+14 -4
View File
@@ -247,6 +247,9 @@ class _TranslationsSettingsBg extends TranslationsSettingsEn {
@override String get continueWatchingAction => 'Действие за продължаване на гледането';
@override String get continueWatchingPlay => 'Пусни';
@override String get continueWatchingDetails => 'Отвори подробности';
@override String get episodeAction => 'Действие за епизод';
@override String get episodePlay => 'Пусни';
@override String get episodeDetails => 'Отвори подробности';
@override String get useGlobalHubs => 'Използвай начално оформление';
@override String get useGlobalHubsDescription => 'Показвай обединени начални хъбове. В противен случай използвай препоръките на библиотеката.';
@override String get showServerNameOnHubs => 'Показвай името на сървъра в хъбовете';
@@ -1285,6 +1288,7 @@ class _TranslationsDownloadsBg extends TranslationsDownloadsEn {
@override String get unwatchedOnly => 'Само негледани';
@override String nextNUnwatched({required Object count}) => 'Следващите ${count} негледани';
@override String get customAmount => 'Персонален брой...';
@override String get includeSpecials => 'Включи специалните';
@override String get howManyEpisodes => 'Колко епизода?';
@override String itemsQueued({required Object count}) => '${count} елемента са добавени в опашката за изтегляне';
@override String get keepSynced => 'Поддържай синхронизирано';
@@ -1755,6 +1759,7 @@ class _TranslationsLibrariesSortLabelsBg extends TranslationsLibrariesSortLabels
@override String get random => 'Случайно';
@override String get dateShared => 'Дата на споделяне';
@override String get latestEpisodeAirDate => 'Дата на излъчване на последния епизод';
@override String get lastEpisodeDateAdded => 'Дата на добавяне на последния епизод';
}
// Path: companionRemote.session
@@ -2029,6 +2034,9 @@ extension on TranslationsBg {
'settings.continueWatchingAction' => 'Действие за продължаване на гледането',
'settings.continueWatchingPlay' => 'Пусни',
'settings.continueWatchingDetails' => 'Отвори подробности',
'settings.episodeAction' => 'Действие за епизод',
'settings.episodePlay' => 'Пусни',
'settings.episodeDetails' => 'Отвори подробности',
'settings.useGlobalHubs' => 'Използвай начално оформление',
'settings.useGlobalHubsDescription' => 'Показвай обединени начални хъбове. В противен случай използвай препоръките на библиотеката.',
'settings.showServerNameOnHubs' => 'Показвай името на сървъра в хъбовете',
@@ -2430,11 +2438,11 @@ extension on TranslationsBg {
'messages.logsUploaded' => 'Логовете са качени',
'messages.logsUploadFailed' => 'Неуспешно качване на логовете',
'messages.logId' => 'ID на лога',
_ => null,
} ?? switch (path) {
'subtitlingStyling.text' => 'Текст',
'subtitlingStyling.border' => 'Рамка',
'subtitlingStyling.background' => 'Фон',
_ => null,
} ?? switch (path) {
'subtitlingStyling.fontSize' => 'Размер на шрифта',
'subtitlingStyling.textColor' => 'Цвят на текста',
'subtitlingStyling.borderSize' => 'Размер на рамката',
@@ -2638,6 +2646,7 @@ extension on TranslationsBg {
'libraries.sortLabels.random' => 'Случайно',
'libraries.sortLabels.dateShared' => 'Дата на споделяне',
'libraries.sortLabels.latestEpisodeAirDate' => 'Дата на излъчване на последния епизод',
'libraries.sortLabels.lastEpisodeDateAdded' => 'Дата на добавяне на последния епизод',
'about.title' => 'Относно',
'about.openSourceLicenses' => 'Лицензи с отворен код',
'about.versionLabel' => ({required Object version}) => 'Версия ${version}',
@@ -2870,6 +2879,7 @@ extension on TranslationsBg {
'downloads.unwatchedOnly' => 'Само негледани',
'downloads.nextNUnwatched' => ({required Object count}) => 'Следващите ${count} негледани',
'downloads.customAmount' => 'Персонален брой...',
'downloads.includeSpecials' => 'Включи специалните',
'downloads.howManyEpisodes' => 'Колко епизода?',
'downloads.itemsQueued' => ({required Object count}) => '${count} елемента са добавени в опашката за изтегляне',
'downloads.keepSynced' => 'Поддържай синхронизирано',
@@ -2942,13 +2952,13 @@ extension on TranslationsBg {
'companionRemote.pairing.authFailed' => 'Удостоверяването е неуспешно. Двете устройства трябва да използват същия Plex акаунт.',
'companionRemote.pairing.failedToConnect' => ({required Object error}) => 'Неуспешно свързване: ${error}',
'companionRemote.remote.disconnectConfirm' => 'Искате ли да прекъснете връзката с дистанционната сесия?',
_ => null,
} ?? switch (path) {
'companionRemote.remote.reconnecting' => 'Повторно свързване...',
'companionRemote.remote.attemptOf' => ({required Object current}) => 'Опит ${current} от 5',
'companionRemote.remote.retryNow' => 'Опитай сега',
'companionRemote.remote.tabRemote' => 'Дистанционно',
'companionRemote.remote.tabPlay' => 'Пускане',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabMore' => 'Още',
'companionRemote.remote.menu' => 'Меню',
'companionRemote.remote.tabNavigation' => 'Навигация с Tab',
+14 -4
View File
@@ -247,6 +247,9 @@ class _TranslationsSettingsDa extends TranslationsSettingsEn {
@override String get continueWatchingAction => 'Handling for Fortsæt med at se';
@override String get continueWatchingPlay => 'Afspil';
@override String get continueWatchingDetails => 'Åbn detaljer';
@override String get episodeAction => 'Handling for afsnit';
@override String get episodePlay => 'Afspil';
@override String get episodeDetails => 'Åbn detaljer';
@override String get useGlobalHubs => 'Brug startlayout';
@override String get useGlobalHubsDescription => 'Vis samlet startsideindhold. Brug ellers biblioteksanbefalinger.';
@override String get showServerNameOnHubs => 'Vis servernavn på hubbe';
@@ -1285,6 +1288,7 @@ class _TranslationsDownloadsDa extends TranslationsDownloadsEn {
@override String get unwatchedOnly => 'Kun usete';
@override String nextNUnwatched({required Object count}) => 'Næste ${count} usete';
@override String get customAmount => 'Angiv antal...';
@override String get includeSpecials => 'Inkludér specials';
@override String get howManyEpisodes => 'Hvor mange episoder?';
@override String itemsQueued({required Object count}) => '${count} elementer sat i kø til download';
@override String get keepSynced => 'Hold synkroniseret';
@@ -1755,6 +1759,7 @@ class _TranslationsLibrariesSortLabelsDa extends TranslationsLibrariesSortLabels
@override String get random => 'Tilfældig';
@override String get dateShared => 'Delt dato';
@override String get latestEpisodeAirDate => 'Seneste episodes premieredato';
@override String get lastEpisodeDateAdded => 'Dato for senest tilføjede episode';
}
// Path: companionRemote.session
@@ -2029,6 +2034,9 @@ extension on TranslationsDa {
'settings.continueWatchingAction' => 'Handling for Fortsæt med at se',
'settings.continueWatchingPlay' => 'Afspil',
'settings.continueWatchingDetails' => 'Åbn detaljer',
'settings.episodeAction' => 'Handling for afsnit',
'settings.episodePlay' => 'Afspil',
'settings.episodeDetails' => 'Åbn detaljer',
'settings.useGlobalHubs' => 'Brug startlayout',
'settings.useGlobalHubsDescription' => 'Vis samlet startsideindhold. Brug ellers biblioteksanbefalinger.',
'settings.showServerNameOnHubs' => 'Vis servernavn på hubbe',
@@ -2430,11 +2438,11 @@ extension on TranslationsDa {
'messages.logsUploaded' => 'Logs uploadet',
'messages.logsUploadFailed' => 'Kunne ikke uploade logs',
'messages.logId' => 'Log-ID',
_ => null,
} ?? switch (path) {
'subtitlingStyling.text' => 'Tekst',
'subtitlingStyling.border' => 'Kant',
'subtitlingStyling.background' => 'Baggrund',
_ => null,
} ?? switch (path) {
'subtitlingStyling.fontSize' => 'Skriftstørrelse',
'subtitlingStyling.textColor' => 'Tekstfarve',
'subtitlingStyling.borderSize' => 'Kantstørrelse',
@@ -2638,6 +2646,7 @@ extension on TranslationsDa {
'libraries.sortLabels.random' => 'Tilfældig',
'libraries.sortLabels.dateShared' => 'Delt dato',
'libraries.sortLabels.latestEpisodeAirDate' => 'Seneste episodes premieredato',
'libraries.sortLabels.lastEpisodeDateAdded' => 'Dato for senest tilføjede episode',
'about.title' => 'Om',
'about.openSourceLicenses' => 'Open source-licenser',
'about.versionLabel' => ({required Object version}) => 'Version ${version}',
@@ -2870,6 +2879,7 @@ extension on TranslationsDa {
'downloads.unwatchedOnly' => 'Kun usete',
'downloads.nextNUnwatched' => ({required Object count}) => 'Næste ${count} usete',
'downloads.customAmount' => 'Angiv antal...',
'downloads.includeSpecials' => 'Inkludér specials',
'downloads.howManyEpisodes' => 'Hvor mange episoder?',
'downloads.itemsQueued' => ({required Object count}) => '${count} elementer sat i kø til download',
'downloads.keepSynced' => 'Hold synkroniseret',
@@ -2942,13 +2952,13 @@ extension on TranslationsDa {
'companionRemote.pairing.authFailed' => 'Godkendelse mislykkedes. Begge enheder skal bruge samme Plex-konto.',
'companionRemote.pairing.failedToConnect' => ({required Object error}) => 'Kunne ikke oprette forbindelse: ${error}',
'companionRemote.remote.disconnectConfirm' => 'Vil du afbryde fra fjernsessionen?',
_ => null,
} ?? switch (path) {
'companionRemote.remote.reconnecting' => 'Genopretter forbindelse...',
'companionRemote.remote.attemptOf' => ({required Object current}) => 'Forsøg ${current} af 5',
'companionRemote.remote.retryNow' => 'Prøv igen nu',
'companionRemote.remote.tabRemote' => 'Fjernbetjening',
'companionRemote.remote.tabPlay' => 'Afspil',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabMore' => 'Mere',
'companionRemote.remote.menu' => 'Menu',
'companionRemote.remote.tabNavigation' => 'Fanenavigation',
+14 -4
View File
@@ -247,6 +247,9 @@ class _TranslationsSettingsDe extends TranslationsSettingsEn {
@override String get continueWatchingAction => 'Aktion für Weiterschauen';
@override String get continueWatchingPlay => 'Abspielen';
@override String get continueWatchingDetails => 'Details öffnen';
@override String get episodeAction => 'Episodenaktion';
@override String get episodePlay => 'Abspielen';
@override String get episodeDetails => 'Details öffnen';
@override String get useGlobalHubs => 'Startlayout verwenden';
@override String get useGlobalHubsDescription => 'Einheitliche Start-Hubs anzeigen. Sonst Bibliotheksempfehlungen verwenden.';
@override String get showServerNameOnHubs => 'Servername bei Hubs anzeigen';
@@ -1285,6 +1288,7 @@ class _TranslationsDownloadsDe extends TranslationsDownloadsEn {
@override String get unwatchedOnly => 'Nur ungesehene';
@override String nextNUnwatched({required Object count}) => 'Nächste ${count} ungesehene';
@override String get customAmount => 'Eigene Anzahl...';
@override String get includeSpecials => 'Specials einschließen';
@override String get howManyEpisodes => 'Wie viele Episoden?';
@override String itemsQueued({required Object count}) => '${count} Elemente zum Download eingereiht';
@override String get keepSynced => 'Synchronisiert halten';
@@ -1755,6 +1759,7 @@ class _TranslationsLibrariesSortLabelsDe extends TranslationsLibrariesSortLabels
@override String get random => 'Zufällig';
@override String get dateShared => 'Datum geteilt';
@override String get latestEpisodeAirDate => 'Letztes Folgenausstrahlungsdatum';
@override String get lastEpisodeDateAdded => 'Datum der zuletzt hinzugefügten Folge';
}
// Path: companionRemote.session
@@ -2029,6 +2034,9 @@ extension on TranslationsDe {
'settings.continueWatchingAction' => 'Aktion für Weiterschauen',
'settings.continueWatchingPlay' => 'Abspielen',
'settings.continueWatchingDetails' => 'Details öffnen',
'settings.episodeAction' => 'Episodenaktion',
'settings.episodePlay' => 'Abspielen',
'settings.episodeDetails' => 'Details öffnen',
'settings.useGlobalHubs' => 'Startlayout verwenden',
'settings.useGlobalHubsDescription' => 'Einheitliche Start-Hubs anzeigen. Sonst Bibliotheksempfehlungen verwenden.',
'settings.showServerNameOnHubs' => 'Servername bei Hubs anzeigen',
@@ -2430,11 +2438,11 @@ extension on TranslationsDe {
'messages.logsUploaded' => 'Protokolle hochgeladen',
'messages.logsUploadFailed' => 'Protokolle konnten nicht hochgeladen werden',
'messages.logId' => 'Protokoll-ID',
_ => null,
} ?? switch (path) {
'subtitlingStyling.text' => 'Text',
'subtitlingStyling.border' => 'Rahmen',
'subtitlingStyling.background' => 'Hintergrund',
_ => null,
} ?? switch (path) {
'subtitlingStyling.fontSize' => 'Schriftgröße',
'subtitlingStyling.textColor' => 'Textfarbe',
'subtitlingStyling.borderSize' => 'Rahmengröße',
@@ -2638,6 +2646,7 @@ extension on TranslationsDe {
'libraries.sortLabels.random' => 'Zufällig',
'libraries.sortLabels.dateShared' => 'Datum geteilt',
'libraries.sortLabels.latestEpisodeAirDate' => 'Letztes Folgenausstrahlungsdatum',
'libraries.sortLabels.lastEpisodeDateAdded' => 'Datum der zuletzt hinzugefügten Folge',
'about.title' => 'Über',
'about.openSourceLicenses' => 'Open-Source-Lizenzen',
'about.versionLabel' => ({required Object version}) => 'Version ${version}',
@@ -2870,6 +2879,7 @@ extension on TranslationsDe {
'downloads.unwatchedOnly' => 'Nur ungesehene',
'downloads.nextNUnwatched' => ({required Object count}) => 'Nächste ${count} ungesehene',
'downloads.customAmount' => 'Eigene Anzahl...',
'downloads.includeSpecials' => 'Specials einschließen',
'downloads.howManyEpisodes' => 'Wie viele Episoden?',
'downloads.itemsQueued' => ({required Object count}) => '${count} Elemente zum Download eingereiht',
'downloads.keepSynced' => 'Synchronisiert halten',
@@ -2942,13 +2952,13 @@ extension on TranslationsDe {
'companionRemote.pairing.authFailed' => 'Authentifizierung fehlgeschlagen. Beide Geräte benötigen dasselbe Plex-Konto.',
'companionRemote.pairing.failedToConnect' => ({required Object error}) => 'Verbindung fehlgeschlagen: ${error}',
'companionRemote.remote.disconnectConfirm' => 'Möchtest du die Verbindung zur Fernsteuerungssitzung trennen?',
_ => null,
} ?? switch (path) {
'companionRemote.remote.reconnecting' => 'Verbindung wird wiederhergestellt...',
'companionRemote.remote.attemptOf' => ({required Object current}) => 'Versuch ${current} von 5',
'companionRemote.remote.retryNow' => 'Jetzt wiederholen',
'companionRemote.remote.tabRemote' => 'Fernbedienung',
'companionRemote.remote.tabPlay' => 'Wiedergabe',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabMore' => 'Mehr',
'companionRemote.remote.menu' => 'Menü',
'companionRemote.remote.tabNavigation' => 'Tab-Navigation',
+24 -4
View File
@@ -465,6 +465,15 @@ class TranslationsSettingsEn {
/// en: 'Open Details'
String get continueWatchingDetails => 'Open Details';
/// en: 'Episode Action'
String get episodeAction => 'Episode Action';
/// en: 'Play'
String get episodePlay => 'Play';
/// en: 'Open Details'
String get episodeDetails => 'Open Details';
/// en: 'Use Home Layout'
String get useGlobalHubs => 'Use Home Layout';
@@ -3075,6 +3084,9 @@ class TranslationsDownloadsEn {
/// en: 'Custom amount...'
String get customAmount => 'Custom amount...';
/// en: 'Include Specials'
String get includeSpecials => 'Include Specials';
/// en: 'How many episodes?'
String get howManyEpisodes => 'How many episodes?';
@@ -4164,6 +4176,9 @@ class TranslationsLibrariesSortLabelsEn {
/// en: 'Latest Episode Air Date'
String get latestEpisodeAirDate => 'Latest Episode Air Date';
/// en: 'Last Episode Date Added'
String get lastEpisodeDateAdded => 'Last Episode Date Added';
}
// Path: companionRemote.session
@@ -4606,6 +4621,9 @@ extension on Translations {
'settings.continueWatchingAction' => 'Continue Watching Action',
'settings.continueWatchingPlay' => 'Play',
'settings.continueWatchingDetails' => 'Open Details',
'settings.episodeAction' => 'Episode Action',
'settings.episodePlay' => 'Play',
'settings.episodeDetails' => 'Open Details',
'settings.useGlobalHubs' => 'Use Home Layout',
'settings.useGlobalHubsDescription' => 'Show unified home hubs. Otherwise use library recommendations.',
'settings.showServerNameOnHubs' => 'Show Server Name on Hubs',
@@ -5007,11 +5025,11 @@ extension on Translations {
'messages.noItemsAvailable' => 'No items available',
'messages.failedToCreatePlayQueueNoItems' => 'Failed to create play queue - no items',
'messages.failedPlayback' => ({required Object action, required Object error}) => 'Failed to ${action}: ${error}',
_ => null,
} ?? switch (path) {
'messages.switchingToCompatiblePlayer' => 'Switching to compatible player...',
'messages.serverLimitTitle' => 'Playback failed',
'messages.serverLimitBody' => 'Server error (HTTP 500). A bandwidth/transcoding limit likely rejected this session. Ask the owner to adjust it.',
_ => null,
} ?? switch (path) {
'messages.logsUploaded' => 'Logs uploaded',
'messages.logsUploadFailed' => 'Failed to upload logs',
'messages.logId' => 'Log ID',
@@ -5221,6 +5239,7 @@ extension on Translations {
'libraries.sortLabels.random' => 'Random',
'libraries.sortLabels.dateShared' => 'Date Shared',
'libraries.sortLabels.latestEpisodeAirDate' => 'Latest Episode Air Date',
'libraries.sortLabels.lastEpisodeDateAdded' => 'Last Episode Date Added',
'about.title' => 'About',
'about.openSourceLicenses' => 'Open Source Licenses',
'about.versionLabel' => ({required Object version}) => 'Version ${version}',
@@ -5456,6 +5475,7 @@ extension on Translations {
'downloads.unwatchedOnly' => 'Unwatched only',
'downloads.nextNUnwatched' => ({required Object count}) => 'Next ${count} unwatched',
'downloads.customAmount' => 'Custom amount...',
'downloads.includeSpecials' => 'Include Specials',
'downloads.howManyEpisodes' => 'How many episodes?',
'downloads.itemsQueued' => ({required Object count}) => '${count} items queued for download',
'downloads.keepSynced' => 'Keep synced',
@@ -5519,13 +5539,13 @@ extension on Translations {
'companionRemote.pairing.noDevicesFound' => 'No devices found on your network',
'companionRemote.pairing.noDevicesHint' => 'Open Plezy on desktop and use the same WiFi',
'companionRemote.pairing.availableDevices' => 'Available Devices',
_ => null,
} ?? switch (path) {
'companionRemote.pairing.manualConnection' => 'Manual Connection',
'companionRemote.pairing.cryptoInitFailed' => 'Couldn\'t start secure connection. Sign in to Plex first.',
'companionRemote.pairing.validationHostRequired' => 'Please enter host address',
'companionRemote.pairing.validationHostFormat' => 'Format must be IP:port (e.g., 192.168.1.100:48632)',
'companionRemote.pairing.connectionTimedOut' => 'Connection timed out. Use the same network on both devices.',
_ => null,
} ?? switch (path) {
'companionRemote.pairing.sessionNotFound' => 'Device not found. Make sure Plezy is running on the host.',
'companionRemote.pairing.authFailed' => 'Authentication failed. Both devices need the same Plex account.',
'companionRemote.pairing.failedToConnect' => ({required Object error}) => 'Failed to connect: ${error}',
+14 -4
View File
@@ -247,6 +247,9 @@ class _TranslationsSettingsEs extends TranslationsSettingsEn {
@override String get continueWatchingAction => 'Acción de Seguir viendo';
@override String get continueWatchingPlay => 'Reproducir';
@override String get continueWatchingDetails => 'Abrir detalles';
@override String get episodeAction => 'Acción de episodio';
@override String get episodePlay => 'Reproducir';
@override String get episodeDetails => 'Abrir detalles';
@override String get useGlobalHubs => 'Usar diseño de inicio';
@override String get useGlobalHubsDescription => 'Mostrar hubs de inicio unificados. Si no, usar recomendaciones de biblioteca.';
@override String get showServerNameOnHubs => 'Mostrar Nombre del Servidor en los Hubs';
@@ -1285,6 +1288,7 @@ class _TranslationsDownloadsEs extends TranslationsDownloadsEn {
@override String get unwatchedOnly => 'Solo no vistos';
@override String nextNUnwatched({required Object count}) => 'Próximos ${count} no vistos';
@override String get customAmount => 'Cantidad personalizada...';
@override String get includeSpecials => 'Incluir especiales';
@override String get howManyEpisodes => '¿Cuántos episodios?';
@override String itemsQueued({required Object count}) => '${count} elementos en cola de descarga';
@override String get keepSynced => 'Mantener sincronizado';
@@ -1755,6 +1759,7 @@ class _TranslationsLibrariesSortLabelsEs extends TranslationsLibrariesSortLabels
@override String get random => 'Aleatorio';
@override String get dateShared => 'Fecha de compartición';
@override String get latestEpisodeAirDate => 'Última fecha de emisión del episodio';
@override String get lastEpisodeDateAdded => 'Fecha de adición del último episodio';
}
// Path: companionRemote.session
@@ -2029,6 +2034,9 @@ extension on TranslationsEs {
'settings.continueWatchingAction' => 'Acción de Seguir viendo',
'settings.continueWatchingPlay' => 'Reproducir',
'settings.continueWatchingDetails' => 'Abrir detalles',
'settings.episodeAction' => 'Acción de episodio',
'settings.episodePlay' => 'Reproducir',
'settings.episodeDetails' => 'Abrir detalles',
'settings.useGlobalHubs' => 'Usar diseño de inicio',
'settings.useGlobalHubsDescription' => 'Mostrar hubs de inicio unificados. Si no, usar recomendaciones de biblioteca.',
'settings.showServerNameOnHubs' => 'Mostrar Nombre del Servidor en los Hubs',
@@ -2430,11 +2438,11 @@ extension on TranslationsEs {
'messages.logsUploaded' => 'Registros subidos',
'messages.logsUploadFailed' => 'Error al subir registros',
'messages.logId' => 'ID de registro',
_ => null,
} ?? switch (path) {
'subtitlingStyling.text' => 'Texto',
'subtitlingStyling.border' => 'Borde',
'subtitlingStyling.background' => 'Fondo',
_ => null,
} ?? switch (path) {
'subtitlingStyling.fontSize' => 'Tamaño de Fuente',
'subtitlingStyling.textColor' => 'Color de Texto',
'subtitlingStyling.borderSize' => 'Tamaño de Borde',
@@ -2638,6 +2646,7 @@ extension on TranslationsEs {
'libraries.sortLabels.random' => 'Aleatorio',
'libraries.sortLabels.dateShared' => 'Fecha de compartición',
'libraries.sortLabels.latestEpisodeAirDate' => 'Última fecha de emisión del episodio',
'libraries.sortLabels.lastEpisodeDateAdded' => 'Fecha de adición del último episodio',
'about.title' => 'Acerca de',
'about.openSourceLicenses' => 'Licencias de Código Abierto',
'about.versionLabel' => ({required Object version}) => 'Versión ${version}',
@@ -2870,6 +2879,7 @@ extension on TranslationsEs {
'downloads.unwatchedOnly' => 'Solo no vistos',
'downloads.nextNUnwatched' => ({required Object count}) => 'Próximos ${count} no vistos',
'downloads.customAmount' => 'Cantidad personalizada...',
'downloads.includeSpecials' => 'Incluir especiales',
'downloads.howManyEpisodes' => '¿Cuántos episodios?',
'downloads.itemsQueued' => ({required Object count}) => '${count} elementos en cola de descarga',
'downloads.keepSynced' => 'Mantener sincronizado',
@@ -2942,13 +2952,13 @@ extension on TranslationsEs {
'companionRemote.pairing.authFailed' => 'Autenticación fallida. Ambos dispositivos necesitan la misma cuenta Plex.',
'companionRemote.pairing.failedToConnect' => ({required Object error}) => 'Error al conectar: ${error}',
'companionRemote.remote.disconnectConfirm' => '¿Quieres desconectarte de la sesión remota?',
_ => null,
} ?? switch (path) {
'companionRemote.remote.reconnecting' => 'Reconectando...',
'companionRemote.remote.attemptOf' => ({required Object current}) => 'Intento ${current} de 5',
'companionRemote.remote.retryNow' => 'Reintentar ahora',
'companionRemote.remote.tabRemote' => 'Remoto',
'companionRemote.remote.tabPlay' => 'Reproducir',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabMore' => 'Más',
'companionRemote.remote.menu' => 'Menú',
'companionRemote.remote.tabNavigation' => 'Navegación por pestañas',
+14 -4
View File
@@ -247,6 +247,9 @@ class _TranslationsSettingsFr extends TranslationsSettingsEn {
@override String get continueWatchingAction => 'Action Continuer à regarder';
@override String get continueWatchingPlay => 'Lire';
@override String get continueWatchingDetails => 'Ouvrir les détails';
@override String get episodeAction => 'Action des épisodes';
@override String get episodePlay => 'Lire';
@override String get episodeDetails => 'Ouvrir les détails';
@override String get useGlobalHubs => 'Utiliser la mise en page d\'accueil';
@override String get useGlobalHubsDescription => 'Afficher des hubs d\'accueil unifiés. Sinon, utiliser les recommandations de bibliothèque.';
@override String get showServerNameOnHubs => 'Afficher le nom du serveur sur les hubs';
@@ -1285,6 +1288,7 @@ class _TranslationsDownloadsFr extends TranslationsDownloadsEn {
@override String get unwatchedOnly => 'Non vus uniquement';
@override String nextNUnwatched({required Object count}) => '${count} prochains non vus';
@override String get customAmount => 'Quantité personnalisée...';
@override String get includeSpecials => 'Inclure les spéciaux';
@override String get howManyEpisodes => 'Combien d\'épisodes ?';
@override String itemsQueued({required Object count}) => '${count} éléments mis en file d\'attente';
@override String get keepSynced => 'Garder synchronisé';
@@ -1755,6 +1759,7 @@ class _TranslationsLibrariesSortLabelsFr extends TranslationsLibrariesSortLabels
@override String get random => 'Aléatoire';
@override String get dateShared => 'Date de partage';
@override String get latestEpisodeAirDate => 'Dernière date de diffusion';
@override String get lastEpisodeDateAdded => 'Date d\'ajout du dernier épisode';
}
// Path: companionRemote.session
@@ -2029,6 +2034,9 @@ extension on TranslationsFr {
'settings.continueWatchingAction' => 'Action Continuer à regarder',
'settings.continueWatchingPlay' => 'Lire',
'settings.continueWatchingDetails' => 'Ouvrir les détails',
'settings.episodeAction' => 'Action des épisodes',
'settings.episodePlay' => 'Lire',
'settings.episodeDetails' => 'Ouvrir les détails',
'settings.useGlobalHubs' => 'Utiliser la mise en page d\'accueil',
'settings.useGlobalHubsDescription' => 'Afficher des hubs d\'accueil unifiés. Sinon, utiliser les recommandations de bibliothèque.',
'settings.showServerNameOnHubs' => 'Afficher le nom du serveur sur les hubs',
@@ -2430,11 +2438,11 @@ extension on TranslationsFr {
'messages.logsUploaded' => 'Logs envoyés',
'messages.logsUploadFailed' => 'Échec de l\'envoi des logs',
'messages.logId' => 'ID du log',
_ => null,
} ?? switch (path) {
'subtitlingStyling.text' => 'Texte',
'subtitlingStyling.border' => 'Bordure',
'subtitlingStyling.background' => 'Arrière-plan',
_ => null,
} ?? switch (path) {
'subtitlingStyling.fontSize' => 'Taille de la police',
'subtitlingStyling.textColor' => 'Couleur du texte',
'subtitlingStyling.borderSize' => 'Taille de la bordure',
@@ -2638,6 +2646,7 @@ extension on TranslationsFr {
'libraries.sortLabels.random' => 'Aléatoire',
'libraries.sortLabels.dateShared' => 'Date de partage',
'libraries.sortLabels.latestEpisodeAirDate' => 'Dernière date de diffusion',
'libraries.sortLabels.lastEpisodeDateAdded' => 'Date d\'ajout du dernier épisode',
'about.title' => 'À propos',
'about.openSourceLicenses' => 'Licences Open Source',
'about.versionLabel' => ({required Object version}) => 'Version ${version}',
@@ -2870,6 +2879,7 @@ extension on TranslationsFr {
'downloads.unwatchedOnly' => 'Non vus uniquement',
'downloads.nextNUnwatched' => ({required Object count}) => '${count} prochains non vus',
'downloads.customAmount' => 'Quantité personnalisée...',
'downloads.includeSpecials' => 'Inclure les spéciaux',
'downloads.howManyEpisodes' => 'Combien d\'épisodes ?',
'downloads.itemsQueued' => ({required Object count}) => '${count} éléments mis en file d\'attente',
'downloads.keepSynced' => 'Garder synchronisé',
@@ -2942,13 +2952,13 @@ extension on TranslationsFr {
'companionRemote.pairing.authFailed' => 'Échec de l\'authentification. Les deux appareils doivent utiliser le même compte Plex.',
'companionRemote.pairing.failedToConnect' => ({required Object error}) => 'Échec de la connexion : ${error}',
'companionRemote.remote.disconnectConfirm' => 'Voulez-vous vous déconnecter de la session distante ?',
_ => null,
} ?? switch (path) {
'companionRemote.remote.reconnecting' => 'Reconnexion...',
'companionRemote.remote.attemptOf' => ({required Object current}) => 'Tentative ${current} sur 5',
'companionRemote.remote.retryNow' => 'Réessayer maintenant',
'companionRemote.remote.tabRemote' => 'Télécommande',
'companionRemote.remote.tabPlay' => 'Lecture',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabMore' => 'Plus',
'companionRemote.remote.menu' => 'Menu',
'companionRemote.remote.tabNavigation' => 'Navigation par onglets',
+14 -4
View File
@@ -247,6 +247,9 @@ class _TranslationsSettingsIt extends TranslationsSettingsEn {
@override String get continueWatchingAction => 'Azione Continua a guardare';
@override String get continueWatchingPlay => 'Riproduci';
@override String get continueWatchingDetails => 'Apri dettagli';
@override String get episodeAction => 'Azione episodio';
@override String get episodePlay => 'Riproduci';
@override String get episodeDetails => 'Apri dettagli';
@override String get useGlobalHubs => 'Usa layout home';
@override String get useGlobalHubsDescription => 'Mostra hub Home unificati. Altrimenti usa i consigli della libreria.';
@override String get showServerNameOnHubs => 'Mostra nome server sugli hub';
@@ -1285,6 +1288,7 @@ class _TranslationsDownloadsIt extends TranslationsDownloadsEn {
@override String get unwatchedOnly => 'Solo non visti';
@override String nextNUnwatched({required Object count}) => 'Prossimi ${count} non visti';
@override String get customAmount => 'Quantità personalizzata...';
@override String get includeSpecials => 'Includi gli speciali';
@override String get howManyEpisodes => 'Quanti episodi?';
@override String itemsQueued({required Object count}) => '${count} elementi in coda per il download';
@override String get keepSynced => 'Mantieni sincronizzato';
@@ -1755,6 +1759,7 @@ class _TranslationsLibrariesSortLabelsIt extends TranslationsLibrariesSortLabels
@override String get random => 'Casuale';
@override String get dateShared => 'Data di condivisione';
@override String get latestEpisodeAirDate => 'Data ultima messa in onda';
@override String get lastEpisodeDateAdded => 'Data aggiunta ultimo episodio';
}
// Path: companionRemote.session
@@ -2029,6 +2034,9 @@ extension on TranslationsIt {
'settings.continueWatchingAction' => 'Azione Continua a guardare',
'settings.continueWatchingPlay' => 'Riproduci',
'settings.continueWatchingDetails' => 'Apri dettagli',
'settings.episodeAction' => 'Azione episodio',
'settings.episodePlay' => 'Riproduci',
'settings.episodeDetails' => 'Apri dettagli',
'settings.useGlobalHubs' => 'Usa layout home',
'settings.useGlobalHubsDescription' => 'Mostra hub Home unificati. Altrimenti usa i consigli della libreria.',
'settings.showServerNameOnHubs' => 'Mostra nome server sugli hub',
@@ -2430,11 +2438,11 @@ extension on TranslationsIt {
'messages.logsUploaded' => 'Log caricati',
'messages.logsUploadFailed' => 'Caricamento log fallito',
'messages.logId' => 'ID log',
_ => null,
} ?? switch (path) {
'subtitlingStyling.text' => 'Testo',
'subtitlingStyling.border' => 'Bordo',
'subtitlingStyling.background' => 'Sfondo',
_ => null,
} ?? switch (path) {
'subtitlingStyling.fontSize' => 'Dimensione',
'subtitlingStyling.textColor' => 'Colore testo',
'subtitlingStyling.borderSize' => 'Dimensione bordo',
@@ -2638,6 +2646,7 @@ extension on TranslationsIt {
'libraries.sortLabels.random' => 'Casuale',
'libraries.sortLabels.dateShared' => 'Data di condivisione',
'libraries.sortLabels.latestEpisodeAirDate' => 'Data ultima messa in onda',
'libraries.sortLabels.lastEpisodeDateAdded' => 'Data aggiunta ultimo episodio',
'about.title' => 'Informazioni',
'about.openSourceLicenses' => 'Licenze Open Source',
'about.versionLabel' => ({required Object version}) => 'Versione ${version}',
@@ -2870,6 +2879,7 @@ extension on TranslationsIt {
'downloads.unwatchedOnly' => 'Solo non visti',
'downloads.nextNUnwatched' => ({required Object count}) => 'Prossimi ${count} non visti',
'downloads.customAmount' => 'Quantità personalizzata...',
'downloads.includeSpecials' => 'Includi gli speciali',
'downloads.howManyEpisodes' => 'Quanti episodi?',
'downloads.itemsQueued' => ({required Object count}) => '${count} elementi in coda per il download',
'downloads.keepSynced' => 'Mantieni sincronizzato',
@@ -2942,13 +2952,13 @@ extension on TranslationsIt {
'companionRemote.pairing.authFailed' => 'Autenticazione non riuscita. Entrambi i dispositivi devono usare lo stesso account Plex.',
'companionRemote.pairing.failedToConnect' => ({required Object error}) => 'Connessione fallita: ${error}',
'companionRemote.remote.disconnectConfirm' => 'Vuoi disconnetterti dalla sessione remota?',
_ => null,
} ?? switch (path) {
'companionRemote.remote.reconnecting' => 'Riconnessione...',
'companionRemote.remote.attemptOf' => ({required Object current}) => 'Tentativo ${current} di 5',
'companionRemote.remote.retryNow' => 'Riprova ora',
'companionRemote.remote.tabRemote' => 'Telecomando',
'companionRemote.remote.tabPlay' => 'Riproduci',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabMore' => 'Altro',
'companionRemote.remote.menu' => 'Menu',
'companionRemote.remote.tabNavigation' => 'Navigazione schede',
+14 -4
View File
@@ -247,6 +247,9 @@ class _TranslationsSettingsJa extends TranslationsSettingsEn {
@override String get continueWatchingAction => '視聴中の操作';
@override String get continueWatchingPlay => '再生';
@override String get continueWatchingDetails => '詳細を開く';
@override String get episodeAction => 'エピソードの操作';
@override String get episodePlay => '再生';
@override String get episodeDetails => '詳細を開く';
@override String get useGlobalHubs => 'ホームレイアウトを使用';
@override String get useGlobalHubsDescription => '統合ホームハブを表示します。オフの場合はライブラリのおすすめを使用します。';
@override String get showServerNameOnHubs => 'ハブにサーバー名を表示';
@@ -1285,6 +1288,7 @@ class _TranslationsDownloadsJa extends TranslationsDownloadsEn {
@override String get unwatchedOnly => '未視聴のみ';
@override String nextNUnwatched({required Object count}) => '次の${count}件の未視聴';
@override String get customAmount => '数を指定...';
@override String get includeSpecials => 'スペシャルを含める';
@override String get howManyEpisodes => '何エピソード?';
@override String itemsQueued({required Object count}) => '${count}件をダウンロードキューに追加';
@override String get keepSynced => '同期を維持';
@@ -1755,6 +1759,7 @@ class _TranslationsLibrariesSortLabelsJa extends TranslationsLibrariesSortLabels
@override String get random => 'ランダム';
@override String get dateShared => '共有日';
@override String get latestEpisodeAirDate => '最新エピソード放送日';
@override String get lastEpisodeDateAdded => '最新エピソード追加日';
}
// Path: companionRemote.session
@@ -2029,6 +2034,9 @@ extension on TranslationsJa {
'settings.continueWatchingAction' => '視聴中の操作',
'settings.continueWatchingPlay' => '再生',
'settings.continueWatchingDetails' => '詳細を開く',
'settings.episodeAction' => 'エピソードの操作',
'settings.episodePlay' => '再生',
'settings.episodeDetails' => '詳細を開く',
'settings.useGlobalHubs' => 'ホームレイアウトを使用',
'settings.useGlobalHubsDescription' => '統合ホームハブを表示します。オフの場合はライブラリのおすすめを使用します。',
'settings.showServerNameOnHubs' => 'ハブにサーバー名を表示',
@@ -2430,11 +2438,11 @@ extension on TranslationsJa {
'messages.logsUploaded' => 'ログをアップロードしました',
'messages.logsUploadFailed' => 'ログのアップロードに失敗しました',
'messages.logId' => 'ログID',
_ => null,
} ?? switch (path) {
'subtitlingStyling.text' => 'テキスト',
'subtitlingStyling.border' => '枠線',
'subtitlingStyling.background' => '背景',
_ => null,
} ?? switch (path) {
'subtitlingStyling.fontSize' => 'フォントサイズ',
'subtitlingStyling.textColor' => 'テキストの色',
'subtitlingStyling.borderSize' => '枠線サイズ',
@@ -2638,6 +2646,7 @@ extension on TranslationsJa {
'libraries.sortLabels.random' => 'ランダム',
'libraries.sortLabels.dateShared' => '共有日',
'libraries.sortLabels.latestEpisodeAirDate' => '最新エピソード放送日',
'libraries.sortLabels.lastEpisodeDateAdded' => '最新エピソード追加日',
'about.title' => 'アプリについて',
'about.openSourceLicenses' => 'オープンソースライセンス',
'about.versionLabel' => ({required Object version}) => 'バージョン ${version}',
@@ -2870,6 +2879,7 @@ extension on TranslationsJa {
'downloads.unwatchedOnly' => '未視聴のみ',
'downloads.nextNUnwatched' => ({required Object count}) => '次の${count}件の未視聴',
'downloads.customAmount' => '数を指定...',
'downloads.includeSpecials' => 'スペシャルを含める',
'downloads.howManyEpisodes' => '何エピソード?',
'downloads.itemsQueued' => ({required Object count}) => '${count}件をダウンロードキューに追加',
'downloads.keepSynced' => '同期を維持',
@@ -2942,13 +2952,13 @@ extension on TranslationsJa {
'companionRemote.pairing.authFailed' => '認証に失敗しました。両方のデバイスで同じPlexアカウントが必要です。',
'companionRemote.pairing.failedToConnect' => ({required Object error}) => '接続に失敗しました: ${error}',
'companionRemote.remote.disconnectConfirm' => 'リモートセッションから切断しますか?',
_ => null,
} ?? switch (path) {
'companionRemote.remote.reconnecting' => '再接続中...',
'companionRemote.remote.attemptOf' => ({required Object current}) => '試行 ${current}/5',
'companionRemote.remote.retryNow' => '今すぐ再試行',
'companionRemote.remote.tabRemote' => 'リモート',
'companionRemote.remote.tabPlay' => '再生',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabMore' => 'その他',
'companionRemote.remote.menu' => 'メニュー',
'companionRemote.remote.tabNavigation' => 'タブナビゲーション',
+14 -4
View File
@@ -247,6 +247,9 @@ class _TranslationsSettingsKo extends TranslationsSettingsEn {
@override String get continueWatchingAction => '계속 보기 동작';
@override String get continueWatchingPlay => '재생';
@override String get continueWatchingDetails => '상세 정보 열기';
@override String get episodeAction => '에피소드 동작';
@override String get episodePlay => '재생';
@override String get episodeDetails => '상세 정보 열기';
@override String get useGlobalHubs => '홈 레이아웃 사용';
@override String get useGlobalHubsDescription => '통합 홈 허브를 표시합니다. 끄면 라이브러리 추천을 사용합니다.';
@override String get showServerNameOnHubs => '허브에 서버 이름 표시';
@@ -1285,6 +1288,7 @@ class _TranslationsDownloadsKo extends TranslationsDownloadsEn {
@override String get unwatchedOnly => '시청하지 않은 것만';
@override String nextNUnwatched({required Object count}) => '다음 ${count}개 미시청';
@override String get customAmount => '직접 입력...';
@override String get includeSpecials => '스페셜 포함';
@override String get howManyEpisodes => '몇 개의 에피소드?';
@override String itemsQueued({required Object count}) => '${count}개 항목이 다운로드 대기열에 추가됨';
@override String get keepSynced => '동기화 유지';
@@ -1755,6 +1759,7 @@ class _TranslationsLibrariesSortLabelsKo extends TranslationsLibrariesSortLabels
@override String get random => '무작위';
@override String get dateShared => '공유된 날짜';
@override String get latestEpisodeAirDate => '최신 에피소드 방영일';
@override String get lastEpisodeDateAdded => '최신 에피소드 추가일';
}
// Path: companionRemote.session
@@ -2029,6 +2034,9 @@ extension on TranslationsKo {
'settings.continueWatchingAction' => '계속 보기 동작',
'settings.continueWatchingPlay' => '재생',
'settings.continueWatchingDetails' => '상세 정보 열기',
'settings.episodeAction' => '에피소드 동작',
'settings.episodePlay' => '재생',
'settings.episodeDetails' => '상세 정보 열기',
'settings.useGlobalHubs' => '홈 레이아웃 사용',
'settings.useGlobalHubsDescription' => '통합 홈 허브를 표시합니다. 끄면 라이브러리 추천을 사용합니다.',
'settings.showServerNameOnHubs' => '허브에 서버 이름 표시',
@@ -2430,11 +2438,11 @@ extension on TranslationsKo {
'messages.logsUploaded' => '로그 업로드 완료',
'messages.logsUploadFailed' => '로그 업로드 실패',
'messages.logId' => '로그 ID',
_ => null,
} ?? switch (path) {
'subtitlingStyling.text' => '텍스트',
'subtitlingStyling.border' => '테두리',
'subtitlingStyling.background' => '배경',
_ => null,
} ?? switch (path) {
'subtitlingStyling.fontSize' => '글자 크기',
'subtitlingStyling.textColor' => '텍스트 색상',
'subtitlingStyling.borderSize' => '테두리 크기',
@@ -2638,6 +2646,7 @@ extension on TranslationsKo {
'libraries.sortLabels.random' => '무작위',
'libraries.sortLabels.dateShared' => '공유된 날짜',
'libraries.sortLabels.latestEpisodeAirDate' => '최신 에피소드 방영일',
'libraries.sortLabels.lastEpisodeDateAdded' => '최신 에피소드 추가일',
'about.title' => '소개',
'about.openSourceLicenses' => '오픈소스 라이선스',
'about.versionLabel' => ({required Object version}) => '버전 ${version}',
@@ -2870,6 +2879,7 @@ extension on TranslationsKo {
'downloads.unwatchedOnly' => '시청하지 않은 것만',
'downloads.nextNUnwatched' => ({required Object count}) => '다음 ${count}개 미시청',
'downloads.customAmount' => '직접 입력...',
'downloads.includeSpecials' => '스페셜 포함',
'downloads.howManyEpisodes' => '몇 개의 에피소드?',
'downloads.itemsQueued' => ({required Object count}) => '${count}개 항목이 다운로드 대기열에 추가됨',
'downloads.keepSynced' => '동기화 유지',
@@ -2942,13 +2952,13 @@ extension on TranslationsKo {
'companionRemote.pairing.authFailed' => '인증에 실패했습니다. 두 기기 모두 같은 Plex 계정이 필요합니다.',
'companionRemote.pairing.failedToConnect' => ({required Object error}) => '연결 실패: ${error}',
'companionRemote.remote.disconnectConfirm' => '원격 세션 연결을 해제하시겠습니까?',
_ => null,
} ?? switch (path) {
'companionRemote.remote.reconnecting' => '재연결 중...',
'companionRemote.remote.attemptOf' => ({required Object current}) => '${current}/5 시도 중',
'companionRemote.remote.retryNow' => '지금 재시도',
'companionRemote.remote.tabRemote' => '리모컨',
'companionRemote.remote.tabPlay' => '재생',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabMore' => '더 보기',
'companionRemote.remote.menu' => '메뉴',
'companionRemote.remote.tabNavigation' => '탭 탐색',
+14 -4
View File
@@ -247,6 +247,9 @@ class _TranslationsSettingsNb extends TranslationsSettingsEn {
@override String get continueWatchingAction => 'Handling for Fortsett å se';
@override String get continueWatchingPlay => 'Spill av';
@override String get continueWatchingDetails => 'Åpne detaljer';
@override String get episodeAction => 'Handling for episoder';
@override String get episodePlay => 'Spill av';
@override String get episodeDetails => 'Åpne detaljer';
@override String get useGlobalHubs => 'Bruk startoppsett';
@override String get useGlobalHubsDescription => 'Vis samlet startinnhold. Ellers brukes bibliotekanbefalinger.';
@override String get showServerNameOnHubs => 'Vis servernavn på huber';
@@ -1285,6 +1288,7 @@ class _TranslationsDownloadsNb extends TranslationsDownloadsEn {
@override String get unwatchedOnly => 'Kun usette';
@override String nextNUnwatched({required Object count}) => 'Neste ${count} usette';
@override String get customAmount => 'Egendefinert antall...';
@override String get includeSpecials => 'Inkluder spesialepisoder';
@override String get howManyEpisodes => 'Hvor mange episoder?';
@override String itemsQueued({required Object count}) => '${count} elementer i nedlastingskø';
@override String get keepSynced => 'Hold synkronisert';
@@ -1755,6 +1759,7 @@ class _TranslationsLibrariesSortLabelsNb extends TranslationsLibrariesSortLabels
@override String get random => 'Tilfeldig';
@override String get dateShared => 'Delingsdato';
@override String get latestEpisodeAirDate => 'Siste episodes sendedato';
@override String get lastEpisodeDateAdded => 'Dato for sist lagt til episode';
}
// Path: companionRemote.session
@@ -2029,6 +2034,9 @@ extension on TranslationsNb {
'settings.continueWatchingAction' => 'Handling for Fortsett å se',
'settings.continueWatchingPlay' => 'Spill av',
'settings.continueWatchingDetails' => 'Åpne detaljer',
'settings.episodeAction' => 'Handling for episoder',
'settings.episodePlay' => 'Spill av',
'settings.episodeDetails' => 'Åpne detaljer',
'settings.useGlobalHubs' => 'Bruk startoppsett',
'settings.useGlobalHubsDescription' => 'Vis samlet startinnhold. Ellers brukes bibliotekanbefalinger.',
'settings.showServerNameOnHubs' => 'Vis servernavn på huber',
@@ -2430,11 +2438,11 @@ extension on TranslationsNb {
'messages.logsUploaded' => 'Logger lastet opp',
'messages.logsUploadFailed' => 'Kunne ikke laste opp logger',
'messages.logId' => 'Logg-ID',
_ => null,
} ?? switch (path) {
'subtitlingStyling.text' => 'Tekst',
'subtitlingStyling.border' => 'Kantlinje',
'subtitlingStyling.background' => 'Bakgrunn',
_ => null,
} ?? switch (path) {
'subtitlingStyling.fontSize' => 'Skriftstørrelse',
'subtitlingStyling.textColor' => 'Tekstfarge',
'subtitlingStyling.borderSize' => 'Kantstørrelse',
@@ -2638,6 +2646,7 @@ extension on TranslationsNb {
'libraries.sortLabels.random' => 'Tilfeldig',
'libraries.sortLabels.dateShared' => 'Delingsdato',
'libraries.sortLabels.latestEpisodeAirDate' => 'Siste episodes sendedato',
'libraries.sortLabels.lastEpisodeDateAdded' => 'Dato for sist lagt til episode',
'about.title' => 'Om',
'about.openSourceLicenses' => 'Åpen kildekode-lisenser',
'about.versionLabel' => ({required Object version}) => 'Versjon ${version}',
@@ -2870,6 +2879,7 @@ extension on TranslationsNb {
'downloads.unwatchedOnly' => 'Kun usette',
'downloads.nextNUnwatched' => ({required Object count}) => 'Neste ${count} usette',
'downloads.customAmount' => 'Egendefinert antall...',
'downloads.includeSpecials' => 'Inkluder spesialepisoder',
'downloads.howManyEpisodes' => 'Hvor mange episoder?',
'downloads.itemsQueued' => ({required Object count}) => '${count} elementer i nedlastingskø',
'downloads.keepSynced' => 'Hold synkronisert',
@@ -2942,13 +2952,13 @@ extension on TranslationsNb {
'companionRemote.pairing.authFailed' => 'Autentisering mislyktes. Begge enheter må bruke samme Plex-konto.',
'companionRemote.pairing.failedToConnect' => ({required Object error}) => 'Kunne ikke koble til: ${error}',
'companionRemote.remote.disconnectConfirm' => 'Vil du koble fra fjernøkten?',
_ => null,
} ?? switch (path) {
'companionRemote.remote.reconnecting' => 'Kobler til på nytt...',
'companionRemote.remote.attemptOf' => ({required Object current}) => 'Forsøk ${current} av 5',
'companionRemote.remote.retryNow' => 'Prøv nå',
'companionRemote.remote.tabRemote' => 'Fjernkontroll',
'companionRemote.remote.tabPlay' => 'Spill av',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabMore' => 'Mer',
'companionRemote.remote.menu' => 'Meny',
'companionRemote.remote.tabNavigation' => 'Fanenavigering',
+14 -4
View File
@@ -247,6 +247,9 @@ class _TranslationsSettingsNl extends TranslationsSettingsEn {
@override String get continueWatchingAction => 'Actie voor Doorgaan met kijken';
@override String get continueWatchingPlay => 'Afspelen';
@override String get continueWatchingDetails => 'Details openen';
@override String get episodeAction => 'Afleveringsactie';
@override String get episodePlay => 'Afspelen';
@override String get episodeDetails => 'Details openen';
@override String get useGlobalHubs => 'Startlayout gebruiken';
@override String get useGlobalHubsDescription => 'Toon gecombineerde home-hubs. Anders bibliotheekaanbevelingen gebruiken.';
@override String get showServerNameOnHubs => 'Servernaam tonen bij hubs';
@@ -1285,6 +1288,7 @@ class _TranslationsDownloadsNl extends TranslationsDownloadsEn {
@override String get unwatchedOnly => 'Alleen onbekeken';
@override String nextNUnwatched({required Object count}) => 'Volgende ${count} onbekeken';
@override String get customAmount => 'Aangepast aantal...';
@override String get includeSpecials => 'Specials opnemen';
@override String get howManyEpisodes => 'Hoeveel afleveringen?';
@override String itemsQueued({required Object count}) => '${count} items in downloadwachtrij';
@override String get keepSynced => 'Gesynchroniseerd houden';
@@ -1755,6 +1759,7 @@ class _TranslationsLibrariesSortLabelsNl extends TranslationsLibrariesSortLabels
@override String get random => 'Willekeurig';
@override String get dateShared => 'Gedeeld op';
@override String get latestEpisodeAirDate => 'Laatste afleveringsuitzending';
@override String get lastEpisodeDateAdded => 'Datum laatst toegevoegde aflevering';
}
// Path: companionRemote.session
@@ -2029,6 +2034,9 @@ extension on TranslationsNl {
'settings.continueWatchingAction' => 'Actie voor Doorgaan met kijken',
'settings.continueWatchingPlay' => 'Afspelen',
'settings.continueWatchingDetails' => 'Details openen',
'settings.episodeAction' => 'Afleveringsactie',
'settings.episodePlay' => 'Afspelen',
'settings.episodeDetails' => 'Details openen',
'settings.useGlobalHubs' => 'Startlayout gebruiken',
'settings.useGlobalHubsDescription' => 'Toon gecombineerde home-hubs. Anders bibliotheekaanbevelingen gebruiken.',
'settings.showServerNameOnHubs' => 'Servernaam tonen bij hubs',
@@ -2430,11 +2438,11 @@ extension on TranslationsNl {
'messages.logsUploaded' => 'Logs geüpload',
'messages.logsUploadFailed' => 'Uploaden van logs mislukt',
'messages.logId' => 'Log-ID',
_ => null,
} ?? switch (path) {
'subtitlingStyling.text' => 'Tekst',
'subtitlingStyling.border' => 'Rand',
'subtitlingStyling.background' => 'Achtergrond',
_ => null,
} ?? switch (path) {
'subtitlingStyling.fontSize' => 'Lettergrootte',
'subtitlingStyling.textColor' => 'Tekstkleur',
'subtitlingStyling.borderSize' => 'Rand grootte',
@@ -2638,6 +2646,7 @@ extension on TranslationsNl {
'libraries.sortLabels.random' => 'Willekeurig',
'libraries.sortLabels.dateShared' => 'Gedeeld op',
'libraries.sortLabels.latestEpisodeAirDate' => 'Laatste afleveringsuitzending',
'libraries.sortLabels.lastEpisodeDateAdded' => 'Datum laatst toegevoegde aflevering',
'about.title' => 'Over',
'about.openSourceLicenses' => 'Open Source licenties',
'about.versionLabel' => ({required Object version}) => 'Versie ${version}',
@@ -2870,6 +2879,7 @@ extension on TranslationsNl {
'downloads.unwatchedOnly' => 'Alleen onbekeken',
'downloads.nextNUnwatched' => ({required Object count}) => 'Volgende ${count} onbekeken',
'downloads.customAmount' => 'Aangepast aantal...',
'downloads.includeSpecials' => 'Specials opnemen',
'downloads.howManyEpisodes' => 'Hoeveel afleveringen?',
'downloads.itemsQueued' => ({required Object count}) => '${count} items in downloadwachtrij',
'downloads.keepSynced' => 'Gesynchroniseerd houden',
@@ -2942,13 +2952,13 @@ extension on TranslationsNl {
'companionRemote.pairing.authFailed' => 'Authenticatie mislukt. Beide apparaten hebben hetzelfde Plex-account nodig.',
'companionRemote.pairing.failedToConnect' => ({required Object error}) => 'Kan niet verbinden: ${error}',
'companionRemote.remote.disconnectConfirm' => 'Wil je de verbinding met de externe sessie verbreken?',
_ => null,
} ?? switch (path) {
'companionRemote.remote.reconnecting' => 'Opnieuw verbinden...',
'companionRemote.remote.attemptOf' => ({required Object current}) => 'Poging ${current} van 5',
'companionRemote.remote.retryNow' => 'Nu opnieuw proberen',
'companionRemote.remote.tabRemote' => 'Afstandsbediening',
'companionRemote.remote.tabPlay' => 'Afspelen',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabMore' => 'Meer',
'companionRemote.remote.menu' => 'Menu',
'companionRemote.remote.tabNavigation' => 'Tabnavigatie',
+14 -4
View File
@@ -247,6 +247,9 @@ class _TranslationsSettingsPl extends TranslationsSettingsEn {
@override String get continueWatchingAction => 'Akcja Kontynuuj oglądanie';
@override String get continueWatchingPlay => 'Odtwórz';
@override String get continueWatchingDetails => 'Otwórz szczegóły';
@override String get episodeAction => 'Akcja odcinka';
@override String get episodePlay => 'Odtwórz';
@override String get episodeDetails => 'Otwórz szczegóły';
@override String get useGlobalHubs => 'Użyj układu strony głównej';
@override String get useGlobalHubsDescription => 'Pokaż ujednolicone huby ekranu głównego. W przeciwnym razie użyj rekomendacji bibliotek.';
@override String get showServerNameOnHubs => 'Pokaż nazwę serwera w hubach';
@@ -1285,6 +1288,7 @@ class _TranslationsDownloadsPl extends TranslationsDownloadsEn {
@override String get unwatchedOnly => 'Tylko nieobejrzane';
@override String nextNUnwatched({required Object count}) => 'Następne ${count} nieobejrzanych';
@override String get customAmount => 'Własna ilość...';
@override String get includeSpecials => 'Uwzględnij odcinki specjalne';
@override String get howManyEpisodes => 'Ile odcinków?';
@override String itemsQueued({required Object count}) => '${count} elementów dodanych do kolejki pobierania';
@override String get keepSynced => 'Synchronizuj na bieżąco';
@@ -1755,6 +1759,7 @@ class _TranslationsLibrariesSortLabelsPl extends TranslationsLibrariesSortLabels
@override String get random => 'Losowo';
@override String get dateShared => 'Data udostępnienia';
@override String get latestEpisodeAirDate => 'Data emisji ostatniego odcinka';
@override String get lastEpisodeDateAdded => 'Data dodania ostatniego odcinka';
}
// Path: companionRemote.session
@@ -2029,6 +2034,9 @@ extension on TranslationsPl {
'settings.continueWatchingAction' => 'Akcja Kontynuuj oglądanie',
'settings.continueWatchingPlay' => 'Odtwórz',
'settings.continueWatchingDetails' => 'Otwórz szczegóły',
'settings.episodeAction' => 'Akcja odcinka',
'settings.episodePlay' => 'Odtwórz',
'settings.episodeDetails' => 'Otwórz szczegóły',
'settings.useGlobalHubs' => 'Użyj układu strony głównej',
'settings.useGlobalHubsDescription' => 'Pokaż ujednolicone huby ekranu głównego. W przeciwnym razie użyj rekomendacji bibliotek.',
'settings.showServerNameOnHubs' => 'Pokaż nazwę serwera w hubach',
@@ -2430,11 +2438,11 @@ extension on TranslationsPl {
'messages.logsUploaded' => 'Logi przesłane',
'messages.logsUploadFailed' => 'Nie udało się przesłać logów',
'messages.logId' => 'ID logu',
_ => null,
} ?? switch (path) {
'subtitlingStyling.text' => 'Tekst',
'subtitlingStyling.border' => 'Obramowanie',
'subtitlingStyling.background' => 'Tło',
_ => null,
} ?? switch (path) {
'subtitlingStyling.fontSize' => 'Rozmiar czcionki',
'subtitlingStyling.textColor' => 'Kolor tekstu',
'subtitlingStyling.borderSize' => 'Rozmiar obramowania',
@@ -2638,6 +2646,7 @@ extension on TranslationsPl {
'libraries.sortLabels.random' => 'Losowo',
'libraries.sortLabels.dateShared' => 'Data udostępnienia',
'libraries.sortLabels.latestEpisodeAirDate' => 'Data emisji ostatniego odcinka',
'libraries.sortLabels.lastEpisodeDateAdded' => 'Data dodania ostatniego odcinka',
'about.title' => 'O aplikacji',
'about.openSourceLicenses' => 'Licencje open source',
'about.versionLabel' => ({required Object version}) => 'Wersja ${version}',
@@ -2870,6 +2879,7 @@ extension on TranslationsPl {
'downloads.unwatchedOnly' => 'Tylko nieobejrzane',
'downloads.nextNUnwatched' => ({required Object count}) => 'Następne ${count} nieobejrzanych',
'downloads.customAmount' => 'Własna ilość...',
'downloads.includeSpecials' => 'Uwzględnij odcinki specjalne',
'downloads.howManyEpisodes' => 'Ile odcinków?',
'downloads.itemsQueued' => ({required Object count}) => '${count} elementów dodanych do kolejki pobierania',
'downloads.keepSynced' => 'Synchronizuj na bieżąco',
@@ -2942,13 +2952,13 @@ extension on TranslationsPl {
'companionRemote.pairing.authFailed' => 'Uwierzytelnianie nie powiodło się. Oba urządzenia muszą używać tego samego konta Plex.',
'companionRemote.pairing.failedToConnect' => ({required Object error}) => 'Nie udało się połączyć: ${error}',
'companionRemote.remote.disconnectConfirm' => 'Czy chcesz się rozłączyć od sesji zdalnej?',
_ => null,
} ?? switch (path) {
'companionRemote.remote.reconnecting' => 'Ponowne łączenie...',
'companionRemote.remote.attemptOf' => ({required Object current}) => 'Próba ${current} z 5',
'companionRemote.remote.retryNow' => 'Ponów teraz',
'companionRemote.remote.tabRemote' => 'Pilot',
'companionRemote.remote.tabPlay' => 'Odtwórz',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabMore' => 'Więcej',
'companionRemote.remote.menu' => 'Menu',
'companionRemote.remote.tabNavigation' => 'Nawigacja',
+14 -4
View File
@@ -247,6 +247,9 @@ class _TranslationsSettingsPt extends TranslationsSettingsEn {
@override String get continueWatchingAction => 'Ação de Continuar Assistindo';
@override String get continueWatchingPlay => 'Reproduzir';
@override String get continueWatchingDetails => 'Abrir detalhes';
@override String get episodeAction => 'Ação de Episódio';
@override String get episodePlay => 'Reproduzir';
@override String get episodeDetails => 'Abrir detalhes';
@override String get useGlobalHubs => 'Usar layout inicial';
@override String get useGlobalHubsDescription => 'Mostrar hubs iniciais unificados. Caso contrário, usar recomendações da biblioteca.';
@override String get showServerNameOnHubs => 'Mostrar Nome do Servidor nos Hubs';
@@ -1285,6 +1288,7 @@ class _TranslationsDownloadsPt extends TranslationsDownloadsEn {
@override String get unwatchedOnly => 'Apenas não assistidos';
@override String nextNUnwatched({required Object count}) => 'Próximos ${count} não assistidos';
@override String get customAmount => 'Quantidade personalizada...';
@override String get includeSpecials => 'Incluir especiais';
@override String get howManyEpisodes => 'Quantos episódios?';
@override String itemsQueued({required Object count}) => '${count} itens na fila de download';
@override String get keepSynced => 'Manter sincronizado';
@@ -1755,6 +1759,7 @@ class _TranslationsLibrariesSortLabelsPt extends TranslationsLibrariesSortLabels
@override String get random => 'Aleatório';
@override String get dateShared => 'Data de compartilhamento';
@override String get latestEpisodeAirDate => 'Última data de exibição do episódio';
@override String get lastEpisodeDateAdded => 'Data de adição do último episódio';
}
// Path: companionRemote.session
@@ -2029,6 +2034,9 @@ extension on TranslationsPt {
'settings.continueWatchingAction' => 'Ação de Continuar Assistindo',
'settings.continueWatchingPlay' => 'Reproduzir',
'settings.continueWatchingDetails' => 'Abrir detalhes',
'settings.episodeAction' => 'Ação de Episódio',
'settings.episodePlay' => 'Reproduzir',
'settings.episodeDetails' => 'Abrir detalhes',
'settings.useGlobalHubs' => 'Usar layout inicial',
'settings.useGlobalHubsDescription' => 'Mostrar hubs iniciais unificados. Caso contrário, usar recomendações da biblioteca.',
'settings.showServerNameOnHubs' => 'Mostrar Nome do Servidor nos Hubs',
@@ -2430,11 +2438,11 @@ extension on TranslationsPt {
'messages.logsUploaded' => 'Logs enviados',
'messages.logsUploadFailed' => 'Falha ao enviar logs',
'messages.logId' => 'ID do Log',
_ => null,
} ?? switch (path) {
'subtitlingStyling.text' => 'Texto',
'subtitlingStyling.border' => 'Borda',
'subtitlingStyling.background' => 'Fundo',
_ => null,
} ?? switch (path) {
'subtitlingStyling.fontSize' => 'Tamanho da Fonte',
'subtitlingStyling.textColor' => 'Cor do Texto',
'subtitlingStyling.borderSize' => 'Tamanho da Borda',
@@ -2638,6 +2646,7 @@ extension on TranslationsPt {
'libraries.sortLabels.random' => 'Aleatório',
'libraries.sortLabels.dateShared' => 'Data de compartilhamento',
'libraries.sortLabels.latestEpisodeAirDate' => 'Última data de exibição do episódio',
'libraries.sortLabels.lastEpisodeDateAdded' => 'Data de adição do último episódio',
'about.title' => 'Sobre',
'about.openSourceLicenses' => 'Licenças Open Source',
'about.versionLabel' => ({required Object version}) => 'Versão ${version}',
@@ -2870,6 +2879,7 @@ extension on TranslationsPt {
'downloads.unwatchedOnly' => 'Apenas não assistidos',
'downloads.nextNUnwatched' => ({required Object count}) => 'Próximos ${count} não assistidos',
'downloads.customAmount' => 'Quantidade personalizada...',
'downloads.includeSpecials' => 'Incluir especiais',
'downloads.howManyEpisodes' => 'Quantos episódios?',
'downloads.itemsQueued' => ({required Object count}) => '${count} itens na fila de download',
'downloads.keepSynced' => 'Manter sincronizado',
@@ -2942,13 +2952,13 @@ extension on TranslationsPt {
'companionRemote.pairing.authFailed' => 'Falha na autenticação. Ambos os dispositivos precisam da mesma conta Plex.',
'companionRemote.pairing.failedToConnect' => ({required Object error}) => 'Falha ao conectar: ${error}',
'companionRemote.remote.disconnectConfirm' => 'Deseja desconectar da sessão remota?',
_ => null,
} ?? switch (path) {
'companionRemote.remote.reconnecting' => 'Reconectando...',
'companionRemote.remote.attemptOf' => ({required Object current}) => 'Tentativa ${current} de 5',
'companionRemote.remote.retryNow' => 'Tentar Agora',
'companionRemote.remote.tabRemote' => 'Remoto',
'companionRemote.remote.tabPlay' => 'Reproduzir',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabMore' => 'Mais',
'companionRemote.remote.menu' => 'Menu',
'companionRemote.remote.tabNavigation' => 'Navegação',
+14 -4
View File
@@ -247,6 +247,9 @@ class _TranslationsSettingsRu extends TranslationsSettingsEn {
@override String get continueWatchingAction => 'Действие для «Продолжить просмотр»';
@override String get continueWatchingPlay => 'Воспроизвести';
@override String get continueWatchingDetails => 'Открыть сведения';
@override String get episodeAction => 'Действие для эпизодов';
@override String get episodePlay => 'Воспроизвести';
@override String get episodeDetails => 'Открыть сведения';
@override String get useGlobalHubs => 'Использовать макет главной';
@override String get useGlobalHubsDescription => 'Показывать единые разделы главной. Иначе использовать рекомендации библиотек.';
@override String get showServerNameOnHubs => 'Показывать имя сервера в хабах';
@@ -1285,6 +1288,7 @@ class _TranslationsDownloadsRu extends TranslationsDownloadsEn {
@override String get unwatchedOnly => 'Только непросмотренные';
@override String nextNUnwatched({required Object count}) => 'Следующие ${count} непросмотренных';
@override String get customAmount => 'Указать количество...';
@override String get includeSpecials => 'Включить спецвыпуски';
@override String get howManyEpisodes => 'Сколько эпизодов?';
@override String itemsQueued({required Object count}) => '${count} элементов добавлено в очередь загрузки';
@override String get keepSynced => 'Синхронизировать';
@@ -1755,6 +1759,7 @@ class _TranslationsLibrariesSortLabelsRu extends TranslationsLibrariesSortLabels
@override String get random => 'Случайно';
@override String get dateShared => 'Дата открытия доступа';
@override String get latestEpisodeAirDate => 'Дата выхода последнего эпизода';
@override String get lastEpisodeDateAdded => 'Дата добавления последнего эпизода';
}
// Path: companionRemote.session
@@ -2029,6 +2034,9 @@ extension on TranslationsRu {
'settings.continueWatchingAction' => 'Действие для «Продолжить просмотр»',
'settings.continueWatchingPlay' => 'Воспроизвести',
'settings.continueWatchingDetails' => 'Открыть сведения',
'settings.episodeAction' => 'Действие для эпизодов',
'settings.episodePlay' => 'Воспроизвести',
'settings.episodeDetails' => 'Открыть сведения',
'settings.useGlobalHubs' => 'Использовать макет главной',
'settings.useGlobalHubsDescription' => 'Показывать единые разделы главной. Иначе использовать рекомендации библиотек.',
'settings.showServerNameOnHubs' => 'Показывать имя сервера в хабах',
@@ -2430,11 +2438,11 @@ extension on TranslationsRu {
'messages.logsUploaded' => 'Логи загружены',
'messages.logsUploadFailed' => 'Не удалось загрузить логи',
'messages.logId' => 'ID лога',
_ => null,
} ?? switch (path) {
'subtitlingStyling.text' => 'Текст',
'subtitlingStyling.border' => 'Обводка',
'subtitlingStyling.background' => 'Фон',
_ => null,
} ?? switch (path) {
'subtitlingStyling.fontSize' => 'Размер шрифта',
'subtitlingStyling.textColor' => 'Цвет текста',
'subtitlingStyling.borderSize' => 'Размер обводки',
@@ -2638,6 +2646,7 @@ extension on TranslationsRu {
'libraries.sortLabels.random' => 'Случайно',
'libraries.sortLabels.dateShared' => 'Дата открытия доступа',
'libraries.sortLabels.latestEpisodeAirDate' => 'Дата выхода последнего эпизода',
'libraries.sortLabels.lastEpisodeDateAdded' => 'Дата добавления последнего эпизода',
'about.title' => 'О приложении',
'about.openSourceLicenses' => 'Лицензии открытого ПО',
'about.versionLabel' => ({required Object version}) => 'Версия ${version}',
@@ -2870,6 +2879,7 @@ extension on TranslationsRu {
'downloads.unwatchedOnly' => 'Только непросмотренные',
'downloads.nextNUnwatched' => ({required Object count}) => 'Следующие ${count} непросмотренных',
'downloads.customAmount' => 'Указать количество...',
'downloads.includeSpecials' => 'Включить спецвыпуски',
'downloads.howManyEpisodes' => 'Сколько эпизодов?',
'downloads.itemsQueued' => ({required Object count}) => '${count} элементов добавлено в очередь загрузки',
'downloads.keepSynced' => 'Синхронизировать',
@@ -2942,13 +2952,13 @@ extension on TranslationsRu {
'companionRemote.pairing.authFailed' => 'Аутентификация не удалась. На обоих устройствах нужен один аккаунт Plex.',
'companionRemote.pairing.failedToConnect' => ({required Object error}) => 'Не удалось подключиться: ${error}',
'companionRemote.remote.disconnectConfirm' => 'Отключиться от удалённой сессии?',
_ => null,
} ?? switch (path) {
'companionRemote.remote.reconnecting' => 'Переподключение...',
'companionRemote.remote.attemptOf' => ({required Object current}) => 'Попытка ${current} из 5',
'companionRemote.remote.retryNow' => 'Повторить сейчас',
'companionRemote.remote.tabRemote' => 'Пульт',
'companionRemote.remote.tabPlay' => 'Воспроизведение',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabMore' => 'Ещё',
'companionRemote.remote.menu' => 'Меню',
'companionRemote.remote.tabNavigation' => 'Навигация',
+14 -4
View File
@@ -247,6 +247,9 @@ class _TranslationsSettingsSv extends TranslationsSettingsEn {
@override String get continueWatchingAction => 'Åtgärd för Fortsätt titta';
@override String get continueWatchingPlay => 'Spela';
@override String get continueWatchingDetails => 'Öppna detaljer';
@override String get episodeAction => 'Åtgärd för avsnitt';
@override String get episodePlay => 'Spela';
@override String get episodeDetails => 'Öppna detaljer';
@override String get useGlobalHubs => 'Använd startlayout';
@override String get useGlobalHubsDescription => 'Visa enhetliga startsideshubbar. Annars används biblioteksrekommendationer.';
@override String get showServerNameOnHubs => 'Visa servernamn på hubbar';
@@ -1285,6 +1288,7 @@ class _TranslationsDownloadsSv extends TranslationsDownloadsEn {
@override String get unwatchedOnly => 'Endast osedda';
@override String nextNUnwatched({required Object count}) => 'Nästa ${count} osedda';
@override String get customAmount => 'Ange antal...';
@override String get includeSpecials => 'Inkludera specialavsnitt';
@override String get howManyEpisodes => 'Hur många avsnitt?';
@override String itemsQueued({required Object count}) => '${count} objekt köade för nedladdning';
@override String get keepSynced => 'Håll synkroniserad';
@@ -1755,6 +1759,7 @@ class _TranslationsLibrariesSortLabelsSv extends TranslationsLibrariesSortLabels
@override String get random => 'Slumpmässigt';
@override String get dateShared => 'Delningsdatum';
@override String get latestEpisodeAirDate => 'Senaste avsnittets sändningsdatum';
@override String get lastEpisodeDateAdded => 'Datum då senaste avsnittet lades till';
}
// Path: companionRemote.session
@@ -2029,6 +2034,9 @@ extension on TranslationsSv {
'settings.continueWatchingAction' => 'Åtgärd för Fortsätt titta',
'settings.continueWatchingPlay' => 'Spela',
'settings.continueWatchingDetails' => 'Öppna detaljer',
'settings.episodeAction' => 'Åtgärd för avsnitt',
'settings.episodePlay' => 'Spela',
'settings.episodeDetails' => 'Öppna detaljer',
'settings.useGlobalHubs' => 'Använd startlayout',
'settings.useGlobalHubsDescription' => 'Visa enhetliga startsideshubbar. Annars används biblioteksrekommendationer.',
'settings.showServerNameOnHubs' => 'Visa servernamn på hubbar',
@@ -2430,11 +2438,11 @@ extension on TranslationsSv {
'messages.logsUploaded' => 'Loggar uppladdade',
'messages.logsUploadFailed' => 'Uppladdning av loggar misslyckades',
'messages.logId' => 'Logg-ID',
_ => null,
} ?? switch (path) {
'subtitlingStyling.text' => 'Text',
'subtitlingStyling.border' => 'Kantlinje',
'subtitlingStyling.background' => 'Bakgrund',
_ => null,
} ?? switch (path) {
'subtitlingStyling.fontSize' => 'Teckenstorlek',
'subtitlingStyling.textColor' => 'Textfärg',
'subtitlingStyling.borderSize' => 'Kantstorlek',
@@ -2638,6 +2646,7 @@ extension on TranslationsSv {
'libraries.sortLabels.random' => 'Slumpmässigt',
'libraries.sortLabels.dateShared' => 'Delningsdatum',
'libraries.sortLabels.latestEpisodeAirDate' => 'Senaste avsnittets sändningsdatum',
'libraries.sortLabels.lastEpisodeDateAdded' => 'Datum då senaste avsnittet lades till',
'about.title' => 'Om',
'about.openSourceLicenses' => 'Öppen källkod-licenser',
'about.versionLabel' => ({required Object version}) => 'Version ${version}',
@@ -2870,6 +2879,7 @@ extension on TranslationsSv {
'downloads.unwatchedOnly' => 'Endast osedda',
'downloads.nextNUnwatched' => ({required Object count}) => 'Nästa ${count} osedda',
'downloads.customAmount' => 'Ange antal...',
'downloads.includeSpecials' => 'Inkludera specialavsnitt',
'downloads.howManyEpisodes' => 'Hur många avsnitt?',
'downloads.itemsQueued' => ({required Object count}) => '${count} objekt köade för nedladdning',
'downloads.keepSynced' => 'Håll synkroniserad',
@@ -2942,13 +2952,13 @@ extension on TranslationsSv {
'companionRemote.pairing.authFailed' => 'Autentisering misslyckades. Båda enheter behöver samma Plex-konto.',
'companionRemote.pairing.failedToConnect' => ({required Object error}) => 'Kunde inte ansluta: ${error}',
'companionRemote.remote.disconnectConfirm' => 'Vill du koppla från fjärrsessionen?',
_ => null,
} ?? switch (path) {
'companionRemote.remote.reconnecting' => 'Återansluter...',
'companionRemote.remote.attemptOf' => ({required Object current}) => 'Försök ${current} av 5',
'companionRemote.remote.retryNow' => 'Försök nu',
'companionRemote.remote.tabRemote' => 'Fjärrkontroll',
'companionRemote.remote.tabPlay' => 'Spela',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabMore' => 'Mer',
'companionRemote.remote.menu' => 'Meny',
'companionRemote.remote.tabNavigation' => 'Fliknavigering',
+14 -4
View File
@@ -247,6 +247,9 @@ class _TranslationsSettingsZh extends TranslationsSettingsEn {
@override String get continueWatchingAction => '继续观看操作';
@override String get continueWatchingPlay => '播放';
@override String get continueWatchingDetails => '打开详情';
@override String get episodeAction => '剧集操作';
@override String get episodePlay => '播放';
@override String get episodeDetails => '打开详情';
@override String get useGlobalHubs => '使用主页布局';
@override String get useGlobalHubsDescription => '显示统一主页中心。否则使用资料库推荐。';
@override String get showServerNameOnHubs => '在推荐栏显示服务器名称';
@@ -1285,6 +1288,7 @@ class _TranslationsDownloadsZh extends TranslationsDownloadsEn {
@override String get unwatchedOnly => '仅未观看';
@override String nextNUnwatched({required Object count}) => '接下来 ${count} 集未观看';
@override String get customAmount => '自定义数量...';
@override String get includeSpecials => '包含特别篇';
@override String get howManyEpisodes => '下载几集?';
@override String itemsQueued({required Object count}) => '${count} 个项目已加入下载队列';
@override String get keepSynced => '保持同步';
@@ -1755,6 +1759,7 @@ class _TranslationsLibrariesSortLabelsZh extends TranslationsLibrariesSortLabels
@override String get random => '随机';
@override String get dateShared => '共享日期';
@override String get latestEpisodeAirDate => '最新一集播出日期';
@override String get lastEpisodeDateAdded => '最新一集添加日期';
}
// Path: companionRemote.session
@@ -2029,6 +2034,9 @@ extension on TranslationsZh {
'settings.continueWatchingAction' => '继续观看操作',
'settings.continueWatchingPlay' => '播放',
'settings.continueWatchingDetails' => '打开详情',
'settings.episodeAction' => '剧集操作',
'settings.episodePlay' => '播放',
'settings.episodeDetails' => '打开详情',
'settings.useGlobalHubs' => '使用主页布局',
'settings.useGlobalHubsDescription' => '显示统一主页中心。否则使用资料库推荐。',
'settings.showServerNameOnHubs' => '在推荐栏显示服务器名称',
@@ -2430,11 +2438,11 @@ extension on TranslationsZh {
'messages.logsUploaded' => '日志已上传',
'messages.logsUploadFailed' => '上传日志失败',
'messages.logId' => '日志 ID',
_ => null,
} ?? switch (path) {
'subtitlingStyling.text' => '文本',
'subtitlingStyling.border' => '边框',
'subtitlingStyling.background' => '背景',
_ => null,
} ?? switch (path) {
'subtitlingStyling.fontSize' => '字号',
'subtitlingStyling.textColor' => '文本颜色',
'subtitlingStyling.borderSize' => '边框大小',
@@ -2638,6 +2646,7 @@ extension on TranslationsZh {
'libraries.sortLabels.random' => '随机',
'libraries.sortLabels.dateShared' => '共享日期',
'libraries.sortLabels.latestEpisodeAirDate' => '最新一集播出日期',
'libraries.sortLabels.lastEpisodeDateAdded' => '最新一集添加日期',
'about.title' => '关于',
'about.openSourceLicenses' => '开源许可证',
'about.versionLabel' => ({required Object version}) => '版本 ${version}',
@@ -2870,6 +2879,7 @@ extension on TranslationsZh {
'downloads.unwatchedOnly' => '仅未观看',
'downloads.nextNUnwatched' => ({required Object count}) => '接下来 ${count} 集未观看',
'downloads.customAmount' => '自定义数量...',
'downloads.includeSpecials' => '包含特别篇',
'downloads.howManyEpisodes' => '下载几集?',
'downloads.itemsQueued' => ({required Object count}) => '${count} 个项目已加入下载队列',
'downloads.keepSynced' => '保持同步',
@@ -2942,13 +2952,13 @@ extension on TranslationsZh {
'companionRemote.pairing.authFailed' => '认证失败。两台设备需要使用同一 Plex 账号。',
'companionRemote.pairing.failedToConnect' => ({required Object error}) => '连接失败:${error}',
'companionRemote.remote.disconnectConfirm' => '是否要断开远程会话的连接?',
_ => null,
} ?? switch (path) {
'companionRemote.remote.reconnecting' => '重新连接中...',
'companionRemote.remote.attemptOf' => ({required Object current}) => '第 ${current} 次尝试,共 5 次',
'companionRemote.remote.retryNow' => '立即重试',
'companionRemote.remote.tabRemote' => '遥控',
'companionRemote.remote.tabPlay' => '播放',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabMore' => '更多',
'companionRemote.remote.menu' => '菜单',
'companionRemote.remote.tabNavigation' => '标签导航',
+6 -1
View File
@@ -118,6 +118,9 @@
"continueWatchingAction": "Åtgärd för Fortsätt titta",
"continueWatchingPlay": "Spela",
"continueWatchingDetails": "Öppna detaljer",
"episodeAction": "Åtgärd för avsnitt",
"episodePlay": "Spela",
"episodeDetails": "Öppna detaljer",
"useGlobalHubs": "Använd startlayout",
"useGlobalHubsDescription": "Visa enhetliga startsideshubbar. Annars används biblioteksrekommendationer.",
"showServerNameOnHubs": "Visa servernamn på hubbar",
@@ -771,7 +774,8 @@
"studio": "Studio",
"random": "Slumpmässigt",
"dateShared": "Delningsdatum",
"latestEpisodeAirDate": "Senaste avsnittets sändningsdatum"
"latestEpisodeAirDate": "Senaste avsnittets sändningsdatum",
"lastEpisodeDateAdded": "Datum då senaste avsnittet lades till"
}
},
"about": {
@@ -1027,6 +1031,7 @@
"unwatchedOnly": "Endast osedda",
"nextNUnwatched": "Nästa ${count} osedda",
"customAmount": "Ange antal...",
"includeSpecials": "Inkludera specialavsnitt",
"howManyEpisodes": "Hur många avsnitt?",
"itemsQueued": "${count} objekt köade för nedladdning",
"keepSynced": "Håll synkroniserad",
+6 -1
View File
@@ -118,6 +118,9 @@
"continueWatchingAction": "继续观看操作",
"continueWatchingPlay": "播放",
"continueWatchingDetails": "打开详情",
"episodeAction": "剧集操作",
"episodePlay": "播放",
"episodeDetails": "打开详情",
"useGlobalHubs": "使用主页布局",
"useGlobalHubsDescription": "显示统一主页中心。否则使用资料库推荐。",
"showServerNameOnHubs": "在推荐栏显示服务器名称",
@@ -771,7 +774,8 @@
"studio": "工作室",
"random": "随机",
"dateShared": "共享日期",
"latestEpisodeAirDate": "最新一集播出日期"
"latestEpisodeAirDate": "最新一集播出日期",
"lastEpisodeDateAdded": "最新一集添加日期"
}
},
"about": {
@@ -1027,6 +1031,7 @@
"unwatchedOnly": "仅未观看",
"nextNUnwatched": "接下来 ${count} 集未观看",
"customAmount": "自定义数量...",
"includeSpecials": "包含特别篇",
"howManyEpisodes": "下载几集?",
"itemsQueued": "${count} 个项目已加入下载队列",
"keepSynced": "保持同步",
+72 -145
View File
@@ -1,5 +1,4 @@
import 'dart:async';
import 'media/ids.dart';
import 'dart:io' show Directory, Platform, ProcessInfo;
import 'dart:ui' show AppExitResponse;
import 'package:flutter/foundation.dart';
@@ -15,14 +14,16 @@ import 'package:sentry_flutter/sentry_flutter.dart';
import 'connection/connection.dart';
import 'connection/connection_bootstrap.dart';
import 'connection/connection_registry.dart';
import 'navigation/profile_navigation_scope.dart';
import 'navigation/profile_session_screen.dart';
import 'profiles/active_profile_binder.dart';
import 'profiles/active_profile_provider.dart';
import 'profiles/profile.dart';
import 'profiles/profile_connection_cleanup.dart';
import 'profiles/profile_connection_registry.dart';
import 'profiles/profile_registry.dart';
import 'mixins/mounted_set_state_mixin.dart';
import 'profiles/plex_home_service.dart';
import 'screens/main_screen.dart';
import 'screens/auth_screen.dart';
import 'screens/profile/pin_entry_dialog.dart';
import 'screens/profile/profile_switch_screen.dart';
@@ -41,23 +42,14 @@ import 'services/gamepad_service.dart';
import 'services/trakt/trakt_scrobble_service.dart';
import 'services/trakt/trakt_sync_service.dart';
import 'services/trackers/tracker_coordinator.dart';
import 'providers/trakt_account_provider.dart';
import 'providers/trackers_provider.dart';
import 'providers/user_profile_provider.dart';
import 'providers/multi_server_provider.dart';
import 'providers/theme_provider.dart';
import 'providers/hidden_libraries_provider.dart';
import 'providers/libraries_provider.dart';
import 'providers/discover_provider.dart';
import 'providers/playback_state_provider.dart';
import 'providers/download_provider.dart';
import 'providers/offline_mode_provider.dart';
import 'providers/offline_watch_provider.dart';
import 'providers/watch_state_store.dart';
import 'providers/companion_remote_provider.dart';
import 'providers/shader_provider.dart';
import 'utils/snackbar_helper.dart';
import 'watch_together/providers/watch_together_provider.dart';
import 'services/multi_server_manager.dart';
import 'services/offline_watch_sync_service.dart';
import 'services/data_aggregation_service.dart';
@@ -76,7 +68,6 @@ import 'utils/media_server_http_client.dart';
import 'utils/orientation_helper.dart';
import 'utils/watch_state_notifier.dart';
import 'i18n/strings.g.dart';
import 'media/media_server_client.dart';
import 'focus/input_mode_tracker.dart';
import 'focus/key_event_utils.dart';
import 'package:intl/date_symbol_data_local.dart';
@@ -415,7 +406,6 @@ void _registerShaderLicenses() {
});
}
final RouteObserver<PageRoute> routeObserver = RouteObserver<PageRoute>();
final rootNavigatorKey = GlobalKey<NavigatorState>();
@visibleForTesting
@@ -424,10 +414,10 @@ bool shouldEnterOfflineModeAfterStartupBind({required bool bindingSucceeded, req
}
/// Top-level PIN prompt used by [ActiveProfileBinder] when it runs above the
/// per-screen widget tree. Routes through [rootNavigatorKey] so the dialog
/// renders correctly whether the binder fires from the splash, MainScreen,
/// or any future host. Returns `null` when no Navigator is available yet
/// (early boot, post-dispose) so the binder treats it as "PIN cancelled".
/// profile-scoped widget tree. Routes through the app-global
/// [rootNavigatorKey] so the dialog survives profile-session remounts. Returns
/// `null` when no Navigator is available yet (early boot, post-dispose) so the
/// binder treats it as "PIN cancelled".
Future<String?> _rootPinPrompt(Profile profile, {String? errorMessage}) {
final ctx = rootNavigatorKey.currentContext;
if (ctx == null) return Future.value(null);
@@ -856,98 +846,18 @@ class _MainAppState extends State<MainApp> with WidgetsBindingObserver {
),
ChangeNotifierProvider(create: (context) => ThemeProvider()),
// Shader presets are app-global — deliberately outside the
// profile-scoped subtree below.
// profile-scoped session in ProfileSessionScreen.
ChangeNotifierProvider(create: (context) => ShaderProvider()),
],
// Profile boundary: everything below is profile-scoped BY TREE
// POSITION. Switching the active profile changes the KeyedSubtree key,
// which disposes and recreates the inner providers and the whole app
// shell — including navigation, so routes showing the previous
// profile's content cannot survive into the next. A provider belongs in
// the inner list when its state is per-profile; app-global state
// (theme, shader presets, downloads, server manager) stays above.
// Shared singletons that span profiles (DownloadProvider's sync rules,
// OfflineWatchSyncService) keep their explicit setActiveProfileId
// wiring instead.
child: Consumer<ActiveProfileProvider>(
builder: (context, activeProfile, _) {
final activeId = activeProfile.activeId;
return KeyedSubtree(
key: ValueKey<String?>(activeId),
child: MultiProvider(
providers: [
ChangeNotifierProxyProvider<MultiServerProvider, WatchStateStore>(
create: (_) => WatchStateStore(),
update: (_, multiServer, previous) {
final provider = previous ?? WatchStateStore();
provider.setActiveProfileId(activeId);
provider.setActiveClientScopesByServer({
for (final serverId in multiServer.serverManager.serverIds)
serverId: multiServer.serverManager.getClient(ServerId(serverId))?.cacheServerId,
});
return provider;
},
),
// Tracker accounts hydrate for the active profile on create —
// the subtree remount on profile switch is the rebind.
ChangeNotifierProvider(
create: (context) {
final provider = TraktAccountProvider();
unawaited(
provider.onActiveProfileChanged(activeId).catchError((Object e, StackTrace s) {
appLogger.w('Trakt profile hydrate failed', error: e, stackTrace: s);
}),
);
return provider;
},
),
ChangeNotifierProvider(
create: (context) {
final provider = TrackersProvider();
unawaited(
provider.onActiveProfileChanged(activeId).catchError((Object e, StackTrace s) {
appLogger.w('Trackers profile hydrate failed', error: e, stackTrace: s);
}),
);
return provider;
},
),
ChangeNotifierProvider(
create: (context) => HiddenLibrariesProvider(storageService: context.read<StorageService>()),
lazy: true,
),
ChangeNotifierProvider(
create: (context) => LibrariesProvider(
storageService: context.read<StorageService>(),
multiServer: context.read<MultiServerProvider>(),
),
),
ChangeNotifierProvider(
create: (context) {
final activeProfile = context.read<ActiveProfileProvider>();
return DiscoverProvider(
context.read<MultiServerProvider>(),
context.read<HiddenLibrariesProvider>(),
context.read<LibrariesProvider>(),
isProfileBinding: () => activeProfile.isBinding,
);
},
),
ChangeNotifierProvider(create: (context) => PlaybackStateProvider()),
ChangeNotifierProvider(create: (context) => WatchTogetherProvider()),
ChangeNotifierProvider(create: (context) => CompanionRemoteProvider()),
],
child: const _AppShell(),
),
);
},
),
child: const _AppShell(),
);
}
}
/// The app shell below the profile boundary: theme consumer, translations,
/// global input handling, and the MaterialApp.
/// App-global shell: theme consumer, translations, root input handling, and the
/// root MaterialApp. Profile-scoped providers/navigation live in
/// [ProfileSessionScreen], not here, so root auth/PIN/global dialogs survive a
/// profile switch.
class _AppShell extends StatelessWidget {
const _AppShell();
@@ -959,51 +869,58 @@ class _AppShell extends StatelessWidget {
child: Builder(
builder: (context) {
return Listener(
onPointerDown: (event) {
if ((event.buttons & kBackMouseButton) != 0) {
rootNavigatorKey.currentState?.maybePop();
onPointerDown: (event) {
if ((event.buttons & kBackMouseButton) != 0) {
unawaited(() async {
final rootNavigator = rootNavigatorKey.currentState;
if (rootNavigator?.canPop() ?? false) {
await rootNavigator?.maybePop();
return;
}
await profileNavigationRegistry.maybePopProfileRoute();
}());
}
},
behavior: HitTestBehavior.translucent,
child: InputModeTracker(
child: MaterialApp(
title: t.app.title,
debugShowCheckedModeBanner: false,
theme: themeProvider.lightTheme,
darkTheme: themeProvider.darkTheme,
themeMode: themeProvider.materialThemeMode,
navigatorKey: rootNavigatorKey,
navigatorObservers: [BackKeySuppressorObserver()],
home: const OrientationAwareSetup(),
// Siri Remote select + gamepad A report as
// LogicalKeyboardKey.{select,gameButtonA} which aren't
// in Flutter's default shortcut set — Material-level
// widgets (menu items, showModalBottomSheet actions)
// ignore them. Map both to ActivateIntent so tapping
// select on tvOS activates the focused widget.
shortcuts: <ShortcutActivator, Intent>{
...WidgetsApp.defaultShortcuts,
const SingleActivator(LogicalKeyboardKey.select): const ActivateIntent(),
const SingleActivator(LogicalKeyboardKey.gameButtonA): const ActivateIntent(),
const SingleActivator(LogicalKeyboardKey.goBack): const DismissIntent(),
const SingleActivator(LogicalKeyboardKey.browserBack): const DismissIntent(),
const SingleActivator(LogicalKeyboardKey.gameButtonB): const DismissIntent(),
},
behavior: HitTestBehavior.translucent,
child: InputModeTracker(
child: MaterialApp(
title: t.app.title,
debugShowCheckedModeBanner: false,
theme: themeProvider.lightTheme,
darkTheme: themeProvider.darkTheme,
themeMode: themeProvider.materialThemeMode,
navigatorKey: rootNavigatorKey,
navigatorObservers: [routeObserver, BackKeySuppressorObserver()],
home: const OrientationAwareSetup(),
// Siri Remote select + gamepad A report as
// LogicalKeyboardKey.{select,gameButtonA} which aren't
// in Flutter's default shortcut set — Material-level
// widgets (menu items, showModalBottomSheet actions)
// ignore them. Map both to ActivateIntent so tapping
// select on tvOS activates the focused widget.
shortcuts: <ShortcutActivator, Intent>{
...WidgetsApp.defaultShortcuts,
const SingleActivator(LogicalKeyboardKey.select): const ActivateIntent(),
const SingleActivator(LogicalKeyboardKey.gameButtonA): const ActivateIntent(),
const SingleActivator(LogicalKeyboardKey.goBack): const DismissIntent(),
const SingleActivator(LogicalKeyboardKey.browserBack): const DismissIntent(),
const SingleActivator(LogicalKeyboardKey.gameButtonB): const DismissIntent(),
},
builder: (context, child) => ScaffoldMessenger(
key: rootScaffoldMessengerKey,
child: Scaffold(
backgroundColor: Colors.transparent,
body: _AppleTvScale(child: child),
),
),
builder: (context, child) => ScaffoldMessenger(
key: rootScaffoldMessengerKey,
child: Scaffold(
backgroundColor: Colors.transparent,
body: _AppleTvScale(child: child),
),
),
);
},
),
);
},
),
),
);
},
),
);
},
);
}
}
@@ -1110,7 +1027,7 @@ class _SetupScreenState extends State<SetupScreen> with MountedSetStateMixin {
_setStatus(t.common.startingOfflineMode);
await context.read<DownloadProvider>().ensureInitialized();
if (!mounted) return;
unawaited(Navigator.pushReplacement(context, fadeRoute(const MainScreen(isOfflineMode: true))));
unawaited(Navigator.pushReplacement(context, fadeRoute(const ProfileSessionScreen(isOfflineMode: true))));
}
Future<void> _loadSavedCredentials() async {
@@ -1125,6 +1042,7 @@ class _SetupScreenState extends State<SetupScreen> with MountedSetStateMixin {
if (mounted) {
try {
final connRegistry = context.read<ConnectionRegistry>();
final profileConnections = context.read<ProfileConnectionRegistry>();
final profileRegistry = context.read<ProfileRegistry>();
final activeProfiles = context.read<ActiveProfileProvider>();
final bootstrap = ConnectionBootstrap(
@@ -1134,6 +1052,15 @@ class _SetupScreenState extends State<SetupScreen> with MountedSetStateMixin {
profileRegistry: profileRegistry,
);
await bootstrap.run();
final pruned = await pruneUnreferencedJellyfinConnections(
profileConnections: profileConnections,
connections: connRegistry,
storage: storage,
serverManager: context.read<MultiServerProvider>().serverManager,
);
if (pruned > 0) {
appLogger.i('Setup: pruned $pruned unreferenced Jellyfin connection${pruned == 1 ? '' : 's'}');
}
// Provider initialization starts before this screen runs the legacy
// migration. Reload after bootstrap so copied Plex Home users and the
// selected active profile are visible before setup decides binding is
@@ -1303,7 +1230,7 @@ class _SetupScreenState extends State<SetupScreen> with MountedSetStateMixin {
await downloadProvider.refreshMetadataFromCache();
if (!mounted) return;
unawaited(Navigator.pushReplacement(context, fadeRoute(MainScreen(initialPromptHandled: shouldPrompt))));
unawaited(Navigator.pushReplacement(context, fadeRoute(ProfileSessionScreen(initialPromptHandled: shouldPrompt))));
}
/// Wire per-server status updates from [MultiServerManager] into the
+113 -12
View File
@@ -20,8 +20,16 @@ Future<void> collectEpisodesForShow(
required bool unwatchedOnly,
required List<MediaItem> out,
MediaItem? fallback,
bool includeSpecials = true,
}) {
return _collectPlayable(client, showRatingKey, unwatchedOnly: unwatchedOnly, out: out, fallback: fallback);
return _collectPlayable(
client,
showRatingKey,
unwatchedOnly: unwatchedOnly,
out: out,
fallback: fallback,
includeSpecials: includeSpecials,
);
}
/// Collect every episode of a single season into [out] via the same
@@ -33,25 +41,50 @@ Future<void> collectEpisodesForSeason(
required bool unwatchedOnly,
required List<MediaItem> out,
MediaItem? fallback,
bool includeSpecials = true,
}) {
return _collectPlayable(client, seasonRatingKey, unwatchedOnly: unwatchedOnly, out: out, fallback: fallback);
return _collectPlayable(
client,
seasonRatingKey,
unwatchedOnly: unwatchedOnly,
out: out,
fallback: fallback,
includeSpecials: includeSpecials,
);
}
/// Fetch just the first episode of a season without walking the entire season.
/// Use this for representative lookups and immediate "play first" actions.
Future<MediaItem?> fetchFirstEpisodeForSeason(MediaServerClient client, String seasonRatingKey) async {
final page = await client.fetchChildrenPage(seasonRatingKey, start: 0, size: 1);
Future<MediaItem?> fetchFirstEpisodeForSeason(
MediaServerClient client,
String seasonRatingKey, {
String? seriesId,
}) async {
final seasonPagingClient = client is SeasonEpisodePagingClient ? client as SeasonEpisodePagingClient : null;
final page = seriesId != null && seasonPagingClient != null
? await seasonPagingClient.fetchSeasonEpisodesPage(seriesId, seasonRatingKey, start: 0, size: 1)
: await client.fetchChildrenPage(seasonRatingKey, start: 0, size: 1);
for (final item in page.items) {
if (item.kind == MediaKind.episode) return item;
}
return null;
}
/// A season number of 0 (or missing) denotes the Specials folder. Season
/// selection treats it as a last resort for "what to watch next" — see
/// [defaultPlaybackSeasonIndex] and [firstUnwatchedSeasonIndex], which open on
/// the first regular season. Episode ordering ([compareEpisodesByWatchOrder])
/// instead places Specials by air date, only falling back to Specials-last when
/// an episode has no air date.
bool isSpecialSeasonNumber(int? seasonNumber) => (seasonNumber ?? 0) == 0;
/// Prefer the first regular season over specials, falling back to the first
/// season row when a show only has specials or lacks season indexes.
int defaultPlaybackSeasonIndex(List<MediaItem> seasons) {
if (seasons.isEmpty) return 0;
final regularSeasonIndex = seasons.indexWhere((season) => season.kind == MediaKind.season && (season.index ?? 0) > 0);
final regularSeasonIndex = seasons.indexWhere(
(season) => season.kind == MediaKind.season && !isSpecialSeasonNumber(season.index),
);
if (regularSeasonIndex != -1) return regularSeasonIndex;
final firstSeasonIndex = seasons.indexWhere((season) => season.kind == MediaKind.season);
return firstSeasonIndex == -1 ? 0 : firstSeasonIndex;
@@ -77,7 +110,7 @@ int? firstUnwatchedSeasonIndex(List<MediaItem> seasons) {
final leaf = season.leafCount;
if (leaf == null || leaf <= 0) continue;
if ((season.viewedLeafCount ?? 0) >= leaf) continue; // fully watched
if ((season.index ?? 0) > 0) return i; // first regular season with unwatched
if (!isSpecialSeasonNumber(season.index)) return i; // first regular season with unwatched
firstSpecial ??= i; // specials only count as a last resort
}
return firstSpecial;
@@ -89,12 +122,63 @@ int? firstUnwatchedSeasonIndex(List<MediaItem> seasons) {
MediaItem? firstUnwatchedEpisode(List<MediaItem> episodes) {
for (final episode in episodes) {
if (episode.kind != MediaKind.episode) continue;
if (episode.isWatched && !episode.hasActiveProgress) continue;
if (!episode.isUnwatchedOrInProgress) continue;
return episode;
}
return null;
}
/// Orders episodes into the **aired watch order** — the sequence they're meant
/// to be played in: primarily by air date ([MediaItem.originallyAvailableAt]),
/// so a Special that aired between two regular episodes is played between them,
/// the way Plex's own play queue and clients do (#1416). This is the single
/// shared definition of episode order, used by the offline next/prev queue, the
/// Jellyfin online queue, the offline OnDeck list, and the count-capped
/// "download / sync next N" selection — keeping streaming, offline, and
/// download order consistent across both backends.
///
/// Episodes without a usable air date sort *after* dated ones, falling back to
/// season → episode order with Specials last. So undated Specials never wedge
/// into the middle of the aired run, and a "next N" cut still leads with regular
/// episodes — preserving the #1414 guarantee that the whole Specials folder is
/// never front-loaded. The trailing id comparison keeps ties deterministic
/// (Dart's [List.sort] is not stable) so the "next N" cut is stable across runs.
int compareEpisodesByWatchOrder(MediaItem a, MediaItem b) {
final aDate = _airDateKey(a);
final bDate = _airDateKey(b);
if (aDate != null && bDate != null) {
final byDate = aDate.compareTo(bDate);
if (byDate != 0) return byDate;
} else if (aDate == null && bDate != null) {
return 1; // undated episodes sort after dated ones
} else if (aDate != null && bDate == null) {
return -1;
}
// Same air date, or both undated: regular seasons before Specials, then by
// season number, episode number, and id.
final aSpecial = isSpecialSeasonNumber(a.parentIndex);
final bSpecial = isSpecialSeasonNumber(b.parentIndex);
if (aSpecial != bSpecial) return aSpecial ? 1 : -1;
final season = (a.parentIndex ?? 0).compareTo(b.parentIndex ?? 0);
if (season != 0) return season;
final episode = (a.index ?? 0).compareTo(b.index ?? 0);
if (episode != 0) return episode;
return a.id.compareTo(b.id);
}
/// Air date used to order episodes in [compareEpisodesByWatchOrder], or null
/// when absent. Both backends normalize [MediaItem.originallyAvailableAt] to
/// `YYYY-MM-DD` (Plex natively, Jellyfin from `PremiereDate`), so a plain
/// lexicographic comparison is chronological.
String? _airDateKey(MediaItem episode) {
final date = episode.originallyAvailableAt;
return (date == null || date.isEmpty) ? null : date;
}
/// In-place sort by [compareEpisodesByWatchOrder]. See that function for the
/// ordering rationale.
void sortEpisodesByWatchOrder(List<MediaItem> episodes) => episodes.sort(compareEpisodesByWatchOrder);
/// Find the season index matching an explicit navigation target or on-deck
/// episode. With neither, fall back to the first season that still has
/// unwatched episodes (so a partially-watched show removed from Continue
@@ -136,8 +220,8 @@ int preferredSeasonIndex(
return defaultPlaybackSeasonIndex(seasons);
}
/// Fetch a page of direct season children and normalize the episode identity
/// fields detail rows depend on. Local/session progress stays layered in UI.
/// Fetch a page of season episodes and normalize the episode identity fields
/// detail rows depend on. Local/session progress stays layered in UI.
Future<LibraryPage<MediaItem>> fetchSeasonEpisodePage(
MediaServerClient client, {
required MediaItem show,
@@ -145,7 +229,10 @@ Future<LibraryPage<MediaItem>> fetchSeasonEpisodePage(
required int start,
required int size,
}) async {
final page = await client.fetchChildrenPage(season.id, start: start, size: size);
final seasonPagingClient = client is SeasonEpisodePagingClient ? client as SeasonEpisodePagingClient : null;
final page = seasonPagingClient != null
? await seasonPagingClient.fetchSeasonEpisodesPage(show.id, season.id, start: start, size: size)
: await client.fetchChildrenPage(season.id, start: start, size: size);
return LibraryPage<MediaItem>(
items: normalizeSeasonEpisodes(page.items, show: show, season: season),
totalCount: page.totalCount,
@@ -159,6 +246,7 @@ List<MediaItem> normalizeSeasonEpisodes(
required MediaItem season,
}) {
return episodes
.where((episode) => episode.kind == MediaKind.episode)
.map(
(episode) => _withFallbackLibrary(
episode.copyWith(
@@ -181,13 +269,26 @@ Future<void> _collectPlayable(
required bool unwatchedOnly,
required List<MediaItem> out,
MediaItem? fallback,
bool includeSpecials = true,
}) async {
final leaves = await client.fetchPlayableDescendants(parentId);
// Collect into a local list and order it before handing back: the backend
// returns episodes in raw container order (Plex /grandchildren puts S00
// first). Sorting into aired watch order means order-capped callers ("next N
// unwatched" download, sync-rule deficit) slice the next episodes in the order
// they're meant to be watched — Specials interleaved by air date, never the
// whole Specials folder front-loaded (#1414). Sort the per-call slice, not the
// shared `out` accumulator, so multi-container callers don't interleave across
// shows.
final collected = <MediaItem>[];
for (final ep in leaves) {
if (ep.kind != MediaKind.episode) continue;
if (unwatchedOnly && ep.isWatched && !ep.hasActiveProgress) continue;
out.add(_withFallbackLibrary(ep, fallback));
if (!includeSpecials && isSpecialSeasonNumber(ep.parentIndex)) continue;
if (unwatchedOnly && !ep.isUnwatchedOrInProgress) continue;
collected.add(_withFallbackLibrary(ep, fallback));
}
sortEpisodesByWatchOrder(collected);
out.addAll(collected);
}
MediaItem _withFallbackLibrary(MediaItem item, MediaItem? fallback) {
+6
View File
@@ -387,6 +387,12 @@ sealed class MediaItem with _$MediaItem {
return viewOffsetMs! > 0 && viewOffsetMs! < durationMs!;
}
/// Whether this item still counts toward an "unwatched only" selection:
/// not fully watched, or watched-but-resumable (has active progress). The
/// shared predicate behind every `unwatchedOnly` filter (downloads, sync
/// rules, the unwatched-episode lookups in episode_collection.dart).
bool get isUnwatchedOrInProgress => !isWatched || hasActiveProgress;
/// Whether this container (show/season) has some but not all leaves watched.
bool get isPartiallyWatched =>
viewedLeafCount != null && leafCount != null && viewedLeafCount! > 0 && viewedLeafCount! < leafCount!;
+3 -6
View File
@@ -15,14 +15,11 @@ extension MediaItemTypes on MediaItem {
kind == MediaKind.movie || kind == MediaKind.show || kind == MediaKind.season || kind == MediaKind.episode;
/// Whether this episode should have spoiler protection applied.
/// True when the item is an unwatched episode watched less than 50%.
/// True for any episode that has not yet been marked watched, regardless of
/// in-progress playback position (#1397).
bool get shouldHideSpoiler {
if (!isEpisode) return false;
if (isWatched) return false;
if (viewOffsetMs != null && viewOffsetMs! > 0 && durationMs != null && durationMs! > 0) {
return viewOffsetMs! / durationMs! < 0.5;
}
return true;
return !isWatched;
}
/// Non-spoiler art path for episodes (show/season background).
+13
View File
@@ -631,6 +631,19 @@ extension MediaServerClientScope on MediaServerClient {
}
}
/// Optional capability for clients that can fetch a season's episodes without
/// listing generic children. Jellyfin uses this to avoid mixing local extras or
/// missing/virtual placeholders into normal season episode rails.
abstract interface class SeasonEpisodePagingClient {
Future<LibraryPage<MediaItem>> fetchSeasonEpisodesPage(
String seriesId,
String seasonId, {
int? start,
int? size,
AbortController? abort,
});
}
/// Cache-aware fetch helpers shared by both backends so the offline-first /
/// network-then-cache pattern lives in one place.
///
+45 -6
View File
@@ -15,6 +15,38 @@ Object? _readTmdbSeason(Map json, String key) {
return season is Map ? season['tmdb'] : null;
}
/// Flatten Fribb's `themoviedb_id` into a flat id list. Current schema is an
/// object: `{"tv": <int>}` (always a single id) or `{"movie": [<int>, ...]}`
/// (one or more). Tolerant of a legacy flat int / numeric string / bare list
/// so the parser survives a future schema re-flip.
List<int>? _flattenTmdbIds(Object? v) {
final ids = <int>[];
void add(Object? e) {
final n = flexibleInt(e);
if (n != null) ids.add(n);
}
switch (v) {
case final Map m:
add(m['tv']);
final movie = m['movie'];
if (movie is List) {
movie.forEach(add);
} else {
add(movie);
}
case final List l:
l.forEach(add);
default:
add(v);
}
return ids.isEmpty ? null : ids;
}
/// Defensive String coercion — Fribb's `type` is a string enum today, but the
/// schema has churned, so never hard-cast it.
String? _typeString(Object? v) => v is String ? v : null;
/// One row from `anime-list-mini.json` (Fribb/anime-lists).
@JsonSerializable(createToJson: false)
class FribbMappingRow {
@@ -22,14 +54,20 @@ class FribbMappingRow {
final int? anidbId;
@JsonKey(name: 'anilist_id', fromJson: flexibleInt)
final int? anilistId;
@JsonKey(name: 'imdb_id')
final String? imdbId;
/// Fribb's `imdb_id` is an array of IMDb GUIDs (movie collections / multi-part
/// can carry several); a Plex item matches if its single IMDb id is any one.
@JsonKey(name: 'imdb_id', fromJson: flexibleStringList)
final List<String>? imdbIds;
@JsonKey(name: 'mal_id', fromJson: flexibleInt)
final int? malId;
@JsonKey(name: 'simkl_id', fromJson: flexibleInt)
final int? simklId;
@JsonKey(name: 'themoviedb_id', fromJson: flexibleInt)
final int? tmdbId;
/// Fribb's `themoviedb_id` is `{"tv": id}` or `{"movie": [ids]}`. Flattened to
/// a list so a Plex item matches if its single TMDB id is any one.
@JsonKey(name: 'themoviedb_id', fromJson: _flattenTmdbIds)
final List<int>? tmdbIds;
@JsonKey(name: 'tvdb_id', fromJson: flexibleInt)
final int? tvdbId;
@@ -42,15 +80,16 @@ class FribbMappingRow {
final int? tmdbSeason;
/// `TV` / `MOVIE` / `OVA` / `ONA` / `SPECIAL` / `UNKNOWN` / `null`.
@JsonKey(fromJson: _typeString)
final String? type;
const FribbMappingRow({
this.anidbId,
this.anilistId,
this.imdbId,
this.imdbIds,
this.malId,
this.simklId,
this.tmdbId,
this.tmdbIds,
this.tvdbId,
this.tvdbSeason,
this.tmdbSeason,
+3 -3
View File
@@ -10,12 +10,12 @@ FribbMappingRow _$FribbMappingRowFromJson(Map<String, dynamic> json) =>
FribbMappingRow(
anidbId: flexibleInt(json['anidb_id']),
anilistId: flexibleInt(json['anilist_id']),
imdbId: json['imdb_id'] as String?,
imdbIds: flexibleStringList(json['imdb_id']),
malId: flexibleInt(json['mal_id']),
simklId: flexibleInt(json['simkl_id']),
tmdbId: flexibleInt(json['themoviedb_id']),
tmdbIds: _flattenTmdbIds(json['themoviedb_id']),
tvdbId: flexibleInt(json['tvdb_id']),
tvdbSeason: flexibleInt(_readTvdbSeason(json, 'tvdbSeason')),
tmdbSeason: flexibleInt(_readTmdbSeason(json, 'tmdbSeason')),
type: json['type'] as String?,
type: _typeString(json['type']),
);
+54 -7
View File
@@ -1,6 +1,8 @@
import 'package:collection/collection.dart';
import 'package:flutter/services.dart';
import '../../../services/device_performance.dart';
import '../../../services/settings_service.dart';
import '../../models.dart';
import '../player_base.dart';
@@ -13,6 +15,9 @@ class PlayerAndroid extends PlayerBase {
bool _tunnelingEnabled = true;
String _dvConversionMode = 'auto';
bool _audioNormalizationEnabled = false;
bool _audioPassthroughEnabled = false;
static const String _passthroughCodecs = 'ac3,eac3,dts,dts-hd,truehd';
/// The native plugin switched from ExoPlayer to its mpv fallback for this
/// session. Sticky for the instance lifetime, mirroring the native flag
@@ -36,11 +41,11 @@ class PlayerAndroid extends PlayerBase {
@override
bool get supportsSecondarySubtitles => false;
// Under the mpv fallback the native open path drops the externalSubtitles
// argument, so subsequent opens must use the post-open sub-add dance
// (handleAddSubtitleTrack routes to mpv natively).
// ExoPlayer attaches external subtitles to the MediaItem before prepare;
// the Android mpv fallback mirrors PlayerNative by passing sub-files through
// loadfile options.
@override
bool get attachesExternalSubtitlesAtOpen => !_usingMpvFallback;
bool get attachesExternalSubtitlesAtOpen => true;
// The fallback runs mpv over MediaCodec — the same display-switch decoder
// constraint as PlayerNative on Android. The whole startup-gate chain
@@ -55,14 +60,20 @@ class PlayerAndroid extends PlayerBase {
@override
bool get providesNativeStats => true;
@override
bool get audioPassthroughActive => _audioPassthroughEnabled;
@override
void handlePlayerEvent(String name, Map? data) {
if (name == 'backend-switched') {
// Native player switched from ExoPlayer to MPV due to unsupported format.
// Clear stale ExoPlayer tracks so applyTrackSelectionWhenReady waits for
// mpv's track-list instead of immediately applying with ExoPlayer IDs.
final wasUsingMpvFallback = _usingMpvFallback;
_usingMpvFallback = true;
clearTracks();
if (!wasUsingMpvFallback) {
clearTracks();
}
backendSwitchedController.add(null);
return;
}
@@ -88,6 +99,15 @@ class PlayerAndroid extends PlayerBase {
'bufferSizeBytes': _bufferSizeBytes,
'tunnelingEnabled': _tunnelingEnabled,
'dvConversionMode': _dvConversionMode,
'audioPassthroughEnabled': _audioPassthroughEnabled,
// Cheap (32-bit) TV boxes run the hardware video path a frame behind a GL
// subtitle overlay; render the ASS one frame earlier there to realign.
'assVideoLatencyFrames': DevicePerformance.isLowEndHardware ? 1 : 0,
// libass overlay raster scale from the "Render Resolution" subtitle setting
// (Full / ¾ / ½ / ⅓ / ¼); < 1 trades sharpness for throughput on slow GPUs.
'subtitleRenderScale': SettingsService.instance
.read(SettingsService.subtitleRenderResolution)
.androidRenderScale,
});
if (result != true) {
throw Exception('Failed to initialize ExoPlayer');
@@ -119,12 +139,13 @@ class PlayerAndroid extends PlayerBase {
if (disposed) return;
await _ensureInitialized();
final startPosition = media.start ?? Duration.zero;
final hasStartPosition = media.start != null && startPosition > Duration.zero;
// ExoPlayer reports Plex copyts transcodes in source-time coordinates,
// unlike mpv which rebases them to zero. Do not add the timeline offset
// again on Android ExoPlayer or seeks/progress jump to roughly 2x (#1221).
configureTimeline(offset: Duration.zero, duration: timelineDuration);
clearTracks();
resetPlaybackProgress(media.start ?? timelineOffset);
setExternalSubtitleMetadata(externalSubtitles);
setSeekable(false);
// Show the video layer
@@ -134,6 +155,7 @@ class PlayerAndroid extends PlayerBase {
'uri': media.uri,
'headers': media.headers,
'startPositionMs': startPosition.inMilliseconds,
'hasStartPosition': hasStartPosition,
'autoPlay': play,
'isLive': isLive,
if (externalSubtitles != null && externalSubtitles.isNotEmpty)
@@ -151,6 +173,7 @@ class PlayerAndroid extends PlayerBase {
)
.toList(),
});
resetPlaybackProgress(media.start ?? timelineOffset);
}
@override
@@ -278,6 +301,22 @@ class PlayerAndroid extends PlayerBase {
await super.setAudioNormalization(enabled);
}
@override
Future<void> setAudioPassthrough(bool enabled) async {
if (disposed) return;
_audioPassthroughEnabled = enabled;
final initFuture = _initFuture;
if (initialized) {
await invoke('setAudioPassthrough', {'enabled': enabled});
} else if (initFuture != null) {
await initFuture;
if (!disposed && initialized && _audioPassthroughEnabled == enabled) {
await invoke('setAudioPassthrough', {'enabled': enabled});
}
}
await setProperty('audio-spdif', enabled ? _passthroughCodecs : '');
}
@override
Future<String?> getProperty(String name) async {
if (disposed) return null;
@@ -430,12 +469,20 @@ class PlayerAndroid extends PlayerBase {
}
@override
Future<bool> setVideoFrameRate(double fps, int durationMs, {int extraDelayMs = 0}) async {
Future<bool> setVideoFrameRate(
double fps,
int durationMs, {
int extraDelayMs = 0,
int videoWidth = 0,
int videoHeight = 0,
}) async {
if (disposed || !initialized) return false;
final result = await invoke<bool>('setVideoFrameRate', {
'fps': fps,
'duration': durationMs,
'extraDelayMs': extraDelayMs,
'videoWidth': videoWidth,
'videoHeight': videoHeight,
});
return result ?? false;
}
+7 -1
View File
@@ -254,7 +254,13 @@ abstract class Player {
/// the caller is responsible for starting playback itself.
///
/// On other platforms, this is a no-op that returns `false`.
Future<bool> setVideoFrameRate(double fps, int durationMs, {int extraDelayMs = 0});
Future<bool> setVideoFrameRate(
double fps,
int durationMs, {
int extraDelayMs = 0,
int videoWidth = 0,
int videoHeight = 0,
});
/// Clear the video frame rate hint and restore default display mode.
///
+28 -7
View File
@@ -56,6 +56,7 @@ abstract class PlayerBase with PlayerStreamControllersMixin implements Player {
Duration? _timelineDuration;
int _nextPropId = 0;
final Map<int, String> _propIdToName = {};
Map<String, SubtitleTrack> _externalSubtitleMetadataByUri = const {};
@protected
bool initialized = false;
@@ -447,16 +448,18 @@ abstract class PlayerBase with PlayerStreamControllersMixin implements Player {
} else if (type == 'sub') {
if (selected) selectedSubtitleId = id;
final codec = track['codec'] as String?;
final externalFilename = track['external-filename'] as String?;
final externalMetadata = externalFilename == null ? null : _externalSubtitleMetadataByUri[externalFilename];
subtitleTracks.add(
SubtitleTrack(
id: id,
title: cleanSubtitleTitle(track['title'] as String?, codec: codec),
language: cleanTrackMetadataValue(track['lang'] as String?),
codec: codec,
isDefault: track['default'] as bool? ?? false,
isForced: track['forced'] as bool? ?? false,
title: externalMetadata?.title ?? cleanSubtitleTitle(track['title'] as String?, codec: codec),
language: externalMetadata?.language ?? cleanTrackMetadataValue(track['lang'] as String?),
codec: externalMetadata?.codec ?? codec,
isDefault: externalMetadata?.isDefault ?? (track['default'] as bool? ?? false),
isForced: externalMetadata?.isForced ?? (track['forced'] as bool? ?? false),
isExternal: track['external'] as bool? ?? false,
uri: track['external-filename'] as String?,
uri: externalFilename,
),
);
}
@@ -514,6 +517,18 @@ abstract class PlayerBase with PlayerStreamControllersMixin implements Player {
tracksController.add(empty);
}
@protected
void setExternalSubtitleMetadata(List<SubtitleTrack>? externalSubtitles) {
final metadataByUri = <String, SubtitleTrack>{};
for (final subtitle in externalSubtitles ?? const <SubtitleTrack>[]) {
final uri = subtitle.uri;
if (uri != null && uri.isNotEmpty) {
metadataByUri[uri] = subtitle;
}
}
_externalSubtitleMetadataByUri = metadataByUri;
}
@protected
void setVolumeState(double volume) {
if (_state.volume == volume) return;
@@ -598,7 +613,13 @@ abstract class PlayerBase with PlayerStreamControllersMixin implements Player {
Future<void> updateFrame() async {}
@override
Future<bool> setVideoFrameRate(double fps, int durationMs, {int extraDelayMs = 0}) async => false;
Future<bool> setVideoFrameRate(
double fps,
int durationMs, {
int extraDelayMs = 0,
int videoWidth = 0,
int videoHeight = 0,
}) async => false;
@override
// ignore: no-empty-block - base no-op, overridden by platform subclasses
+53 -5
View File
@@ -1,3 +1,4 @@
import 'dart:convert';
import 'dart:io' show Platform;
import 'package:flutter/services.dart';
@@ -6,9 +7,7 @@ import '../../media/media_display_criteria.dart';
import '../models.dart';
import 'player_base.dart';
/// Shared native implementation of [Player] for iOS, macOS, Android (MPV fallback), and Linux.
/// Uses MPVKit via platform channels with Metal rendering (Apple), native window (Android),
/// or FlTextureGL (Linux).
/// MPV-backed player for platforms where AetherEngine is not the native route.
class PlayerNative extends PlayerBase {
int? _textureIdValue;
String _dvConversionMode = 'auto';
@@ -32,6 +31,12 @@ class PlayerNative extends PlayerBase {
@override
String get playerType => 'mpv';
@override
bool get providesNativeStats => Platform.isAndroid;
@override
bool get attachesExternalSubtitlesAtOpen => true;
/// Node properties are returned as structured maps on macOS/iOS/Linux,
/// but as JSON strings on Android/Windows.
static final String _nodeFormat = (Platform.isAndroid || Platform.isWindows) ? 'string' : 'node';
@@ -52,6 +57,27 @@ class PlayerNative extends PlayerBase {
};
}
static String _fixedLengthQuote(String value) {
return '%${utf8.encode(value).length}%$value';
}
static String _escapePathListEntry(String value, String separator) {
return value.replaceAll(r'\', r'\\').replaceAll(separator, '\\$separator');
}
static String? _externalSubtitlesLoadfileOption(List<SubtitleTrack>? externalSubtitles) {
final separator = Platform.isWindows ? ';' : ':';
final escapedUris = externalSubtitles
?.map((subtitle) => subtitle.uri)
.whereType<String>()
.where((uri) => uri.isNotEmpty)
.map((uri) => _escapePathListEntry(uri, separator))
.toList();
if (escapedUris == null || escapedUris.isEmpty) return null;
return 'sub-files=${_fixedLengthQuote(escapedUris.join(separator))}';
}
MediaDisplayCriteria? _effectiveDisplayCriteria(MediaDisplayCriteria? criteria) {
if (criteria == null || (criteria.doviProfile ?? 0) != 7) return criteria;
@@ -148,6 +174,7 @@ class PlayerNative extends PlayerBase {
final startPosition = media.start ?? Duration.zero;
configureTimeline(offset: timelineOffset, duration: timelineDuration);
clearTracks();
setExternalSubtitleMetadata(externalSubtitles);
resetPlaybackProgress(startPosition);
setSeekable(false);
@@ -184,7 +211,12 @@ class PlayerNative extends PlayerBase {
}
}
await command(['loadfile', uri, 'replace']);
final loadfileArgs = ['loadfile', uri, 'replace'];
final loadfileOption = _externalSubtitlesLoadfileOption(externalSubtitles);
if (loadfileOption != null) {
loadfileArgs.addAll(['-1', loadfileOption]);
}
await command(loadfileArgs);
// mpv's pause property survives loadfile; in-place reloads pause the old
// file before resolving, so explicitly unpause for the replacement. Set
@@ -294,6 +326,14 @@ class PlayerNative extends PlayerBase {
return await invoke<String>('getProperty', {'name': name});
}
@override
Future<Map<String, dynamic>> getStats() async {
if (disposed || !Platform.isAndroid) return super.getStats();
await _ensureInitialized();
final result = await invoke<Map>('getStats');
return Map<String, dynamic>.from(result ?? const {});
}
@override
Future<void> command(List<String> args) async {
if (disposed) return;
@@ -361,12 +401,20 @@ class PlayerNative extends PlayerBase {
}
@override
Future<bool> setVideoFrameRate(double fps, int durationMs, {int extraDelayMs = 0}) async {
Future<bool> setVideoFrameRate(
double fps,
int durationMs, {
int extraDelayMs = 0,
int videoWidth = 0,
int videoHeight = 0,
}) async {
if (!Platform.isAndroid || disposed || !initialized) return false;
final result = await invoke<bool>('setVideoFrameRate', {
'fps': fps,
'duration': durationMs,
'extraDelayMs': extraDelayMs,
'videoWidth': videoWidth,
'videoHeight': videoHeight,
});
return result ?? false;
}
+45 -6
View File
@@ -1,5 +1,6 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'player/player.dart';
@@ -23,8 +24,15 @@ class Video extends StatefulWidget {
final Player player;
final Widget Function(BuildContext context)? controls;
final Color backgroundColor;
final ValueListenable<bool>? hasFirstFrame;
const Video({super.key, required this.player, this.controls, this.backgroundColor = Colors.black});
const Video({
super.key,
required this.player,
this.controls,
this.backgroundColor = Colors.black,
this.hasFirstFrame,
});
@override
State<Video> createState() => _VideoState();
@@ -38,19 +46,50 @@ class _VideoState extends State<Video> {
@override
void initState() {
super.initState();
_playbackRestartSubscription = widget.player.streams.playbackRestart.listen((_) {
if (!_hasFirstFrame && mounted) {
setState(() => _hasFirstFrame = true);
}
});
_hasFirstFrame = widget.hasFirstFrame?.value ?? false;
widget.hasFirstFrame?.addListener(_syncExternalFirstFrame);
_listenForPlaybackRestart();
}
@override
void didUpdateWidget(covariant Video oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.hasFirstFrame != widget.hasFirstFrame) {
oldWidget.hasFirstFrame?.removeListener(_syncExternalFirstFrame);
widget.hasFirstFrame?.addListener(_syncExternalFirstFrame);
_syncExternalFirstFrame();
}
if (oldWidget.player != widget.player) {
_playbackRestartSubscription?.cancel();
_listenForPlaybackRestart();
_syncExternalFirstFrame();
}
}
@override
void dispose() {
widget.hasFirstFrame?.removeListener(_syncExternalFirstFrame);
_playbackRestartSubscription?.cancel();
super.dispose();
}
void _listenForPlaybackRestart() {
_playbackRestartSubscription = widget.player.streams.playbackRestart.listen((_) {
_setHasFirstFrame(true);
});
}
void _syncExternalFirstFrame() {
final external = widget.hasFirstFrame;
if (external == null) return;
_setHasFirstFrame(external.value);
}
void _setHasFirstFrame(bool value) {
if (_hasFirstFrame == value || !mounted) return;
setState(() => _hasFirstFrame = value);
}
@override
Widget build(BuildContext context) {
return ColoredBox(
@@ -0,0 +1,77 @@
import 'package:flutter/material.dart';
/// Tracks the currently mounted profile-scoped navigator and main
/// ScaffoldMessenger without making their GlobalKeys app-lifetime widgets.
///
/// The keys are created inside the profile session and registered here only so
/// app-global helpers (mouse back, background snackbars) can reach the active
/// profile surface. A profile switch unregisters the old keys before the new
/// session registers fresh ones.
class ProfileNavigationRegistry {
GlobalKey<NavigatorState>? _navigatorKey;
GlobalKey<ScaffoldMessengerState>? _mainScaffoldMessengerKey;
NavigatorState? get navigator => _navigatorKey?.currentState;
ScaffoldMessengerState? get mainScaffoldMessenger => _mainScaffoldMessengerKey?.currentState;
void attachNavigator(GlobalKey<NavigatorState> key) {
_navigatorKey = key;
}
void detachNavigator(GlobalKey<NavigatorState> key) {
if (identical(_navigatorKey, key)) {
_navigatorKey = null;
}
}
void attachMainScaffoldMessenger(GlobalKey<ScaffoldMessengerState> key) {
_mainScaffoldMessengerKey = key;
}
void detachMainScaffoldMessenger(GlobalKey<ScaffoldMessengerState> key) {
if (identical(_mainScaffoldMessengerKey, key)) {
_mainScaffoldMessengerKey = null;
}
}
Future<bool> maybePopProfileRoute() async {
final state = navigator;
if (state == null) return false;
return state.maybePop();
}
}
final profileNavigationRegistry = ProfileNavigationRegistry();
class ProfileNavigationScope extends InheritedWidget {
const ProfileNavigationScope({
super.key,
required this.navigatorKey,
required this.routeObserver,
required this.mainScaffoldMessengerKey,
required super.child,
});
final GlobalKey<NavigatorState> navigatorKey;
final RouteObserver<PageRoute<dynamic>> routeObserver;
final GlobalKey<ScaffoldMessengerState> mainScaffoldMessengerKey;
static ProfileNavigationScope of(BuildContext context) {
final scope = context.dependOnInheritedWidgetOfExactType<ProfileNavigationScope>();
if (scope == null) {
throw StateError('ProfileNavigationScope is required for profile routes.');
}
return scope;
}
static ProfileNavigationScope? maybeOf(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<ProfileNavigationScope>();
}
@override
bool updateShouldNotify(ProfileNavigationScope oldWidget) {
return navigatorKey != oldWidget.navigatorKey ||
routeObserver != oldWidget.routeObserver ||
mainScaffoldMessengerKey != oldWidget.mainScaffoldMessengerKey;
}
}
+224
View File
@@ -0,0 +1,224 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../focus/key_event_utils.dart';
import '../media/ids.dart';
import '../media/media_server_client.dart';
import '../profiles/active_profile_provider.dart';
import '../providers/companion_remote_provider.dart';
import '../providers/discover_provider.dart';
import '../providers/hidden_libraries_provider.dart';
import '../providers/libraries_provider.dart';
import '../providers/multi_server_provider.dart';
import '../providers/playback_state_provider.dart';
import '../providers/trakt_account_provider.dart';
import '../providers/trackers_provider.dart';
import '../providers/watch_state_store.dart';
import '../screens/main_screen.dart';
import '../services/storage_service.dart';
import '../utils/app_logger.dart';
import '../watch_together/providers/watch_together_provider.dart';
import 'profile_navigation_scope.dart';
/// Root route for an active profile session.
///
/// The root app navigator owns setup/auth/profile-picking. This route owns the
/// profile-scoped provider tree and a nested navigator for all content routes.
/// Changing the active profile changes the keyed boundary below, disposing the
/// old nested navigator, MainScreen, tab state, and profile-scoped providers.
///
/// Keep profile-owned routes, dialogs, sheets, and virtual keyboards on the
/// nearest navigator from this subtree. Keep setup/auth/PIN/profile-picker flows
/// on the root navigator so they survive this subtree being replaced.
class ProfileSessionScreen extends StatefulWidget {
const ProfileSessionScreen({super.key, this.isOfflineMode = false, this.initialPromptHandled = false})
: profileShellBuilder = null;
@visibleForTesting
const ProfileSessionScreen.forTesting({
super.key,
this.isOfflineMode = false,
this.initialPromptHandled = false,
required this.profileShellBuilder,
});
final bool isOfflineMode;
final bool initialPromptHandled;
final WidgetBuilder? profileShellBuilder;
@override
State<ProfileSessionScreen> createState() => _ProfileSessionScreenState();
}
class _ProfileSessionScreenState extends State<ProfileSessionScreen> {
// Profile changes remount the inner session, but the root route survives.
// Treat the initial launch/profile prompt as handled after the first session
// frame so switching profiles from the root picker does not immediately open
// another required-selection picker underneath it. Flipped via a post-frame
// callback rather than during build to avoid mutating state mid-build.
bool _hasBuiltSession = false;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) _hasBuiltSession = true;
});
}
@override
Widget build(BuildContext context) {
return Consumer<ActiveProfileProvider>(
builder: (context, activeProfile, _) {
final activeId = activeProfile.activeId;
final initialPromptHandled = widget.initialPromptHandled || _hasBuiltSession;
return KeyedSubtree(
key: ValueKey<String?>('profile-session:$activeId'),
child: MultiProvider(
providers: [
ChangeNotifierProxyProvider<MultiServerProvider, WatchStateStore>(
create: (_) => WatchStateStore(),
update: (_, multiServer, previous) {
final provider = previous ?? WatchStateStore();
provider.setActiveProfileId(activeId);
provider.setActiveClientScopesByServer({
for (final serverId in multiServer.serverManager.serverIds)
serverId: multiServer.serverManager.getClient(ServerId(serverId))?.cacheServerId,
});
return provider;
},
),
ChangeNotifierProvider(
create: (context) {
final provider = TraktAccountProvider();
unawaited(
provider.onActiveProfileChanged(activeId).catchError((Object e, StackTrace s) {
appLogger.w('Trakt profile hydrate failed', error: e, stackTrace: s);
}),
);
return provider;
},
),
ChangeNotifierProvider(
create: (context) {
final provider = TrackersProvider();
unawaited(
provider.onActiveProfileChanged(activeId).catchError((Object e, StackTrace s) {
appLogger.w('Trackers profile hydrate failed', error: e, stackTrace: s);
}),
);
return provider;
},
),
ChangeNotifierProvider(
create: (context) =>
HiddenLibrariesProvider(storageService: context.read<StorageService>(), profileId: activeId),
lazy: true,
),
ChangeNotifierProvider(
create: (context) => LibrariesProvider(
storageService: context.read<StorageService>(),
multiServer: context.read<MultiServerProvider>(),
),
),
ChangeNotifierProvider(
create: (context) {
final activeProfile = context.read<ActiveProfileProvider>();
return DiscoverProvider(
context.read<MultiServerProvider>(),
context.read<HiddenLibrariesProvider>(),
context.read<LibrariesProvider>(),
isProfileBinding: () => activeProfile.isBinding,
);
},
),
ChangeNotifierProvider(create: (context) => PlaybackStateProvider()),
ChangeNotifierProvider(create: (context) => WatchTogetherProvider()),
ChangeNotifierProvider(create: (context) => CompanionRemoteProvider()),
],
child: _ProfileSessionNavigator(
isOfflineMode: widget.isOfflineMode,
initialPromptHandled: initialPromptHandled,
profileShellBuilder: widget.profileShellBuilder,
),
),
);
},
);
}
}
class _ProfileSessionNavigator extends StatefulWidget {
const _ProfileSessionNavigator({
required this.isOfflineMode,
required this.initialPromptHandled,
required this.profileShellBuilder,
});
final bool isOfflineMode;
final bool initialPromptHandled;
final WidgetBuilder? profileShellBuilder;
@override
State<_ProfileSessionNavigator> createState() => _ProfileSessionNavigatorState();
}
class _ProfileSessionNavigatorState extends State<_ProfileSessionNavigator> {
final _navigatorKey = GlobalKey<NavigatorState>();
final _mainScaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>();
final _routeObserver = RouteObserver<PageRoute<dynamic>>();
@override
void initState() {
super.initState();
profileNavigationRegistry.attachNavigator(_navigatorKey);
profileNavigationRegistry.attachMainScaffoldMessenger(_mainScaffoldMessengerKey);
}
@override
void dispose() {
profileNavigationRegistry.detachNavigator(_navigatorKey);
profileNavigationRegistry.detachMainScaffoldMessenger(_mainScaffoldMessengerKey);
super.dispose();
}
@override
Widget build(BuildContext context) {
return ProfileNavigationScope(
navigatorKey: _navigatorKey,
routeObserver: _routeObserver,
mainScaffoldMessengerKey: _mainScaffoldMessengerKey,
child: PopScope(
canPop: false,
onPopInvokedWithResult: (didPop, _) {
if (didPop) return;
unawaited(_navigatorKey.currentState?.maybePop());
},
child: Navigator(
key: _navigatorKey,
observers: [_routeObserver, BackKeySuppressorObserver()],
onGenerateRoute: _onGenerateRoute,
),
),
);
}
Route<dynamic> _onGenerateRoute(RouteSettings settings) {
// This navigator's initial route is the profile shell. Content routes are
// pushed imperatively from inside the shell, so named routes belong to the
// root navigator unless this method is expanded intentionally.
final routeName = settings.name;
if (routeName != null && routeName != Navigator.defaultRouteName) {
throw FlutterError('ProfileSessionNavigator does not handle named route "$routeName".');
}
return MaterialPageRoute<void>(
settings: settings,
builder: (context) =>
widget.profileShellBuilder?.call(context) ??
MainScreen(isOfflineMode: widget.isOfflineMode, initialPromptHandled: widget.initialPromptHandled),
);
}
}
@@ -0,0 +1,203 @@
import '../connection/connection.dart';
import '../connection/connection_registry.dart';
import '../media/ids.dart';
import '../services/multi_server_manager.dart';
import '../services/storage_service.dart';
import 'profile_connection_registry.dart';
Future<void> removeProfileConnectionAndCleanup({
required String profileId,
required Connection connection,
required ProfileConnectionRegistry profileConnections,
required ConnectionRegistry connections,
required StorageService storage,
MultiServerManager? serverManager,
}) async {
final removedServerIds = _serverIdsForConnection(connection);
await profileConnections.remove(profileId, connection.id);
await _clearProfileServerPrefsNoLongerReferenced(
profileId: profileId,
removedServerIds: removedServerIds,
profileConnections: profileConnections,
connections: connections,
storage: storage,
clearEverywhereWhenUnreferenced: connection is JellyfinConnection,
);
if (connection is JellyfinConnection) {
await _removeUnreferencedJellyfinConnection(
connection,
profileConnections: profileConnections,
connections: connections,
storage: storage,
serverManager: serverManager,
);
}
}
Future<void> removeAllProfileConnectionsAndCleanup({
required String profileId,
required ProfileConnectionRegistry profileConnections,
required ConnectionRegistry connections,
required StorageService storage,
MultiServerManager? serverManager,
}) async {
final rows = await profileConnections.listForProfile(profileId);
if (rows.isEmpty) return;
final all = await connections.list();
final byId = {for (final connection in all) connection.id: connection};
for (final row in rows) {
final connection = byId[row.connectionId];
if (connection == null) {
await profileConnections.remove(profileId, row.connectionId);
continue;
}
await removeProfileConnectionAndCleanup(
profileId: profileId,
connection: connection,
profileConnections: profileConnections,
connections: connections,
storage: storage,
serverManager: serverManager,
);
}
}
Future<int> pruneUnreferencedJellyfinConnections({
required ProfileConnectionRegistry profileConnections,
required ConnectionRegistry connections,
required StorageService storage,
MultiServerManager? serverManager,
}) async {
final all = await connections.list();
final referencedConnectionIds = (await profileConnections.listAll()).map((row) => row.connectionId).toSet();
var removed = 0;
for (final connection in all.whereType<JellyfinConnection>()) {
if (referencedConnectionIds.contains(connection.id)) continue;
await _removeJellyfinConnection(
connection,
profileConnections: profileConnections,
connections: connections,
storage: storage,
serverManager: serverManager,
);
removed++;
}
return removed;
}
Future<void> _removeUnreferencedJellyfinConnection(
JellyfinConnection connection, {
required ProfileConnectionRegistry profileConnections,
required ConnectionRegistry connections,
required StorageService storage,
MultiServerManager? serverManager,
}) async {
if ((await profileConnections.listForConnection(connection.id)).isNotEmpty) return;
await _removeJellyfinConnection(
connection,
profileConnections: profileConnections,
connections: connections,
storage: storage,
serverManager: serverManager,
);
}
Future<void> _removeJellyfinConnection(
JellyfinConnection connection, {
required ProfileConnectionRegistry profileConnections,
required ConnectionRegistry connections,
required StorageService storage,
MultiServerManager? serverManager,
}) async {
await connections.remove(connection.id);
serverManager?.removeJellyfinConnection(connection);
final serverId = ServerId.tryParse(connection.serverMachineId);
if (serverId != null &&
!await _isServerReferenced(serverId, profileConnections: profileConnections, connections: connections)) {
await storage.clearLibraryPreferencesForServerEverywhere(serverId);
}
}
Future<void> _clearProfileServerPrefsNoLongerReferenced({
required String profileId,
required Set<ServerId> removedServerIds,
required ProfileConnectionRegistry profileConnections,
required ConnectionRegistry connections,
required StorageService storage,
required bool clearEverywhereWhenUnreferenced,
}) async {
if (removedServerIds.isEmpty) return;
final remainingProfileServerIds = await _serverIdsForProfile(
profileId,
profileConnections: profileConnections,
connections: connections,
);
final activeProfileId = storage.getActiveProfileId();
for (final serverId in removedServerIds) {
if (remainingProfileServerIds.contains(serverId)) continue;
final serverStillReferenced = await _isServerReferenced(
serverId,
profileConnections: profileConnections,
connections: connections,
);
if (serverStillReferenced || !clearEverywhereWhenUnreferenced) {
await storage.clearLibraryPreferencesForServer(
serverId,
profileId: profileId,
includeLegacy: activeProfileId == profileId,
);
} else {
await storage.clearLibraryPreferencesForServerEverywhere(serverId);
}
}
}
Future<Set<ServerId>> _serverIdsForProfile(
String profileId, {
required ProfileConnectionRegistry profileConnections,
required ConnectionRegistry connections,
}) async {
final rows = await profileConnections.listForProfile(profileId);
if (rows.isEmpty) return const {};
final all = await connections.list();
final byId = {for (final connection in all) connection.id: connection};
return {
for (final row in rows)
if (byId[row.connectionId] case final connection?) ..._serverIdsForConnection(connection),
};
}
Future<bool> _isServerReferenced(
ServerId serverId, {
required ProfileConnectionRegistry profileConnections,
required ConnectionRegistry connections,
}) async {
final rows = await profileConnections.listAll();
if (rows.isEmpty) return false;
final all = await connections.list();
final byId = {for (final connection in all) connection.id: connection};
for (final row in rows) {
final connection = byId[row.connectionId];
if (connection != null && _serverIdsForConnection(connection).contains(serverId)) return true;
}
return false;
}
Set<ServerId> _serverIdsForConnection(Connection connection) {
return switch (connection) {
PlexAccountConnection(:final servers) => {
for (final server in servers)
if (ServerId.tryParse(server.clientIdentifier) case final serverId?) serverId,
},
JellyfinConnection(:final serverMachineId) => {
if (ServerId.tryParse(serverMachineId) case final serverId?) serverId,
},
};
}
+9 -9
View File
@@ -126,11 +126,9 @@ class DiscoverProvider extends ChangeNotifier with DisposableChangeNotifierMixin
/// and merged in; already-loaded servers are not refetched.
Future<void> syncToOnlineServers(Set<String> onlineServerIds) {
if (onlineServerIds.isEmpty || isProfileBinding()) return Future<void>.value();
if (
_onDeckState == DiscoverLoadState.loaded &&
_hubsState == DiscoverLoadState.loaded &&
_fullyLoadedServerIds.containsAll(onlineServerIds)
) {
if (_onDeckState == DiscoverLoadState.loaded &&
_hubsState == DiscoverLoadState.loaded &&
_fullyLoadedServerIds.containsAll(onlineServerIds)) {
return Future<void>.value();
}
// Nothing (or a failed pass) to merge into yet — run the full load.
@@ -490,10 +488,12 @@ class DiscoverProvider extends ChangeNotifier with DisposableChangeNotifierMixin
try {
final settings = await SettingsService.getInstance();
final syncableOnDeck = onDeck.where((item) {
final serverId = item.serverId;
return serverId != null && _multiServer.getClientForServer(ServerId(serverId)) != null;
}).toList(growable: false);
final syncableOnDeck = onDeck
.where((item) {
final serverId = item.serverId;
return serverId != null && _multiServer.getClientForServer(ServerId(serverId)) != null;
})
.toList(growable: false);
await SystemShelfService().syncFromContinueWatching(
syncableOnDeck,
_clientForShelfItem,
+28 -3
View File
@@ -845,6 +845,7 @@ class DownloadProvider extends ChangeNotifier with DisposableChangeNotifierMixin
DownloadVersionConfig? versionConfig,
DownloadFilter filter = DownloadFilter.all,
int? maxCount,
bool includeSpecials = true,
}) async {
if (!_downloadManager.downloadsSupported) return 0;
@@ -870,7 +871,14 @@ class DownloadProvider extends ChangeNotifier with DisposableChangeNotifierMixin
final hadMetadata = _metadata.containsKey(globalKey);
_metadata[globalKey] = metadata;
try {
return await _queueShowDownload(metadata, client, versionConfig: config, filter: filter, maxCount: maxCount);
return await _queueShowDownload(
metadata,
client,
versionConfig: config,
filter: filter,
maxCount: maxCount,
includeSpecials: includeSpecials,
);
} catch (_) {
if (!hadMetadata) _metadata.remove(globalKey);
rethrow;
@@ -885,6 +893,7 @@ class DownloadProvider extends ChangeNotifier with DisposableChangeNotifierMixin
versionConfig: config,
filter: filter,
maxCount: maxCount,
includeSpecials: includeSpecials,
);
} catch (_) {
if (!hadMetadata) _metadata.remove(globalKey);
@@ -921,7 +930,7 @@ class DownloadProvider extends ChangeNotifier with DisposableChangeNotifierMixin
int count = 0;
Future<void> queueItem(MediaItem item) async {
if (unwatchedOnly && item.isWatched && !item.hasActiveProgress) return;
if (unwatchedOnly && !item.isUnwatchedOrInProgress) return;
final queued = await _queueSingleDownload(item, client, relatedContext: relatedContext);
if (queued) count++;
}
@@ -1120,6 +1129,7 @@ class DownloadProvider extends ChangeNotifier with DisposableChangeNotifierMixin
DownloadVersionConfig? versionConfig,
DownloadFilter filter = DownloadFilter.all,
int? maxCount,
bool includeSpecials = true,
}) async {
return _expandAndQueue(
container: show,
@@ -1128,6 +1138,7 @@ class DownloadProvider extends ChangeNotifier with DisposableChangeNotifierMixin
filter: filter,
maxCount: maxCount,
skipExisting: false,
includeSpecials: includeSpecials,
);
}
@@ -1138,6 +1149,7 @@ class DownloadProvider extends ChangeNotifier with DisposableChangeNotifierMixin
DownloadVersionConfig? versionConfig,
DownloadFilter filter = DownloadFilter.all,
int? maxCount,
bool includeSpecials = true,
}) async {
return _expandAndQueue(
container: season,
@@ -1146,6 +1158,7 @@ class DownloadProvider extends ChangeNotifier with DisposableChangeNotifierMixin
filter: filter,
maxCount: maxCount,
skipExisting: false,
includeSpecials: includeSpecials,
);
}
@@ -1183,8 +1196,13 @@ class DownloadProvider extends ChangeNotifier with DisposableChangeNotifierMixin
required DownloadFilter filter,
required int? maxCount,
required bool skipExisting,
bool includeSpecials = true,
}) async {
final unwatchedOnly = filter == DownloadFilter.unwatched;
// Downloading the Specials season itself must still queue its episodes —
// only suppress Specials when sweeping a whole show or a regular season.
final effectiveIncludeSpecials =
includeSpecials || (container.kind == MediaKind.season && isSpecialSeasonNumber(container.index));
final relatedContext = _RelatedMetadataDownloadContext();
final episodes = <MediaItem>[];
if (container.kind == MediaKind.show) {
@@ -1194,6 +1212,7 @@ class DownloadProvider extends ChangeNotifier with DisposableChangeNotifierMixin
unwatchedOnly: unwatchedOnly,
out: episodes,
fallback: container,
includeSpecials: effectiveIncludeSpecials,
);
} else {
await collectEpisodesForSeason(
@@ -1202,6 +1221,7 @@ class DownloadProvider extends ChangeNotifier with DisposableChangeNotifierMixin
unwatchedOnly: unwatchedOnly,
out: episodes,
fallback: container,
includeSpecials: effectiveIncludeSpecials,
);
}
@@ -1552,6 +1572,7 @@ class DownloadProvider extends ChangeNotifier with DisposableChangeNotifierMixin
required int episodeCount,
int mediaIndex = 0,
String downloadFilter = SyncRuleFilter.unwatched,
bool includeSpecials = true,
MediaItem? targetMetadata,
}) async {
final profileId = _requireActiveProfileId();
@@ -1566,6 +1587,7 @@ class DownloadProvider extends ChangeNotifier with DisposableChangeNotifierMixin
episodeCount: episodeCount,
mediaIndex: mediaIndex,
downloadFilter: downloadFilter,
includeSpecials: includeSpecials,
);
if (targetMetadata != null) {
@@ -1579,7 +1601,10 @@ class DownloadProvider extends ChangeNotifier with DisposableChangeNotifierMixin
_syncRules[rule.globalKey] = rule;
safeNotifyListeners();
}
appLogger.i('Created sync rule: $scopedGlobalKey ($targetType, filter=$downloadFilter, keep $episodeCount)');
appLogger.i(
'Created sync rule: $scopedGlobalKey '
'($targetType, filter=$downloadFilter, keep $episodeCount, includeSpecials=$includeSpecials)',
);
}
/// Update the episode count for an existing show/season sync rule.
+25 -7
View File
@@ -7,11 +7,12 @@ import '../services/storage_service.dart';
/// all other screens are automatically updated.
class HiddenLibrariesProvider extends ChangeNotifier with DisposableChangeNotifierMixin {
StorageService? _storageService;
final String? profileId;
Set<String> _hiddenLibraryKeys = {};
bool _isInitialized = false;
Future<void>? _initFuture;
HiddenLibrariesProvider({StorageService? storageService}) : _storageService = storageService {
HiddenLibrariesProvider({StorageService? storageService, this.profileId}) : _storageService = storageService {
// Start initialization eagerly to reduce race conditions
_initFuture = _initialize();
}
@@ -29,19 +30,36 @@ class HiddenLibrariesProvider extends ChangeNotifier with DisposableChangeNotifi
/// Initialize the provider by loading hidden libraries from storage
Future<void> _initialize() async {
if (_isInitialized) return;
final storage = _storageService ??= await StorageService.getInstance();
_hiddenLibraryKeys = storage.getHiddenLibraries();
await _loadFromStorage();
_isInitialized = true;
safeNotifyListeners();
}
Future<void> _loadFromStorage() async {
final storage = _storageService ??= await StorageService.getInstance();
final scopedProfileId = profileId;
_hiddenLibraryKeys = scopedProfileId == null
? storage.getHiddenLibraries()
: storage.getHiddenLibrariesForProfile(scopedProfileId);
}
Future<void> _saveToStorage() async {
final storage = _storageService ??= await StorageService.getInstance();
final scopedProfileId = profileId;
if (scopedProfileId == null) {
await storage.saveHiddenLibraries(_hiddenLibraryKeys);
} else {
await storage.saveHiddenLibrariesForProfile(scopedProfileId, _hiddenLibraryKeys);
}
}
/// Hide a library by its key
/// Updates both in-memory state and persistent storage
Future<void> hideLibrary(String libraryKey) async {
if (!_isInitialized) await _initialize();
if (!_hiddenLibraryKeys.contains(libraryKey)) {
_hiddenLibraryKeys = Set.from(_hiddenLibraryKeys)..add(libraryKey);
await _storageService!.saveHiddenLibraries(_hiddenLibraryKeys);
await _saveToStorage();
safeNotifyListeners();
}
}
@@ -52,7 +70,7 @@ class HiddenLibrariesProvider extends ChangeNotifier with DisposableChangeNotifi
if (!_isInitialized) await _initialize();
if (_hiddenLibraryKeys.contains(libraryKey)) {
_hiddenLibraryKeys = Set.from(_hiddenLibraryKeys)..remove(libraryKey);
await _storageService!.saveHiddenLibraries(_hiddenLibraryKeys);
await _saveToStorage();
safeNotifyListeners();
}
}
@@ -63,8 +81,8 @@ class HiddenLibrariesProvider extends ChangeNotifier with DisposableChangeNotifi
/// Refresh hidden libraries from storage
/// Useful if storage was modified outside the provider
Future<void> refresh() async {
final storage = _storageService ??= await StorageService.getInstance();
_hiddenLibraryKeys = storage.getHiddenLibraries();
await _loadFromStorage();
_isInitialized = true;
safeNotifyListeners();
}
}
+5 -12
View File
@@ -2,6 +2,7 @@ import 'package:flutter/foundation.dart';
import '../media/ids.dart';
import '../i18n/strings.g.dart';
import '../media/episode_collection.dart';
import '../media/media_item.dart';
import '../media/media_item_types.dart';
import '../mixins/disposable_change_notifier_mixin.dart';
@@ -85,21 +86,13 @@ class OfflineWatchProvider extends ChangeNotifier with DisposableChangeNotifierM
return metadata?.viewOffsetMs;
}
/// Get sorted episodes for a show (by season, then episode number).
/// Get sorted episodes for a show: regular seasons first, Specials last,
/// then season then episode — the shared [sortEpisodesByWatchOrder] order,
/// so the offline watch order matches what "download next N" selects (#1414).
List<MediaItem> _getSortedEpisodes(String showId) {
final episodes = _downloadProvider.getDownloadedEpisodesForShow(showId);
if (episodes.isEmpty) return episodes;
// Sort Season 0 (Specials) to the end so regular seasons play first
episodes.sort((a, b) {
final aIsSpecial = (a.parentIndex ?? 0) == 0;
final bIsSpecial = (b.parentIndex ?? 0) == 0;
if (aIsSpecial != bIsSpecial) return aIsSpecial ? 1 : -1;
final seasonCompare = (a.parentIndex ?? 0).compareTo(b.parentIndex ?? 0);
if (seasonCompare != 0) return seasonCompare;
return (a.index ?? 0).compareTo(b.index ?? 0);
});
sortEpisodesByWatchOrder(episodes);
return episodes;
}
+118 -54
View File
@@ -3,26 +3,21 @@ import 'dart:async';
import 'package:flutter/foundation.dart';
import '../models/trackers/device_code.dart';
import '../services/trackers/anilist/anilist_account_store.dart';
import '../services/trackers/anilist/anilist_auth_service.dart';
import '../services/trackers/anilist/anilist_client.dart';
import '../services/trackers/anilist/anilist_session.dart';
import '../services/trackers/anilist/anilist_tracker.dart';
import '../services/trackers/mal/mal_account_store.dart';
import '../services/trackers/mal/mal_auth_service.dart';
import '../services/trackers/mal/mal_client.dart';
import '../services/trackers/mal/mal_session.dart';
import '../services/trackers/mal/mal_tracker.dart';
import '../services/trackers/oauth_proxy_client.dart';
import '../services/trackers/simkl/simkl_account_store.dart';
import '../services/trackers/simkl/simkl_auth_service.dart';
import '../services/trackers/simkl/simkl_client.dart';
import '../services/trackers/simkl/simkl_session.dart';
import '../services/trackers/simkl/simkl_tracker.dart';
import '../services/trackers/tracker_account_store.dart';
import '../services/trackers/tracker_connect_runner.dart';
import '../services/trackers/tracker_constants.dart';
import '../services/trackers/tracker_coordinator.dart';
import '../services/trackers/tracker_session.dart';
import '../utils/app_logger.dart';
import '../mixins/disposable_change_notifier_mixin.dart';
@@ -33,18 +28,31 @@ class TrackersProvider extends ChangeNotifier with DisposableChangeNotifierMixin
final MalAuthService _malAuth = MalAuthService();
final AnilistAuthService _anilistAuth = AnilistAuthService();
final SimklAuthService _simklAuth = SimklAuthService();
final TrackerAccountStore _malStore = trackerAccountStore(TrackerService.mal);
final TrackerAccountStore _anilistStore = trackerAccountStore(TrackerService.anilist);
final TrackerAccountStore _simklStore = trackerAccountStore(TrackerService.simkl);
MalSession? _mal;
AnilistSession? _anilist;
SimklSession? _simkl;
TrackerSession? _mal;
TrackerSession? _anilist;
TrackerSession? _simkl;
String _activeUserUuid = '';
int _profileBindingGeneration = 0;
TrackerService? _connecting;
Completer<void>? _cancelCompleter;
MalSession? get mal => _mal;
AnilistSession? get anilist => _anilist;
SimklSession? get simkl => _simkl;
// Bumped on every rebind so a late callback from a disposed client (e.g. an
// in-flight MAL token refresh that resolves after a profile switch) can't
// persist or clear a session under the wrong profile, and so a disconnect
// racing an in-flight profile load only suppresses its own service. Mirrors
// TraktAccountProvider's binding-generation guard, but per service.
final _RebindGeneration _malRebind = _RebindGeneration();
final _RebindGeneration _anilistRebind = _RebindGeneration();
final _RebindGeneration _simklRebind = _RebindGeneration();
TrackerSession? get mal => _mal;
TrackerSession? get anilist => _anilist;
TrackerSession? get simkl => _simkl;
bool get isMalConnected => _mal != null;
bool get isAnilistConnected => _anilist != null;
@@ -68,20 +76,40 @@ class TrackersProvider extends ChangeNotifier with DisposableChangeNotifierMixin
// holds a PlexClient + session cache) before binding to the new profile.
TrackerCoordinator.instance.cancelInFlight();
_activeUserUuid = newUserUuid ?? '';
final results = await Future.wait([
malAccountStore.load(_activeUserUuid),
anilistAccountStore.load(_activeUserUuid),
simklAccountStore.load(_activeUserUuid),
final userUuid = newUserUuid ?? '';
final generation = ++_profileBindingGeneration;
_activeUserUuid = userUuid;
// Snapshot each service's rebind generation before the await so a disconnect
// that races this load only suppresses its own service (whose generation
// moves) rather than dropping the freshly-loaded sessions for the others.
final malRebind = _malRebind.value;
final anilistRebind = _anilistRebind.value;
final simklRebind = _simklRebind.value;
final results = await Future.wait<TrackerSession?>([
_malStore.load(userUuid),
_anilistStore.load(userUuid),
_simklStore.load(userUuid),
]);
_mal = results.first as MalSession?;
_anilist = results[1] as AnilistSession?;
_simkl = results[2] as SimklSession?;
_rebindAll();
if (!_isCurrentProfileBinding(userUuid, generation)) return;
if (_malRebind.value == malRebind) {
_mal = results.first;
_rebindMal();
}
if (_anilistRebind.value == anilistRebind) {
_anilist = results[1];
_rebindAnilist();
}
if (_simklRebind.value == simklRebind) {
_simkl = results[2];
_rebindSimkl();
}
// Connect/disconnect may flip `needsFribb` — drop cached resolver IDs so
// the next lookup re-evaluates whether to consult Fribb.
TrackerCoordinator.instance.invalidateResolverCache();
safeNotifyListeners();
}
Future<bool> connectMal({required void Function(OAuthProxyStart) onCodeReady}) => _runConnect<MalSession>(
Future<bool> connectMal({required void Function(OAuthProxyStart) onCodeReady}) => _runConnect(
service: TrackerService.mal,
alreadyConnected: isMalConnected,
authorize: () => _malAuth.authorize(
@@ -90,19 +118,19 @@ class TrackersProvider extends ChangeNotifier with DisposableChangeNotifierMixin
onCancel: _cancelCompleter!.future,
),
enrich: _enrichMal,
store: malAccountStore,
store: _malStore,
assign: (s) {
_mal = s;
_rebindMal();
},
);
Future<void> disconnectMal() => _clearAndRebind(malAccountStore, () {
Future<void> disconnectMal() => _clearAndRebind(_malStore, () {
_mal = null;
_rebindMal();
});
Future<bool> connectAnilist({required void Function(OAuthProxyStart) onCodeReady}) => _runConnect<AnilistSession>(
Future<bool> connectAnilist({required void Function(OAuthProxyStart) onCodeReady}) => _runConnect(
service: TrackerService.anilist,
alreadyConnected: isAnilistConnected,
authorize: () => _anilistAuth.authorize(
@@ -111,19 +139,19 @@ class TrackersProvider extends ChangeNotifier with DisposableChangeNotifierMixin
onCancel: _cancelCompleter!.future,
),
enrich: _enrichAnilist,
store: anilistAccountStore,
store: _anilistStore,
assign: (s) {
_anilist = s;
_rebindAnilist();
},
);
Future<void> disconnectAnilist() => _clearAndRebind(anilistAccountStore, () {
Future<void> disconnectAnilist() => _clearAndRebind(_anilistStore, () {
_anilist = null;
_rebindAnilist();
});
Future<bool> connectSimkl({required void Function(DeviceCode code) onCodeReady}) => _runConnect<SimklSession>(
Future<bool> connectSimkl({required void Function(DeviceCode code) onCodeReady}) => _runConnect(
service: TrackerService.simkl,
alreadyConnected: isSimklConnected,
authorize: () => _simklAuth.authorize(
@@ -132,32 +160,32 @@ class TrackersProvider extends ChangeNotifier with DisposableChangeNotifierMixin
onCancel: _cancelCompleter!.future,
),
enrich: _enrichSimkl,
store: simklAccountStore,
store: _simklStore,
assign: (s) {
_simkl = s;
_rebindSimkl();
},
);
Future<void> disconnectSimkl() => _clearAndRebind(simklAccountStore, () {
Future<void> disconnectSimkl() => _clearAndRebind(_simklStore, () {
_simkl = null;
_rebindSimkl();
});
Future<bool> _runConnect<T>({
Future<bool> _runConnect({
required TrackerService service,
required bool alreadyConnected,
required Future<T?> Function() authorize,
required Future<T> Function(T raw) enrich,
required TrackerAccountStore<T> store,
required void Function(T session) assign,
required Future<TrackerSession?> Function() authorize,
required Future<TrackerSession> Function(TrackerSession raw) enrich,
required TrackerAccountStore store,
required void Function(TrackerSession session) assign,
}) async {
if (_connecting != null || alreadyConnected) return false;
_connecting = service;
_cancelCompleter = Completer<void>();
safeNotifyListeners();
try {
return await runConnectPipeline<T>(
return await runConnectPipeline<TrackerSession>(
logLabel: service.name,
authorize: authorize,
enrich: enrich,
@@ -173,13 +201,22 @@ class TrackersProvider extends ChangeNotifier with DisposableChangeNotifierMixin
}
}
Future<void> _clearAndRebind<T>(TrackerAccountStore<T> store, void Function() clearAndRebind) async {
await store.clear(_activeUserUuid);
Future<void> _clearAndRebind(TrackerAccountStore store, void Function() clearAndRebind) async {
final userUuid = _activeUserUuid;
// `clearAndRebind` bumps the affected service's rebind generation, which is
// what stops an in-flight profile load from resurrecting the cleared
// session — so we no longer touch the shared profile-binding generation
// (which would also abort that load for the other two services).
clearAndRebind();
safeNotifyListeners();
await store.clear(userUuid);
}
Future<MalSession> _enrichMal(MalSession raw) async {
bool _isCurrentProfileBinding(String userUuid, int generation) {
return !isDisposed && userUuid == _activeUserUuid && generation == _profileBindingGeneration;
}
Future<TrackerSession> _enrichMal(TrackerSession raw) async {
MalClient? tmp;
try {
tmp = MalClient(raw, onSessionInvalidated: () {});
@@ -194,7 +231,7 @@ class TrackersProvider extends ChangeNotifier with DisposableChangeNotifierMixin
}
}
Future<AnilistSession> _enrichAnilist(AnilistSession raw) async {
Future<TrackerSession> _enrichAnilist(TrackerSession raw) async {
AnilistClient? tmp;
try {
tmp = AnilistClient(raw, onSessionInvalidated: () {});
@@ -208,7 +245,7 @@ class TrackersProvider extends ChangeNotifier with DisposableChangeNotifierMixin
}
}
Future<SimklSession> _enrichSimkl(SimklSession raw) async {
Future<TrackerSession> _enrichSimkl(TrackerSession raw) async {
SimklClient? tmp;
try {
tmp = SimklClient(raw, onSessionInvalidated: () {});
@@ -224,43 +261,60 @@ class TrackersProvider extends ChangeNotifier with DisposableChangeNotifierMixin
}
}
void _rebindAll() {
_rebindMal();
_rebindAnilist();
_rebindSimkl();
// Connect/disconnect may flip `needsFribb` — drop cached resolver IDs so
// the next lookup re-evaluates whether to consult Fribb.
TrackerCoordinator.instance.invalidateResolverCache();
/// Snapshot the active profile + bump this service's rebind generation,
/// returning the bound uuid and an `isCurrent` predicate. Bumping here is what
/// lets a stale client callback — or a racing profile load — detect that it
/// has been superseded for this service.
(String, bool Function()) _beginRebind(_RebindGeneration gen) {
final boundUuid = _activeUserUuid;
final generation = gen.bump();
bool isCurrent() => !isDisposed && boundUuid == _activeUserUuid && generation == gen.value;
return (boundUuid, isCurrent);
}
void _rebindMal() {
final (boundUuid, isCurrent) = _beginRebind(_malRebind);
MalTracker.instance.rebindSession(
_mal,
onSessionInvalidated: () => _handleInvalidated(malAccountStore, () => _mal = null, _rebindMal),
onSessionInvalidated: () {
if (isCurrent()) _handleInvalidated(_malStore, boundUuid, () => _mal = null, _rebindMal);
},
onSessionUpdated: (next) {
if (!isCurrent()) return;
_mal = next;
malAccountStore.save(_activeUserUuid, next);
_malStore.save(boundUuid, next);
safeNotifyListeners();
},
);
}
void _rebindAnilist() {
final (boundUuid, isCurrent) = _beginRebind(_anilistRebind);
AnilistTracker.instance.rebindSession(
_anilist,
onSessionInvalidated: () => _handleInvalidated(anilistAccountStore, () => _anilist = null, _rebindAnilist),
onSessionInvalidated: () {
if (isCurrent()) _handleInvalidated(_anilistStore, boundUuid, () => _anilist = null, _rebindAnilist);
},
);
}
void _rebindSimkl() {
final (boundUuid, isCurrent) = _beginRebind(_simklRebind);
SimklTracker.instance.rebindSession(
_simkl,
onSessionInvalidated: () => _handleInvalidated(simklAccountStore, () => _simkl = null, _rebindSimkl),
onSessionInvalidated: () {
if (isCurrent()) _handleInvalidated(_simklStore, boundUuid, () => _simkl = null, _rebindSimkl);
},
);
}
void _handleInvalidated<T>(TrackerAccountStore<T> store, void Function() clearSession, void Function() rebind) {
store.clear(_activeUserUuid);
void _handleInvalidated(
TrackerAccountStore store,
String userUuid,
void Function() clearSession,
void Function() rebind,
) {
store.clear(userUuid);
clearSession();
rebind();
safeNotifyListeners();
@@ -274,3 +328,13 @@ class TrackersProvider extends ChangeNotifier with DisposableChangeNotifierMixin
super.dispose();
}
}
/// A monotonic per-service rebind counter. Each rebind bumps it so a stale
/// client callback — or a profile load that started earlier — can tell it has
/// been superseded for that service.
class _RebindGeneration {
int _value = 0;
int bump() => ++_value;
int get value => _value;
}
+70 -21
View File
@@ -4,12 +4,13 @@ import 'package:flutter/foundation.dart';
import '../mixins/disposable_change_notifier_mixin.dart';
import '../models/trackers/device_code.dart';
import '../services/trackers/tracker_account_store.dart';
import '../services/trackers/tracker_connect_runner.dart';
import '../services/trakt/trakt_account_store.dart';
import '../services/trackers/tracker_constants.dart';
import '../services/trackers/tracker_session.dart';
import '../services/trakt/trakt_auth_service.dart';
import '../services/trakt/trakt_client.dart';
import '../services/trakt/trakt_scrobble_service.dart';
import '../services/trakt/trakt_session.dart';
import '../services/trakt/trakt_sync_service.dart';
import '../utils/app_logger.dart';
@@ -19,14 +20,15 @@ import '../utils/app_logger.dart';
/// session and pushes it to both `TraktScrobbleService` and `TraktSyncService`.
class TraktAccountProvider extends ChangeNotifier with DisposableChangeNotifierMixin {
final TraktAuthService _auth = TraktAuthService();
final _store = traktAccountStore;
final TrackerAccountStore _store = trackerAccountStore(TrackerService.trakt);
TraktSession? _session;
TrackerSession? _session;
String _activeUserUuid = '';
int _bindingGeneration = 0;
bool _isConnecting = false;
Completer<void>? _cancelCompleter;
TraktSession? get session => _session;
TrackerSession? get session => _session;
bool get isConnected => _session != null;
String? get username => _session?.username;
bool get isConnecting => _isConnecting;
@@ -41,9 +43,12 @@ class TraktAccountProvider extends ChangeNotifier with DisposableChangeNotifierM
/// Called whenever the active Plex profile changes (or on initial load).
Future<void> onActiveProfileChanged(String? newUserUuid) async {
_activeUserUuid = newUserUuid ?? '';
final loaded = await _store.load(_activeUserUuid);
_setSessionAndRebind(loaded);
if (isDisposed) return;
final userUuid = newUserUuid ?? '';
final generation = ++_bindingGeneration;
_activeUserUuid = userUuid;
final loaded = await _store.load(userUuid);
_setSessionAndRebind(userUuid, generation, loaded);
}
/// Run the device-code OAuth flow.
@@ -56,7 +61,7 @@ class TraktAccountProvider extends ChangeNotifier with DisposableChangeNotifierM
_cancelCompleter = Completer<void>();
notifyListeners();
try {
return await runConnectPipeline<TraktSession>(
return await runConnectPipeline<TrackerSession>(
logLabel: 'Trakt',
authorize: () => _auth.authorize(
onCodeReady: onCodeReady,
@@ -65,7 +70,7 @@ class TraktAccountProvider extends ChangeNotifier with DisposableChangeNotifierM
),
enrich: _enrichUsername,
save: (s) => _store.save(_activeUserUuid, s),
assign: _setSessionAndRebind,
assign: _bindCurrentSession,
);
} finally {
final c = _cancelCompleter;
@@ -76,7 +81,7 @@ class TraktAccountProvider extends ChangeNotifier with DisposableChangeNotifierM
}
}
Future<TraktSession> _enrichUsername(TraktSession raw) async {
Future<TrackerSession> _enrichUsername(TrackerSession raw) async {
TraktClient? tmp;
try {
tmp = TraktClient(raw, onSessionInvalidated: () {});
@@ -92,7 +97,10 @@ class TraktAccountProvider extends ChangeNotifier with DisposableChangeNotifierM
/// Revoke the access token and clear local state.
Future<void> disconnect() async {
final userUuid = _activeUserUuid;
final generation = ++_bindingGeneration;
final session = _session;
_setSessionAndRebind(userUuid, generation, null);
if (session != null) {
final client = TraktClient(session, onSessionInvalidated: () {});
try {
@@ -101,26 +109,67 @@ class TraktAccountProvider extends ChangeNotifier with DisposableChangeNotifierM
client.dispose();
}
}
await _store.clear(_activeUserUuid);
_setSessionAndRebind(null);
await _store.clear(userUuid);
}
void _setSessionAndRebind(TraktSession? session) {
void _bindCurrentSession(TrackerSession? session) {
_setSessionAndRebind(_activeUserUuid, ++_bindingGeneration, session);
}
void _setSessionAndRebind(String userUuid, int generation, TrackerSession? session) {
if (!_isCurrentBinding(userUuid, generation)) return;
_session = session;
TraktScrobbleService.instance.rebindToProfile(session, onSessionInvalidated: _handleSessionInvalidated);
TraktSyncService.instance.rebindToProfile(
_activeUserUuid,
void handleInvalidated() => _handleSessionInvalidated(userUuid, generation);
void handleUpdated(TrackerSession next) => _handleSessionUpdated(userUuid, generation, next);
TraktScrobbleService.instance.rebindToProfile(
session,
onSessionInvalidated: _handleSessionInvalidated,
onSessionInvalidated: handleInvalidated,
onSessionUpdated: handleUpdated,
);
TraktSyncService.instance.rebindToProfile(
userUuid,
session,
onSessionInvalidated: handleInvalidated,
onSessionUpdated: handleUpdated,
);
safeNotifyListeners();
}
bool _isCurrentBinding(String userUuid, int generation) {
return !isDisposed && userUuid == _activeUserUuid && generation == _bindingGeneration;
}
void _handleSessionUpdated(String userUuid, int generation, TrackerSession session) {
if (!_isCurrentBinding(userUuid, generation)) return;
_session = session;
TraktScrobbleService.instance.updateSession(session);
TraktSyncService.instance.updateSession(session);
unawaited(_store.save(userUuid, session));
safeNotifyListeners();
}
/// Called by [TraktClient] when refresh fails permanently. Clears local state
/// so the UI shows "not connected" and the user can re-link.
void _handleSessionInvalidated() {
_store.clear(_activeUserUuid);
_setSessionAndRebind(null);
void _handleSessionInvalidated(String userUuid, int generation) {
if (!_isCurrentBinding(userUuid, generation)) return;
final nextGeneration = ++_bindingGeneration;
unawaited(_store.clear(userUuid));
_setSessionAndRebind(userUuid, nextGeneration, null);
}
@visibleForTesting
int get debugBindingGenerationForTesting => _bindingGeneration;
@visibleForTesting
void debugHandleSessionUpdatedForTesting(String userUuid, int generation, TrackerSession session) {
_handleSessionUpdated(userUuid, generation, session);
}
@visibleForTesting
void debugHandleSessionInvalidatedForTesting(String userUuid, int generation) {
_handleSessionInvalidated(userUuid, generation);
}
@override
+5 -3
View File
@@ -20,11 +20,11 @@ import '../focus/focusable_button.dart';
import '../focus/focusable_text_field.dart';
import '../focus/key_event_utils.dart';
import '../media/media_backend.dart';
import '../navigation/profile_session_screen.dart';
import '../utils/navigation_transitions.dart';
import '../widgets/backend_badge.dart';
import '../widgets/dialog_action_button.dart';
import 'auth/plex_pin_auth_flow.dart';
import 'main_screen.dart';
import 'profile/profile_switch_screen.dart';
import 'settings/add_jellyfin_screen.dart';
@@ -172,7 +172,9 @@ class _AuthScreenState extends State<AuthScreen> {
await context.read<UserProfileProvider>().initialize();
if (!mounted) return;
unawaited(Navigator.pushReplacement(context, fadeRoute(MainScreen(initialPromptHandled: promptHandled))));
unawaited(
Navigator.pushReplacement(context, fadeRoute(ProfileSessionScreen(initialPromptHandled: promptHandled))),
);
} catch (e) {
appLogger.e('Failed to connect to servers', error: e);
if (!mounted) return;
@@ -196,7 +198,7 @@ class _AuthScreenState extends State<AuthScreen> {
// The connection persisted and the manager registered the client; move
// straight to the main screen. [MainScreen] reads the active client
// from the server provider, so no client argument is needed here.
unawaited(Navigator.pushReplacement(context, fadeRoute(const MainScreen())));
unawaited(Navigator.pushReplacement(context, fadeRoute(const ProfileSessionScreen())));
}
void _showDebugTokenDialog() {
+13 -10
View File
@@ -737,13 +737,10 @@ class _DiscoverScreenState extends State<DiscoverScreen>
return Symbols.auto_awesome_rounded;
}
/// Get the set of hub titles that appear more than once (duplicates)
Set<String> _getDuplicateHubTitles() {
final titleCounts = <String, int>{};
for (final hub in _hubs) {
titleCounts[hub.title] = (titleCounts[hub.title] ?? 0) + 1;
}
return titleCounts.entries.where((e) => e.value > 1).map((e) => e.key).toSet();
/// Whether the loaded hubs span more than one connected server.
bool _hubsSpanMultipleServers() {
final serverIds = _hubs.where((hub) => hub.serverId != null).map((hub) => hub.serverId).toSet();
return serverIds.length > 1;
}
Future<void> _handleLogout() async {
@@ -793,7 +790,10 @@ class _DiscoverScreenState extends State<DiscoverScreen>
}
void _handleSwitchProfile(BuildContext context) {
Navigator.push(context, MaterialPageRoute(builder: (context) => const ProfileSwitchScreen()));
Navigator.of(
context,
rootNavigator: true,
).push(MaterialPageRoute(builder: (context) => const ProfileSwitchScreen()));
}
void _handleOpenSettings(BuildContext context) {
@@ -1068,7 +1068,7 @@ class _DiscoverScreenState extends State<DiscoverScreen>
}
final showServerNameOnHubs = svc.read(SettingsService.showServerNameOnHubs);
final duplicateHubTitles = _getDuplicateHubTitles();
final hubsSpanMultipleServers = _hubsSpanMultipleServers();
final bottomPadding = MediaQuery.paddingOf(context).bottom;
final theme = Theme.of(context);
@@ -1126,7 +1126,7 @@ class _DiscoverScreenState extends State<DiscoverScreen>
key: i < _orderedHubKeys.length ? _orderedHubKeys[i] : null,
hub: _hubs[i],
icon: _getHubIcon(_hubs[i].title),
showServerName: showServerNameOnHubs || duplicateHubTitles.contains(_hubs[i].title),
showServerName: showServerNameOnHubs || hubsSpanMultipleServers,
onRefresh: _discover.updateItem,
// Hub index is i + 1 if continue watching exists, otherwise i
onVerticalNavigation: (isUp) => _handleVerticalNavigation(_onDeck.isNotEmpty ? i + 1 : i, isUp),
@@ -1210,6 +1210,8 @@ class _DiscoverScreenState extends State<DiscoverScreen>
final theme = Theme.of(context);
final svc = SettingsService.instance;
final hideSpoilers = svc.read(SettingsService.hideSpoilers);
final showServerNameOnHubs = svc.read(SettingsService.showServerNameOnHubs);
final hubsSpanMultipleServers = _hubsSpanMultipleServers();
final browseHubs = _tvBrowseHubs;
final scale = TvLayoutConstants.scaleForSize(size);
// Only layout-aspect (flip-stable) scope values may be read here: an
@@ -1308,6 +1310,7 @@ class _DiscoverScreenState extends State<DiscoverScreen>
child: TvBrowseRail(
key: _tvBrowseRailKey,
hubs: browseHubs,
showServerName: showServerNameOnHubs || hubsSpanMultipleServers,
iconForHub: (hub, _) =>
hub.id == 'continue_watching' ? Symbols.play_circle_rounded : _getHubIcon(hub.title),
onFocusedItemChanged: _setSpotlightItem,
+15 -24
View File
@@ -677,7 +677,7 @@ class _LibrariesScreenState extends State<LibrariesScreen>
final allLibraries = librariesProvider.libraries;
if (PlatformDetector.isTV()) {
showDialog(
showScopedDialog<void>(
context: context,
builder: (context) => _LibraryManagementSheet(
isDialog: true,
@@ -808,15 +808,6 @@ class _LibrariesScreenState extends State<LibrariesScreen>
);
}
/// Get set of library names that appear more than once (not globally unique)
Set<String> _getNonUniqueLibraryNames(List<MediaLibrary> libraries) {
final nameCounts = <String, int>{};
for (final lib in libraries) {
nameCounts[lib.title] = (nameCounts[lib.title] ?? 0) + 1;
}
return nameCounts.entries.where((e) => e.value > 1).map((e) => e.key).toSet();
}
Widget _buildLibraryServerLabel(
MediaLibrary library,
TextStyle? style, {
@@ -879,9 +870,12 @@ class _LibrariesScreenState extends State<LibrariesScreen>
required bool showServerHeaders,
}) {
if (!showServerHeaders) {
final nonUniqueNames = _getNonUniqueLibraryNames(visibleLibraries);
// With multiple servers connected (but not grouped under headers), show the
// server name on every library so its origin is always clear — not only when
// two libraries happen to share a title.
final showServerNames = _hasMultipleServers(visibleLibraries);
return visibleLibraries.map((library) {
final showServerName = library.serverName != null && nonUniqueNames.contains(library.title);
final showServerName = library.serverName != null && showServerNames;
return _buildLibraryMenuItem(library, showServerName: showServerName);
}).toList();
}
@@ -1430,13 +1424,10 @@ class _LibraryManagementSheetState extends State<_LibraryManagementSheet> {
);
}
/// Get set of library names that appear more than once (not globally unique)
Set<String> _getNonUniqueLibraryNames() {
final nameCounts = <String, int>{};
for (final lib in _tempLibraries) {
nameCounts[lib.title] = (nameCounts[lib.title] ?? 0) + 1;
}
return nameCounts.entries.where((e) => e.value > 1).map((e) => e.key).toSet();
/// Whether the libraries span more than one connected server.
bool _hasMultipleServers() {
final serverIds = _tempLibraries.where((lib) => lib.serverId != null).map((lib) => lib.serverId).toSet();
return serverIds.length > 1;
}
@override
@@ -1525,7 +1516,7 @@ class _LibraryManagementSheetState extends State<_LibraryManagementSheet> {
/// Build library list for dialog (TV) using ListView with scroll-into-view support
Widget _buildFlatLibraryListDialog(Set<String> hiddenLibraryKeys) {
final nonUniqueNames = _getNonUniqueLibraryNames();
final showServerNames = _hasMultipleServers();
final isKeyboardMode = InputModeTracker.isKeyboardMode(context);
return ReorderableListView.builder(
@@ -1536,7 +1527,7 @@ class _LibraryManagementSheetState extends State<_LibraryManagementSheet> {
buildDefaultDragHandles: false,
itemBuilder: (context, index) {
final library = _tempLibraries[index];
final showServerName = nonUniqueNames.contains(library.title) && library.serverName != null;
final showServerName = showServerNames && library.serverName != null;
final isFocused = isKeyboardMode && index == _focusedIndex;
final isMoving = index == _movingIndex;
@@ -1553,9 +1544,9 @@ class _LibraryManagementSheetState extends State<_LibraryManagementSheet> {
);
}
/// Build flat library list with server subtitle for non-unique names
/// Build flat library list with a server subtitle when multiple servers are connected
Widget _buildFlatLibraryList(ScrollController scrollController, Set<String> hiddenLibraryKeys) {
final nonUniqueNames = _getNonUniqueLibraryNames();
final showServerNames = _hasMultipleServers();
final isKeyboardMode = InputModeTracker.isKeyboardMode(context);
return ReorderableListView.builder(
@@ -1566,7 +1557,7 @@ class _LibraryManagementSheetState extends State<_LibraryManagementSheet> {
buildDefaultDragHandles: false,
itemBuilder: (context, index) {
final library = _tempLibraries[index];
final showServerName = nonUniqueNames.contains(library.title) && library.serverName != null;
final showServerName = showServerNames && library.serverName != null;
final isFocused = isKeyboardMode && index == _focusedIndex;
final isMoving = index == _movingIndex;
return _buildLibraryTile(
@@ -640,7 +640,7 @@ class _LibraryBrowseTabState extends BaseLibraryTabState<MediaItem, LibraryBrows
return filterParams;
}
Future<void> _loadItems() async {
Future<void> _loadItems({bool preserveFocus = false}) async {
final generation = _contentRequestId;
setState(() {
isLoading = true;
@@ -661,10 +661,12 @@ class _LibraryBrowseTabState extends BaseLibraryTabState<MediaItem, LibraryBrows
});
hasLoadedData = true;
tryFocus();
if (!preserveFocus) {
tryFocus();
}
// Notify parent
if (widget.onDataLoaded != null) {
if (!preserveFocus && widget.onDataLoaded != null) {
WidgetsBinding.instance.addPostFrameCallback((_) {
widget.onDataLoaded!();
});
@@ -1267,7 +1269,7 @@ class _LibraryBrowseTabState extends BaseLibraryTabState<MediaItem, LibraryBrows
isLoading = true;
});
_scheduleTopScrollReset();
_loadItems();
_loadItems(preserveFocus: _alphaJumpBarFocusNode.hasFocus && nextPrefix != null);
}
/// Scroll the current layout so that [index] is visible just below the chrome.
@@ -140,7 +140,8 @@ class _LibraryCollectionsTabState extends BaseLibraryTabState<MediaItem, Library
padding: _effectivePadding,
sliver: SliverList.builder(
itemCount: totalSize,
itemBuilder: (context, index) => _buildMediaCardItem(index, isFirstColumn: true, disableScale: true),
itemBuilder: (context, index) =>
_buildMediaCardItem(index, isFirstRow: index == 0, isFirstColumn: true, disableScale: true),
),
);
}
@@ -161,6 +162,7 @@ class _LibraryCollectionsTabState extends BaseLibraryTabState<MediaItem, Library
itemCount: totalSize,
itemBuilder: (context, index) => _buildMediaCardItem(
index,
isFirstRow: GridSizeCalculator.isFirstRow(index, geometry.columnCount),
isFirstColumn: GridSizeCalculator.isFirstColumn(index, geometry.columnCount),
fullBleedImage: fullCardLayout,
),
@@ -172,6 +174,7 @@ class _LibraryCollectionsTabState extends BaseLibraryTabState<MediaItem, Library
Widget _buildMediaCardItem(
int index, {
required bool isFirstRow,
required bool isFirstColumn,
bool disableScale = false,
bool fullBleedImage = false,
@@ -189,6 +192,7 @@ class _LibraryCollectionsTabState extends BaseLibraryTabState<MediaItem, Library
disableScale: disableScale,
fullBleedImage: fullBleedImage,
onListRefresh: loadItems,
onNavigateUp: isFirstRow ? widget.onBack : null,
onBack: widget.onBack,
onNavigateLeft: isFirstColumn ? _navigateToSidebar : null,
);
@@ -142,7 +142,8 @@ class _LibraryPlaylistsTabState extends BaseLibraryTabState<MediaPlaylist, Libra
padding: _effectivePadding,
sliver: SliverList.builder(
itemCount: totalSize,
itemBuilder: (context, index) => _buildPlaylistCard(index, isFirstColumn: true, disableScale: true),
itemBuilder: (context, index) =>
_buildPlaylistCard(index, isFirstRow: index == 0, isFirstColumn: true, disableScale: true),
),
);
}
@@ -163,6 +164,7 @@ class _LibraryPlaylistsTabState extends BaseLibraryTabState<MediaPlaylist, Libra
itemCount: totalSize,
itemBuilder: (context, index) => _buildPlaylistCard(
index,
isFirstRow: GridSizeCalculator.isFirstRow(index, geometry.columnCount),
isFirstColumn: GridSizeCalculator.isFirstColumn(index, geometry.columnCount),
fullBleedImage: fullCardLayout,
),
@@ -174,6 +176,7 @@ class _LibraryPlaylistsTabState extends BaseLibraryTabState<MediaPlaylist, Libra
Widget _buildPlaylistCard(
int index, {
required bool isFirstRow,
required bool isFirstColumn,
bool disableScale = false,
bool fullBleedImage = false,
@@ -191,6 +194,7 @@ class _LibraryPlaylistsTabState extends BaseLibraryTabState<MediaPlaylist, Libra
disableScale: disableScale,
fullBleedImage: fullBleedImage,
onListRefresh: loadItems,
onNavigateUp: isFirstRow ? widget.onBack : null,
onBack: widget.onBack,
onNavigateLeft: isFirstColumn ? _navigateToSidebar : null,
);
+92 -13
View File
@@ -23,12 +23,12 @@ import '../utils/platform_detector.dart';
import '../utils/snackbar_helper.dart';
import '../utils/update_dialog.dart';
import '../utils/video_player_navigation.dart';
import '../main.dart';
import '../mixins/mounted_set_state_mixin.dart';
import '../mixins/refreshable.dart';
import '../widgets/overlay_sheet.dart';
import '../mixins/tab_visibility_aware.dart';
import '../navigation/navigation_tabs.dart';
import '../navigation/profile_navigation_scope.dart';
import '../profiles/active_profile_binder.dart';
import '../profiles/active_profile_provider.dart';
import '../profiles/plex_home_service.dart';
@@ -99,6 +99,20 @@ bool shouldRenderMainScreenOffline({
return providerOffline || (startupOfflineUntilConnected && !hasVisibleConnectedServers);
}
@visibleForTesting
List<NavigationTab> mainScreenBottomNavigationTabs({
required List<NavigationTab> visibleTabs,
required bool isMobile,
required bool isOffline,
required NavigationTabId currentTab,
}) {
if (!isMobile) return visibleTabs;
return visibleTabs.where((tab) {
if (tab.id != NavigationTabId.settings) return true;
return isOffline || currentTab == NavigationTabId.settings;
}).toList();
}
@visibleForTesting
bool shouldPassTvosMenuToSystem({
required bool isAppleTV,
@@ -118,6 +132,30 @@ bool shouldPassTvosMenuToSystem({
isCurrentTabRoot;
}
@visibleForTesting
enum ProfileInvalidationAction { none, waitForProfileSwitch, invalidateNow }
@visibleForTesting
ProfileInvalidationAction profileInvalidationAction({
required String? previousProfileId,
required String? currentProfileId,
required bool wasBindingPreviously,
required bool isBindingNow,
required bool hasPendingProfileSwitchInvalidation,
required String? pendingProfileSwitchInvalidationId,
}) {
if (currentProfileId != previousProfileId) {
return ProfileInvalidationAction.waitForProfileSwitch;
}
if (hasPendingProfileSwitchInvalidation && pendingProfileSwitchInvalidationId == currentProfileId) {
return ProfileInvalidationAction.none;
}
if (wasBindingPreviously && !isBindingNow) {
return ProfileInvalidationAction.invalidateNow;
}
return ProfileInvalidationAction.none;
}
class MainScreen extends StatefulWidget {
final bool isOfflineMode;
@@ -161,6 +199,7 @@ class _MainScreenState extends State<MainScreen>
OfflineModeProvider? _offlineModeProvider;
MultiServerProvider? _multiServerProvider;
RouteObserver<PageRoute<dynamic>>? _profileRouteObserver;
bool _lastHasLiveTv = false;
/// Whether a reconnection attempt is in progress
@@ -203,6 +242,8 @@ class _MainScreenState extends State<MainScreen>
// we only invalidate on id change and the libraries sidebar keeps
// stale entries until the user switches profiles.
bool _wasBindingPrev = false;
bool _hasPendingProfileSwitchInvalidation = false;
String? _pendingProfileSwitchInvalidationId;
/// Subscription to MultiServerManager status changes. Used to resume any
/// queued downloads as soon as a Plex client comes online for the first
@@ -462,10 +503,20 @@ class _MainScreenState extends State<MainScreen>
if (activeProfile == null) return;
final id = activeProfile.activeId;
final isBindingNow = activeProfile.isBinding;
final action = profileInvalidationAction(
previousProfileId: _lastSeenProfileId,
currentProfileId: id,
wasBindingPreviously: _wasBindingPrev,
isBindingNow: isBindingNow,
hasPendingProfileSwitchInvalidation: _hasPendingProfileSwitchInvalidation,
pendingProfileSwitchInvalidationId: _pendingProfileSwitchInvalidationId,
);
if (id != _lastSeenProfileId) {
if (action == ProfileInvalidationAction.waitForProfileSwitch) {
_lastSeenProfileId = id;
_wasBindingPrev = isBindingNow;
_hasPendingProfileSwitchInvalidation = true;
_pendingProfileSwitchInvalidationId = id;
// We're called inside the synchronous notify cascade *before* the
// binder's listener has fired (registration order). At this exact
// instant `_isBinding` is still false, so calling awaitBindingSettle
@@ -473,10 +524,22 @@ class _MainScreenState extends State<MainScreen>
// listener gets to flip the flag first, then wait properly.
unawaited(
Future.microtask(() async {
final scheduledProfileId = id;
if (!mounted) return;
await activeProfile.awaitBindingSettle();
if (!mounted) return;
await _invalidateAllScreens();
try {
if (_hasPendingProfileSwitchInvalidation &&
_pendingProfileSwitchInvalidationId == scheduledProfileId &&
activeProfile.activeId == scheduledProfileId) {
await _invalidateAllScreens();
}
} finally {
if (_hasPendingProfileSwitchInvalidation && _pendingProfileSwitchInvalidationId == scheduledProfileId) {
_hasPendingProfileSwitchInvalidation = false;
_pendingProfileSwitchInvalidationId = null;
}
}
}),
);
return;
@@ -486,7 +549,7 @@ class _MainScreenState extends State<MainScreen>
// (true → false transition). Fires after borrow / connection-removal
// flows trigger ActiveProfileBinder.rebindIfActive, so the libraries
// sidebar reflects the new server set without an app restart.
if (_wasBindingPrev && !isBindingNow) {
if (action == ProfileInvalidationAction.invalidateNow) {
_wasBindingPrev = isBindingNow;
unawaited(_invalidateAllScreens());
return;
@@ -522,6 +585,7 @@ class _MainScreenState extends State<MainScreen>
_setTvosMenuPassthrough(false);
await Navigator.of(
context,
rootNavigator: true,
).push(MaterialPageRoute(builder: (context) => const ProfileSwitchScreen(requireSelection: true)));
if (!mounted) return;
_isShowingProfileSelection = false;
@@ -569,9 +633,10 @@ class _MainScreenState extends State<MainScreen>
};
watchTogether.onHostExitedPlayer = () {
appLogger.d('WatchTogether: Host exited player - exiting player for guest');
// Use rootNavigator to ensure we pop the video player even if nested
// Watch Together playback lives in the profile navigator; root-level
// dialogs/profile picker must not be affected.
if (!mounted) return;
final navigator = Navigator.of(context, rootNavigator: true);
final navigator = Navigator.of(context);
bool isVideoPlayerOnTop = false;
navigator.popUntil((route) {
if (route.isCurrent) {
@@ -687,7 +752,15 @@ class _MainScreenState extends State<MainScreen>
_setupCompanionRemote();
}
routeObserver.subscribe(this, ModalRoute.of(context) as PageRoute);
final scopedRouteObserver = ProfileNavigationScope.of(context).routeObserver;
if (scopedRouteObserver != _profileRouteObserver) {
_profileRouteObserver?.unsubscribe(this);
_profileRouteObserver = scopedRouteObserver;
final route = ModalRoute.of(context);
if (route is PageRoute<dynamic>) {
scopedRouteObserver.subscribe(this, route);
}
}
}
void _setupCompanionRemote() {
@@ -742,7 +815,7 @@ class _MainScreenState extends State<MainScreen>
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
routeObserver.unsubscribe(this);
_profileRouteObserver?.unsubscribe(this);
if (PlatformDetector.isDesktopOS()) {
windowManager.removeListener(this);
windowManager.setPreventClose(false);
@@ -806,6 +879,7 @@ class _MainScreenState extends State<MainScreen>
_setTvosMenuPassthrough(false);
await Navigator.of(
context,
rootNavigator: true,
).push(MaterialPageRoute(builder: (context) => const ProfileSwitchScreen(requireSelection: true)));
if (!mounted) return;
_isShowingProfileSelection = false;
@@ -1262,6 +1336,9 @@ class _MainScreenState extends State<MainScreen>
appLogger.w('Failed to clear ApiCache on profile switch', error: e, stackTrace: st);
}
await hiddenLibrariesProvider.refresh();
if (!mounted) return;
librariesProvider.clear();
if (multiServerProvider.serverManager.serverIds.isNotEmpty) {
@@ -1274,7 +1351,6 @@ class _MainScreenState extends State<MainScreen>
await librariesProvider.refresh();
}
unawaited(hiddenLibrariesProvider.refresh());
playbackStateProvider.clearShuffle();
if (_discoverKey.currentState case final FullRefreshable refreshable) {
@@ -1432,9 +1508,12 @@ class _MainScreenState extends State<MainScreen>
}
List<NavigationTab> _getBottomNavigationTabs(BuildContext context) {
final tabs = _getVisibleTabs(_isOffline);
if (!PlatformDetector.isMobile(context)) return tabs;
return tabs.where((tab) => tab.id != NavigationTabId.settings).toList();
return mainScreenBottomNavigationTabs(
visibleTabs: _getVisibleTabs(_isOffline),
isMobile: PlatformDetector.isMobile(context),
isOffline: _isOffline,
currentTab: _currentTab,
);
}
/// Get the GlobalKey for a given tab.
@@ -1637,7 +1716,7 @@ class _MainScreenState extends State<MainScreen>
_handleMainBack();
},
child: ScaffoldMessenger(
key: mainScaffoldMessengerKey,
key: ProfileNavigationScope.of(context).mainScaffoldMessengerKey,
child: Scaffold(
body: _buildTickerAwareStack(),
bottomNavigationBar: Column(
+93 -14
View File
@@ -5,7 +5,7 @@ import 'dart:io';
import 'package:cached_network_image_ce/cached_network_image.dart';
import 'package:flutter/material.dart';
import '../main.dart' show routeObserver;
import '../navigation/profile_navigation_scope.dart';
import '../services/image_cache_service.dart';
import 'package:flutter/services.dart';
import 'package:plezy/utils/platform_detector.dart';
@@ -261,6 +261,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
bool _hasLoadedRelatedHubs = false;
final _tvDetailRailKey = GlobalKey<TvBrowseRailState>();
PageRoute<dynamic>? _route;
RouteObserver<PageRoute<dynamic>>? _routeObserver;
late final ScrollController _scrollController;
final ScrollController _extrasScrollController = ScrollController();
bool _watchStateChanged = false;
@@ -662,10 +663,13 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
@override
void didChangeDependencies() {
super.didChangeDependencies();
final routeObserver = ProfileNavigationScope.of(context).routeObserver;
final route = ModalRoute.of(context);
if (route is! PageRoute<dynamic> || route == _route) return;
if (_route != null) routeObserver.unsubscribe(this);
if (route is! PageRoute<dynamic>) return;
if (route == _route && routeObserver == _routeObserver) return;
_routeObserver?.unsubscribe(this);
_route = route;
_routeObserver = routeObserver;
routeObserver.subscribe(this, route);
}
@@ -771,7 +775,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
@override
void dispose() {
routeObserver.unsubscribe(this);
_routeObserver?.unsubscribe(this);
_scrollController.dispose();
_scrollOffset.dispose();
_extrasScrollController.dispose();
@@ -2769,6 +2773,11 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
return null;
}
String? _seriesIdForSeason(MediaItem season) {
if (_metadata.isShow) return (_fullMetadata ?? _metadata).id;
return season.grandparentId ?? season.parentId ?? _metadata.grandparentId ?? _metadata.parentId;
}
Future<LibraryPage<MediaItem>> _fetchFlattenedEpisodePage(
MediaServerClient client,
ServerId serverId, {
@@ -2777,7 +2786,11 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
}) async {
final season = _flattenedSeasonForDirectEpisodePaging;
if (season != null) {
final page = await client.fetchChildrenPage(season.id, start: start, size: size);
final seriesId = _seriesIdForSeason(season);
final seasonPagingClient = client is SeasonEpisodePagingClient ? client as SeasonEpisodePagingClient : null;
final page = seriesId != null && seasonPagingClient != null
? await seasonPagingClient.fetchSeasonEpisodesPage(seriesId, season.id, start: start, size: size)
: await client.fetchChildrenPage(season.id, start: start, size: size);
return LibraryPage<MediaItem>(
items: _enrichDirectSeasonEpisodes(page.items, season: season, serverId: serverId),
totalCount: page.totalCount,
@@ -2991,7 +3004,11 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
} else {
final client = getServerBoundMediaClient(context);
if (client == null) return;
firstEpisode = await fetchFirstEpisodeForSeason(client, firstSeason.id);
firstEpisode = await fetchFirstEpisodeForSeason(
client,
firstSeason.id,
seriesId: _seriesIdForSeason(firstSeason),
);
}
if (firstEpisode == null) {
@@ -3109,9 +3126,14 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
// Main content
SliverToBoxAdapter(
child: Padding(
padding: .symmetric(
horizontal: isTv ? TvLayoutConstants.horizontalInset : 16,
vertical: isTv ? 8 : 16,
// Reduced top inset keeps the Overview/first section
// tight under the hero's action row (the hero already
// contributes its own bottom inset above this).
padding: .fromLTRB(
isTv ? TvLayoutConstants.horizontalInset : 16,
isTv ? 8 : 4,
isTv ? TvLayoutConstants.horizontalInset : 16,
isTv ? 8 : 16,
),
child: Column(
crossAxisAlignment: .start,
@@ -3429,22 +3451,29 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
final availableHeight = constraints.maxHeight.isFinite ? constraints.maxHeight : 264.0;
final desiredLogoHeight = 220 * scale;
final minLogoHeight = 72 * scale;
final minLogoHeight = 60 * scale;
final desiredLogoWidth = 790 * scale;
final metadataLineHeight = 22 * scale;
final genreLineHeight = 22 * scale;
final genreGap = 6 * scale;
final logoMetadataGap = 10 * scale;
final summaryGap = 10 * scale;
final summaryGap = 6 * scale;
final summaryFontSize = availableHeight < 260 * scale ? 16.2 * scale : 18 * scale;
final summaryLineHeight = summaryFontSize * 1.35;
final actionHeight = _tvDetailActionSize * scale;
final actionGap = 12 * scale;
final hasDescription = description != null && description.isNotEmpty;
// Genres come from the show/movie, not the focused episode, so the line
// stays stable as episode rows gain focus.
final genres = metadata.genres ?? const <String>[];
final genreBlockHeight = genres.isEmpty ? 0.0 : genreGap + genreLineHeight;
var summaryMaxLines = 0;
var logoHeight = 0.0;
for (var lines = hasDescription ? 3 : 0; lines >= 0; lines--) {
final descriptionHeight = lines > 0 ? summaryGap + (summaryLineHeight * lines) : 0.0;
final reservedHeight = logoMetadataGap + metadataLineHeight + descriptionHeight + actionGap + actionHeight;
final reservedHeight =
logoMetadataGap + metadataLineHeight + genreBlockHeight + descriptionHeight + actionGap + actionHeight;
final remainingForLogo = availableHeight - reservedHeight;
if (remainingForLogo >= minLogoHeight || lines == 0) {
summaryMaxLines = lines;
@@ -3458,6 +3487,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
final contentHeight =
(showLogo ? logoHeight + logoMetadataGap : 0) +
metadataLineHeight +
genreBlockHeight +
descriptionHeight +
actionGap +
actionHeight;
@@ -3496,6 +3526,26 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
height: metadataLineHeight,
child: Align(alignment: .centerLeft, child: _buildTvDetailMetadataLine(context, metadata, scale)),
),
if (genres.isNotEmpty) ...[
SizedBox(height: genreGap),
SizedBox(
height: genreLineHeight,
child: Align(
alignment: .centerLeft,
child: Text(
genres.join(' • '),
maxLines: 1,
overflow: .ellipsis,
style: TextStyle(
color: mutedForegroundColor,
fontSize: 16 * scale,
fontWeight: .w600,
letterSpacing: 0.1,
),
),
),
),
],
if (hasDescription && summaryMaxLines > 0) ...[
SizedBox(height: summaryGap),
SizedBox(
@@ -3637,7 +3687,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
if (lineMetadata.contentRating != null) addTextPart(formatContentRating(lineMetadata.contentRating!));
if (lineMetadata.durationMs != null) addTextPart(formatDurationTextual(lineMetadata.durationMs!));
if (lineMetadata.isEpisode && lineMetadata.originallyAvailableAt != null) {
addTextPart(formatFullDate(lineMetadata.originallyAvailableAt!));
addTextPart(formatAbbreviatedDate(lineMetadata.originallyAvailableAt!));
} else if (lineMetadata.year != null) {
addTextPart(lineMetadata.year.toString());
}
@@ -4089,8 +4139,12 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
bottom: 16,
left: 0,
right: 0,
// bottom: false — the hero is the top sliver, so the bottom safe-area
// inset would otherwise push the action row far up off the hero edge.
// Left/right stay enabled for the landscape notch.
child: SafeArea(
top: false,
bottom: false,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: _buildHeroHeaderContent(context, metadata),
@@ -4118,13 +4172,24 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
for (final label in buildMediaQualityLabels(metadata)) _buildMetadataChip(label),
..._buildRatingChips(metadata),
];
// Genres render on their own line below the metadata chips.
final genreChips = [for (final genre in metadata.genres ?? const <String>[]) _buildMetadataChip(genre)];
final showActions = availableHeight >= actionHeight;
final remainingAfterActions = availableHeight - (showActions ? actionHeight : 0);
final showChips = chips.isNotEmpty && remainingAfterActions >= 88;
final chipHeight = showChips ? (remainingAfterActions >= 170 ? 68.0 : 32.0) : 0.0;
final chipActionGap = showChips && showActions ? (availableHeight < 180 ? 8.0 : 16.0) : 0.0;
final remainingForLogo = remainingAfterActions - chipHeight - chipActionGap;
// Reserve a dedicated genre row, but only when the logo still keeps room
// afterwards so the title isn't crowded out on short heroes.
const genreRowHeight = 32.0;
const genreGap = 8.0;
final showGenres =
showChips &&
genreChips.isNotEmpty &&
remainingAfterActions - chipHeight - chipActionGap - (genreRowHeight + genreGap) >= 52;
final genreBlockHeight = showGenres ? genreRowHeight + genreGap : 0.0;
final remainingForLogo = remainingAfterActions - chipHeight - chipActionGap - genreBlockHeight;
final logoGap = remainingForLogo >= 52 && (showChips || showActions)
? (availableHeight < 180 ? 8.0 : 12.0)
: 0.0;
@@ -4136,6 +4201,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
final contentHeight =
(showLogo ? logoHeight + effectiveLogoGap : 0.0) +
chipHeight +
genreBlockHeight +
chipActionGap +
(showActions ? actionHeight : 0.0);
@@ -4179,6 +4245,19 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
),
),
),
if (showGenres) ...[
const SizedBox(height: genreGap),
ClipRect(
child: ConstrainedBox(
constraints: const BoxConstraints(maxHeight: genreRowHeight),
child: Align(
alignment: .bottomLeft,
heightFactor: 1,
child: Wrap(spacing: 8, runSpacing: 8, children: genreChips),
),
),
),
],
if (chipActionGap > 0) SizedBox(height: chipActionGap),
if (showActions) SizedBox(height: actionHeight, child: _buildActionButtons(metadata)),
],
+4 -3
View File
@@ -142,6 +142,7 @@ class _MetadataEditScreenState extends State<MetadataEditScreen> {
initialDate: initial,
firstDate: DateTime(1800),
lastDate: DateTime(2200),
useRootNavigator: false,
);
if (picked != null && mounted) {
@@ -154,7 +155,7 @@ class _MetadataEditScreenState extends State<MetadataEditScreen> {
Future<void> _editStringList(MetadataEditField field) async {
final draft = _draft;
if (draft == null) return;
final result = await showDialog<List<String>>(
final result = await showScopedDialog<List<String>>(
context: context,
builder: (context) => TagEditDialog(title: field.label, initialTags: metadataStringList(draft.values[field.id])),
);
@@ -168,7 +169,7 @@ class _MetadataEditScreenState extends State<MetadataEditScreen> {
final draft = _draft;
if (adapter == null || draft == null) return;
final current = draft.value<String>(field.id) ?? '';
final result = await showDialog<String>(
final result = await showScopedDialog<String>(
context: context,
builder: (dialogContext) {
String selected = current;
@@ -229,7 +230,7 @@ class _MetadataEditScreenState extends State<MetadataEditScreen> {
final adapter = _adapter;
final draft = _draft;
if (adapter == null || draft == null) return;
final result = await showDialog<bool>(
final result = await showScopedDialog<bool>(
context: context,
builder: (context) => ArtworkPickerDialog(adapter: adapter, draft: draft, field: field),
);
@@ -687,8 +687,11 @@ class _PinKey {
/// Shows the PIN entry dialog and returns the entered PIN, or null if cancelled
Future<String?> showPinEntryDialog(BuildContext context, String userName, {String? errorMessage}) {
// PIN entry guards root-owned profile activation and must survive disposal of
// the active profile session while the binder switches users.
return showDialog<String>(
context: context,
useRootNavigator: true,
barrierDismissible: false,
builder: (context) => PinEntryDialog(userName: userName, errorMessage: errorMessage),
);
+12 -1
View File
@@ -1,12 +1,16 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../connection/connection_registry.dart';
import '../../i18n/strings.g.dart';
import '../../profiles/active_profile_provider.dart';
import '../../profiles/profile.dart';
import '../../profiles/profile_connection_cleanup.dart';
import '../../profiles/profile_connection_registry.dart';
import '../../profiles/profile_registry.dart';
import '../../providers/download_provider.dart';
import '../../providers/multi_server_provider.dart';
import '../../services/storage_service.dart';
import '../../utils/app_logger.dart';
import '../../utils/dialogs.dart';
import '../../utils/snackbar_helper.dart';
@@ -35,13 +39,20 @@ Future<bool> confirmAndDeleteProfile(
Future<void> deleteProfile(BuildContext context, Profile profile) async {
final pcRegistry = context.read<ProfileConnectionRegistry>();
final connRegistry = context.read<ConnectionRegistry>();
final profileRegistry = context.read<ProfileRegistry>();
final downloadProvider = context.read<DownloadProvider>();
final active = context.read<ActiveProfileProvider>();
final wasActive = active.activeId == profile.id;
await downloadProvider.deleteDownloadsForProfile(profile.id);
await pcRegistry.removeAllForProfile(profile.id);
await removeAllProfileConnectionsAndCleanup(
profileId: profile.id,
profileConnections: pcRegistry,
connections: connRegistry,
storage: context.read<StorageService>(),
serverManager: context.read<MultiServerProvider>().serverManager,
);
await profileRegistry.remove(profile.id);
if (!wasActive) return;
+14 -1
View File
@@ -13,11 +13,15 @@ import '../../profiles/active_profile_binder.dart';
import '../../profiles/plex_home_service.dart';
import '../../profiles/profile.dart';
import '../../profiles/profile_avatar.dart';
import '../../profiles/profile_connection_cleanup.dart';
import '../../profiles/profile_connection.dart';
import '../../profiles/profile_connection_registry.dart';
import '../../profiles/profile_registry.dart';
import '../../profiles/profiles_view.dart';
import '../../providers/download_provider.dart';
import '../../providers/hidden_libraries_provider.dart';
import '../../providers/multi_server_provider.dart';
import '../../services/storage_service.dart';
import '../../utils/snackbar_helper.dart';
import '../../focus/focusable_button.dart';
import '../../widgets/app_icon.dart';
@@ -127,7 +131,16 @@ class _ProfileDetailScreenState extends State<ProfileDetailScreen> with Controll
_serverIdsForConnection(conn),
);
if (!mounted) return;
await context.read<ProfileConnectionRegistry>().remove(_profile.id, pc.connectionId);
await removeProfileConnectionAndCleanup(
profileId: _profile.id,
connection: conn,
profileConnections: context.read<ProfileConnectionRegistry>(),
connections: context.read<ConnectionRegistry>(),
storage: context.read<StorageService>(),
serverManager: context.read<MultiServerProvider>().serverManager,
);
if (!mounted) return;
await context.read<HiddenLibrariesProvider?>()?.refresh();
if (!mounted) return;
unawaited(context.read<ActiveProfileBinder>().rebindIfActive(_profile.id));
}
@@ -368,7 +368,7 @@ class _ProfileSwitchScreenState extends State<ProfileSwitchScreen> with MountedS
if (_switching) return;
setState(() => _switching = true);
try {
final navigator = Navigator.of(context);
final navigator = Navigator.of(context, rootNavigator: true);
final switched = await switchProfileFromUi(context, profile);
if (!mounted || !switched) return;
if (widget.requireSelection) {

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