Compare commits

..
26 Commits
Author SHA1 Message Date
github-actions[bot] 77af810d1f chore: bump version to 2.6.0 2026-06-10 19:04:45 +00:00
edde746 1292d7ac34 fix(dovi): bump MPVKit to v1.0.2 for profile 8 DV hardware decode
close #1262
2026-06-10 20:26:11 +02:00
edde746 e75ab94eb9 fix(tv): make osk search key focus results
The TV keyboard dialog froze the field's callbacks at open time, so the
search screen's done key fell through to unfocus() once results arrived.
Resolve callbacks against the latest field widget at invoke time, and
give the search screen a TV submit handler that focuses the first result
or flushes the pending debounce.
2026-06-10 16:37:35 +02:00
edde746 804bea8e9a fix(android): keep only the active dynamic HDR metadata in DV bitstreams
close #1296
2026-06-10 15:39:51 +02:00
edde746 0502dd7ba0 fix(discover): resolve hero watch state in build 2026-06-10 15:10:52 +02:00
edde746 3221a0cb1a feat: add continue watching details navigation
close #1295
2026-06-10 12:50:32 +02:00
edde746 e7efa458e5 fix(images): preserve fallback placeholder size
close #1293
2026-06-10 09:55:22 +02:00
edde746 9b48f26463 refactor(watch): shared point-of-use resolution across consumers
Adds context.withFreshWatchState/readFreshWatchState and sweeps the
remaining session-critical readers: context menu actions, folder tree
rows, discover hero, and TV spotlight minutes-left.
2026-06-10 05:38:33 +02:00
edde746 903b8eced8 refactor(detail): drop hand-patched watch state for store resolution
Delete the per-event list patching, parent-count adjustment, and the
screen-local progress overlay; rows and the hero resolve against
WatchStateStore at build. Also backfill parentId on playable-descendant
pages so hierarchy resolution covers season detail pages.
2026-06-10 05:30:52 +02:00
edde746 3753967caf fix(watch): resolve watch state per item at cards and playback open
Cards consult the hierarchy-aware store so container marks flip episode
rows instantly and a stale per-episode patch can no longer shadow a newer
show/season mark; playback opens with the session-fresh resume offset.
2026-06-10 05:23:09 +02:00
edde746 516925cf50 refactor(watch): promote overlay to hierarchy-aware WatchStateStore
Resolution now considers parentChain ancestors (newest event wins) and
watched patches set container leaf counts, so container marks reach
descendant cards and vice versa.
2026-06-10 05:18:02 +02:00
edde746 cd9498abb8 refactor(player): centralize playback opening
close #1280
2026-06-10 02:26:26 +02:00
edde746 18642cae15 fix(tv): correct grid calculation
close #1288
2026-06-09 12:47:47 +02:00
edde746 92063bd58f fix(playback): skip redundant mark-watched
close #1287
2026-06-09 12:19:27 +02:00
edde746 726281ed44 fix(tvos): top shelf sync 2026-06-09 08:06:42 +02:00
edde746 e02daa89b8 fix(tvos): stop Home nav auto-playing continue watching
close #1281
2026-06-09 06:10:22 +02:00
edde746 7de7802368 fix(hubs): keep recently-added detail scoped to its library
close #1282
2026-06-08 22:03:28 +02:00
edde746 d44a8994ce fix(discover): open server tasks with remote
close #1272
2026-06-08 08:23:57 +02:00
edde746 42d9168941 fix(player): stabilize mobile content strip 2026-06-08 00:50:22 +02:00
edde746 38616770e5 fix(i18n): localize season & episode labels in downloads tree 2026-06-07 21:46:44 +02:00
edde746 bf7558f80d fix(i18n): localize generic season names from server
close #1271
2026-06-07 21:46:24 +02:00
edde746 381e82d61a fix(detail): highlight next unwatched ep when not in continue watching
close #1269
2026-06-07 18:42:41 +02:00
edde746 9cebcb97c5 feat(plex): add Plays and User Rating sort options
close #1264
2026-06-07 17:50:36 +02:00
edde746 eef73e6447 fix: expand home hub previews
close #1268
2026-06-07 17:35:56 +02:00
edde746 e8df18e7b2 fix(jellyfin): order continue watching + up next by recency 2026-06-07 16:34:18 +02:00
github-actions[bot] 54512b8f93 chore: update cask to 2.5.0 2026-06-07 12:45:47 +00:00
170 changed files with 7336 additions and 2547 deletions
+2 -2
View File
@@ -1,6 +1,6 @@
cask "plezy" do
version "2.4.1"
sha256 "c0658bf43b793a04755a9beaedd27c05c897f2c72298cd5da6531463baf15e0c"
version "2.5.0"
sha256 "9f71d8c1cafb74c113e8cbdd8e66ec2a86c26a846b823a3459a8b9a7ab0c31fa"
url "https://github.com/edde746/plezy/releases/download/#{version}/plezy-macos.dmg"
name "Plezy"
+2
View File
@@ -188,4 +188,6 @@ dependencies {
// libass-android for ASS/SSA subtitle rendering
assAars.forEach { implementation(files(File(assDir, it))) }
testImplementation("junit:junit:4.13.2")
}
@@ -0,0 +1,140 @@
package com.edde746.plezy.exoplayer
import java.nio.ByteBuffer
/**
* In-place sanitizer for HEVC Annex B buffers carrying both Dolby Vision and HDR10+
* dynamic metadata. Buggy chipsets (Fire TV 4K Max, MediaTek-based Google TV, ...)
* crash or black-screen when a native DV codec also receives in-band HDR10+ SEI, so
* only the metadata the active decode path consumes may be kept:
*
* - Native DV codec: strip HDR10+ SEI NALs (types 39/40 with ST 2094-40 payload),
* the decoder follows the DV RPU. Port of androidx/media#3085 / Kodi xbmc#24584.
* - HEVC fallback for a DV format: strip DV RPU/EL NALs (types 62/63) instead,
* leaving HDR10+ for the display.
*
* Pure JVM (no android/media3 imports) so it stays unit-testable on the host.
*/
object DvBitstreamSanitizer {
private const val NAL_TYPE_PREFIX_SEI = 39
private const val NAL_TYPE_SUFFIX_SEI = 40
private const val NAL_TYPE_UNSPEC62 = 62 // DV RPU
private const val NAL_TYPE_UNSPEC63 = 63 // DV Enhancement Layer
private const val SEI_PAYLOAD_TYPE_ITU_T_T35 = 4
/**
* Scans `[position, limit)` of [data] for Annex B NAL units and removes the selected
* metadata NALs by compacting the buffer in place and reducing its limit. The position
* is left unchanged.
*/
fun sanitize(data: ByteBuffer, stripHdr10PlusSei: Boolean, stripDvRpu: Boolean) {
val startPos = data.position()
val limit = data.limit()
var writePos = startPos
var nalStartIndex = -1
var startCodeLen = 0
var i = startPos
while (i <= limit) {
// Find next start code or end of buffer.
val atEnd = i == limit
var foundStartCode = false
var nextStartCodeLen = 0
if (!atEnd && i + 2 < limit && data.get(i).toInt() == 0 && data.get(i + 1).toInt() == 0) {
if (data.get(i + 2).toInt() == 1) {
foundStartCode = true
nextStartCodeLen = 3
} else if (data.get(i + 2).toInt() == 0 && i + 3 < limit && data.get(i + 3).toInt() == 1) {
foundStartCode = true
nextStartCodeLen = 4
}
}
if (foundStartCode || atEnd) {
if (nalStartIndex >= 0) {
// Complete NAL unit (including its start code) from nalStartIndex to i.
val nalDataStart = nalStartIndex + startCodeLen
val nalEnd = i
var strip = false
if (nalEnd - nalDataStart >= 2) {
// HEVC NAL header: forbidden_zero_bit(1) + nal_unit_type(6) + nuh_layer_id MSB(1).
val nalUnitType = (data.get(nalDataStart).toInt() and 0x7E) shr 1
strip = when (nalUnitType) {
NAL_TYPE_UNSPEC62, NAL_TYPE_UNSPEC63 -> stripDvRpu
NAL_TYPE_PREFIX_SEI, NAL_TYPE_SUFFIX_SEI ->
stripHdr10PlusSei && isHdr10PlusSeiNalUnit(data, nalDataStart + 2, nalEnd)
else -> false
}
}
if (!strip) {
if (writePos != nalStartIndex) {
for (j in nalStartIndex until nalEnd) {
data.put(writePos++, data.get(j))
}
} else {
writePos = nalEnd
}
}
}
nalStartIndex = i
startCodeLen = nextStartCodeLen
i += if (nextStartCodeLen > 0) nextStartCodeLen else 1
} else {
i++
}
}
data.limit(writePos)
data.position(startPos)
}
/**
* Returns whether the SEI RBSP (starting after the 2-byte HEVC NAL header) begins with an
* HDR10+ message: user_data_registered_itu_t_t35 with country code 0xB5 (United States),
* provider code 0x003C (Samsung), provider oriented code 0x0001, application identifier 4
* (ST 2094-40), application version 0 or 1. Malformed/truncated data returns false so the
* NAL is kept.
*/
private fun isHdr10PlusSeiNalUnit(data: ByteBuffer, rbspStart: Int, nalEnd: Int): Boolean {
var pos = rbspStart
if (pos >= nalEnd) return false
// SEI payload type: accumulated 0xFF bytes plus the final byte.
var payloadType = 0
while (pos < nalEnd) {
val b = data.get(pos++).toInt() and 0xFF
payloadType += b
if (b != 0xFF) break
}
// SEI payload size, same encoding.
var payloadSize = 0
while (pos < nalEnd) {
val b = data.get(pos++).toInt() and 0xFF
payloadSize += b
if (b != 0xFF) break
}
if (payloadType != SEI_PAYLOAD_TYPE_ITU_T_T35 || payloadSize < 7 || pos + 7 > nalEnd) {
return false
}
// The identifier bytes (B5 00 3C 00 01 04 00/01) cannot contain the 0x000003 emulation
// prevention pattern, so they can be read without RBSP unescaping.
val countryCode = data.get(pos).toInt() and 0xFF
val providerCode = ((data.get(pos + 1).toInt() and 0xFF) shl 8) or (data.get(pos + 2).toInt() and 0xFF)
val orientedCode = ((data.get(pos + 3).toInt() and 0xFF) shl 8) or (data.get(pos + 4).toInt() and 0xFF)
val appIdentifier = data.get(pos + 5).toInt() and 0xFF
val appVersion = data.get(pos + 6).toInt() and 0xFF
return countryCode == 0xB5 &&
providerCode == 0x003C &&
orientedCode == 0x0001 &&
appIdentifier == 4 &&
(appVersion == 0 || appVersion == 1)
}
}
@@ -466,6 +466,7 @@ class ExoPlayerCore(private val activity: Activity) : Player.Listener {
// Use DefaultRenderersFactory with FFmpeg fallback for unsupported or blocked audio codecs.
val renderersFactory = PlezyRenderersFactory(activity).apply {
audioDiagnosticsLogger = { level, prefix, message -> emitLog(level, prefix, message) }
videoDiagnosticsLogger = { level, prefix, message -> emitLog(level, prefix, message) }
shouldBlockDirectAudioOutput = { format -> this@ExoPlayerCore.shouldBlockDirectAudioOutput(format, "sink support") }
onAudioCapabilitiesChanged = { updateAudioDecoderPolicy("audio capabilities changed") }
setEnableDecoderFallback(true)
@@ -38,13 +38,26 @@ class ExoPlayerPlugin :
private var fallbackInProgress: Boolean = false
private var activity: Activity? = null
private var activityBinding: ActivityPluginBinding? = null
private val nameToId = mutableMapOf<String, Int>()
// Every Dart observeProperty registration, kept so an ExoPlayer→MPV
// fallback can re-observe exactly what Dart asked for instead of
// maintaining a parallel hard-coded list.
private data class ObservedProperty(val id: Int, val format: String)
private val observedProperties = LinkedHashMap<String, ObservedProperty>()
private val mainHandler = Handler(Looper.getMainLooper())
private var configuredBufferSizeBytes: Int? = null
private var sessionGeneration = 0
private var debugLoggingEnabled: Boolean = false
private val pendingMpvProperties = mutableListOf<Pair<String, String>>()
// mpv properties set while ExoPlayer is active (including before
// initialize — Dart queues its startup properties first), replayed into a
// fallback MPV core. Keyed by property name (last write wins) and cleared
// only at real session boundaries (dispose, engine detach, open while the
// fallback is already active) so one playback's properties never leak into
// the next session's fallback.
private val pendingMpvProperties = LinkedHashMap<String, String>()
// FlutterPlugin
@@ -80,6 +93,7 @@ class ExoPlayerPlugin :
mpvCore = null
usingMpvFallback = false
fallbackInProgress = false
pendingMpvProperties.clear()
activity = null
activityBinding = null
Log.d(TAG, "Detached from activity")
@@ -186,6 +200,9 @@ class ExoPlayerPlugin :
currentActivity.runOnUiThread {
sessionGeneration++
// Do NOT clear pendingMpvProperties here: Dart queues its startup
// properties (sub-ass, subtitle fonts, ...) before initialize, and the
// fallback replay in setupMpvFallback needs them. Dispose/detach clear.
if (mpvCore != null || fallbackInProgress) {
mpvCore?.dispose()
@@ -228,6 +245,7 @@ class ExoPlayerPlugin :
mpvCore = null
usingMpvFallback = false
fallbackInProgress = false
pendingMpvProperties.clear()
Log.d(TAG, "Disposed")
result.success(null)
} ?: result.success(null)
@@ -503,13 +521,14 @@ class ExoPlayerPlugin :
private fun handleObserveProperty(call: MethodCall, result: MethodChannel.Result) {
val name = call.argument<String>("name")
val id = call.argument<Int>("id")
val format = call.argument<String>("format") ?: "string"
if (name == null || id == null) {
result.error("INVALID_ARGS", "Missing 'name' or 'id'", null)
return
}
nameToId[name] = id
observedProperties[name] = ObservedProperty(id, format)
result.success(null)
}
@@ -610,7 +629,7 @@ class ExoPlayerPlugin :
mpvCore?.setProperty(name, value)
} else {
// Store for later application if ExoPlayer falls back to MPV
pendingMpvProperties.add(Pair(name, value))
pendingMpvProperties[name] = value
}
result.success(null)
}
@@ -701,7 +720,7 @@ class ExoPlayerPlugin :
// ExoPlayerDelegate
override fun onPropertyChange(name: String, value: Any?) {
val propId = nameToId[name] ?: return
val propId = observedProperties[name]?.id ?: return
mainHandler.post { eventSink?.success(listOf(propId, value)) }
}
@@ -736,6 +755,94 @@ class ExoPlayerPlugin :
}
}
/**
* Configure a freshly initialized MPV fallback core: replay the properties
* and observers Dart registered against the ExoPlayer session, then resume
* the media at the handoff position. Runs in MpvPlayerCore.initialize's
* completion callback on the main thread.
*/
private fun setupMpvFallback(
core: MpvPlayerCore,
act: Activity,
uri: String,
headers: Map<String, String>?,
positionMs: Long
) {
// Snapshot Dart-registered state on main thread before clearing
val pendingProps = pendingMpvProperties.toList()
pendingMpvProperties.clear()
val observedProps = observedProperties.toList()
// Compute content FD on main thread (needs contentResolver)
val mpvUri = openContentFd(uri, act.contentResolver)
?.let { "fdclose://$it" } ?: uri
// Buffer size for closure
val bufferSize = configuredBufferSizeBytes
if (mpvCore !== core) {
core.dispose()
fallbackInProgress = false
return
}
// Configure basic MPV properties for Plex playback
core.setProperty("hwdec", "mediacodec,mediacodec-copy")
core.setProperty("vo", "gpu")
core.setProperty("ao", "audiotrack")
// Forward user's buffer config to MPV fallback
if (bufferSize != null && bufferSize > 0) {
core.setProperty("demuxer-max-bytes", bufferSize.toString())
}
// Apply pending MPV properties from Dart
for ((propName, propValue) in pendingProps) {
core.setProperty(propName, propValue)
}
// Re-observe exactly what Dart registered via observeProperty, so the
// event stream keeps flowing for every property the Dart side consumes.
for ((propName, observed) in observedProps) {
core.observeProperty(propName, observed.format)
}
// Show the MPV surface (internally posts to UI)
core.setVisible(true)
// Load media at the same position
val startSeconds = positionMs / 1000.0
val options = mutableListOf<String>()
options.add("start=$startSeconds")
headers?.forEach { (key, value) ->
options.add("http-header-fields-append=$key: $value")
}
val optionsStr = options.joinToString(",")
core.command(arrayOf("loadfile", mpvUri, "replace", "-1", optionsStr))
// On GPUs without compute shaders, MPV can't do dynamic peak detection
// and spline tone-mapping produces dim/washed-out results with extreme
// static HDR peak metadata. Use reinhard which handles this better.
Thread {
val peakDetection = core.getProperty("hdr-compute-peak")
if (peakDetection == "no") {
Log.i(TAG, "No compute shaders — overriding tone-mapping to reinhard")
core.setProperty("tone-mapping", "reinhard")
core.setProperty("tone-mapping-param", "0.7")
core.setProperty("tone-mapping-mode", "luma")
}
}.start()
// Request audio focus
core.requestAudioFocus()
// Emit backend-switched event on main thread
activity?.runOnUiThread {
onEvent("backend-switched", null)
}
Log.i(TAG, "Successfully switched to MPV fallback")
}
override fun onFormatUnsupported(
uri: String,
headers: Map<String, String>?,
@@ -813,86 +920,7 @@ class ExoPlayerPlugin :
usingMpvFallback = true
fallbackInProgress = false
// Snapshot pending properties on main thread before clearing
val pendingProps = pendingMpvProperties.toList()
pendingMpvProperties.clear()
// Compute content FD on main thread (needs contentResolver)
val mpvUri = openContentFd(uri, act.contentResolver)
?.let { "fdclose://$it" } ?: uri
// Buffer size for closure
val bufferSize = configuredBufferSizeBytes
if (mpvCore !== core) {
core.dispose()
fallbackInProgress = false
return@initialize
}
// Configure basic MPV properties for Plex playback
core.setProperty("hwdec", "mediacodec,mediacodec-copy")
core.setProperty("vo", "gpu")
core.setProperty("ao", "audiotrack")
// Forward user's buffer config to MPV fallback
if (bufferSize != null && bufferSize > 0) {
core.setProperty("demuxer-max-bytes", bufferSize.toString())
}
// Apply pending MPV properties from Dart
for ((propName, propValue) in pendingProps) {
core.setProperty(propName, propValue)
}
// Setup property observers
core.observeProperty("time-pos", "double")
core.observeProperty("duration", "double")
core.observeProperty("seekable", "flag")
core.observeProperty("pause", "flag")
core.observeProperty("paused-for-cache", "flag")
core.observeProperty("demuxer-cache-time", "double")
core.observeProperty("eof-reached", "flag")
core.observeProperty("track-list", "string")
core.observeProperty("aid", "string")
core.observeProperty("sid", "string")
core.observeProperty("volume", "double")
core.observeProperty("speed", "double")
// Show the MPV surface (internally posts to UI)
core.setVisible(true)
// Load media at the same position
val startSeconds = positionMs / 1000.0
val options = mutableListOf<String>()
options.add("start=$startSeconds")
headers?.forEach { (key, value) ->
options.add("http-header-fields-append=$key: $value")
}
val optionsStr = options.joinToString(",")
core.command(arrayOf("loadfile", mpvUri, "replace", "-1", optionsStr))
// On GPUs without compute shaders, MPV can't do dynamic peak detection
// and spline tone-mapping produces dim/washed-out results with extreme
// static HDR peak metadata. Use reinhard which handles this better.
Thread {
val peakDetection = core.getProperty("hdr-compute-peak")
if (peakDetection == "no") {
Log.i(TAG, "No compute shaders — overriding tone-mapping to reinhard")
core.setProperty("tone-mapping", "reinhard")
core.setProperty("tone-mapping-param", "0.7")
core.setProperty("tone-mapping-mode", "luma")
}
}.start()
// Request audio focus
core.requestAudioFocus()
// Emit backend-switched event on main thread
activity?.runOnUiThread {
onEvent("backend-switched", null)
}
Log.i(TAG, "Successfully switched to MPV fallback")
setupMpvFallback(core, act, uri, headers, positionMs)
}
} catch (e: Exception) {
fallbackInProgress = false
@@ -3,11 +3,14 @@ package com.edde746.plezy.exoplayer
import android.content.Context
import android.media.AudioDeviceInfo
import android.os.Build
import android.os.Handler
import androidx.annotation.OptIn
import androidx.media3.common.Format
import androidx.media3.common.MimeTypes
import androidx.media3.common.PlaybackParameters
import androidx.media3.common.util.Clock
import androidx.media3.common.util.UnstableApi
import androidx.media3.decoder.DecoderInputBuffer
import androidx.media3.exoplayer.DefaultRenderersFactory
import androidx.media3.exoplayer.Renderer
import androidx.media3.exoplayer.analytics.PlayerId
@@ -18,6 +21,10 @@ import androidx.media3.exoplayer.audio.AudioTrackAudioOutputProvider
import androidx.media3.exoplayer.audio.DefaultAudioSink
import androidx.media3.exoplayer.audio.DefaultAudioTrackBufferSizeProvider
import androidx.media3.exoplayer.audio.ForwardingAudioSink
import androidx.media3.exoplayer.mediacodec.MediaCodecAdapter
import androidx.media3.exoplayer.mediacodec.MediaCodecSelector
import androidx.media3.exoplayer.video.MediaCodecVideoRenderer
import androidx.media3.exoplayer.video.VideoRendererEventListener
import java.nio.ByteBuffer
import java.util.concurrent.atomic.AtomicLong
import kotlin.math.abs
@@ -36,6 +43,46 @@ class PlezyRenderersFactory(context: Context) : DefaultRenderersFactory(context)
var audioDiagnosticsLogger: ((String, String, String) -> Unit)? = null
var videoDiagnosticsLogger: ((String, String, String) -> Unit)? = null
override fun buildVideoRenderers(
context: Context,
extensionRendererMode: Int,
mediaCodecSelector: MediaCodecSelector,
enableDecoderFallback: Boolean,
eventHandler: Handler,
eventListener: VideoRendererEventListener,
allowedVideoJoiningTimeMs: Long,
out: ArrayList<Renderer>
) {
// Let super build the full list (it also appends extension renderers reflectively,
// e.g. the jellyfin ffmpeg artifact's video renderer), then swap the stock
// MediaCodecVideoRenderer for the DV-sanitizing variant at the same index.
super.buildVideoRenderers(
context,
extensionRendererMode,
mediaCodecSelector,
enableDecoderFallback,
eventHandler,
eventListener,
allowedVideoJoiningTimeMs,
out
)
val index = out.indexOfFirst { it.javaClass == MediaCodecVideoRenderer::class.java }
if (index < 0) return
out[index] = DvSanitizingVideoRenderer(
MediaCodecVideoRenderer.Builder(context)
.setCodecAdapterFactory(codecAdapterFactory)
.setMediaCodecSelector(mediaCodecSelector)
.setAllowedJoiningTimeMs(allowedVideoJoiningTimeMs)
.setEnableDecoderFallback(enableDecoderFallback)
.setEventHandler(eventHandler)
.setEventListener(eventListener)
.setMaxDroppedFramesToNotify(MAX_DROPPED_VIDEO_FRAME_COUNT_TO_NOTIFY),
videoDiagnosticsLogger
)
}
override fun buildAudioSink(
context: Context,
enableFloatOutput: Boolean,
@@ -280,6 +327,69 @@ internal class SubtitleDelayRenderer(
}
}
/**
* MediaCodecVideoRenderer that resolves the DV / HDR10+ dual-dynamic-metadata conflict
* per decode path (#1296, generalizes androidx/media#3085):
* - native DV codec selected (media3 only selects one when decoder AND display support DV):
* strip in-band HDR10+ SEI — conflicting dynamic metadata crashes Fire TV-class chipsets
* - HEVC fallback for an HEVC-based DV format: strip DV RPU/EL NALs (profiles 7/8, where the
* base layer remains valid HDR10/HLG), keeping HDR10+ for the display
*
* Flags are reassigned on every codec init: tunneling toggles and DV retries re-init the
* codec without recreating renderers, and decoder fallback can switch the codec MIME.
*/
@OptIn(UnstableApi::class)
internal class DvSanitizingVideoRenderer(
builder: Builder,
private val log: ((String, String, String) -> Unit)?
) : MediaCodecVideoRenderer(builder) {
private var stripHdr10PlusSei = false
private var stripDvRpu = false
override fun onCodecInitialized(
name: String,
configuration: MediaCodecAdapter.Configuration,
initializedTimestampMs: Long,
initializationDurationMs: Long
) {
super.onCodecInitialized(name, configuration, initializedTimestampMs, initializationDurationMs)
val codecs = configuration.format.codecs?.lowercase() ?: ""
val dvHevcFormat = configuration.format.sampleMimeType == MimeTypes.VIDEO_DOLBY_VISION &&
(codecs.startsWith("dvhe.") || codecs.startsWith("dvh1."))
val codecMimeType = configuration.codecInfo.codecMimeType
val newStripHdr10PlusSei = dvHevcFormat && codecMimeType == MimeTypes.VIDEO_DOLBY_VISION
val newStripDvRpu = dvHevcFormat &&
codecMimeType == MimeTypes.VIDEO_H265 &&
isBlCompatibleDvProfile(codecs)
if (newStripHdr10PlusSei != stripHdr10PlusSei || newStripDvRpu != stripDvRpu) {
log?.invoke(
"info",
"video",
"DV bitstream sanitizing: stripHdr10PlusSei=$newStripHdr10PlusSei, " +
"stripDvRpu=$newStripDvRpu (codec=$name, codecs=${configuration.format.codecs})"
)
}
stripHdr10PlusSei = newStripHdr10PlusSei
stripDvRpu = newStripDvRpu
}
override fun onQueueInputBuffer(buffer: DecoderInputBuffer) {
if (stripHdr10PlusSei || stripDvRpu) {
val data = buffer.data
if (data != null && data.hasRemaining() && !buffer.isEncrypted) {
DvBitstreamSanitizer.sanitize(data, stripHdr10PlusSei, stripDvRpu)
}
}
super.onQueueInputBuffer(buffer)
}
private fun isBlCompatibleDvProfile(codecs: String): Boolean = codecs.startsWith("dvhe.07") ||
codecs.startsWith("dvh1.07") ||
codecs.startsWith("dvhe.08") ||
codecs.startsWith("dvh1.08")
}
// --- AudioOutput wrapping: shares raw position with PositionFixAudioSink ---
// Also implements AudioTrack reuse across seeks to avoid expensive teardown/recreation.
// DefaultAudioSink releases the AudioOutput on every flush (seek), which destroys the
@@ -0,0 +1,201 @@
package com.edde746.plezy.exoplayer
import java.nio.ByteBuffer
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class DvBitstreamSanitizerTest {
// --- HDR10+ SEI stripping (native DV codec path) ---
@Test
fun stripsHdr10PlusPrefixSeiBetweenVclNals() {
val vcl1 = annexBNal(1, byteArrayOf(0x01, 0x02))
val vcl2 = annexBNal(1, byteArrayOf(0x03, 0x04))
val buffer = bufferOf(vcl1, hdr10PlusSei(), vcl2)
val originalLimit = buffer.limit()
DvBitstreamSanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
assertTrue(buffer.limit() < originalLimit)
assertEquals(0, buffer.position())
}
@Test
fun stripsSuffixSei() {
val vcl = annexBNal(1, byteArrayOf(0x01))
val suffixSei = annexBNal(40, hdr10PlusSeiPayload())
val buffer = bufferOf(vcl, suffixSei)
DvBitstreamSanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
assertArrayEquals(vcl, remainingBytes(buffer))
}
@Test
fun handles3ByteStartCodes() {
val vcl1 = annexBNal(1, byteArrayOf(0x01, 0x02), startCodeLen = 3)
val sei = annexBNal(39, hdr10PlusSeiPayload(), startCodeLen = 3)
val vcl2 = annexBNal(1, byteArrayOf(0x03), startCodeLen = 3)
val buffer = bufferOf(vcl1, sei, vcl2)
DvBitstreamSanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
}
@Test
fun preservesNonHdr10PlusT35Sei() {
// Same T.35 layout but wrong country code (0x00 instead of 0xB5).
val sei = annexBNal(
39,
byteArrayOf(0x04, 0x07, 0x00, 0x00, 0x3C, 0x00, 0x01, 0x04, 0x00)
)
val buffer = bufferOf(annexBNal(1, byteArrayOf(0x01)), sei, annexBNal(1, byteArrayOf(0x02)))
val original = remainingBytes(buffer)
DvBitstreamSanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
assertArrayEquals(original, remainingBytes(buffer))
}
@Test
fun noOpWithoutSeiNals() {
val buffer = bufferOf(annexBNal(1, byteArrayOf(0x01, 0x02)), annexBNal(1, byteArrayOf(0x03)))
val original = remainingBytes(buffer)
DvBitstreamSanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = true)
assertArrayEquals(original, remainingBytes(buffer))
}
@Test
fun keepsTruncatedSei() {
// Declares payload size 7 but the identifier bytes are cut short.
val truncated = annexBNal(39, byteArrayOf(0x04, 0x07, 0xB5.toByte(), 0x00, 0x3C))
val buffer = bufferOf(annexBNal(1, byteArrayOf(0x01)), truncated)
val original = remainingBytes(buffer)
DvBitstreamSanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
assertArrayEquals(original, remainingBytes(buffer))
}
@Test
fun keepsHdr10PlusSeiWhenFlagOff() {
val buffer = bufferOf(annexBNal(1, byteArrayOf(0x01)), hdr10PlusSei())
val original = remainingBytes(buffer)
DvBitstreamSanitizer.sanitize(buffer, stripHdr10PlusSei = false, stripDvRpu = false)
assertArrayEquals(original, remainingBytes(buffer))
}
// --- DV RPU/EL stripping (HEVC fallback path) ---
@Test
fun rpuModeStripsRpuAndElButKeepsHdr10PlusSei() {
val vcl = annexBNal(1, byteArrayOf(0x01))
val rpu = annexBNal(62, byteArrayOf(0x19, 0x08))
val el = annexBNal(63, byteArrayOf(0x42))
val sei = hdr10PlusSei()
val buffer = bufferOf(vcl, rpu, sei, el)
DvBitstreamSanitizer.sanitize(buffer, stripHdr10PlusSei = false, stripDvRpu = true)
assertArrayEquals(concat(vcl, sei), remainingBytes(buffer))
}
@Test
fun bothFlagsStripBothMetadataKinds() {
val vcl1 = annexBNal(19, byteArrayOf(0x00)) // IDR_W_RADL
val vcl2 = annexBNal(1, byteArrayOf(0x05))
val buffer = bufferOf(vcl1, annexBNal(62, byteArrayOf(0x19)), hdr10PlusSei(), vcl2)
DvBitstreamSanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = true)
assertArrayEquals(concat(vcl1, vcl2), remainingBytes(buffer))
}
// --- Buffer handling ---
@Test
fun respectsPositionAndRestoresIt() {
val prefix = byteArrayOf(0xAA.toByte(), 0xBB.toByte())
val vcl = annexBNal(1, byteArrayOf(0x01))
val content = concat(prefix, vcl, hdr10PlusSei())
val buffer = ByteBuffer.wrap(content.copyOf())
buffer.position(prefix.size)
DvBitstreamSanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
assertEquals(prefix.size, buffer.position())
assertArrayEquals(vcl, remainingBytes(buffer))
// Bytes before the position are untouched.
assertEquals(0xAA.toByte(), buffer.get(0))
assertEquals(0xBB.toByte(), buffer.get(1))
}
@Test
fun worksOnDirectBuffers() {
val vcl = annexBNal(1, byteArrayOf(0x01, 0x02))
val content = concat(vcl, hdr10PlusSei())
val buffer = ByteBuffer.allocateDirect(content.size)
buffer.put(content)
buffer.flip()
DvBitstreamSanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = false)
assertArrayEquals(vcl, remainingBytes(buffer))
}
@Test
fun emptyBufferIsNoOp() {
val buffer = ByteBuffer.allocate(0)
DvBitstreamSanitizer.sanitize(buffer, stripHdr10PlusSei = true, stripDvRpu = true)
assertEquals(0, buffer.position())
assertEquals(0, buffer.limit())
}
// --- Helpers ---
/** Builds an HEVC NAL unit: start code + 2-byte NAL header encoding [nalUnitType] + payload. */
private fun annexBNal(nalUnitType: Int, payload: ByteArray, startCodeLen: Int = 4): ByteArray {
val startCode = if (startCodeLen == 3) byteArrayOf(0, 0, 1) else byteArrayOf(0, 0, 0, 1)
val header = byteArrayOf(((nalUnitType shl 1) and 0x7E).toByte(), 0x01)
return concat(startCode, header, payload)
}
/**
* SEI payload: type 4 (user_data_registered_itu_t_t35), size 7, then the HDR10+
* identifiers — country 0xB5, provider 0x003C, oriented code 0x0001, app id 4, version 0 —
* closed by the rbsp_trailing_bits stop byte real SEI NALs always end with (a trailing 0x00
* would otherwise be ambiguous against a following 3-byte start code).
*/
private fun hdr10PlusSeiPayload(): ByteArray = byteArrayOf(0x04, 0x07, 0xB5.toByte(), 0x00, 0x3C, 0x00, 0x01, 0x04, 0x00, 0x80.toByte())
private fun hdr10PlusSei(): ByteArray = annexBNal(39, hdr10PlusSeiPayload())
private fun concat(vararg parts: ByteArray): ByteArray {
val result = ByteArray(parts.sumOf { it.size })
var offset = 0
for (part in parts) {
part.copyInto(result, offset)
offset += part.size
}
return result
}
private fun bufferOf(vararg parts: ByteArray): ByteBuffer = ByteBuffer.wrap(concat(*parts))
private fun remainingBytes(buffer: ByteBuffer): ByteArray {
val copy = ByteArray(buffer.remaining())
buffer.duplicate().get(copy)
return copy
}
}
+1 -1
View File
@@ -789,7 +789,7 @@
repositoryURL = "https://github.com/edde746/MPVKit";
requirement = {
kind = revision;
revision = 1b0134a2ea04a3b967f61a726b5864351280b420;
revision = 1fc33029bc0317583866c62811dc0ab2aa2415b6;
};
};
/* End XCRemoteSwiftPackageReference section */
@@ -40,7 +40,7 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/edde746/MPVKit",
"state" : {
"revision" : "1b0134a2ea04a3b967f61a726b5864351280b420"
"revision" : "1fc33029bc0317583866c62811dc0ab2aa2415b6"
}
},
{
@@ -40,7 +40,7 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/edde746/MPVKit",
"state" : {
"revision" : "1b0134a2ea04a3b967f61a726b5864351280b420"
"revision" : "1fc33029bc0317583866c62811dc0ab2aa2415b6"
}
},
{
+280 -16
View File
@@ -13,10 +13,19 @@ class MpvPlayerCore: MpvPlayerCoreBase {
private var mainBlankView: UIView?
private var isVisible = false
private var isDisposed = false
private var activeDisplayCriteriaKey: String?
private static var activeDisplayCriteriaKey: String?
private var lastDisplayCriteriaMutation: DisplayCriteriaMutation = .skipped
#if os(tvOS)
private var displayModeSwitchWaiter: DisplayModeSwitchWaiter?
private var displayModeSwitchWaiterGeneration = 0
#endif
var isPipStarting = false
private static func log(_ message: String) {
NSLog("[MpvPlayerCore] %@", message)
}
func initialize(in window: UIWindow) -> Bool {
guard !isInitialized else {
print("[MpvPlayerCore] Already initialized")
@@ -245,6 +254,7 @@ class MpvPlayerCore: MpvPlayerCoreBase {
colorMatrix: String?
) -> Bool {
#if os(tvOS)
lastDisplayCriteriaMutation = .skipped
guard let window = containerView?.window ?? self.window else { return false }
let displayManager = window.avDisplayManager
@@ -255,7 +265,9 @@ class MpvPlayerCore: MpvPlayerCoreBase {
let refreshRate = Float(fps > 0 ? fps : 0)
let sourceHasDolbyVision = doviProfile > 0
guard sourceHasDolbyVision || sigPeak > 0 || gamma != nil || primaries != nil || colorMatrix != nil else {
guard
refreshRate > 0 || sourceHasDolbyVision || sigPeak > 0 || gamma != nil || primaries != nil || colorMatrix != nil
else {
clearDisplayCriteria(displayManager, reason: "no display metadata")
return false
}
@@ -315,15 +327,20 @@ class MpvPlayerCore: MpvPlayerCoreBase {
let criteriaKey =
"\(displayRange.rawValue)|\(refreshRate)|\(width)x\(height)|\(doviProfile)|\(doviLevel)|\(doviCompatibilityId ?? -1)"
if activeDisplayCriteriaKey == criteriaKey { return true }
if Self.activeDisplayCriteriaKey == criteriaKey && displayManager.preferredDisplayCriteria != nil {
lastDisplayCriteriaMutation = .unchanged
return true
}
displayManager.preferredDisplayCriteria = AVDisplayCriteria(
let displayCriteria = AVDisplayCriteria(
refreshRate: refreshRate,
formatDescription: formatDescription
)
activeDisplayCriteriaKey = criteriaKey
print(
"[MpvPlayerCore] preferredDisplayCriteria set to \(displayRange.rawValue) (source: \(sourceRange.rawValue), fps: \(refreshRate), \(width)x\(height), DV profile: \(doviProfile), level: \(doviLevel), compat: \(doviCompatibilityId ?? -1))"
displayManager.preferredDisplayCriteria = displayCriteria
Self.activeDisplayCriteriaKey = criteriaKey
lastDisplayCriteriaMutation = .set
Self.log(
"preferredDisplayCriteria set to \(displayRange.rawValue) (source: \(sourceRange.rawValue), fps: \(refreshRate), \(width)x\(height), DV profile: \(doviProfile), level: \(doviLevel), compat: \(doviCompatibilityId ?? -1))"
)
return true
#else
@@ -331,6 +348,49 @@ class MpvPlayerCore: MpvPlayerCoreBase {
#endif
}
func setServerDisplayCriteriaForPlayback(
_ criteria: ServerDisplayCriteria?,
extraDelayMs: Int,
completion: @escaping () -> Void
) {
let apply = { [weak self] in
guard let self else {
completion()
return
}
self.setServerDisplayCriteria(criteria) { [weak self] applied in
guard let self else {
completion()
return
}
#if os(tvOS)
guard applied || self.lastDisplayCriteriaMutation == .cleared else {
completion()
return
}
self.waitForDisplayModeSwitchIfNeeded(extraDelayMs: extraDelayMs, completion: completion)
#else
completion()
#endif
}
}
if Thread.isMainThread {
apply()
} else {
DispatchQueue.main.async(execute: apply)
}
}
private enum DisplayCriteriaMutation {
case skipped
case unchanged
case set
case cleared
}
#if os(tvOS)
private enum DisplayDynamicRange: String {
case sdr = "SDR"
@@ -340,10 +400,197 @@ class MpvPlayerCore: MpvPlayerCoreBase {
}
private func clearDisplayCriteria(_ displayManager: AVDisplayManager, reason: String) {
if activeDisplayCriteriaKey != nil || displayManager.preferredDisplayCriteria != nil {
if Self.activeDisplayCriteriaKey != nil || displayManager.preferredDisplayCriteria != nil {
displayManager.preferredDisplayCriteria = nil
activeDisplayCriteriaKey = nil
print("[MpvPlayerCore] preferredDisplayCriteria cleared (\(reason))")
Self.activeDisplayCriteriaKey = nil
lastDisplayCriteriaMutation = .cleared
Self.log("preferredDisplayCriteria cleared (\(reason))")
} else {
lastDisplayCriteriaMutation = .unchanged
}
}
private func waitForDisplayModeSwitchIfNeeded(extraDelayMs: Int, completion: @escaping () -> Void) {
guard let window = containerView?.window ?? self.window else {
completion()
return
}
let displayManager = window.avDisplayManager
let mutation = lastDisplayCriteriaMutation
let shouldWaitForStart = mutation == .set || mutation == .cleared
if !shouldWaitForStart && !displayManager.isDisplayModeSwitchInProgress {
completion()
return
}
displayModeSwitchWaiter?.cancel(complete: true)
displayModeSwitchWaiterGeneration += 1
let waiterGeneration = displayModeSwitchWaiterGeneration
let waiter = DisplayModeSwitchWaiter(
displayManager: displayManager,
shouldWaitForStart: shouldWaitForStart,
extraDelayMs: extraDelayMs
) { [weak self] in
if let self, self.displayModeSwitchWaiterGeneration == waiterGeneration {
self.displayModeSwitchWaiter = nil
}
completion()
}
displayModeSwitchWaiter = waiter
waiter.start()
}
private final class DisplayModeSwitchWaiter {
private weak var displayManager: AVDisplayManager?
private let shouldWaitForStart: Bool
private let extraDelayMs: Int
private let completion: () -> Void
private var startObserver: NSObjectProtocol?
private var endObserver: NSObjectProtocol?
private var startWatchdog: DispatchWorkItem?
private var endWatchdog: DispatchWorkItem?
private var settleWorkItem: DispatchWorkItem?
private var finished = false
private var completionDelivered = false
private static let startWindowMs = 500
private static let switchWatchdogMs = 8000
private static let settleMs = 200
init(
displayManager: AVDisplayManager,
shouldWaitForStart: Bool,
extraDelayMs: Int,
completion: @escaping () -> Void
) {
self.displayManager = displayManager
self.shouldWaitForStart = shouldWaitForStart
self.extraDelayMs = max(0, min(extraDelayMs, 10_000))
self.completion = completion
}
func start() {
guard let displayManager else {
finish(waited: false, reason: "manager unavailable")
return
}
if displayManager.isDisplayModeSwitchInProgress {
beginWaitingForEnd(reason: "already in progress")
return
}
guard shouldWaitForStart else {
finish(waited: false, reason: "no switch in progress")
return
}
let center = NotificationCenter.default
startObserver = center.addObserver(
forName: .AVDisplayManagerModeSwitchStart,
object: nil,
queue: .main
) { [weak self] _ in
self?.beginWaitingForEnd(reason: "start notification")
}
let watchdog = DispatchWorkItem { [weak self] in
guard let self else { return }
if self.displayManager?.isDisplayModeSwitchInProgress == true {
self.beginWaitingForEnd(reason: "progress poll")
} else {
self.finish(waited: false, reason: "start watchdog")
}
}
startWatchdog = watchdog
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(Self.startWindowMs), execute: watchdog)
}
func cancel(complete: Bool = false) {
finished = true
cleanup()
if complete { completeOnce() }
}
private func beginWaitingForEnd(reason: String) {
guard !finished else { return }
startWatchdog?.cancel()
startWatchdog = nil
if let startObserver {
NotificationCenter.default.removeObserver(startObserver)
self.startObserver = nil
}
guard displayManager?.isDisplayModeSwitchInProgress == true else {
finish(waited: true, reason: "ended before wait (\(reason))")
return
}
let center = NotificationCenter.default
endObserver = center.addObserver(
forName: .AVDisplayManagerModeSwitchEnd,
object: nil,
queue: .main
) { [weak self] _ in
self?.finish(waited: true, reason: "end notification")
}
let watchdog = DispatchWorkItem { [weak self] in
self?.finish(waited: true, reason: "end watchdog")
}
endWatchdog = watchdog
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(Self.switchWatchdogMs), execute: watchdog)
}
private func finish(waited: Bool, reason: String) {
guard !finished else { return }
finished = true
cleanup()
let delayMs = waited ? Self.settleMs + extraDelayMs : 0
MpvPlayerCore.log(
"display mode switch wait complete "
+ "(\(reason), waited: \(waited), extraDelayMs: \(extraDelayMs))"
)
guard delayMs > 0 else {
completeOnce()
return
}
let workItem = DispatchWorkItem { [weak self] in
self?.completeOnce()
}
settleWorkItem = workItem
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(delayMs), execute: workItem)
}
private func completeOnce() {
guard !completionDelivered else { return }
completionDelivered = true
settleWorkItem?.cancel()
settleWorkItem = nil
completion()
}
private func cleanup() {
startWatchdog?.cancel()
endWatchdog?.cancel()
settleWorkItem?.cancel()
startWatchdog = nil
endWatchdog = nil
settleWorkItem = nil
if let startObserver {
NotificationCenter.default.removeObserver(startObserver)
self.startObserver = nil
}
if let endObserver {
NotificationCenter.default.removeObserver(endObserver)
self.endObserver = nil
}
}
deinit {
cancel()
}
}
@@ -529,21 +776,37 @@ class MpvPlayerCore: MpvPlayerCoreBase {
}
#endif
func dispose() {
func dispose(preserveDisplayCriteria: Bool = false) {
// Guard double-dispose: the plugin calls dispose() then drops the
// strong ref, which fires deinit → dispose() again. The second call
// would re-enter and crash on weak-ref formation during dealloc.
guard !isDisposed else { return }
isDisposed = true
#if os(tvOS)
if preserveDisplayCriteria {
Self.log("dispose preserving display criteria (key: \(Self.activeDisplayCriteriaKey ?? "nil"))")
}
#endif
// Reset the HDMI mode hint synchronously while self is still alive
// and on main. An async-to-main dispatch here would be drained after
// dealloc (the plugin sets playerCore = nil right after this call
// returns), leaving the link stuck at the last clip's refresh rate.
updateDisplayCriteria(
doviProfile: 0, doviLevel: 0, doviCompatibilityId: nil,
fps: 0, width: 0, height: 0, sigPeak: 0,
gamma: nil, primaries: nil, colorMatrix: nil)
// During video-to-video replacement, keep the hint so tvOS doesn't
// renegotiate back to default before the replacement route can set its
// next criteria.
if !preserveDisplayCriteria {
updateDisplayCriteria(
doviProfile: 0, doviLevel: 0, doviCompatibilityId: nil,
fps: 0, width: 0, height: 0, sigPeak: 0,
gamma: nil, primaries: nil, colorMatrix: nil)
}
#if os(tvOS)
displayModeSwitchWaiter?.cancel(complete: true)
displayModeSwitchWaiter = nil
#endif
NotificationCenter.default.removeObserver(self)
#if os(iOS)
@@ -558,7 +821,8 @@ class MpvPlayerCore: MpvPlayerCoreBase {
mainBlankView?.removeFromSuperview()
mainBlankView = nil
isInitialized = false
print("[MpvPlayerCore] Disposed")
Self.log("Disposed")
}
deinit {
+16 -31
View File
@@ -72,7 +72,7 @@ class MpvPlayerPlugin: NSObject, FlutterPlugin, FlutterStreamHandler, MpvPluginS
case "initialize":
handleInitialize(result: result)
case "dispose":
handleDispose(result: result)
handleDispose(call: call, result: result)
case "setProperty":
handleSetProperty(call: call, result: result)
case "getProperty":
@@ -326,45 +326,27 @@ class MpvPlayerPlugin: NSObject, FlutterPlugin, FlutterStreamHandler, MpvPluginS
}
}
private func handleDispose(result: @escaping FlutterResult) {
private func handleDispose(call: FlutterMethodCall, result: @escaping FlutterResult) {
let args = call.arguments as? [String: Any]
let preserveDisplayMode = args?["preserveDisplayMode"] as? Bool ?? false
DispatchQueue.main.async { [weak self] in
guard let self = self else { result(nil); return }
NSLog("[MpvPlayerPlugin] dispose preserveDisplayMode=%@", preserveDisplayMode.description)
self.pipController?.teardown()
self.pipController = nil
self.autoPipEnabled = false
self.pendingInlineRestoreAfterPip = false
self.unregisterSceneActivationObserver()
self.stopPipTimebaseSync()
self.playerCore?.dispose()
self.playerCore?.dispose(preserveDisplayCriteria: preserveDisplayMode)
self.playerCore = nil
result(nil)
}
}
private func handleSetProperty(call: FlutterMethodCall, result: @escaping FlutterResult) {
guard let args = call.arguments as? [String: Any],
let name = args["name"] as? String,
let value = args["value"] as? String
else {
result(
FlutterError(
code: "INVALID_ARGS", message: "Missing 'name' or 'value' argument",
details: nil))
return
}
guard let core = playerCore else {
result(nil)
return
}
core.setPropertyAsync(name, value: value) { [weak self] _ in
if name == "pause" {
self?.pipController?.invalidatePlaybackState()
if core.isPipActive == true { self?.syncPipTimebase() }
}
result(nil)
}
func didSetPauseProperty(value: String) {
pipController?.invalidatePlaybackState()
if playerCore?.isPipActive == true { syncPipTimebase() }
}
private func handleSetDisplayCriteria(call: FlutterMethodCall, result: @escaping FlutterResult) {
@@ -378,10 +360,12 @@ class MpvPlayerPlugin: NSObject, FlutterPlugin, FlutterStreamHandler, MpvPluginS
return
}
let extraDelayMs = int64Value(args["extraDelayMs"]).map { Int(clamping: $0) } ?? 0
guard let raw = args["criteria"] as? [String: Any] else {
DispatchQueue.main.async {
core.setServerDisplayCriteria(nil)
result(nil)
core.setServerDisplayCriteriaForPlayback(nil, extraDelayMs: extraDelayMs) {
result(nil)
}
}
return
}
@@ -398,8 +382,9 @@ class MpvPlayerPlugin: NSObject, FlutterPlugin, FlutterStreamHandler, MpvPluginS
colorMatrix: stringValue(raw["matrix"])
)
DispatchQueue.main.async {
core.setServerDisplayCriteria(criteria)
result(nil)
core.setServerDisplayCriteriaForPlayback(criteria, extraDelayMs: extraDelayMs) {
result(nil)
}
}
}
+29 -19
View File
@@ -585,24 +585,6 @@ abstract class _FocusableTextInputBase extends StatelessWidget {
return null;
}
Future<void> _showTvKeyboard(BuildContext context) {
if (!enabled) return Future.value();
return showTvVirtualKeyboard(
context: context,
controller: controller,
hintText: _keyboardHint(decoration),
keyboardType: keyboardType,
textInputAction: textInputAction,
inputFormatters: inputFormatters,
obscureText: obscureText,
maxLength: maxLength,
maxLines: maxLines,
onChanged: onChanged,
onSubmitted: onSubmitted,
onAction: _handleTvKeyboardAction,
);
}
void _handleTvKeyboardAction() {
if (onEditingComplete != null) {
onEditingComplete!();
@@ -776,8 +758,36 @@ class _FocusableTextInputHostState extends State<_FocusableTextInputHost> {
_suppressTvKeyboardForCurrentFocus = false;
_suppressTvKeyboardAutoOpen = true;
_logTvTextInput('Host.openTvKeyboard node=${_installedFocusNode?.debugLabel}');
// The dialog outlives input rebuilds (e.g. a search field whose
// onNavigateDown appears once results arrive while the keyboard is up),
// so only static configuration may be snapshotted here — the callbacks
// must resolve against widget.input at invoke time.
final input = widget.input;
unawaited(
widget.input._showTvKeyboard(context).whenComplete(() {
showTvVirtualKeyboard(
context: context,
controller: input.controller,
hintText: _keyboardHint(input.decoration),
keyboardType: input.keyboardType,
textInputAction: input.textInputAction,
inputFormatters: input.inputFormatters,
obscureText: input.obscureText,
maxLength: input.maxLength,
maxLines: input.maxLines,
onChanged: (text) {
if (!mounted) return;
widget.input.onChanged?.call(text);
},
onSubmitted: (text) {
if (!mounted) return;
final current = widget.input;
if (current.onSubmitted != null) {
current.onSubmitted!(text);
} else {
current._handleTvKeyboardAction();
}
},
).whenComplete(() {
if (!mounted) return;
_tvKeyboardOpen = false;
WidgetsBinding.instance.addPostFrameCallback((_) {
+6 -2
View File
@@ -54,6 +54,7 @@
"ok": "OK",
"off": "Изкл.",
"seasonNumber": "Сезон ${number}",
"episodeNumberTitle": "Епизод ${number} - ${title}",
"chapterNumber": "Глава ${number}",
"reconnect": "Свържи отново",
"exit": "Изход",
@@ -115,6 +116,9 @@
"gridView": "Мрежа",
"listView": "Списък",
"showHeroSection": "Показвай водеща секция",
"continueWatchingAction": "Действие за продължаване на гледането",
"continueWatchingPlay": "Пусни",
"continueWatchingDetails": "Отвори подробности",
"useGlobalHubs": "Използвай начално оформление",
"useGlobalHubsDescription": "Показвай обединени начални хъбове. В противен случай използвай препоръките на библиотеката.",
"showServerNameOnHubs": "Показвай името на сървъра в хъбовете",
@@ -360,8 +364,8 @@
"markAsWatched": "Маркирай като гледано",
"markAsUnwatched": "Маркирай като негледано",
"removeFromContinueWatching": "Премахни от продължаване на гледането",
"viewDetails": "Виж подробности",
"goToSeries": "Към сериала",
"goToSeason": "Към сезона",
"shufflePlay": "Разбъркано възпроизвеждане",
"shuffleNotAvailableOffline": "Разбърканото възпроизвеждане не е налично офлайн",
"fileInfo": "Информация за файла",
@@ -507,7 +511,6 @@
"fileInfoNotAvailable": "Информацията за файла не е налична",
"errorLoadingFileInfo": "Грешка при зареждане на информация за файла: ${error}",
"errorLoadingSeries": "Грешка при зареждане на сериала",
"errorLoadingSeason": "Грешка при зареждане на сезона",
"musicNotSupported": "Възпроизвеждането на музика все още не се поддържа",
"noDescriptionAvailable": "Няма налично описание",
"noProfilesAvailable": "Няма налични профили",
@@ -751,6 +754,7 @@
"rating": "Рейтинг",
"communityRating": "Оценка от общността",
"criticRating": "Оценка от критиците",
"userRating": "Потребителска оценка",
"lastPlayed": "Последно възпроизведено",
"datePlayed": "Дата на възпроизвеждане",
"playCount": "Брой възпроизвеждания",
+6 -2
View File
@@ -54,6 +54,7 @@
"ok": "OK",
"off": "Fra",
"seasonNumber": "Sæson ${number}",
"episodeNumberTitle": "Episode ${number} - ${title}",
"chapterNumber": "Kapitel ${number}",
"reconnect": "Genopret forbindelse",
"exit": "Afslut",
@@ -115,6 +116,9 @@
"gridView": "Gitter",
"listView": "Liste",
"showHeroSection": "Vis hero-sektion",
"continueWatchingAction": "Handling for Fortsæt med at se",
"continueWatchingPlay": "Afspil",
"continueWatchingDetails": "Åbn detaljer",
"useGlobalHubs": "Brug startlayout",
"useGlobalHubsDescription": "Vis samlet startsideindhold. Brug ellers biblioteksanbefalinger.",
"showServerNameOnHubs": "Vis servernavn på hubbe",
@@ -360,8 +364,8 @@
"markAsWatched": "Markér som set",
"markAsUnwatched": "Markér som uset",
"removeFromContinueWatching": "Fjern fra Fortsæt med at se",
"viewDetails": "Vis detaljer",
"goToSeries": "Gå til serie",
"goToSeason": "Gå til sæson",
"shufflePlay": "Afspil tilfældigt",
"shuffleNotAvailableOffline": "Bland afspilning er ikke tilgængelig offline",
"fileInfo": "Filinfo",
@@ -507,7 +511,6 @@
"fileInfoNotAvailable": "Filinfo ikke tilgængelig",
"errorLoadingFileInfo": "Fejl ved indlæsning af filinfo: ${error}",
"errorLoadingSeries": "Fejl ved indlæsning af serie",
"errorLoadingSeason": "Fejl ved indlæsning af sæson",
"musicNotSupported": "Musikafspilning understøttes endnu ikke",
"noDescriptionAvailable": "Ingen beskrivelse tilgængelig",
"noProfilesAvailable": "Ingen profiler tilgængelige",
@@ -751,6 +754,7 @@
"rating": "Vurdering",
"communityRating": "Fællesskabsvurdering",
"criticRating": "Kritikerbedømmelse",
"userRating": "Brugerbedømmelse",
"lastPlayed": "Sidst afspillet",
"datePlayed": "Afspilningsdato",
"playCount": "Antal afspilninger",
+6 -2
View File
@@ -54,6 +54,7 @@
"ok": "OK",
"off": "Aus",
"seasonNumber": "Staffel ${number}",
"episodeNumberTitle": "Episode ${number} - ${title}",
"chapterNumber": "Kapitel ${number}",
"reconnect": "Erneut verbinden",
"exit": "Beenden",
@@ -115,6 +116,9 @@
"gridView": "Raster",
"listView": "Liste",
"showHeroSection": "Hero-Bereich anzeigen",
"continueWatchingAction": "Aktion für Weiterschauen",
"continueWatchingPlay": "Abspielen",
"continueWatchingDetails": "Details öffnen",
"useGlobalHubs": "Startlayout verwenden",
"useGlobalHubsDescription": "Einheitliche Start-Hubs anzeigen. Sonst Bibliotheksempfehlungen verwenden.",
"showServerNameOnHubs": "Servername bei Hubs anzeigen",
@@ -360,8 +364,8 @@
"markAsWatched": "Als gesehen markieren",
"markAsUnwatched": "Als ungesehen markieren",
"removeFromContinueWatching": "Aus ‚Weiterschauen‘ entfernen",
"viewDetails": "Details anzeigen",
"goToSeries": "Zur Serie",
"goToSeason": "Zur Staffel",
"shufflePlay": "Zufallswiedergabe",
"shuffleNotAvailableOffline": "Zufallswiedergabe ist offline nicht verfügbar",
"fileInfo": "Dateiinfo",
@@ -507,7 +511,6 @@
"fileInfoNotAvailable": "Dateiinfo nicht verfügbar",
"errorLoadingFileInfo": "Fehler beim Laden der Dateiinfo: ${error}",
"errorLoadingSeries": "Fehler beim Laden der Serie",
"errorLoadingSeason": "Fehler beim Laden der Staffel",
"musicNotSupported": "Musikwiedergabe wird noch nicht unterstützt",
"noDescriptionAvailable": "Keine Beschreibung verfügbar",
"noProfilesAvailable": "Keine Profile verfügbar",
@@ -751,6 +754,7 @@
"rating": "Bewertung",
"communityRating": "Community-Bewertung",
"criticRating": "Kritikerbewertung",
"userRating": "Benutzerbewertung",
"lastPlayed": "Zuletzt abgespielt",
"datePlayed": "Wiedergabedatum",
"playCount": "Wiedergaben",
+6 -2
View File
@@ -54,6 +54,7 @@
"ok": "OK",
"off": "Off",
"seasonNumber": "Season ${number}",
"episodeNumberTitle": "Episode ${number} - ${title}",
"chapterNumber": "Chapter ${number}",
"reconnect": "Reconnect",
"exit": "Exit",
@@ -115,6 +116,9 @@
"gridView": "Grid",
"listView": "List",
"showHeroSection": "Show Hero Section",
"continueWatchingAction": "Continue Watching Action",
"continueWatchingPlay": "Play",
"continueWatchingDetails": "Open Details",
"useGlobalHubs": "Use Home Layout",
"useGlobalHubsDescription": "Show unified home hubs. Otherwise use library recommendations.",
"showServerNameOnHubs": "Show Server Name on Hubs",
@@ -360,8 +364,8 @@
"markAsWatched": "Mark as Watched",
"markAsUnwatched": "Mark as Unwatched",
"removeFromContinueWatching": "Remove from Continue Watching",
"viewDetails": "View details",
"goToSeries": "Go to series",
"goToSeason": "Go to season",
"shufflePlay": "Shuffle Play",
"shuffleNotAvailableOffline": "Shuffle not available offline",
"fileInfo": "File Info",
@@ -507,7 +511,6 @@
"fileInfoNotAvailable": "File information not available",
"errorLoadingFileInfo": "Error loading file info: ${error}",
"errorLoadingSeries": "Error loading series",
"errorLoadingSeason": "Error loading season",
"musicNotSupported": "Music playback is not yet supported",
"noDescriptionAvailable": "No description available",
"noProfilesAvailable": "No profiles available",
@@ -751,6 +754,7 @@
"rating": "Rating",
"communityRating": "Community Rating",
"criticRating": "Critic Rating",
"userRating": "User Rating",
"lastPlayed": "Last Played",
"datePlayed": "Date Played",
"playCount": "Play Count",
+6 -2
View File
@@ -54,6 +54,7 @@
"ok": "OK",
"off": "Desactivado",
"seasonNumber": "Temporada ${number}",
"episodeNumberTitle": "Episodio ${number} - ${title}",
"chapterNumber": "Capítulo ${number}",
"reconnect": "Reconectar",
"exit": "Salir",
@@ -115,6 +116,9 @@
"gridView": "Cuadrícula",
"listView": "Lista",
"showHeroSection": "Mostrar Sección Destacada",
"continueWatchingAction": "Acción de Seguir viendo",
"continueWatchingPlay": "Reproducir",
"continueWatchingDetails": "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",
@@ -360,8 +364,8 @@
"markAsWatched": "Marcar como Visto",
"markAsUnwatched": "Marcar como No Visto",
"removeFromContinueWatching": "Eliminar de Seguir Viendo",
"viewDetails": "Ver detalles",
"goToSeries": "Ir a la serie",
"goToSeason": "Ir a la temporada",
"shufflePlay": "Reproducción Aleatoria",
"shuffleNotAvailableOffline": "La reproducción aleatoria no está disponible sin conexión",
"fileInfo": "Información del Archivo",
@@ -507,7 +511,6 @@
"fileInfoNotAvailable": "Información de archivo no disponible",
"errorLoadingFileInfo": "Error al cargar info de archivo: ${error}",
"errorLoadingSeries": "Error al cargar la serie",
"errorLoadingSeason": "Error al cargar la temporada",
"musicNotSupported": "La reproducción de música aún no está soportada",
"noDescriptionAvailable": "No hay descripción disponible",
"noProfilesAvailable": "No hay perfiles disponibles",
@@ -751,6 +754,7 @@
"rating": "Valoración",
"communityRating": "Calificación de comunidad",
"criticRating": "Calificación de crítica",
"userRating": "Calificación del usuario",
"lastPlayed": "Última reproducción",
"datePlayed": "Fecha de reproducción",
"playCount": "Reproducciones",
+6 -2
View File
@@ -54,6 +54,7 @@
"ok": "OK",
"off": "Désactivé",
"seasonNumber": "Saison ${number}",
"episodeNumberTitle": "Épisode ${number} - ${title}",
"chapterNumber": "Chapitre ${number}",
"reconnect": "Reconnecter",
"exit": "Quitter",
@@ -115,6 +116,9 @@
"gridView": "Grille",
"listView": "Liste",
"showHeroSection": "Afficher la section Hero",
"continueWatchingAction": "Action Continuer à regarder",
"continueWatchingPlay": "Lire",
"continueWatchingDetails": "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",
@@ -360,8 +364,8 @@
"markAsWatched": "Marquer comme vu",
"markAsUnwatched": "Marquer comme non visionné",
"removeFromContinueWatching": "Supprimer de la liste \"Continuer à regarder\"",
"viewDetails": "Voir les détails",
"goToSeries": "Aller à la série",
"goToSeason": "Aller à la saison",
"shufflePlay": "Lecture aléatoire",
"shuffleNotAvailableOffline": "La lecture aléatoire n’est pas disponible hors ligne",
"fileInfo": "Informations sur le fichier",
@@ -507,7 +511,6 @@
"fileInfoNotAvailable": "Informations sur le fichier non disponibles",
"errorLoadingFileInfo": "Erreur lors du chargement des informations sur le fichier: ${error}",
"errorLoadingSeries": "Erreur lors du chargement de la série",
"errorLoadingSeason": "Erreur lors du chargement de la saison",
"musicNotSupported": "La lecture de musique n'est pas encore prise en charge",
"noDescriptionAvailable": "Aucune description disponible",
"noProfilesAvailable": "Aucun profil disponible",
@@ -751,6 +754,7 @@
"rating": "Note",
"communityRating": "Note communautaire",
"criticRating": "Note critique",
"userRating": "Note utilisateur",
"lastPlayed": "Dernière lecture",
"datePlayed": "Date de lecture",
"playCount": "Lectures",
+6 -2
View File
@@ -54,6 +54,7 @@
"ok": "OK",
"off": "Disattivato",
"seasonNumber": "Stagione ${number}",
"episodeNumberTitle": "Episodio ${number} - ${title}",
"chapterNumber": "Capitolo ${number}",
"reconnect": "Riconnetti",
"exit": "Esci",
@@ -115,6 +116,9 @@
"gridView": "Griglia",
"listView": "Elenco",
"showHeroSection": "Mostra sezione principale",
"continueWatchingAction": "Azione Continua a guardare",
"continueWatchingPlay": "Riproduci",
"continueWatchingDetails": "Apri dettagli",
"useGlobalHubs": "Usa layout home",
"useGlobalHubsDescription": "Mostra hub Home unificati. Altrimenti usa i consigli della libreria.",
"showServerNameOnHubs": "Mostra nome server sugli hub",
@@ -360,8 +364,8 @@
"markAsWatched": "Segna come visto",
"markAsUnwatched": "Segna come non visto",
"removeFromContinueWatching": "Rimuovi da Continua a guardare",
"viewDetails": "Vedi dettagli",
"goToSeries": "Vai alle serie",
"goToSeason": "Vai alla stagione",
"shufflePlay": "Riproduzione casuale",
"shuffleNotAvailableOffline": "Riproduzione casuale non disponibile offline",
"fileInfo": "Info sul file",
@@ -507,7 +511,6 @@
"fileInfoNotAvailable": "Informazioni sul file non disponibili",
"errorLoadingFileInfo": "Errore caricamento informazioni sul file: ${error}",
"errorLoadingSeries": "Errore caricamento serie",
"errorLoadingSeason": "Errore caricamento stagione",
"musicNotSupported": "La riproduzione musicale non è ancora supportata",
"noDescriptionAvailable": "Nessuna descrizione disponibile",
"noProfilesAvailable": "Nessun profilo disponibile",
@@ -751,6 +754,7 @@
"rating": "Valutazione",
"communityRating": "Valutazione della community",
"criticRating": "Valutazione critica",
"userRating": "Valutazione utente",
"lastPlayed": "Ultima riproduzione",
"datePlayed": "Data di riproduzione",
"playCount": "Riproduzioni",
+6 -2
View File
@@ -54,6 +54,7 @@
"ok": "OK",
"off": "オフ",
"seasonNumber": "シーズン${number}",
"episodeNumberTitle": "エピソード${number} - ${title}",
"chapterNumber": "チャプター${number}",
"reconnect": "再接続",
"exit": "終了",
@@ -115,6 +116,9 @@
"gridView": "グリッド",
"listView": "リスト",
"showHeroSection": "ヒーローセクションを表示",
"continueWatchingAction": "視聴中の操作",
"continueWatchingPlay": "再生",
"continueWatchingDetails": "詳細を開く",
"useGlobalHubs": "ホームレイアウトを使用",
"useGlobalHubsDescription": "統合ホームハブを表示します。オフの場合はライブラリのおすすめを使用します。",
"showServerNameOnHubs": "ハブにサーバー名を表示",
@@ -360,8 +364,8 @@
"markAsWatched": "視聴済みにする",
"markAsUnwatched": "未視聴にする",
"removeFromContinueWatching": "視聴中から削除",
"viewDetails": "詳細を表示",
"goToSeries": "シリーズへ移動",
"goToSeason": "シーズンへ移動",
"shufflePlay": "シャッフル再生",
"shuffleNotAvailableOffline": "オフラインではシャッフルを利用できません",
"fileInfo": "ファイル情報",
@@ -507,7 +511,6 @@
"fileInfoNotAvailable": "ファイル情報が利用できません",
"errorLoadingFileInfo": "ファイル情報の読み込みエラー: ${error}",
"errorLoadingSeries": "シリーズの読み込みエラー",
"errorLoadingSeason": "シーズンの読み込みエラー",
"musicNotSupported": "音楽の再生はまだサポートされていません",
"noDescriptionAvailable": "説明はありません",
"noProfilesAvailable": "利用可能なプロフィールがありません",
@@ -751,6 +754,7 @@
"rating": "評価",
"communityRating": "コミュニティ評価",
"criticRating": "批評家評価",
"userRating": "ユーザー評価",
"lastPlayed": "最終再生",
"datePlayed": "再生日",
"playCount": "再生回数",
+6 -2
View File
@@ -54,6 +54,7 @@
"ok": "확인",
"off": "끔",
"seasonNumber": "시즌 ${number}",
"episodeNumberTitle": "${number}화 - ${title}",
"chapterNumber": "챕터 ${number}",
"reconnect": "다시 연결",
"exit": "종료",
@@ -115,6 +116,9 @@
"gridView": "그리드 보기",
"listView": "목록 보기",
"showHeroSection": "주요 추천 영역 표시",
"continueWatchingAction": "계속 보기 동작",
"continueWatchingPlay": "재생",
"continueWatchingDetails": "상세 정보 열기",
"useGlobalHubs": "홈 레이아웃 사용",
"useGlobalHubsDescription": "통합 홈 허브를 표시합니다. 끄면 라이브러리 추천을 사용합니다.",
"showServerNameOnHubs": "허브에 서버 이름 표시",
@@ -360,8 +364,8 @@
"markAsWatched": "시청 완료로 표시",
"markAsUnwatched": "시청 안 함으로 표시",
"removeFromContinueWatching": "계속 보기에서 제거",
"viewDetails": "상세 정보 보기",
"goToSeries": "시리즈로 이동",
"goToSeason": "시즌으로 이동",
"shufflePlay": "무작위 재생",
"shuffleNotAvailableOffline": "오프라인에서는 셔플을 사용할 수 없습니다",
"fileInfo": "파일 정보",
@@ -507,7 +511,6 @@
"fileInfoNotAvailable": "파일 정보가 없습니다",
"errorLoadingFileInfo": "파일 정보 로딩 중 오류: ${error}",
"errorLoadingSeries": "시리즈 로딩 중 오류",
"errorLoadingSeason": "시즌 로딩 중 오류",
"musicNotSupported": "음악 재생 미지원",
"noDescriptionAvailable": "설명이 없습니다",
"noProfilesAvailable": "사용 가능한 프로필이 없습니다",
@@ -751,6 +754,7 @@
"rating": "평점",
"communityRating": "커뮤니티 평점",
"criticRating": "평론가 평점",
"userRating": "사용자 평점",
"lastPlayed": "마지막 재생",
"datePlayed": "재생일",
"playCount": "재생 횟수",
+6 -2
View File
@@ -54,6 +54,7 @@
"ok": "OK",
"off": "Av",
"seasonNumber": "Sesong ${number}",
"episodeNumberTitle": "Episode ${number} - ${title}",
"chapterNumber": "Kapittel ${number}",
"reconnect": "Koble til på nytt",
"exit": "Avslutt",
@@ -115,6 +116,9 @@
"gridView": "Rutenett",
"listView": "Liste",
"showHeroSection": "Vis fremhevet seksjon",
"continueWatchingAction": "Handling for Fortsett å se",
"continueWatchingPlay": "Spill av",
"continueWatchingDetails": "Åpne detaljer",
"useGlobalHubs": "Bruk startoppsett",
"useGlobalHubsDescription": "Vis samlet startinnhold. Ellers brukes bibliotekanbefalinger.",
"showServerNameOnHubs": "Vis servernavn på huber",
@@ -360,8 +364,8 @@
"markAsWatched": "Merk som sett",
"markAsUnwatched": "Merk som usett",
"removeFromContinueWatching": "Fjern fra Fortsett å se",
"viewDetails": "Vis detaljer",
"goToSeries": "Gå til serie",
"goToSeason": "Gå til sesong",
"shufflePlay": "Tilfeldig avspilling",
"shuffleNotAvailableOffline": "Tilfeldig avspilling er ikke tilgjengelig offline",
"fileInfo": "Filinformasjon",
@@ -507,7 +511,6 @@
"fileInfoNotAvailable": "Filinformasjon ikke tilgjengelig",
"errorLoadingFileInfo": "Feil ved lasting av filinformasjon: ${error}",
"errorLoadingSeries": "Feil ved lasting av serie",
"errorLoadingSeason": "Feil ved lasting av sesong",
"musicNotSupported": "Musikkavspilling støttes ikke ennå",
"noDescriptionAvailable": "Ingen beskrivelse tilgjengelig",
"noProfilesAvailable": "Ingen profiler tilgjengelige",
@@ -751,6 +754,7 @@
"rating": "Vurdering",
"communityRating": "Fellesskapsvurdering",
"criticRating": "Kritikervurdering",
"userRating": "Brukervurdering",
"lastPlayed": "Sist spilt",
"datePlayed": "Avspillingsdato",
"playCount": "Avspillinger",
+6 -2
View File
@@ -54,6 +54,7 @@
"ok": "OK",
"off": "Uit",
"seasonNumber": "Seizoen ${number}",
"episodeNumberTitle": "Aflevering ${number} - ${title}",
"chapterNumber": "Hoofdstuk ${number}",
"reconnect": "Opnieuw verbinden",
"exit": "Afsluiten",
@@ -115,6 +116,9 @@
"gridView": "Raster",
"listView": "Lijst",
"showHeroSection": "Toon hoofdsectie",
"continueWatchingAction": "Actie voor Doorgaan met kijken",
"continueWatchingPlay": "Afspelen",
"continueWatchingDetails": "Details openen",
"useGlobalHubs": "Startlayout gebruiken",
"useGlobalHubsDescription": "Toon gecombineerde home-hubs. Anders bibliotheekaanbevelingen gebruiken.",
"showServerNameOnHubs": "Servernaam tonen bij hubs",
@@ -360,8 +364,8 @@
"markAsWatched": "Markeer als gekeken",
"markAsUnwatched": "Markeer als ongekeken",
"removeFromContinueWatching": "Verwijder uit Doorgaan met kijken",
"viewDetails": "Details bekijken",
"goToSeries": "Ga naar serie",
"goToSeason": "Ga naar seizoen",
"shufflePlay": "Willekeurig afspelen",
"shuffleNotAvailableOffline": "Shuffle is offline niet beschikbaar",
"fileInfo": "Bestand info",
@@ -507,7 +511,6 @@
"fileInfoNotAvailable": "Bestand informatie niet beschikbaar",
"errorLoadingFileInfo": "Fout bij laden bestand info: ${error}",
"errorLoadingSeries": "Fout bij laden serie",
"errorLoadingSeason": "Fout bij laden seizoen",
"musicNotSupported": "Muziek afspelen wordt nog niet ondersteund",
"noDescriptionAvailable": "Geen beschrijving beschikbaar",
"noProfilesAvailable": "Geen profielen beschikbaar",
@@ -751,6 +754,7 @@
"rating": "Beoordeling",
"communityRating": "Communitybeoordeling",
"criticRating": "Criticusbeoordeling",
"userRating": "Gebruikersbeoordeling",
"lastPlayed": "Laatst afgespeeld",
"datePlayed": "Afspeeldatum",
"playCount": "Aantal afspelingen",
+6 -2
View File
@@ -54,6 +54,7 @@
"ok": "OK",
"off": "Wył.",
"seasonNumber": "Sezon ${number}",
"episodeNumberTitle": "Odcinek ${number} - ${title}",
"chapterNumber": "Rozdział ${number}",
"reconnect": "Połącz ponownie",
"exit": "Wyjdź",
@@ -115,6 +116,9 @@
"gridView": "Siatka",
"listView": "Lista",
"showHeroSection": "Pokaż sekcję wyróżnioną",
"continueWatchingAction": "Akcja Kontynuuj oglądanie",
"continueWatchingPlay": "Odtwórz",
"continueWatchingDetails": "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",
@@ -360,8 +364,8 @@
"markAsWatched": "Oznacz jako obejrzane",
"markAsUnwatched": "Oznacz jako nieobejrzane",
"removeFromContinueWatching": "Usuń z kontynuowania oglądania",
"viewDetails": "Pokaż szczegóły",
"goToSeries": "Przejdź do serialu",
"goToSeason": "Przejdź do sezonu",
"shufflePlay": "Odtwarzanie losowe",
"shuffleNotAvailableOffline": "Odtwarzanie losowe nie jest dostępne offline",
"fileInfo": "Informacje o pliku",
@@ -507,7 +511,6 @@
"fileInfoNotAvailable": "Informacje o pliku niedostępne",
"errorLoadingFileInfo": "Błąd ładowania informacji o pliku: ${error}",
"errorLoadingSeries": "Błąd ładowania serialu",
"errorLoadingSeason": "Błąd ładowania sezonu",
"musicNotSupported": "Odtwarzanie muzyki nie jest jeszcze obsługiwane",
"noDescriptionAvailable": "Brak dostępnego opisu",
"noProfilesAvailable": "Brak dostępnych profili",
@@ -751,6 +754,7 @@
"rating": "Ocena",
"communityRating": "Ocena społeczności",
"criticRating": "Ocena krytyków",
"userRating": "Ocena użytkownika",
"lastPlayed": "Ostatnio odtwarzane",
"datePlayed": "Data odtworzenia",
"playCount": "Liczba odtworzeń",
+6 -2
View File
@@ -54,6 +54,7 @@
"ok": "OK",
"off": "Desativado",
"seasonNumber": "Temporada ${number}",
"episodeNumberTitle": "Episódio ${number} - ${title}",
"chapterNumber": "Capítulo ${number}",
"reconnect": "Reconectar",
"exit": "Sair",
@@ -115,6 +116,9 @@
"gridView": "Grade",
"listView": "Lista",
"showHeroSection": "Mostrar Seção de Destaque",
"continueWatchingAction": "Ação de Continuar Assistindo",
"continueWatchingPlay": "Reproduzir",
"continueWatchingDetails": "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",
@@ -360,8 +364,8 @@
"markAsWatched": "Marcar como Assistido",
"markAsUnwatched": "Marcar como Não Assistido",
"removeFromContinueWatching": "Remover de Continuar Assistindo",
"viewDetails": "Ver detalhes",
"goToSeries": "Ir para a série",
"goToSeason": "Ir para a temporada",
"shufflePlay": "Reprodução Aleatória",
"shuffleNotAvailableOffline": "Reprodução aleatória indisponível offline",
"fileInfo": "Info do Arquivo",
@@ -507,7 +511,6 @@
"fileInfoNotAvailable": "Informações do arquivo não disponíveis",
"errorLoadingFileInfo": "Erro ao carregar info do arquivo: ${error}",
"errorLoadingSeries": "Erro ao carregar série",
"errorLoadingSeason": "Erro ao carregar temporada",
"musicNotSupported": "Reprodução de música ainda não é suportada",
"noDescriptionAvailable": "Nenhuma descrição disponível",
"noProfilesAvailable": "Nenhum perfil disponível",
@@ -751,6 +754,7 @@
"rating": "Avaliação",
"communityRating": "Avaliação da comunidade",
"criticRating": "Avaliação da crítica",
"userRating": "Avaliação do usuário",
"lastPlayed": "Última reprodução",
"datePlayed": "Data de reprodução",
"playCount": "Reproduções",
+6 -2
View File
@@ -54,6 +54,7 @@
"ok": "OK",
"off": "Выкл.",
"seasonNumber": "Сезон ${number}",
"episodeNumberTitle": "Эпизод ${number} - ${title}",
"chapterNumber": "Глава ${number}",
"reconnect": "Переподключить",
"exit": "Выход",
@@ -115,6 +116,9 @@
"gridView": "Сетка",
"listView": "Список",
"showHeroSection": "Показать раздел избранного",
"continueWatchingAction": "Действие для «Продолжить просмотр»",
"continueWatchingPlay": "Воспроизвести",
"continueWatchingDetails": "Открыть сведения",
"useGlobalHubs": "Использовать макет главной",
"useGlobalHubsDescription": "Показывать единые разделы главной. Иначе использовать рекомендации библиотек.",
"showServerNameOnHubs": "Показывать имя сервера в хабах",
@@ -360,8 +364,8 @@
"markAsWatched": "Отметить как просмотренное",
"markAsUnwatched": "Отметить как непросмотренное",
"removeFromContinueWatching": "Удалить из «Продолжить просмотр»",
"viewDetails": "Показать сведения",
"goToSeries": "Перейти к сериалу",
"goToSeason": "Перейти к сезону",
"shufflePlay": "Случайное воспроизведение",
"shuffleNotAvailableOffline": "Перемешивание недоступно офлайн",
"fileInfo": "Информация о файле",
@@ -507,7 +511,6 @@
"fileInfoNotAvailable": "Информация о файле недоступна",
"errorLoadingFileInfo": "Ошибка загрузки информации о файле: ${error}",
"errorLoadingSeries": "Ошибка загрузки сериала",
"errorLoadingSeason": "Ошибка загрузки сезона",
"musicNotSupported": "Воспроизведение музыки пока не поддерживается",
"noDescriptionAvailable": "Описание недоступно",
"noProfilesAvailable": "Профили недоступны",
@@ -751,6 +754,7 @@
"rating": "Рейтинг",
"communityRating": "Оценка сообщества",
"criticRating": "Оценка критиков",
"userRating": "Пользовательская оценка",
"lastPlayed": "Последний просмотр",
"datePlayed": "Дата просмотра",
"playCount": "Количество просмотров",
+1 -1
View File
@@ -4,7 +4,7 @@
/// To regenerate, run: `dart run slang`
///
/// Locales: 16
/// Strings: 20320 (1270 per locale)
/// Strings: 20384 (1274 per locale)
// coverage:ignore-file
// ignore_for_file: type=lint, unused_import
+16 -8
View File
@@ -162,6 +162,7 @@ class _TranslationsCommonBg extends TranslationsCommonEn {
@override String get ok => 'OK';
@override String get off => 'Изкл.';
@override String seasonNumber({required Object number}) => 'Сезон ${number}';
@override String episodeNumberTitle({required Object number, required Object title}) => 'Епизод ${number} - ${title}';
@override String chapterNumber({required Object number}) => 'Глава ${number}';
@override String get reconnect => 'Свържи отново';
@override String get exit => 'Изход';
@@ -244,6 +245,9 @@ class _TranslationsSettingsBg extends TranslationsSettingsEn {
@override String get gridView => 'Мрежа';
@override String get listView => 'Списък';
@override String get showHeroSection => 'Показвай водеща секция';
@override String get continueWatchingAction => 'Действие за продължаване на гледането';
@override String get continueWatchingPlay => 'Пусни';
@override String get continueWatchingDetails => 'Отвори подробности';
@override String get useGlobalHubs => 'Използвай начално оформление';
@override String get useGlobalHubsDescription => 'Показвай обединени начални хъбове. В противен случай използвай препоръките на библиотеката.';
@override String get showServerNameOnHubs => 'Показвай името на сървъра в хъбовете';
@@ -491,8 +495,8 @@ class _TranslationsMediaMenuBg extends TranslationsMediaMenuEn {
@override String get markAsWatched => 'Маркирай като гледано';
@override String get markAsUnwatched => 'Маркирай като негледано';
@override String get removeFromContinueWatching => 'Премахни от продължаване на гледането';
@override String get viewDetails => 'Виж подробности';
@override String get goToSeries => 'Към сериала';
@override String get goToSeason => 'Към сезона';
@override String get shufflePlay => 'Разбъркано възпроизвеждане';
@override String get shuffleNotAvailableOffline => 'Разбърканото възпроизвеждане не е налично офлайн';
@override String get fileInfo => 'Информация за файла';
@@ -672,7 +676,6 @@ class _TranslationsMessagesBg extends TranslationsMessagesEn {
@override String get fileInfoNotAvailable => 'Информацията за файла не е налична';
@override String errorLoadingFileInfo({required Object error}) => 'Грешка при зареждане на информация за файла: ${error}';
@override String get errorLoadingSeries => 'Грешка при зареждане на сериала';
@override String get errorLoadingSeason => 'Грешка при зареждане на сезона';
@override String get musicNotSupported => 'Възпроизвеждането на музика все още не се поддържа';
@override String get noDescriptionAvailable => 'Няма налично описание';
@override String get noProfilesAvailable => 'Няма налични профили';
@@ -1740,6 +1743,7 @@ class _TranslationsLibrariesSortLabelsBg extends TranslationsLibrariesSortLabels
@override String get rating => 'Рейтинг';
@override String get communityRating => 'Оценка от общността';
@override String get criticRating => 'Оценка от критиците';
@override String get userRating => 'Потребителска оценка';
@override String get lastPlayed => 'Последно възпроизведено';
@override String get datePlayed => 'Дата на възпроизвеждане';
@override String get playCount => 'Брой възпроизвеждания';
@@ -1969,6 +1973,7 @@ extension on TranslationsBg {
'common.ok' => 'OK',
'common.off' => 'Изкл.',
'common.seasonNumber' => ({required Object number}) => 'Сезон ${number}',
'common.episodeNumberTitle' => ({required Object number, required Object title}) => 'Епизод ${number} - ${title}',
'common.chapterNumber' => ({required Object number}) => 'Глава ${number}',
'common.reconnect' => 'Свържи отново',
'common.exit' => 'Изход',
@@ -2024,6 +2029,9 @@ extension on TranslationsBg {
'settings.gridView' => 'Мрежа',
'settings.listView' => 'Списък',
'settings.showHeroSection' => 'Показвай водеща секция',
'settings.continueWatchingAction' => 'Действие за продължаване на гледането',
'settings.continueWatchingPlay' => 'Пусни',
'settings.continueWatchingDetails' => 'Отвори подробности',
'settings.useGlobalHubs' => 'Използвай начално оформление',
'settings.useGlobalHubsDescription' => 'Показвай обединени начални хъбове. В противен случай използвай препоръките на библиотеката.',
'settings.showServerNameOnHubs' => 'Показвай името на сървъра в хъбовете',
@@ -2259,8 +2267,8 @@ extension on TranslationsBg {
'mediaMenu.markAsWatched' => 'Маркирай като гледано',
'mediaMenu.markAsUnwatched' => 'Маркирай като негледано',
'mediaMenu.removeFromContinueWatching' => 'Премахни от продължаване на гледането',
'mediaMenu.viewDetails' => 'Виж подробности',
'mediaMenu.goToSeries' => 'Към сериала',
'mediaMenu.goToSeason' => 'Към сезона',
'mediaMenu.shufflePlay' => 'Разбъркано възпроизвеждане',
'mediaMenu.shuffleNotAvailableOffline' => 'Разбърканото възпроизвеждане не е налично офлайн',
'mediaMenu.fileInfo' => 'Информация за файла',
@@ -2392,7 +2400,6 @@ extension on TranslationsBg {
'messages.fileInfoNotAvailable' => 'Информацията за файла не е налична',
'messages.errorLoadingFileInfo' => ({required Object error}) => 'Грешка при зареждане на информация за файла: ${error}',
'messages.errorLoadingSeries' => 'Грешка при зареждане на сериала',
'messages.errorLoadingSeason' => 'Грешка при зареждане на сезона',
'messages.musicNotSupported' => 'Възпроизвеждането на музика все още не се поддържа',
'messages.noDescriptionAvailable' => 'Няма налично описание',
'messages.noProfilesAvailable' => 'Няма налични профили',
@@ -2428,11 +2435,11 @@ extension on TranslationsBg {
'subtitlingStyling.border' => 'Рамка',
'subtitlingStyling.background' => 'Фон',
'subtitlingStyling.fontSize' => 'Размер на шрифта',
_ => null,
} ?? switch (path) {
'subtitlingStyling.textColor' => 'Цвят на текста',
'subtitlingStyling.borderSize' => 'Размер на рамката',
'subtitlingStyling.borderColor' => 'Цвят на рамката',
_ => null,
} ?? switch (path) {
'subtitlingStyling.backgroundOpacity' => 'Прозрачност на фона',
'subtitlingStyling.backgroundColor' => 'Цвят на фона',
'subtitlingStyling.position' => 'Позиция',
@@ -2615,6 +2622,7 @@ extension on TranslationsBg {
'libraries.sortLabels.rating' => 'Рейтинг',
'libraries.sortLabels.communityRating' => 'Оценка от общността',
'libraries.sortLabels.criticRating' => 'Оценка от критиците',
'libraries.sortLabels.userRating' => 'Потребителска оценка',
'libraries.sortLabels.lastPlayed' => 'Последно възпроизведено',
'libraries.sortLabels.datePlayed' => 'Дата на възпроизвеждане',
'libraries.sortLabels.playCount' => 'Брой възпроизвеждания',
@@ -2941,12 +2949,12 @@ extension on TranslationsBg {
'companionRemote.remote.menu' => 'Меню',
'companionRemote.remote.tabNavigation' => 'Навигация с Tab',
'companionRemote.remote.tabDiscover' => 'Открий',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabLibraries' => 'Библиотеки',
'companionRemote.remote.tabSearch' => 'Търсене',
'companionRemote.remote.tabDownloads' => 'Изтегляния',
'companionRemote.remote.tabSettings' => 'Настройки',
_ => null,
} ?? switch (path) {
'companionRemote.remote.previous' => 'Предишен',
'companionRemote.remote.playPause' => 'Пускане/пауза',
'companionRemote.remote.next' => 'Следващ',
+16 -8
View File
@@ -162,6 +162,7 @@ class _TranslationsCommonDa extends TranslationsCommonEn {
@override String get ok => 'OK';
@override String get off => 'Fra';
@override String seasonNumber({required Object number}) => 'Sæson ${number}';
@override String episodeNumberTitle({required Object number, required Object title}) => 'Episode ${number} - ${title}';
@override String chapterNumber({required Object number}) => 'Kapitel ${number}';
@override String get reconnect => 'Genopret forbindelse';
@override String get exit => 'Afslut';
@@ -244,6 +245,9 @@ class _TranslationsSettingsDa extends TranslationsSettingsEn {
@override String get gridView => 'Gitter';
@override String get listView => 'Liste';
@override String get showHeroSection => 'Vis hero-sektion';
@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 useGlobalHubs => 'Brug startlayout';
@override String get useGlobalHubsDescription => 'Vis samlet startsideindhold. Brug ellers biblioteksanbefalinger.';
@override String get showServerNameOnHubs => 'Vis servernavn på hubbe';
@@ -491,8 +495,8 @@ class _TranslationsMediaMenuDa extends TranslationsMediaMenuEn {
@override String get markAsWatched => 'Markér som set';
@override String get markAsUnwatched => 'Markér som uset';
@override String get removeFromContinueWatching => 'Fjern fra Fortsæt med at se';
@override String get viewDetails => 'Vis detaljer';
@override String get goToSeries => 'Gå til serie';
@override String get goToSeason => 'Gå til sæson';
@override String get shufflePlay => 'Afspil tilfældigt';
@override String get shuffleNotAvailableOffline => 'Bland afspilning er ikke tilgængelig offline';
@override String get fileInfo => 'Filinfo';
@@ -672,7 +676,6 @@ class _TranslationsMessagesDa extends TranslationsMessagesEn {
@override String get fileInfoNotAvailable => 'Filinfo ikke tilgængelig';
@override String errorLoadingFileInfo({required Object error}) => 'Fejl ved indlæsning af filinfo: ${error}';
@override String get errorLoadingSeries => 'Fejl ved indlæsning af serie';
@override String get errorLoadingSeason => 'Fejl ved indlæsning af sæson';
@override String get musicNotSupported => 'Musikafspilning understøttes endnu ikke';
@override String get noDescriptionAvailable => 'Ingen beskrivelse tilgængelig';
@override String get noProfilesAvailable => 'Ingen profiler tilgængelige';
@@ -1740,6 +1743,7 @@ class _TranslationsLibrariesSortLabelsDa extends TranslationsLibrariesSortLabels
@override String get rating => 'Vurdering';
@override String get communityRating => 'Fællesskabsvurdering';
@override String get criticRating => 'Kritikerbedømmelse';
@override String get userRating => 'Brugerbedømmelse';
@override String get lastPlayed => 'Sidst afspillet';
@override String get datePlayed => 'Afspilningsdato';
@override String get playCount => 'Antal afspilninger';
@@ -1969,6 +1973,7 @@ extension on TranslationsDa {
'common.ok' => 'OK',
'common.off' => 'Fra',
'common.seasonNumber' => ({required Object number}) => 'Sæson ${number}',
'common.episodeNumberTitle' => ({required Object number, required Object title}) => 'Episode ${number} - ${title}',
'common.chapterNumber' => ({required Object number}) => 'Kapitel ${number}',
'common.reconnect' => 'Genopret forbindelse',
'common.exit' => 'Afslut',
@@ -2024,6 +2029,9 @@ extension on TranslationsDa {
'settings.gridView' => 'Gitter',
'settings.listView' => 'Liste',
'settings.showHeroSection' => 'Vis hero-sektion',
'settings.continueWatchingAction' => 'Handling for Fortsæt med at se',
'settings.continueWatchingPlay' => 'Afspil',
'settings.continueWatchingDetails' => 'Åbn detaljer',
'settings.useGlobalHubs' => 'Brug startlayout',
'settings.useGlobalHubsDescription' => 'Vis samlet startsideindhold. Brug ellers biblioteksanbefalinger.',
'settings.showServerNameOnHubs' => 'Vis servernavn på hubbe',
@@ -2259,8 +2267,8 @@ extension on TranslationsDa {
'mediaMenu.markAsWatched' => 'Markér som set',
'mediaMenu.markAsUnwatched' => 'Markér som uset',
'mediaMenu.removeFromContinueWatching' => 'Fjern fra Fortsæt med at se',
'mediaMenu.viewDetails' => 'Vis detaljer',
'mediaMenu.goToSeries' => 'Gå til serie',
'mediaMenu.goToSeason' => 'Gå til sæson',
'mediaMenu.shufflePlay' => 'Afspil tilfældigt',
'mediaMenu.shuffleNotAvailableOffline' => 'Bland afspilning er ikke tilgængelig offline',
'mediaMenu.fileInfo' => 'Filinfo',
@@ -2392,7 +2400,6 @@ extension on TranslationsDa {
'messages.fileInfoNotAvailable' => 'Filinfo ikke tilgængelig',
'messages.errorLoadingFileInfo' => ({required Object error}) => 'Fejl ved indlæsning af filinfo: ${error}',
'messages.errorLoadingSeries' => 'Fejl ved indlæsning af serie',
'messages.errorLoadingSeason' => 'Fejl ved indlæsning af sæson',
'messages.musicNotSupported' => 'Musikafspilning understøttes endnu ikke',
'messages.noDescriptionAvailable' => 'Ingen beskrivelse tilgængelig',
'messages.noProfilesAvailable' => 'Ingen profiler tilgængelige',
@@ -2428,11 +2435,11 @@ extension on TranslationsDa {
'subtitlingStyling.border' => 'Kant',
'subtitlingStyling.background' => 'Baggrund',
'subtitlingStyling.fontSize' => 'Skriftstørrelse',
_ => null,
} ?? switch (path) {
'subtitlingStyling.textColor' => 'Tekstfarve',
'subtitlingStyling.borderSize' => 'Kantstørrelse',
'subtitlingStyling.borderColor' => 'Kantfarve',
_ => null,
} ?? switch (path) {
'subtitlingStyling.backgroundOpacity' => 'Baggrundsgennemsigtighed',
'subtitlingStyling.backgroundColor' => 'Baggrundsfarve',
'subtitlingStyling.position' => 'Position',
@@ -2615,6 +2622,7 @@ extension on TranslationsDa {
'libraries.sortLabels.rating' => 'Vurdering',
'libraries.sortLabels.communityRating' => 'Fællesskabsvurdering',
'libraries.sortLabels.criticRating' => 'Kritikerbedømmelse',
'libraries.sortLabels.userRating' => 'Brugerbedømmelse',
'libraries.sortLabels.lastPlayed' => 'Sidst afspillet',
'libraries.sortLabels.datePlayed' => 'Afspilningsdato',
'libraries.sortLabels.playCount' => 'Antal afspilninger',
@@ -2941,12 +2949,12 @@ extension on TranslationsDa {
'companionRemote.remote.menu' => 'Menu',
'companionRemote.remote.tabNavigation' => 'Fanenavigation',
'companionRemote.remote.tabDiscover' => 'Opdag',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabLibraries' => 'Biblioteker',
'companionRemote.remote.tabSearch' => 'Søg',
'companionRemote.remote.tabDownloads' => 'Downloads',
'companionRemote.remote.tabSettings' => 'Indstillinger',
_ => null,
} ?? switch (path) {
'companionRemote.remote.previous' => 'Forrige',
'companionRemote.remote.playPause' => 'Afspil/Pause',
'companionRemote.remote.next' => 'Næste',
+16 -8
View File
@@ -162,6 +162,7 @@ class _TranslationsCommonDe extends TranslationsCommonEn {
@override String get ok => 'OK';
@override String get off => 'Aus';
@override String seasonNumber({required Object number}) => 'Staffel ${number}';
@override String episodeNumberTitle({required Object number, required Object title}) => 'Episode ${number} - ${title}';
@override String chapterNumber({required Object number}) => 'Kapitel ${number}';
@override String get reconnect => 'Erneut verbinden';
@override String get exit => 'Beenden';
@@ -244,6 +245,9 @@ class _TranslationsSettingsDe extends TranslationsSettingsEn {
@override String get gridView => 'Raster';
@override String get listView => 'Liste';
@override String get showHeroSection => 'Hero-Bereich anzeigen';
@override String get continueWatchingAction => 'Aktion für Weiterschauen';
@override String get continueWatchingPlay => 'Abspielen';
@override String get continueWatchingDetails => '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';
@@ -491,8 +495,8 @@ class _TranslationsMediaMenuDe extends TranslationsMediaMenuEn {
@override String get markAsWatched => 'Als gesehen markieren';
@override String get markAsUnwatched => 'Als ungesehen markieren';
@override String get removeFromContinueWatching => 'Aus ‚Weiterschauen‘ entfernen';
@override String get viewDetails => 'Details anzeigen';
@override String get goToSeries => 'Zur Serie';
@override String get goToSeason => 'Zur Staffel';
@override String get shufflePlay => 'Zufallswiedergabe';
@override String get shuffleNotAvailableOffline => 'Zufallswiedergabe ist offline nicht verfügbar';
@override String get fileInfo => 'Dateiinfo';
@@ -672,7 +676,6 @@ class _TranslationsMessagesDe extends TranslationsMessagesEn {
@override String get fileInfoNotAvailable => 'Dateiinfo nicht verfügbar';
@override String errorLoadingFileInfo({required Object error}) => 'Fehler beim Laden der Dateiinfo: ${error}';
@override String get errorLoadingSeries => 'Fehler beim Laden der Serie';
@override String get errorLoadingSeason => 'Fehler beim Laden der Staffel';
@override String get musicNotSupported => 'Musikwiedergabe wird noch nicht unterstützt';
@override String get noDescriptionAvailable => 'Keine Beschreibung verfügbar';
@override String get noProfilesAvailable => 'Keine Profile verfügbar';
@@ -1740,6 +1743,7 @@ class _TranslationsLibrariesSortLabelsDe extends TranslationsLibrariesSortLabels
@override String get rating => 'Bewertung';
@override String get communityRating => 'Community-Bewertung';
@override String get criticRating => 'Kritikerbewertung';
@override String get userRating => 'Benutzerbewertung';
@override String get lastPlayed => 'Zuletzt abgespielt';
@override String get datePlayed => 'Wiedergabedatum';
@override String get playCount => 'Wiedergaben';
@@ -1969,6 +1973,7 @@ extension on TranslationsDe {
'common.ok' => 'OK',
'common.off' => 'Aus',
'common.seasonNumber' => ({required Object number}) => 'Staffel ${number}',
'common.episodeNumberTitle' => ({required Object number, required Object title}) => 'Episode ${number} - ${title}',
'common.chapterNumber' => ({required Object number}) => 'Kapitel ${number}',
'common.reconnect' => 'Erneut verbinden',
'common.exit' => 'Beenden',
@@ -2024,6 +2029,9 @@ extension on TranslationsDe {
'settings.gridView' => 'Raster',
'settings.listView' => 'Liste',
'settings.showHeroSection' => 'Hero-Bereich anzeigen',
'settings.continueWatchingAction' => 'Aktion für Weiterschauen',
'settings.continueWatchingPlay' => 'Abspielen',
'settings.continueWatchingDetails' => 'Details öffnen',
'settings.useGlobalHubs' => 'Startlayout verwenden',
'settings.useGlobalHubsDescription' => 'Einheitliche Start-Hubs anzeigen. Sonst Bibliotheksempfehlungen verwenden.',
'settings.showServerNameOnHubs' => 'Servername bei Hubs anzeigen',
@@ -2259,8 +2267,8 @@ extension on TranslationsDe {
'mediaMenu.markAsWatched' => 'Als gesehen markieren',
'mediaMenu.markAsUnwatched' => 'Als ungesehen markieren',
'mediaMenu.removeFromContinueWatching' => 'Aus ‚Weiterschauen‘ entfernen',
'mediaMenu.viewDetails' => 'Details anzeigen',
'mediaMenu.goToSeries' => 'Zur Serie',
'mediaMenu.goToSeason' => 'Zur Staffel',
'mediaMenu.shufflePlay' => 'Zufallswiedergabe',
'mediaMenu.shuffleNotAvailableOffline' => 'Zufallswiedergabe ist offline nicht verfügbar',
'mediaMenu.fileInfo' => 'Dateiinfo',
@@ -2392,7 +2400,6 @@ extension on TranslationsDe {
'messages.fileInfoNotAvailable' => 'Dateiinfo nicht verfügbar',
'messages.errorLoadingFileInfo' => ({required Object error}) => 'Fehler beim Laden der Dateiinfo: ${error}',
'messages.errorLoadingSeries' => 'Fehler beim Laden der Serie',
'messages.errorLoadingSeason' => 'Fehler beim Laden der Staffel',
'messages.musicNotSupported' => 'Musikwiedergabe wird noch nicht unterstützt',
'messages.noDescriptionAvailable' => 'Keine Beschreibung verfügbar',
'messages.noProfilesAvailable' => 'Keine Profile verfügbar',
@@ -2428,11 +2435,11 @@ extension on TranslationsDe {
'subtitlingStyling.border' => 'Rahmen',
'subtitlingStyling.background' => 'Hintergrund',
'subtitlingStyling.fontSize' => 'Schriftgröße',
_ => null,
} ?? switch (path) {
'subtitlingStyling.textColor' => 'Textfarbe',
'subtitlingStyling.borderSize' => 'Rahmengröße',
'subtitlingStyling.borderColor' => 'Rahmenfarbe',
_ => null,
} ?? switch (path) {
'subtitlingStyling.backgroundOpacity' => 'Hintergrunddeckkraft',
'subtitlingStyling.backgroundColor' => 'Hintergrundfarbe',
'subtitlingStyling.position' => 'Position',
@@ -2615,6 +2622,7 @@ extension on TranslationsDe {
'libraries.sortLabels.rating' => 'Bewertung',
'libraries.sortLabels.communityRating' => 'Community-Bewertung',
'libraries.sortLabels.criticRating' => 'Kritikerbewertung',
'libraries.sortLabels.userRating' => 'Benutzerbewertung',
'libraries.sortLabels.lastPlayed' => 'Zuletzt abgespielt',
'libraries.sortLabels.datePlayed' => 'Wiedergabedatum',
'libraries.sortLabels.playCount' => 'Wiedergaben',
@@ -2941,12 +2949,12 @@ extension on TranslationsDe {
'companionRemote.remote.menu' => 'Menü',
'companionRemote.remote.tabNavigation' => 'Tab-Navigation',
'companionRemote.remote.tabDiscover' => 'Entdecken',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabLibraries' => 'Mediatheken',
'companionRemote.remote.tabSearch' => 'Suche',
'companionRemote.remote.tabDownloads' => 'Downloads',
'companionRemote.remote.tabSettings' => 'Einstellungen',
_ => null,
} ?? switch (path) {
'companionRemote.remote.previous' => 'Zurück',
'companionRemote.remote.playPause' => 'Wiedergabe/Pause',
'companionRemote.remote.next' => 'Weiter',
+28 -12
View File
@@ -264,6 +264,9 @@ class TranslationsCommonEn {
/// en: 'Season ${number}'
String seasonNumber({required Object number}) => 'Season ${number}';
/// en: 'Episode ${number} - ${title}'
String episodeNumberTitle({required Object number, required Object title}) => 'Episode ${number} - ${title}';
/// en: 'Chapter ${number}'
String chapterNumber({required Object number}) => 'Chapter ${number}';
@@ -456,6 +459,15 @@ class TranslationsSettingsEn {
/// en: 'Show Hero Section'
String get showHeroSection => 'Show Hero Section';
/// en: 'Continue Watching Action'
String get continueWatchingAction => 'Continue Watching Action';
/// en: 'Play'
String get continueWatchingPlay => 'Play';
/// en: 'Open Details'
String get continueWatchingDetails => 'Open Details';
/// en: 'Use Home Layout'
String get useGlobalHubs => 'Use Home Layout';
@@ -1124,12 +1136,12 @@ class TranslationsMediaMenuEn {
/// en: 'Remove from Continue Watching'
String get removeFromContinueWatching => 'Remove from Continue Watching';
/// en: 'View details'
String get viewDetails => 'View details';
/// en: 'Go to series'
String get goToSeries => 'Go to series';
/// en: 'Go to season'
String get goToSeason => 'Go to season';
/// en: 'Shuffle Play'
String get shufflePlay => 'Shuffle Play';
@@ -1558,9 +1570,6 @@ class TranslationsMessagesEn {
/// en: 'Error loading series'
String get errorLoadingSeries => 'Error loading series';
/// en: 'Error loading season'
String get errorLoadingSeason => 'Error loading season';
/// en: 'Music playback is not yet supported'
String get musicNotSupported => 'Music playback is not yet supported';
@@ -4093,6 +4102,9 @@ class TranslationsLibrariesSortLabelsEn {
/// en: 'Critic Rating'
String get criticRating => 'Critic Rating';
/// en: 'User Rating'
String get userRating => 'User Rating';
/// en: 'Last Played'
String get lastPlayed => 'Last Played';
@@ -4515,6 +4527,7 @@ extension on Translations {
'common.ok' => 'OK',
'common.off' => 'Off',
'common.seasonNumber' => ({required Object number}) => 'Season ${number}',
'common.episodeNumberTitle' => ({required Object number, required Object title}) => 'Episode ${number} - ${title}',
'common.chapterNumber' => ({required Object number}) => 'Chapter ${number}',
'common.reconnect' => 'Reconnect',
'common.exit' => 'Exit',
@@ -4570,6 +4583,9 @@ extension on Translations {
'settings.gridView' => 'Grid',
'settings.listView' => 'List',
'settings.showHeroSection' => 'Show Hero Section',
'settings.continueWatchingAction' => 'Continue Watching Action',
'settings.continueWatchingPlay' => 'Play',
'settings.continueWatchingDetails' => 'Open Details',
'settings.useGlobalHubs' => 'Use Home Layout',
'settings.useGlobalHubsDescription' => 'Show unified home hubs. Otherwise use library recommendations.',
'settings.showServerNameOnHubs' => 'Show Server Name on Hubs',
@@ -4805,8 +4821,8 @@ extension on Translations {
'mediaMenu.markAsWatched' => 'Mark as Watched',
'mediaMenu.markAsUnwatched' => 'Mark as Unwatched',
'mediaMenu.removeFromContinueWatching' => 'Remove from Continue Watching',
'mediaMenu.viewDetails' => 'View details',
'mediaMenu.goToSeries' => 'Go to series',
'mediaMenu.goToSeason' => 'Go to season',
'mediaMenu.shufflePlay' => 'Shuffle Play',
'mediaMenu.shuffleNotAvailableOffline' => 'Shuffle not available offline',
'mediaMenu.fileInfo' => 'File Info',
@@ -4938,7 +4954,6 @@ extension on Translations {
'messages.fileInfoNotAvailable' => 'File information not available',
'messages.errorLoadingFileInfo' => ({required Object error}) => 'Error loading file info: ${error}',
'messages.errorLoadingSeries' => 'Error loading series',
'messages.errorLoadingSeason' => 'Error loading season',
'messages.musicNotSupported' => 'Music playback is not yet supported',
'messages.noDescriptionAvailable' => 'No description available',
'messages.noProfilesAvailable' => 'No profiles available',
@@ -4974,11 +4989,11 @@ extension on Translations {
'subtitlingStyling.border' => 'Border',
'subtitlingStyling.background' => 'Background',
'subtitlingStyling.fontSize' => 'Font Size',
_ => null,
} ?? switch (path) {
'subtitlingStyling.textColor' => 'Text Color',
'subtitlingStyling.borderSize' => 'Border Size',
'subtitlingStyling.borderColor' => 'Border Color',
_ => null,
} ?? switch (path) {
'subtitlingStyling.backgroundOpacity' => 'Background Opacity',
'subtitlingStyling.backgroundColor' => 'Background Color',
'subtitlingStyling.position' => 'Position',
@@ -5161,6 +5176,7 @@ extension on Translations {
'libraries.sortLabels.rating' => 'Rating',
'libraries.sortLabels.communityRating' => 'Community Rating',
'libraries.sortLabels.criticRating' => 'Critic Rating',
'libraries.sortLabels.userRating' => 'User Rating',
'libraries.sortLabels.lastPlayed' => 'Last Played',
'libraries.sortLabels.datePlayed' => 'Date Played',
'libraries.sortLabels.playCount' => 'Play Count',
@@ -5487,12 +5503,12 @@ extension on Translations {
'companionRemote.remote.menu' => 'Menu',
'companionRemote.remote.tabNavigation' => 'Tab Navigation',
'companionRemote.remote.tabDiscover' => 'Discover',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabLibraries' => 'Libraries',
'companionRemote.remote.tabSearch' => 'Search',
'companionRemote.remote.tabDownloads' => 'Downloads',
'companionRemote.remote.tabSettings' => 'Settings',
_ => null,
} ?? switch (path) {
'companionRemote.remote.previous' => 'Previous',
'companionRemote.remote.playPause' => 'Play/Pause',
'companionRemote.remote.next' => 'Next',
+16 -8
View File
@@ -162,6 +162,7 @@ class _TranslationsCommonEs extends TranslationsCommonEn {
@override String get ok => 'OK';
@override String get off => 'Desactivado';
@override String seasonNumber({required Object number}) => 'Temporada ${number}';
@override String episodeNumberTitle({required Object number, required Object title}) => 'Episodio ${number} - ${title}';
@override String chapterNumber({required Object number}) => 'Capítulo ${number}';
@override String get reconnect => 'Reconectar';
@override String get exit => 'Salir';
@@ -244,6 +245,9 @@ class _TranslationsSettingsEs extends TranslationsSettingsEn {
@override String get gridView => 'Cuadrícula';
@override String get listView => 'Lista';
@override String get showHeroSection => 'Mostrar Sección Destacada';
@override String get continueWatchingAction => 'Acción de Seguir viendo';
@override String get continueWatchingPlay => 'Reproducir';
@override String get continueWatchingDetails => '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';
@@ -491,8 +495,8 @@ class _TranslationsMediaMenuEs extends TranslationsMediaMenuEn {
@override String get markAsWatched => 'Marcar como Visto';
@override String get markAsUnwatched => 'Marcar como No Visto';
@override String get removeFromContinueWatching => 'Eliminar de Seguir Viendo';
@override String get viewDetails => 'Ver detalles';
@override String get goToSeries => 'Ir a la serie';
@override String get goToSeason => 'Ir a la temporada';
@override String get shufflePlay => 'Reproducción Aleatoria';
@override String get shuffleNotAvailableOffline => 'La reproducción aleatoria no está disponible sin conexión';
@override String get fileInfo => 'Información del Archivo';
@@ -672,7 +676,6 @@ class _TranslationsMessagesEs extends TranslationsMessagesEn {
@override String get fileInfoNotAvailable => 'Información de archivo no disponible';
@override String errorLoadingFileInfo({required Object error}) => 'Error al cargar info de archivo: ${error}';
@override String get errorLoadingSeries => 'Error al cargar la serie';
@override String get errorLoadingSeason => 'Error al cargar la temporada';
@override String get musicNotSupported => 'La reproducción de música aún no está soportada';
@override String get noDescriptionAvailable => 'No hay descripción disponible';
@override String get noProfilesAvailable => 'No hay perfiles disponibles';
@@ -1740,6 +1743,7 @@ class _TranslationsLibrariesSortLabelsEs extends TranslationsLibrariesSortLabels
@override String get rating => 'Valoración';
@override String get communityRating => 'Calificación de comunidad';
@override String get criticRating => 'Calificación de crítica';
@override String get userRating => 'Calificación del usuario';
@override String get lastPlayed => 'Última reproducción';
@override String get datePlayed => 'Fecha de reproducción';
@override String get playCount => 'Reproducciones';
@@ -1969,6 +1973,7 @@ extension on TranslationsEs {
'common.ok' => 'OK',
'common.off' => 'Desactivado',
'common.seasonNumber' => ({required Object number}) => 'Temporada ${number}',
'common.episodeNumberTitle' => ({required Object number, required Object title}) => 'Episodio ${number} - ${title}',
'common.chapterNumber' => ({required Object number}) => 'Capítulo ${number}',
'common.reconnect' => 'Reconectar',
'common.exit' => 'Salir',
@@ -2024,6 +2029,9 @@ extension on TranslationsEs {
'settings.gridView' => 'Cuadrícula',
'settings.listView' => 'Lista',
'settings.showHeroSection' => 'Mostrar Sección Destacada',
'settings.continueWatchingAction' => 'Acción de Seguir viendo',
'settings.continueWatchingPlay' => 'Reproducir',
'settings.continueWatchingDetails' => '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',
@@ -2259,8 +2267,8 @@ extension on TranslationsEs {
'mediaMenu.markAsWatched' => 'Marcar como Visto',
'mediaMenu.markAsUnwatched' => 'Marcar como No Visto',
'mediaMenu.removeFromContinueWatching' => 'Eliminar de Seguir Viendo',
'mediaMenu.viewDetails' => 'Ver detalles',
'mediaMenu.goToSeries' => 'Ir a la serie',
'mediaMenu.goToSeason' => 'Ir a la temporada',
'mediaMenu.shufflePlay' => 'Reproducción Aleatoria',
'mediaMenu.shuffleNotAvailableOffline' => 'La reproducción aleatoria no está disponible sin conexión',
'mediaMenu.fileInfo' => 'Información del Archivo',
@@ -2392,7 +2400,6 @@ extension on TranslationsEs {
'messages.fileInfoNotAvailable' => 'Información de archivo no disponible',
'messages.errorLoadingFileInfo' => ({required Object error}) => 'Error al cargar info de archivo: ${error}',
'messages.errorLoadingSeries' => 'Error al cargar la serie',
'messages.errorLoadingSeason' => 'Error al cargar la temporada',
'messages.musicNotSupported' => 'La reproducción de música aún no está soportada',
'messages.noDescriptionAvailable' => 'No hay descripción disponible',
'messages.noProfilesAvailable' => 'No hay perfiles disponibles',
@@ -2428,11 +2435,11 @@ extension on TranslationsEs {
'subtitlingStyling.border' => 'Borde',
'subtitlingStyling.background' => 'Fondo',
'subtitlingStyling.fontSize' => 'Tamaño de Fuente',
_ => null,
} ?? switch (path) {
'subtitlingStyling.textColor' => 'Color de Texto',
'subtitlingStyling.borderSize' => 'Tamaño de Borde',
'subtitlingStyling.borderColor' => 'Color de Borde',
_ => null,
} ?? switch (path) {
'subtitlingStyling.backgroundOpacity' => 'Opacidad de Fondo',
'subtitlingStyling.backgroundColor' => 'Color de Fondo',
'subtitlingStyling.position' => 'Posición',
@@ -2615,6 +2622,7 @@ extension on TranslationsEs {
'libraries.sortLabels.rating' => 'Valoración',
'libraries.sortLabels.communityRating' => 'Calificación de comunidad',
'libraries.sortLabels.criticRating' => 'Calificación de crítica',
'libraries.sortLabels.userRating' => 'Calificación del usuario',
'libraries.sortLabels.lastPlayed' => 'Última reproducción',
'libraries.sortLabels.datePlayed' => 'Fecha de reproducción',
'libraries.sortLabels.playCount' => 'Reproducciones',
@@ -2941,12 +2949,12 @@ extension on TranslationsEs {
'companionRemote.remote.menu' => 'Menú',
'companionRemote.remote.tabNavigation' => 'Navegación por pestañas',
'companionRemote.remote.tabDiscover' => 'Descubrir',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabLibraries' => 'Bibliotecas',
'companionRemote.remote.tabSearch' => 'Buscar',
'companionRemote.remote.tabDownloads' => 'Descargas',
'companionRemote.remote.tabSettings' => 'Configuración',
_ => null,
} ?? switch (path) {
'companionRemote.remote.previous' => 'Anterior',
'companionRemote.remote.playPause' => 'Reproducir/Pausar',
'companionRemote.remote.next' => 'Siguiente',
+16 -8
View File
@@ -162,6 +162,7 @@ class _TranslationsCommonFr extends TranslationsCommonEn {
@override String get ok => 'OK';
@override String get off => 'Désactivé';
@override String seasonNumber({required Object number}) => 'Saison ${number}';
@override String episodeNumberTitle({required Object number, required Object title}) => 'Épisode ${number} - ${title}';
@override String chapterNumber({required Object number}) => 'Chapitre ${number}';
@override String get reconnect => 'Reconnecter';
@override String get exit => 'Quitter';
@@ -244,6 +245,9 @@ class _TranslationsSettingsFr extends TranslationsSettingsEn {
@override String get gridView => 'Grille';
@override String get listView => 'Liste';
@override String get showHeroSection => 'Afficher la section Hero';
@override String get continueWatchingAction => 'Action Continuer à regarder';
@override String get continueWatchingPlay => 'Lire';
@override String get continueWatchingDetails => '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';
@@ -491,8 +495,8 @@ class _TranslationsMediaMenuFr extends TranslationsMediaMenuEn {
@override String get markAsWatched => 'Marquer comme vu';
@override String get markAsUnwatched => 'Marquer comme non visionné';
@override String get removeFromContinueWatching => 'Supprimer de la liste "Continuer à regarder"';
@override String get viewDetails => 'Voir les détails';
@override String get goToSeries => 'Aller à la série';
@override String get goToSeason => 'Aller à la saison';
@override String get shufflePlay => 'Lecture aléatoire';
@override String get shuffleNotAvailableOffline => 'La lecture aléatoire n’est pas disponible hors ligne';
@override String get fileInfo => 'Informations sur le fichier';
@@ -672,7 +676,6 @@ class _TranslationsMessagesFr extends TranslationsMessagesEn {
@override String get fileInfoNotAvailable => 'Informations sur le fichier non disponibles';
@override String errorLoadingFileInfo({required Object error}) => 'Erreur lors du chargement des informations sur le fichier: ${error}';
@override String get errorLoadingSeries => 'Erreur lors du chargement de la série';
@override String get errorLoadingSeason => 'Erreur lors du chargement de la saison';
@override String get musicNotSupported => 'La lecture de musique n\'est pas encore prise en charge';
@override String get noDescriptionAvailable => 'Aucune description disponible';
@override String get noProfilesAvailable => 'Aucun profil disponible';
@@ -1740,6 +1743,7 @@ class _TranslationsLibrariesSortLabelsFr extends TranslationsLibrariesSortLabels
@override String get rating => 'Note';
@override String get communityRating => 'Note communautaire';
@override String get criticRating => 'Note critique';
@override String get userRating => 'Note utilisateur';
@override String get lastPlayed => 'Dernière lecture';
@override String get datePlayed => 'Date de lecture';
@override String get playCount => 'Lectures';
@@ -1969,6 +1973,7 @@ extension on TranslationsFr {
'common.ok' => 'OK',
'common.off' => 'Désactivé',
'common.seasonNumber' => ({required Object number}) => 'Saison ${number}',
'common.episodeNumberTitle' => ({required Object number, required Object title}) => 'Épisode ${number} - ${title}',
'common.chapterNumber' => ({required Object number}) => 'Chapitre ${number}',
'common.reconnect' => 'Reconnecter',
'common.exit' => 'Quitter',
@@ -2024,6 +2029,9 @@ extension on TranslationsFr {
'settings.gridView' => 'Grille',
'settings.listView' => 'Liste',
'settings.showHeroSection' => 'Afficher la section Hero',
'settings.continueWatchingAction' => 'Action Continuer à regarder',
'settings.continueWatchingPlay' => 'Lire',
'settings.continueWatchingDetails' => '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',
@@ -2259,8 +2267,8 @@ extension on TranslationsFr {
'mediaMenu.markAsWatched' => 'Marquer comme vu',
'mediaMenu.markAsUnwatched' => 'Marquer comme non visionné',
'mediaMenu.removeFromContinueWatching' => 'Supprimer de la liste "Continuer à regarder"',
'mediaMenu.viewDetails' => 'Voir les détails',
'mediaMenu.goToSeries' => 'Aller à la série',
'mediaMenu.goToSeason' => 'Aller à la saison',
'mediaMenu.shufflePlay' => 'Lecture aléatoire',
'mediaMenu.shuffleNotAvailableOffline' => 'La lecture aléatoire n’est pas disponible hors ligne',
'mediaMenu.fileInfo' => 'Informations sur le fichier',
@@ -2392,7 +2400,6 @@ extension on TranslationsFr {
'messages.fileInfoNotAvailable' => 'Informations sur le fichier non disponibles',
'messages.errorLoadingFileInfo' => ({required Object error}) => 'Erreur lors du chargement des informations sur le fichier: ${error}',
'messages.errorLoadingSeries' => 'Erreur lors du chargement de la série',
'messages.errorLoadingSeason' => 'Erreur lors du chargement de la saison',
'messages.musicNotSupported' => 'La lecture de musique n\'est pas encore prise en charge',
'messages.noDescriptionAvailable' => 'Aucune description disponible',
'messages.noProfilesAvailable' => 'Aucun profil disponible',
@@ -2428,11 +2435,11 @@ extension on TranslationsFr {
'subtitlingStyling.border' => 'Bordure',
'subtitlingStyling.background' => 'Arrière-plan',
'subtitlingStyling.fontSize' => 'Taille de la police',
_ => null,
} ?? switch (path) {
'subtitlingStyling.textColor' => 'Couleur du texte',
'subtitlingStyling.borderSize' => 'Taille de la bordure',
'subtitlingStyling.borderColor' => 'Couleur de la bordure',
_ => null,
} ?? switch (path) {
'subtitlingStyling.backgroundOpacity' => 'Opacité d\'arrière-plan',
'subtitlingStyling.backgroundColor' => 'Couleur d\'arrière-plan',
'subtitlingStyling.position' => 'Position',
@@ -2615,6 +2622,7 @@ extension on TranslationsFr {
'libraries.sortLabels.rating' => 'Note',
'libraries.sortLabels.communityRating' => 'Note communautaire',
'libraries.sortLabels.criticRating' => 'Note critique',
'libraries.sortLabels.userRating' => 'Note utilisateur',
'libraries.sortLabels.lastPlayed' => 'Dernière lecture',
'libraries.sortLabels.datePlayed' => 'Date de lecture',
'libraries.sortLabels.playCount' => 'Lectures',
@@ -2941,12 +2949,12 @@ extension on TranslationsFr {
'companionRemote.remote.menu' => 'Menu',
'companionRemote.remote.tabNavigation' => 'Navigation par onglets',
'companionRemote.remote.tabDiscover' => 'Découvrir',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabLibraries' => 'Bibliothèques',
'companionRemote.remote.tabSearch' => 'Rechercher',
'companionRemote.remote.tabDownloads' => 'Téléchargements',
'companionRemote.remote.tabSettings' => 'Paramètres',
_ => null,
} ?? switch (path) {
'companionRemote.remote.previous' => 'Précédent',
'companionRemote.remote.playPause' => 'Lecture/Pause',
'companionRemote.remote.next' => 'Suivant',
+16 -8
View File
@@ -162,6 +162,7 @@ class _TranslationsCommonIt extends TranslationsCommonEn {
@override String get ok => 'OK';
@override String get off => 'Disattivato';
@override String seasonNumber({required Object number}) => 'Stagione ${number}';
@override String episodeNumberTitle({required Object number, required Object title}) => 'Episodio ${number} - ${title}';
@override String chapterNumber({required Object number}) => 'Capitolo ${number}';
@override String get reconnect => 'Riconnetti';
@override String get exit => 'Esci';
@@ -244,6 +245,9 @@ class _TranslationsSettingsIt extends TranslationsSettingsEn {
@override String get gridView => 'Griglia';
@override String get listView => 'Elenco';
@override String get showHeroSection => 'Mostra sezione principale';
@override String get continueWatchingAction => 'Azione Continua a guardare';
@override String get continueWatchingPlay => 'Riproduci';
@override String get continueWatchingDetails => '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';
@@ -491,8 +495,8 @@ class _TranslationsMediaMenuIt extends TranslationsMediaMenuEn {
@override String get markAsWatched => 'Segna come visto';
@override String get markAsUnwatched => 'Segna come non visto';
@override String get removeFromContinueWatching => 'Rimuovi da Continua a guardare';
@override String get viewDetails => 'Vedi dettagli';
@override String get goToSeries => 'Vai alle serie';
@override String get goToSeason => 'Vai alla stagione';
@override String get shufflePlay => 'Riproduzione casuale';
@override String get shuffleNotAvailableOffline => 'Riproduzione casuale non disponibile offline';
@override String get fileInfo => 'Info sul file';
@@ -672,7 +676,6 @@ class _TranslationsMessagesIt extends TranslationsMessagesEn {
@override String get fileInfoNotAvailable => 'Informazioni sul file non disponibili';
@override String errorLoadingFileInfo({required Object error}) => 'Errore caricamento informazioni sul file: ${error}';
@override String get errorLoadingSeries => 'Errore caricamento serie';
@override String get errorLoadingSeason => 'Errore caricamento stagione';
@override String get musicNotSupported => 'La riproduzione musicale non è ancora supportata';
@override String get noDescriptionAvailable => 'Nessuna descrizione disponibile';
@override String get noProfilesAvailable => 'Nessun profilo disponibile';
@@ -1740,6 +1743,7 @@ class _TranslationsLibrariesSortLabelsIt extends TranslationsLibrariesSortLabels
@override String get rating => 'Valutazione';
@override String get communityRating => 'Valutazione della community';
@override String get criticRating => 'Valutazione critica';
@override String get userRating => 'Valutazione utente';
@override String get lastPlayed => 'Ultima riproduzione';
@override String get datePlayed => 'Data di riproduzione';
@override String get playCount => 'Riproduzioni';
@@ -1969,6 +1973,7 @@ extension on TranslationsIt {
'common.ok' => 'OK',
'common.off' => 'Disattivato',
'common.seasonNumber' => ({required Object number}) => 'Stagione ${number}',
'common.episodeNumberTitle' => ({required Object number, required Object title}) => 'Episodio ${number} - ${title}',
'common.chapterNumber' => ({required Object number}) => 'Capitolo ${number}',
'common.reconnect' => 'Riconnetti',
'common.exit' => 'Esci',
@@ -2024,6 +2029,9 @@ extension on TranslationsIt {
'settings.gridView' => 'Griglia',
'settings.listView' => 'Elenco',
'settings.showHeroSection' => 'Mostra sezione principale',
'settings.continueWatchingAction' => 'Azione Continua a guardare',
'settings.continueWatchingPlay' => 'Riproduci',
'settings.continueWatchingDetails' => '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',
@@ -2259,8 +2267,8 @@ extension on TranslationsIt {
'mediaMenu.markAsWatched' => 'Segna come visto',
'mediaMenu.markAsUnwatched' => 'Segna come non visto',
'mediaMenu.removeFromContinueWatching' => 'Rimuovi da Continua a guardare',
'mediaMenu.viewDetails' => 'Vedi dettagli',
'mediaMenu.goToSeries' => 'Vai alle serie',
'mediaMenu.goToSeason' => 'Vai alla stagione',
'mediaMenu.shufflePlay' => 'Riproduzione casuale',
'mediaMenu.shuffleNotAvailableOffline' => 'Riproduzione casuale non disponibile offline',
'mediaMenu.fileInfo' => 'Info sul file',
@@ -2392,7 +2400,6 @@ extension on TranslationsIt {
'messages.fileInfoNotAvailable' => 'Informazioni sul file non disponibili',
'messages.errorLoadingFileInfo' => ({required Object error}) => 'Errore caricamento informazioni sul file: ${error}',
'messages.errorLoadingSeries' => 'Errore caricamento serie',
'messages.errorLoadingSeason' => 'Errore caricamento stagione',
'messages.musicNotSupported' => 'La riproduzione musicale non è ancora supportata',
'messages.noDescriptionAvailable' => 'Nessuna descrizione disponibile',
'messages.noProfilesAvailable' => 'Nessun profilo disponibile',
@@ -2428,11 +2435,11 @@ extension on TranslationsIt {
'subtitlingStyling.border' => 'Bordo',
'subtitlingStyling.background' => 'Sfondo',
'subtitlingStyling.fontSize' => 'Dimensione',
_ => null,
} ?? switch (path) {
'subtitlingStyling.textColor' => 'Colore testo',
'subtitlingStyling.borderSize' => 'Dimensione bordo',
'subtitlingStyling.borderColor' => 'Colore bordo',
_ => null,
} ?? switch (path) {
'subtitlingStyling.backgroundOpacity' => 'Opacità sfondo',
'subtitlingStyling.backgroundColor' => 'Colore sfondo',
'subtitlingStyling.position' => 'Posizione',
@@ -2615,6 +2622,7 @@ extension on TranslationsIt {
'libraries.sortLabels.rating' => 'Valutazione',
'libraries.sortLabels.communityRating' => 'Valutazione della community',
'libraries.sortLabels.criticRating' => 'Valutazione critica',
'libraries.sortLabels.userRating' => 'Valutazione utente',
'libraries.sortLabels.lastPlayed' => 'Ultima riproduzione',
'libraries.sortLabels.datePlayed' => 'Data di riproduzione',
'libraries.sortLabels.playCount' => 'Riproduzioni',
@@ -2941,12 +2949,12 @@ extension on TranslationsIt {
'companionRemote.remote.menu' => 'Menu',
'companionRemote.remote.tabNavigation' => 'Navigazione schede',
'companionRemote.remote.tabDiscover' => 'Esplora',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabLibraries' => 'Librerie',
'companionRemote.remote.tabSearch' => 'Cerca',
'companionRemote.remote.tabDownloads' => 'Download',
'companionRemote.remote.tabSettings' => 'Impostazioni',
_ => null,
} ?? switch (path) {
'companionRemote.remote.previous' => 'Precedente',
'companionRemote.remote.playPause' => 'Riproduci/Pausa',
'companionRemote.remote.next' => 'Successivo',
+16 -8
View File
@@ -162,6 +162,7 @@ class _TranslationsCommonJa extends TranslationsCommonEn {
@override String get ok => 'OK';
@override String get off => 'オフ';
@override String seasonNumber({required Object number}) => 'シーズン${number}';
@override String episodeNumberTitle({required Object number, required Object title}) => 'エピソード${number} - ${title}';
@override String chapterNumber({required Object number}) => 'チャプター${number}';
@override String get reconnect => '再接続';
@override String get exit => '終了';
@@ -244,6 +245,9 @@ class _TranslationsSettingsJa extends TranslationsSettingsEn {
@override String get gridView => 'グリッド';
@override String get listView => 'リスト';
@override String get showHeroSection => 'ヒーローセクションを表示';
@override String get continueWatchingAction => '視聴中の操作';
@override String get continueWatchingPlay => '再生';
@override String get continueWatchingDetails => '詳細を開く';
@override String get useGlobalHubs => 'ホームレイアウトを使用';
@override String get useGlobalHubsDescription => '統合ホームハブを表示します。オフの場合はライブラリのおすすめを使用します。';
@override String get showServerNameOnHubs => 'ハブにサーバー名を表示';
@@ -491,8 +495,8 @@ class _TranslationsMediaMenuJa extends TranslationsMediaMenuEn {
@override String get markAsWatched => '視聴済みにする';
@override String get markAsUnwatched => '未視聴にする';
@override String get removeFromContinueWatching => '視聴中から削除';
@override String get viewDetails => '詳細を表示';
@override String get goToSeries => 'シリーズへ移動';
@override String get goToSeason => 'シーズンへ移動';
@override String get shufflePlay => 'シャッフル再生';
@override String get shuffleNotAvailableOffline => 'オフラインではシャッフルを利用できません';
@override String get fileInfo => 'ファイル情報';
@@ -672,7 +676,6 @@ class _TranslationsMessagesJa extends TranslationsMessagesEn {
@override String get fileInfoNotAvailable => 'ファイル情報が利用できません';
@override String errorLoadingFileInfo({required Object error}) => 'ファイル情報の読み込みエラー: ${error}';
@override String get errorLoadingSeries => 'シリーズの読み込みエラー';
@override String get errorLoadingSeason => 'シーズンの読み込みエラー';
@override String get musicNotSupported => '音楽の再生はまだサポートされていません';
@override String get noDescriptionAvailable => '説明はありません';
@override String get noProfilesAvailable => '利用可能なプロフィールがありません';
@@ -1740,6 +1743,7 @@ class _TranslationsLibrariesSortLabelsJa extends TranslationsLibrariesSortLabels
@override String get rating => '評価';
@override String get communityRating => 'コミュニティ評価';
@override String get criticRating => '批評家評価';
@override String get userRating => 'ユーザー評価';
@override String get lastPlayed => '最終再生';
@override String get datePlayed => '再生日';
@override String get playCount => '再生回数';
@@ -1969,6 +1973,7 @@ extension on TranslationsJa {
'common.ok' => 'OK',
'common.off' => 'オフ',
'common.seasonNumber' => ({required Object number}) => 'シーズン${number}',
'common.episodeNumberTitle' => ({required Object number, required Object title}) => 'エピソード${number} - ${title}',
'common.chapterNumber' => ({required Object number}) => 'チャプター${number}',
'common.reconnect' => '再接続',
'common.exit' => '終了',
@@ -2024,6 +2029,9 @@ extension on TranslationsJa {
'settings.gridView' => 'グリッド',
'settings.listView' => 'リスト',
'settings.showHeroSection' => 'ヒーローセクションを表示',
'settings.continueWatchingAction' => '視聴中の操作',
'settings.continueWatchingPlay' => '再生',
'settings.continueWatchingDetails' => '詳細を開く',
'settings.useGlobalHubs' => 'ホームレイアウトを使用',
'settings.useGlobalHubsDescription' => '統合ホームハブを表示します。オフの場合はライブラリのおすすめを使用します。',
'settings.showServerNameOnHubs' => 'ハブにサーバー名を表示',
@@ -2259,8 +2267,8 @@ extension on TranslationsJa {
'mediaMenu.markAsWatched' => '視聴済みにする',
'mediaMenu.markAsUnwatched' => '未視聴にする',
'mediaMenu.removeFromContinueWatching' => '視聴中から削除',
'mediaMenu.viewDetails' => '詳細を表示',
'mediaMenu.goToSeries' => 'シリーズへ移動',
'mediaMenu.goToSeason' => 'シーズンへ移動',
'mediaMenu.shufflePlay' => 'シャッフル再生',
'mediaMenu.shuffleNotAvailableOffline' => 'オフラインではシャッフルを利用できません',
'mediaMenu.fileInfo' => 'ファイル情報',
@@ -2392,7 +2400,6 @@ extension on TranslationsJa {
'messages.fileInfoNotAvailable' => 'ファイル情報が利用できません',
'messages.errorLoadingFileInfo' => ({required Object error}) => 'ファイル情報の読み込みエラー: ${error}',
'messages.errorLoadingSeries' => 'シリーズの読み込みエラー',
'messages.errorLoadingSeason' => 'シーズンの読み込みエラー',
'messages.musicNotSupported' => '音楽の再生はまだサポートされていません',
'messages.noDescriptionAvailable' => '説明はありません',
'messages.noProfilesAvailable' => '利用可能なプロフィールがありません',
@@ -2428,11 +2435,11 @@ extension on TranslationsJa {
'subtitlingStyling.border' => '枠線',
'subtitlingStyling.background' => '背景',
'subtitlingStyling.fontSize' => 'フォントサイズ',
_ => null,
} ?? switch (path) {
'subtitlingStyling.textColor' => 'テキストの色',
'subtitlingStyling.borderSize' => '枠線サイズ',
'subtitlingStyling.borderColor' => '枠線の色',
_ => null,
} ?? switch (path) {
'subtitlingStyling.backgroundOpacity' => '背景の不透明度',
'subtitlingStyling.backgroundColor' => '背景色',
'subtitlingStyling.position' => '位置',
@@ -2615,6 +2622,7 @@ extension on TranslationsJa {
'libraries.sortLabels.rating' => '評価',
'libraries.sortLabels.communityRating' => 'コミュニティ評価',
'libraries.sortLabels.criticRating' => '批評家評価',
'libraries.sortLabels.userRating' => 'ユーザー評価',
'libraries.sortLabels.lastPlayed' => '最終再生',
'libraries.sortLabels.datePlayed' => '再生日',
'libraries.sortLabels.playCount' => '再生回数',
@@ -2941,12 +2949,12 @@ extension on TranslationsJa {
'companionRemote.remote.menu' => 'メニュー',
'companionRemote.remote.tabNavigation' => 'タブナビゲーション',
'companionRemote.remote.tabDiscover' => '探す',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabLibraries' => 'ライブラリ',
'companionRemote.remote.tabSearch' => '検索',
'companionRemote.remote.tabDownloads' => 'ダウンロード',
'companionRemote.remote.tabSettings' => '設定',
_ => null,
} ?? switch (path) {
'companionRemote.remote.previous' => '前へ',
'companionRemote.remote.playPause' => '再生/一時停止',
'companionRemote.remote.next' => '次へ',
+16 -8
View File
@@ -162,6 +162,7 @@ class _TranslationsCommonKo extends TranslationsCommonEn {
@override String get ok => '확인';
@override String get off => '끔';
@override String seasonNumber({required Object number}) => '시즌 ${number}';
@override String episodeNumberTitle({required Object number, required Object title}) => '${number}화 - ${title}';
@override String chapterNumber({required Object number}) => '챕터 ${number}';
@override String get reconnect => '다시 연결';
@override String get exit => '종료';
@@ -244,6 +245,9 @@ class _TranslationsSettingsKo extends TranslationsSettingsEn {
@override String get gridView => '그리드 보기';
@override String get listView => '목록 보기';
@override String get showHeroSection => '주요 추천 영역 표시';
@override String get continueWatchingAction => '계속 보기 동작';
@override String get continueWatchingPlay => '재생';
@override String get continueWatchingDetails => '상세 정보 열기';
@override String get useGlobalHubs => '홈 레이아웃 사용';
@override String get useGlobalHubsDescription => '통합 홈 허브를 표시합니다. 끄면 라이브러리 추천을 사용합니다.';
@override String get showServerNameOnHubs => '허브에 서버 이름 표시';
@@ -491,8 +495,8 @@ class _TranslationsMediaMenuKo extends TranslationsMediaMenuEn {
@override String get markAsWatched => '시청 완료로 표시';
@override String get markAsUnwatched => '시청 안 함으로 표시';
@override String get removeFromContinueWatching => '계속 보기에서 제거';
@override String get viewDetails => '상세 정보 보기';
@override String get goToSeries => '시리즈로 이동';
@override String get goToSeason => '시즌으로 이동';
@override String get shufflePlay => '무작위 재생';
@override String get shuffleNotAvailableOffline => '오프라인에서는 셔플을 사용할 수 없습니다';
@override String get fileInfo => '파일 정보';
@@ -672,7 +676,6 @@ class _TranslationsMessagesKo extends TranslationsMessagesEn {
@override String get fileInfoNotAvailable => '파일 정보가 없습니다';
@override String errorLoadingFileInfo({required Object error}) => '파일 정보 로딩 중 오류: ${error}';
@override String get errorLoadingSeries => '시리즈 로딩 중 오류';
@override String get errorLoadingSeason => '시즌 로딩 중 오류';
@override String get musicNotSupported => '음악 재생 미지원';
@override String get noDescriptionAvailable => '설명이 없습니다';
@override String get noProfilesAvailable => '사용 가능한 프로필이 없습니다';
@@ -1740,6 +1743,7 @@ class _TranslationsLibrariesSortLabelsKo extends TranslationsLibrariesSortLabels
@override String get rating => '평점';
@override String get communityRating => '커뮤니티 평점';
@override String get criticRating => '평론가 평점';
@override String get userRating => '사용자 평점';
@override String get lastPlayed => '마지막 재생';
@override String get datePlayed => '재생일';
@override String get playCount => '재생 횟수';
@@ -1969,6 +1973,7 @@ extension on TranslationsKo {
'common.ok' => '확인',
'common.off' => '끔',
'common.seasonNumber' => ({required Object number}) => '시즌 ${number}',
'common.episodeNumberTitle' => ({required Object number, required Object title}) => '${number}화 - ${title}',
'common.chapterNumber' => ({required Object number}) => '챕터 ${number}',
'common.reconnect' => '다시 연결',
'common.exit' => '종료',
@@ -2024,6 +2029,9 @@ extension on TranslationsKo {
'settings.gridView' => '그리드 보기',
'settings.listView' => '목록 보기',
'settings.showHeroSection' => '주요 추천 영역 표시',
'settings.continueWatchingAction' => '계속 보기 동작',
'settings.continueWatchingPlay' => '재생',
'settings.continueWatchingDetails' => '상세 정보 열기',
'settings.useGlobalHubs' => '홈 레이아웃 사용',
'settings.useGlobalHubsDescription' => '통합 홈 허브를 표시합니다. 끄면 라이브러리 추천을 사용합니다.',
'settings.showServerNameOnHubs' => '허브에 서버 이름 표시',
@@ -2259,8 +2267,8 @@ extension on TranslationsKo {
'mediaMenu.markAsWatched' => '시청 완료로 표시',
'mediaMenu.markAsUnwatched' => '시청 안 함으로 표시',
'mediaMenu.removeFromContinueWatching' => '계속 보기에서 제거',
'mediaMenu.viewDetails' => '상세 정보 보기',
'mediaMenu.goToSeries' => '시리즈로 이동',
'mediaMenu.goToSeason' => '시즌으로 이동',
'mediaMenu.shufflePlay' => '무작위 재생',
'mediaMenu.shuffleNotAvailableOffline' => '오프라인에서는 셔플을 사용할 수 없습니다',
'mediaMenu.fileInfo' => '파일 정보',
@@ -2392,7 +2400,6 @@ extension on TranslationsKo {
'messages.fileInfoNotAvailable' => '파일 정보가 없습니다',
'messages.errorLoadingFileInfo' => ({required Object error}) => '파일 정보 로딩 중 오류: ${error}',
'messages.errorLoadingSeries' => '시리즈 로딩 중 오류',
'messages.errorLoadingSeason' => '시즌 로딩 중 오류',
'messages.musicNotSupported' => '음악 재생 미지원',
'messages.noDescriptionAvailable' => '설명이 없습니다',
'messages.noProfilesAvailable' => '사용 가능한 프로필이 없습니다',
@@ -2428,11 +2435,11 @@ extension on TranslationsKo {
'subtitlingStyling.border' => '테두리',
'subtitlingStyling.background' => '배경',
'subtitlingStyling.fontSize' => '글자 크기',
_ => null,
} ?? switch (path) {
'subtitlingStyling.textColor' => '텍스트 색상',
'subtitlingStyling.borderSize' => '테두리 크기',
'subtitlingStyling.borderColor' => '테두리 색상',
_ => null,
} ?? switch (path) {
'subtitlingStyling.backgroundOpacity' => '배경 불투명도',
'subtitlingStyling.backgroundColor' => '배경색',
'subtitlingStyling.position' => '위치',
@@ -2615,6 +2622,7 @@ extension on TranslationsKo {
'libraries.sortLabels.rating' => '평점',
'libraries.sortLabels.communityRating' => '커뮤니티 평점',
'libraries.sortLabels.criticRating' => '평론가 평점',
'libraries.sortLabels.userRating' => '사용자 평점',
'libraries.sortLabels.lastPlayed' => '마지막 재생',
'libraries.sortLabels.datePlayed' => '재생일',
'libraries.sortLabels.playCount' => '재생 횟수',
@@ -2941,12 +2949,12 @@ extension on TranslationsKo {
'companionRemote.remote.menu' => '메뉴',
'companionRemote.remote.tabNavigation' => '탭 탐색',
'companionRemote.remote.tabDiscover' => '발견',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabLibraries' => '미디어 라이브러리',
'companionRemote.remote.tabSearch' => '검색',
'companionRemote.remote.tabDownloads' => '다운로드',
'companionRemote.remote.tabSettings' => '설정',
_ => null,
} ?? switch (path) {
'companionRemote.remote.previous' => '이전',
'companionRemote.remote.playPause' => '재생/일시정지',
'companionRemote.remote.next' => '다음',
+16 -8
View File
@@ -162,6 +162,7 @@ class _TranslationsCommonNb extends TranslationsCommonEn {
@override String get ok => 'OK';
@override String get off => 'Av';
@override String seasonNumber({required Object number}) => 'Sesong ${number}';
@override String episodeNumberTitle({required Object number, required Object title}) => 'Episode ${number} - ${title}';
@override String chapterNumber({required Object number}) => 'Kapittel ${number}';
@override String get reconnect => 'Koble til på nytt';
@override String get exit => 'Avslutt';
@@ -244,6 +245,9 @@ class _TranslationsSettingsNb extends TranslationsSettingsEn {
@override String get gridView => 'Rutenett';
@override String get listView => 'Liste';
@override String get showHeroSection => 'Vis fremhevet seksjon';
@override String get continueWatchingAction => 'Handling for Fortsett å se';
@override String get continueWatchingPlay => 'Spill av';
@override String get continueWatchingDetails => 'Å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';
@@ -491,8 +495,8 @@ class _TranslationsMediaMenuNb extends TranslationsMediaMenuEn {
@override String get markAsWatched => 'Merk som sett';
@override String get markAsUnwatched => 'Merk som usett';
@override String get removeFromContinueWatching => 'Fjern fra Fortsett å se';
@override String get viewDetails => 'Vis detaljer';
@override String get goToSeries => 'Gå til serie';
@override String get goToSeason => 'Gå til sesong';
@override String get shufflePlay => 'Tilfeldig avspilling';
@override String get shuffleNotAvailableOffline => 'Tilfeldig avspilling er ikke tilgjengelig offline';
@override String get fileInfo => 'Filinformasjon';
@@ -672,7 +676,6 @@ class _TranslationsMessagesNb extends TranslationsMessagesEn {
@override String get fileInfoNotAvailable => 'Filinformasjon ikke tilgjengelig';
@override String errorLoadingFileInfo({required Object error}) => 'Feil ved lasting av filinformasjon: ${error}';
@override String get errorLoadingSeries => 'Feil ved lasting av serie';
@override String get errorLoadingSeason => 'Feil ved lasting av sesong';
@override String get musicNotSupported => 'Musikkavspilling støttes ikke ennå';
@override String get noDescriptionAvailable => 'Ingen beskrivelse tilgjengelig';
@override String get noProfilesAvailable => 'Ingen profiler tilgjengelige';
@@ -1740,6 +1743,7 @@ class _TranslationsLibrariesSortLabelsNb extends TranslationsLibrariesSortLabels
@override String get rating => 'Vurdering';
@override String get communityRating => 'Fellesskapsvurdering';
@override String get criticRating => 'Kritikervurdering';
@override String get userRating => 'Brukervurdering';
@override String get lastPlayed => 'Sist spilt';
@override String get datePlayed => 'Avspillingsdato';
@override String get playCount => 'Avspillinger';
@@ -1969,6 +1973,7 @@ extension on TranslationsNb {
'common.ok' => 'OK',
'common.off' => 'Av',
'common.seasonNumber' => ({required Object number}) => 'Sesong ${number}',
'common.episodeNumberTitle' => ({required Object number, required Object title}) => 'Episode ${number} - ${title}',
'common.chapterNumber' => ({required Object number}) => 'Kapittel ${number}',
'common.reconnect' => 'Koble til på nytt',
'common.exit' => 'Avslutt',
@@ -2024,6 +2029,9 @@ extension on TranslationsNb {
'settings.gridView' => 'Rutenett',
'settings.listView' => 'Liste',
'settings.showHeroSection' => 'Vis fremhevet seksjon',
'settings.continueWatchingAction' => 'Handling for Fortsett å se',
'settings.continueWatchingPlay' => 'Spill av',
'settings.continueWatchingDetails' => 'Åpne detaljer',
'settings.useGlobalHubs' => 'Bruk startoppsett',
'settings.useGlobalHubsDescription' => 'Vis samlet startinnhold. Ellers brukes bibliotekanbefalinger.',
'settings.showServerNameOnHubs' => 'Vis servernavn på huber',
@@ -2259,8 +2267,8 @@ extension on TranslationsNb {
'mediaMenu.markAsWatched' => 'Merk som sett',
'mediaMenu.markAsUnwatched' => 'Merk som usett',
'mediaMenu.removeFromContinueWatching' => 'Fjern fra Fortsett å se',
'mediaMenu.viewDetails' => 'Vis detaljer',
'mediaMenu.goToSeries' => 'Gå til serie',
'mediaMenu.goToSeason' => 'Gå til sesong',
'mediaMenu.shufflePlay' => 'Tilfeldig avspilling',
'mediaMenu.shuffleNotAvailableOffline' => 'Tilfeldig avspilling er ikke tilgjengelig offline',
'mediaMenu.fileInfo' => 'Filinformasjon',
@@ -2392,7 +2400,6 @@ extension on TranslationsNb {
'messages.fileInfoNotAvailable' => 'Filinformasjon ikke tilgjengelig',
'messages.errorLoadingFileInfo' => ({required Object error}) => 'Feil ved lasting av filinformasjon: ${error}',
'messages.errorLoadingSeries' => 'Feil ved lasting av serie',
'messages.errorLoadingSeason' => 'Feil ved lasting av sesong',
'messages.musicNotSupported' => 'Musikkavspilling støttes ikke ennå',
'messages.noDescriptionAvailable' => 'Ingen beskrivelse tilgjengelig',
'messages.noProfilesAvailable' => 'Ingen profiler tilgjengelige',
@@ -2428,11 +2435,11 @@ extension on TranslationsNb {
'subtitlingStyling.border' => 'Kantlinje',
'subtitlingStyling.background' => 'Bakgrunn',
'subtitlingStyling.fontSize' => 'Skriftstørrelse',
_ => null,
} ?? switch (path) {
'subtitlingStyling.textColor' => 'Tekstfarge',
'subtitlingStyling.borderSize' => 'Kantstørrelse',
'subtitlingStyling.borderColor' => 'Kantfarge',
_ => null,
} ?? switch (path) {
'subtitlingStyling.backgroundOpacity' => 'Bakgrunnsopasitet',
'subtitlingStyling.backgroundColor' => 'Bakgrunnsfarge',
'subtitlingStyling.position' => 'Posisjon',
@@ -2615,6 +2622,7 @@ extension on TranslationsNb {
'libraries.sortLabels.rating' => 'Vurdering',
'libraries.sortLabels.communityRating' => 'Fellesskapsvurdering',
'libraries.sortLabels.criticRating' => 'Kritikervurdering',
'libraries.sortLabels.userRating' => 'Brukervurdering',
'libraries.sortLabels.lastPlayed' => 'Sist spilt',
'libraries.sortLabels.datePlayed' => 'Avspillingsdato',
'libraries.sortLabels.playCount' => 'Avspillinger',
@@ -2941,12 +2949,12 @@ extension on TranslationsNb {
'companionRemote.remote.menu' => 'Meny',
'companionRemote.remote.tabNavigation' => 'Fanenavigering',
'companionRemote.remote.tabDiscover' => 'Oppdag',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabLibraries' => 'Biblioteker',
'companionRemote.remote.tabSearch' => 'Søk',
'companionRemote.remote.tabDownloads' => 'Nedlastinger',
'companionRemote.remote.tabSettings' => 'Innstillinger',
_ => null,
} ?? switch (path) {
'companionRemote.remote.previous' => 'Forrige',
'companionRemote.remote.playPause' => 'Spill av/Pause',
'companionRemote.remote.next' => 'Neste',
+16 -8
View File
@@ -162,6 +162,7 @@ class _TranslationsCommonNl extends TranslationsCommonEn {
@override String get ok => 'OK';
@override String get off => 'Uit';
@override String seasonNumber({required Object number}) => 'Seizoen ${number}';
@override String episodeNumberTitle({required Object number, required Object title}) => 'Aflevering ${number} - ${title}';
@override String chapterNumber({required Object number}) => 'Hoofdstuk ${number}';
@override String get reconnect => 'Opnieuw verbinden';
@override String get exit => 'Afsluiten';
@@ -244,6 +245,9 @@ class _TranslationsSettingsNl extends TranslationsSettingsEn {
@override String get gridView => 'Raster';
@override String get listView => 'Lijst';
@override String get showHeroSection => 'Toon hoofdsectie';
@override String get continueWatchingAction => 'Actie voor Doorgaan met kijken';
@override String get continueWatchingPlay => 'Afspelen';
@override String get continueWatchingDetails => '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';
@@ -491,8 +495,8 @@ class _TranslationsMediaMenuNl extends TranslationsMediaMenuEn {
@override String get markAsWatched => 'Markeer als gekeken';
@override String get markAsUnwatched => 'Markeer als ongekeken';
@override String get removeFromContinueWatching => 'Verwijder uit Doorgaan met kijken';
@override String get viewDetails => 'Details bekijken';
@override String get goToSeries => 'Ga naar serie';
@override String get goToSeason => 'Ga naar seizoen';
@override String get shufflePlay => 'Willekeurig afspelen';
@override String get shuffleNotAvailableOffline => 'Shuffle is offline niet beschikbaar';
@override String get fileInfo => 'Bestand info';
@@ -672,7 +676,6 @@ class _TranslationsMessagesNl extends TranslationsMessagesEn {
@override String get fileInfoNotAvailable => 'Bestand informatie niet beschikbaar';
@override String errorLoadingFileInfo({required Object error}) => 'Fout bij laden bestand info: ${error}';
@override String get errorLoadingSeries => 'Fout bij laden serie';
@override String get errorLoadingSeason => 'Fout bij laden seizoen';
@override String get musicNotSupported => 'Muziek afspelen wordt nog niet ondersteund';
@override String get noDescriptionAvailable => 'Geen beschrijving beschikbaar';
@override String get noProfilesAvailable => 'Geen profielen beschikbaar';
@@ -1740,6 +1743,7 @@ class _TranslationsLibrariesSortLabelsNl extends TranslationsLibrariesSortLabels
@override String get rating => 'Beoordeling';
@override String get communityRating => 'Communitybeoordeling';
@override String get criticRating => 'Criticusbeoordeling';
@override String get userRating => 'Gebruikersbeoordeling';
@override String get lastPlayed => 'Laatst afgespeeld';
@override String get datePlayed => 'Afspeeldatum';
@override String get playCount => 'Aantal afspelingen';
@@ -1969,6 +1973,7 @@ extension on TranslationsNl {
'common.ok' => 'OK',
'common.off' => 'Uit',
'common.seasonNumber' => ({required Object number}) => 'Seizoen ${number}',
'common.episodeNumberTitle' => ({required Object number, required Object title}) => 'Aflevering ${number} - ${title}',
'common.chapterNumber' => ({required Object number}) => 'Hoofdstuk ${number}',
'common.reconnect' => 'Opnieuw verbinden',
'common.exit' => 'Afsluiten',
@@ -2024,6 +2029,9 @@ extension on TranslationsNl {
'settings.gridView' => 'Raster',
'settings.listView' => 'Lijst',
'settings.showHeroSection' => 'Toon hoofdsectie',
'settings.continueWatchingAction' => 'Actie voor Doorgaan met kijken',
'settings.continueWatchingPlay' => 'Afspelen',
'settings.continueWatchingDetails' => 'Details openen',
'settings.useGlobalHubs' => 'Startlayout gebruiken',
'settings.useGlobalHubsDescription' => 'Toon gecombineerde home-hubs. Anders bibliotheekaanbevelingen gebruiken.',
'settings.showServerNameOnHubs' => 'Servernaam tonen bij hubs',
@@ -2259,8 +2267,8 @@ extension on TranslationsNl {
'mediaMenu.markAsWatched' => 'Markeer als gekeken',
'mediaMenu.markAsUnwatched' => 'Markeer als ongekeken',
'mediaMenu.removeFromContinueWatching' => 'Verwijder uit Doorgaan met kijken',
'mediaMenu.viewDetails' => 'Details bekijken',
'mediaMenu.goToSeries' => 'Ga naar serie',
'mediaMenu.goToSeason' => 'Ga naar seizoen',
'mediaMenu.shufflePlay' => 'Willekeurig afspelen',
'mediaMenu.shuffleNotAvailableOffline' => 'Shuffle is offline niet beschikbaar',
'mediaMenu.fileInfo' => 'Bestand info',
@@ -2392,7 +2400,6 @@ extension on TranslationsNl {
'messages.fileInfoNotAvailable' => 'Bestand informatie niet beschikbaar',
'messages.errorLoadingFileInfo' => ({required Object error}) => 'Fout bij laden bestand info: ${error}',
'messages.errorLoadingSeries' => 'Fout bij laden serie',
'messages.errorLoadingSeason' => 'Fout bij laden seizoen',
'messages.musicNotSupported' => 'Muziek afspelen wordt nog niet ondersteund',
'messages.noDescriptionAvailable' => 'Geen beschrijving beschikbaar',
'messages.noProfilesAvailable' => 'Geen profielen beschikbaar',
@@ -2428,11 +2435,11 @@ extension on TranslationsNl {
'subtitlingStyling.border' => 'Rand',
'subtitlingStyling.background' => 'Achtergrond',
'subtitlingStyling.fontSize' => 'Lettergrootte',
_ => null,
} ?? switch (path) {
'subtitlingStyling.textColor' => 'Tekstkleur',
'subtitlingStyling.borderSize' => 'Rand grootte',
'subtitlingStyling.borderColor' => 'Randkleur',
_ => null,
} ?? switch (path) {
'subtitlingStyling.backgroundOpacity' => 'Achtergrond transparantie',
'subtitlingStyling.backgroundColor' => 'Achtergrondkleur',
'subtitlingStyling.position' => 'Positie',
@@ -2615,6 +2622,7 @@ extension on TranslationsNl {
'libraries.sortLabels.rating' => 'Beoordeling',
'libraries.sortLabels.communityRating' => 'Communitybeoordeling',
'libraries.sortLabels.criticRating' => 'Criticusbeoordeling',
'libraries.sortLabels.userRating' => 'Gebruikersbeoordeling',
'libraries.sortLabels.lastPlayed' => 'Laatst afgespeeld',
'libraries.sortLabels.datePlayed' => 'Afspeeldatum',
'libraries.sortLabels.playCount' => 'Aantal afspelingen',
@@ -2941,12 +2949,12 @@ extension on TranslationsNl {
'companionRemote.remote.menu' => 'Menu',
'companionRemote.remote.tabNavigation' => 'Tabnavigatie',
'companionRemote.remote.tabDiscover' => 'Ontdekken',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabLibraries' => 'Bibliotheken',
'companionRemote.remote.tabSearch' => 'Zoeken',
'companionRemote.remote.tabDownloads' => 'Downloads',
'companionRemote.remote.tabSettings' => 'Instellingen',
_ => null,
} ?? switch (path) {
'companionRemote.remote.previous' => 'Vorige',
'companionRemote.remote.playPause' => 'Afspelen/Pauzeren',
'companionRemote.remote.next' => 'Volgende',
+16 -8
View File
@@ -162,6 +162,7 @@ class _TranslationsCommonPl extends TranslationsCommonEn {
@override String get ok => 'OK';
@override String get off => 'Wył.';
@override String seasonNumber({required Object number}) => 'Sezon ${number}';
@override String episodeNumberTitle({required Object number, required Object title}) => 'Odcinek ${number} - ${title}';
@override String chapterNumber({required Object number}) => 'Rozdział ${number}';
@override String get reconnect => 'Połącz ponownie';
@override String get exit => 'Wyjdź';
@@ -244,6 +245,9 @@ class _TranslationsSettingsPl extends TranslationsSettingsEn {
@override String get gridView => 'Siatka';
@override String get listView => 'Lista';
@override String get showHeroSection => 'Pokaż sekcję wyróżnioną';
@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 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';
@@ -491,8 +495,8 @@ class _TranslationsMediaMenuPl extends TranslationsMediaMenuEn {
@override String get markAsWatched => 'Oznacz jako obejrzane';
@override String get markAsUnwatched => 'Oznacz jako nieobejrzane';
@override String get removeFromContinueWatching => 'Usuń z kontynuowania oglądania';
@override String get viewDetails => 'Pokaż szczegóły';
@override String get goToSeries => 'Przejdź do serialu';
@override String get goToSeason => 'Przejdź do sezonu';
@override String get shufflePlay => 'Odtwarzanie losowe';
@override String get shuffleNotAvailableOffline => 'Odtwarzanie losowe nie jest dostępne offline';
@override String get fileInfo => 'Informacje o pliku';
@@ -672,7 +676,6 @@ class _TranslationsMessagesPl extends TranslationsMessagesEn {
@override String get fileInfoNotAvailable => 'Informacje o pliku niedostępne';
@override String errorLoadingFileInfo({required Object error}) => 'Błąd ładowania informacji o pliku: ${error}';
@override String get errorLoadingSeries => 'Błąd ładowania serialu';
@override String get errorLoadingSeason => 'Błąd ładowania sezonu';
@override String get musicNotSupported => 'Odtwarzanie muzyki nie jest jeszcze obsługiwane';
@override String get noDescriptionAvailable => 'Brak dostępnego opisu';
@override String get noProfilesAvailable => 'Brak dostępnych profili';
@@ -1740,6 +1743,7 @@ class _TranslationsLibrariesSortLabelsPl extends TranslationsLibrariesSortLabels
@override String get rating => 'Ocena';
@override String get communityRating => 'Ocena społeczności';
@override String get criticRating => 'Ocena krytyków';
@override String get userRating => 'Ocena użytkownika';
@override String get lastPlayed => 'Ostatnio odtwarzane';
@override String get datePlayed => 'Data odtworzenia';
@override String get playCount => 'Liczba odtworzeń';
@@ -1969,6 +1973,7 @@ extension on TranslationsPl {
'common.ok' => 'OK',
'common.off' => 'Wył.',
'common.seasonNumber' => ({required Object number}) => 'Sezon ${number}',
'common.episodeNumberTitle' => ({required Object number, required Object title}) => 'Odcinek ${number} - ${title}',
'common.chapterNumber' => ({required Object number}) => 'Rozdział ${number}',
'common.reconnect' => 'Połącz ponownie',
'common.exit' => 'Wyjdź',
@@ -2024,6 +2029,9 @@ extension on TranslationsPl {
'settings.gridView' => 'Siatka',
'settings.listView' => 'Lista',
'settings.showHeroSection' => 'Pokaż sekcję wyróżnioną',
'settings.continueWatchingAction' => 'Akcja Kontynuuj oglądanie',
'settings.continueWatchingPlay' => 'Odtwórz',
'settings.continueWatchingDetails' => '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',
@@ -2259,8 +2267,8 @@ extension on TranslationsPl {
'mediaMenu.markAsWatched' => 'Oznacz jako obejrzane',
'mediaMenu.markAsUnwatched' => 'Oznacz jako nieobejrzane',
'mediaMenu.removeFromContinueWatching' => 'Usuń z kontynuowania oglądania',
'mediaMenu.viewDetails' => 'Pokaż szczegóły',
'mediaMenu.goToSeries' => 'Przejdź do serialu',
'mediaMenu.goToSeason' => 'Przejdź do sezonu',
'mediaMenu.shufflePlay' => 'Odtwarzanie losowe',
'mediaMenu.shuffleNotAvailableOffline' => 'Odtwarzanie losowe nie jest dostępne offline',
'mediaMenu.fileInfo' => 'Informacje o pliku',
@@ -2392,7 +2400,6 @@ extension on TranslationsPl {
'messages.fileInfoNotAvailable' => 'Informacje o pliku niedostępne',
'messages.errorLoadingFileInfo' => ({required Object error}) => 'Błąd ładowania informacji o pliku: ${error}',
'messages.errorLoadingSeries' => 'Błąd ładowania serialu',
'messages.errorLoadingSeason' => 'Błąd ładowania sezonu',
'messages.musicNotSupported' => 'Odtwarzanie muzyki nie jest jeszcze obsługiwane',
'messages.noDescriptionAvailable' => 'Brak dostępnego opisu',
'messages.noProfilesAvailable' => 'Brak dostępnych profili',
@@ -2428,11 +2435,11 @@ extension on TranslationsPl {
'subtitlingStyling.border' => 'Obramowanie',
'subtitlingStyling.background' => 'Tło',
'subtitlingStyling.fontSize' => 'Rozmiar czcionki',
_ => null,
} ?? switch (path) {
'subtitlingStyling.textColor' => 'Kolor tekstu',
'subtitlingStyling.borderSize' => 'Rozmiar obramowania',
'subtitlingStyling.borderColor' => 'Kolor obramowania',
_ => null,
} ?? switch (path) {
'subtitlingStyling.backgroundOpacity' => 'Przezroczystość tła',
'subtitlingStyling.backgroundColor' => 'Kolor tła',
'subtitlingStyling.position' => 'Pozycja',
@@ -2615,6 +2622,7 @@ extension on TranslationsPl {
'libraries.sortLabels.rating' => 'Ocena',
'libraries.sortLabels.communityRating' => 'Ocena społeczności',
'libraries.sortLabels.criticRating' => 'Ocena krytyków',
'libraries.sortLabels.userRating' => 'Ocena użytkownika',
'libraries.sortLabels.lastPlayed' => 'Ostatnio odtwarzane',
'libraries.sortLabels.datePlayed' => 'Data odtworzenia',
'libraries.sortLabels.playCount' => 'Liczba odtworzeń',
@@ -2941,12 +2949,12 @@ extension on TranslationsPl {
'companionRemote.remote.menu' => 'Menu',
'companionRemote.remote.tabNavigation' => 'Nawigacja',
'companionRemote.remote.tabDiscover' => 'Odkryj',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabLibraries' => 'Biblioteki',
'companionRemote.remote.tabSearch' => 'Szukaj',
'companionRemote.remote.tabDownloads' => 'Pobrania',
'companionRemote.remote.tabSettings' => 'Ustawienia',
_ => null,
} ?? switch (path) {
'companionRemote.remote.previous' => 'Poprzedni',
'companionRemote.remote.playPause' => 'Odtwórz/Pauza',
'companionRemote.remote.next' => 'Następny',
+16 -8
View File
@@ -162,6 +162,7 @@ class _TranslationsCommonPt extends TranslationsCommonEn {
@override String get ok => 'OK';
@override String get off => 'Desativado';
@override String seasonNumber({required Object number}) => 'Temporada ${number}';
@override String episodeNumberTitle({required Object number, required Object title}) => 'Episódio ${number} - ${title}';
@override String chapterNumber({required Object number}) => 'Capítulo ${number}';
@override String get reconnect => 'Reconectar';
@override String get exit => 'Sair';
@@ -244,6 +245,9 @@ class _TranslationsSettingsPt extends TranslationsSettingsEn {
@override String get gridView => 'Grade';
@override String get listView => 'Lista';
@override String get showHeroSection => 'Mostrar Seção de Destaque';
@override String get continueWatchingAction => 'Ação de Continuar Assistindo';
@override String get continueWatchingPlay => 'Reproduzir';
@override String get continueWatchingDetails => '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';
@@ -491,8 +495,8 @@ class _TranslationsMediaMenuPt extends TranslationsMediaMenuEn {
@override String get markAsWatched => 'Marcar como Assistido';
@override String get markAsUnwatched => 'Marcar como Não Assistido';
@override String get removeFromContinueWatching => 'Remover de Continuar Assistindo';
@override String get viewDetails => 'Ver detalhes';
@override String get goToSeries => 'Ir para a série';
@override String get goToSeason => 'Ir para a temporada';
@override String get shufflePlay => 'Reprodução Aleatória';
@override String get shuffleNotAvailableOffline => 'Reprodução aleatória indisponível offline';
@override String get fileInfo => 'Info do Arquivo';
@@ -672,7 +676,6 @@ class _TranslationsMessagesPt extends TranslationsMessagesEn {
@override String get fileInfoNotAvailable => 'Informações do arquivo não disponíveis';
@override String errorLoadingFileInfo({required Object error}) => 'Erro ao carregar info do arquivo: ${error}';
@override String get errorLoadingSeries => 'Erro ao carregar série';
@override String get errorLoadingSeason => 'Erro ao carregar temporada';
@override String get musicNotSupported => 'Reprodução de música ainda não é suportada';
@override String get noDescriptionAvailable => 'Nenhuma descrição disponível';
@override String get noProfilesAvailable => 'Nenhum perfil disponível';
@@ -1740,6 +1743,7 @@ class _TranslationsLibrariesSortLabelsPt extends TranslationsLibrariesSortLabels
@override String get rating => 'Avaliação';
@override String get communityRating => 'Avaliação da comunidade';
@override String get criticRating => 'Avaliação da crítica';
@override String get userRating => 'Avaliação do usuário';
@override String get lastPlayed => 'Última reprodução';
@override String get datePlayed => 'Data de reprodução';
@override String get playCount => 'Reproduções';
@@ -1969,6 +1973,7 @@ extension on TranslationsPt {
'common.ok' => 'OK',
'common.off' => 'Desativado',
'common.seasonNumber' => ({required Object number}) => 'Temporada ${number}',
'common.episodeNumberTitle' => ({required Object number, required Object title}) => 'Episódio ${number} - ${title}',
'common.chapterNumber' => ({required Object number}) => 'Capítulo ${number}',
'common.reconnect' => 'Reconectar',
'common.exit' => 'Sair',
@@ -2024,6 +2029,9 @@ extension on TranslationsPt {
'settings.gridView' => 'Grade',
'settings.listView' => 'Lista',
'settings.showHeroSection' => 'Mostrar Seção de Destaque',
'settings.continueWatchingAction' => 'Ação de Continuar Assistindo',
'settings.continueWatchingPlay' => 'Reproduzir',
'settings.continueWatchingDetails' => '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',
@@ -2259,8 +2267,8 @@ extension on TranslationsPt {
'mediaMenu.markAsWatched' => 'Marcar como Assistido',
'mediaMenu.markAsUnwatched' => 'Marcar como Não Assistido',
'mediaMenu.removeFromContinueWatching' => 'Remover de Continuar Assistindo',
'mediaMenu.viewDetails' => 'Ver detalhes',
'mediaMenu.goToSeries' => 'Ir para a série',
'mediaMenu.goToSeason' => 'Ir para a temporada',
'mediaMenu.shufflePlay' => 'Reprodução Aleatória',
'mediaMenu.shuffleNotAvailableOffline' => 'Reprodução aleatória indisponível offline',
'mediaMenu.fileInfo' => 'Info do Arquivo',
@@ -2392,7 +2400,6 @@ extension on TranslationsPt {
'messages.fileInfoNotAvailable' => 'Informações do arquivo não disponíveis',
'messages.errorLoadingFileInfo' => ({required Object error}) => 'Erro ao carregar info do arquivo: ${error}',
'messages.errorLoadingSeries' => 'Erro ao carregar série',
'messages.errorLoadingSeason' => 'Erro ao carregar temporada',
'messages.musicNotSupported' => 'Reprodução de música ainda não é suportada',
'messages.noDescriptionAvailable' => 'Nenhuma descrição disponível',
'messages.noProfilesAvailable' => 'Nenhum perfil disponível',
@@ -2428,11 +2435,11 @@ extension on TranslationsPt {
'subtitlingStyling.border' => 'Borda',
'subtitlingStyling.background' => 'Fundo',
'subtitlingStyling.fontSize' => 'Tamanho da Fonte',
_ => null,
} ?? switch (path) {
'subtitlingStyling.textColor' => 'Cor do Texto',
'subtitlingStyling.borderSize' => 'Tamanho da Borda',
'subtitlingStyling.borderColor' => 'Cor da Borda',
_ => null,
} ?? switch (path) {
'subtitlingStyling.backgroundOpacity' => 'Opacidade do Fundo',
'subtitlingStyling.backgroundColor' => 'Cor de Fundo',
'subtitlingStyling.position' => 'Posição',
@@ -2615,6 +2622,7 @@ extension on TranslationsPt {
'libraries.sortLabels.rating' => 'Avaliação',
'libraries.sortLabels.communityRating' => 'Avaliação da comunidade',
'libraries.sortLabels.criticRating' => 'Avaliação da crítica',
'libraries.sortLabels.userRating' => 'Avaliação do usuário',
'libraries.sortLabels.lastPlayed' => 'Última reprodução',
'libraries.sortLabels.datePlayed' => 'Data de reprodução',
'libraries.sortLabels.playCount' => 'Reproduções',
@@ -2941,12 +2949,12 @@ extension on TranslationsPt {
'companionRemote.remote.menu' => 'Menu',
'companionRemote.remote.tabNavigation' => 'Navegação',
'companionRemote.remote.tabDiscover' => 'Descobrir',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabLibraries' => 'Bibliotecas',
'companionRemote.remote.tabSearch' => 'Buscar',
'companionRemote.remote.tabDownloads' => 'Downloads',
'companionRemote.remote.tabSettings' => 'Configurações',
_ => null,
} ?? switch (path) {
'companionRemote.remote.previous' => 'Anterior',
'companionRemote.remote.playPause' => 'Reproduzir/Pausar',
'companionRemote.remote.next' => 'Próximo',
+16 -8
View File
@@ -162,6 +162,7 @@ class _TranslationsCommonRu extends TranslationsCommonEn {
@override String get ok => 'OK';
@override String get off => 'Выкл.';
@override String seasonNumber({required Object number}) => 'Сезон ${number}';
@override String episodeNumberTitle({required Object number, required Object title}) => 'Эпизод ${number} - ${title}';
@override String chapterNumber({required Object number}) => 'Глава ${number}';
@override String get reconnect => 'Переподключить';
@override String get exit => 'Выход';
@@ -244,6 +245,9 @@ class _TranslationsSettingsRu extends TranslationsSettingsEn {
@override String get gridView => 'Сетка';
@override String get listView => 'Список';
@override String get showHeroSection => 'Показать раздел избранного';
@override String get continueWatchingAction => 'Действие для «Продолжить просмотр»';
@override String get continueWatchingPlay => 'Воспроизвести';
@override String get continueWatchingDetails => 'Открыть сведения';
@override String get useGlobalHubs => 'Использовать макет главной';
@override String get useGlobalHubsDescription => 'Показывать единые разделы главной. Иначе использовать рекомендации библиотек.';
@override String get showServerNameOnHubs => 'Показывать имя сервера в хабах';
@@ -491,8 +495,8 @@ class _TranslationsMediaMenuRu extends TranslationsMediaMenuEn {
@override String get markAsWatched => 'Отметить как просмотренное';
@override String get markAsUnwatched => 'Отметить как непросмотренное';
@override String get removeFromContinueWatching => 'Удалить из «Продолжить просмотр»';
@override String get viewDetails => 'Показать сведения';
@override String get goToSeries => 'Перейти к сериалу';
@override String get goToSeason => 'Перейти к сезону';
@override String get shufflePlay => 'Случайное воспроизведение';
@override String get shuffleNotAvailableOffline => 'Перемешивание недоступно офлайн';
@override String get fileInfo => 'Информация о файле';
@@ -672,7 +676,6 @@ class _TranslationsMessagesRu extends TranslationsMessagesEn {
@override String get fileInfoNotAvailable => 'Информация о файле недоступна';
@override String errorLoadingFileInfo({required Object error}) => 'Ошибка загрузки информации о файле: ${error}';
@override String get errorLoadingSeries => 'Ошибка загрузки сериала';
@override String get errorLoadingSeason => 'Ошибка загрузки сезона';
@override String get musicNotSupported => 'Воспроизведение музыки пока не поддерживается';
@override String get noDescriptionAvailable => 'Описание недоступно';
@override String get noProfilesAvailable => 'Профили недоступны';
@@ -1740,6 +1743,7 @@ class _TranslationsLibrariesSortLabelsRu extends TranslationsLibrariesSortLabels
@override String get rating => 'Рейтинг';
@override String get communityRating => 'Оценка сообщества';
@override String get criticRating => 'Оценка критиков';
@override String get userRating => 'Пользовательская оценка';
@override String get lastPlayed => 'Последний просмотр';
@override String get datePlayed => 'Дата просмотра';
@override String get playCount => 'Количество просмотров';
@@ -1969,6 +1973,7 @@ extension on TranslationsRu {
'common.ok' => 'OK',
'common.off' => 'Выкл.',
'common.seasonNumber' => ({required Object number}) => 'Сезон ${number}',
'common.episodeNumberTitle' => ({required Object number, required Object title}) => 'Эпизод ${number} - ${title}',
'common.chapterNumber' => ({required Object number}) => 'Глава ${number}',
'common.reconnect' => 'Переподключить',
'common.exit' => 'Выход',
@@ -2024,6 +2029,9 @@ extension on TranslationsRu {
'settings.gridView' => 'Сетка',
'settings.listView' => 'Список',
'settings.showHeroSection' => 'Показать раздел избранного',
'settings.continueWatchingAction' => 'Действие для «Продолжить просмотр»',
'settings.continueWatchingPlay' => 'Воспроизвести',
'settings.continueWatchingDetails' => 'Открыть сведения',
'settings.useGlobalHubs' => 'Использовать макет главной',
'settings.useGlobalHubsDescription' => 'Показывать единые разделы главной. Иначе использовать рекомендации библиотек.',
'settings.showServerNameOnHubs' => 'Показывать имя сервера в хабах',
@@ -2259,8 +2267,8 @@ extension on TranslationsRu {
'mediaMenu.markAsWatched' => 'Отметить как просмотренное',
'mediaMenu.markAsUnwatched' => 'Отметить как непросмотренное',
'mediaMenu.removeFromContinueWatching' => 'Удалить из «Продолжить просмотр»',
'mediaMenu.viewDetails' => 'Показать сведения',
'mediaMenu.goToSeries' => 'Перейти к сериалу',
'mediaMenu.goToSeason' => 'Перейти к сезону',
'mediaMenu.shufflePlay' => 'Случайное воспроизведение',
'mediaMenu.shuffleNotAvailableOffline' => 'Перемешивание недоступно офлайн',
'mediaMenu.fileInfo' => 'Информация о файле',
@@ -2392,7 +2400,6 @@ extension on TranslationsRu {
'messages.fileInfoNotAvailable' => 'Информация о файле недоступна',
'messages.errorLoadingFileInfo' => ({required Object error}) => 'Ошибка загрузки информации о файле: ${error}',
'messages.errorLoadingSeries' => 'Ошибка загрузки сериала',
'messages.errorLoadingSeason' => 'Ошибка загрузки сезона',
'messages.musicNotSupported' => 'Воспроизведение музыки пока не поддерживается',
'messages.noDescriptionAvailable' => 'Описание недоступно',
'messages.noProfilesAvailable' => 'Профили недоступны',
@@ -2428,11 +2435,11 @@ extension on TranslationsRu {
'subtitlingStyling.border' => 'Обводка',
'subtitlingStyling.background' => 'Фон',
'subtitlingStyling.fontSize' => 'Размер шрифта',
_ => null,
} ?? switch (path) {
'subtitlingStyling.textColor' => 'Цвет текста',
'subtitlingStyling.borderSize' => 'Размер обводки',
'subtitlingStyling.borderColor' => 'Цвет обводки',
_ => null,
} ?? switch (path) {
'subtitlingStyling.backgroundOpacity' => 'Прозрачность фона',
'subtitlingStyling.backgroundColor' => 'Цвет фона',
'subtitlingStyling.position' => 'Позиция',
@@ -2615,6 +2622,7 @@ extension on TranslationsRu {
'libraries.sortLabels.rating' => 'Рейтинг',
'libraries.sortLabels.communityRating' => 'Оценка сообщества',
'libraries.sortLabels.criticRating' => 'Оценка критиков',
'libraries.sortLabels.userRating' => 'Пользовательская оценка',
'libraries.sortLabels.lastPlayed' => 'Последний просмотр',
'libraries.sortLabels.datePlayed' => 'Дата просмотра',
'libraries.sortLabels.playCount' => 'Количество просмотров',
@@ -2941,12 +2949,12 @@ extension on TranslationsRu {
'companionRemote.remote.menu' => 'Меню',
'companionRemote.remote.tabNavigation' => 'Навигация',
'companionRemote.remote.tabDiscover' => 'Обзор',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabLibraries' => 'Библиотеки',
'companionRemote.remote.tabSearch' => 'Поиск',
'companionRemote.remote.tabDownloads' => 'Загрузки',
'companionRemote.remote.tabSettings' => 'Настройки',
_ => null,
} ?? switch (path) {
'companionRemote.remote.previous' => 'Предыдущий',
'companionRemote.remote.playPause' => 'Воспроизведение/Пауза',
'companionRemote.remote.next' => 'Следующий',
+16 -8
View File
@@ -162,6 +162,7 @@ class _TranslationsCommonSv extends TranslationsCommonEn {
@override String get ok => 'OK';
@override String get off => 'Av';
@override String seasonNumber({required Object number}) => 'Säsong ${number}';
@override String episodeNumberTitle({required Object number, required Object title}) => 'Avsnitt ${number} - ${title}';
@override String chapterNumber({required Object number}) => 'Kapitel ${number}';
@override String get reconnect => 'Återanslut';
@override String get exit => 'Avsluta';
@@ -244,6 +245,9 @@ class _TranslationsSettingsSv extends TranslationsSettingsEn {
@override String get gridView => 'Rutnät';
@override String get listView => 'Lista';
@override String get showHeroSection => 'Visa hjältesektion';
@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 useGlobalHubs => 'Använd startlayout';
@override String get useGlobalHubsDescription => 'Visa enhetliga startsideshubbar. Annars används biblioteksrekommendationer.';
@override String get showServerNameOnHubs => 'Visa servernamn på hubbar';
@@ -491,8 +495,8 @@ class _TranslationsMediaMenuSv extends TranslationsMediaMenuEn {
@override String get markAsWatched => 'Markera som sedd';
@override String get markAsUnwatched => 'Markera som osedd';
@override String get removeFromContinueWatching => 'Ta bort från Fortsätt titta';
@override String get viewDetails => 'Visa detaljer';
@override String get goToSeries => 'Gå till serie';
@override String get goToSeason => 'Gå till säsong';
@override String get shufflePlay => 'Blanda uppspelning';
@override String get shuffleNotAvailableOffline => 'Blandad uppspelning är inte tillgänglig offline';
@override String get fileInfo => 'Filinformation';
@@ -672,7 +676,6 @@ class _TranslationsMessagesSv extends TranslationsMessagesEn {
@override String get fileInfoNotAvailable => 'Filinformation inte tillgänglig';
@override String errorLoadingFileInfo({required Object error}) => 'Fel vid laddning av filinformation: ${error}';
@override String get errorLoadingSeries => 'Fel vid laddning av serie';
@override String get errorLoadingSeason => 'Fel vid laddning av säsong';
@override String get musicNotSupported => 'Musikuppspelning stöds inte ännu';
@override String get noDescriptionAvailable => 'Ingen beskrivning tillgänglig';
@override String get noProfilesAvailable => 'Inga profiler tillgängliga';
@@ -1740,6 +1743,7 @@ class _TranslationsLibrariesSortLabelsSv extends TranslationsLibrariesSortLabels
@override String get rating => 'Betyg';
@override String get communityRating => 'Användarbetyg';
@override String get criticRating => 'Kritikerbetyg';
@override String get userRating => 'Användarbetyg';
@override String get lastPlayed => 'Senast spelad';
@override String get datePlayed => 'Speldatum';
@override String get playCount => 'Antal spelningar';
@@ -1969,6 +1973,7 @@ extension on TranslationsSv {
'common.ok' => 'OK',
'common.off' => 'Av',
'common.seasonNumber' => ({required Object number}) => 'Säsong ${number}',
'common.episodeNumberTitle' => ({required Object number, required Object title}) => 'Avsnitt ${number} - ${title}',
'common.chapterNumber' => ({required Object number}) => 'Kapitel ${number}',
'common.reconnect' => 'Återanslut',
'common.exit' => 'Avsluta',
@@ -2024,6 +2029,9 @@ extension on TranslationsSv {
'settings.gridView' => 'Rutnät',
'settings.listView' => 'Lista',
'settings.showHeroSection' => 'Visa hjältesektion',
'settings.continueWatchingAction' => 'Åtgärd för Fortsätt titta',
'settings.continueWatchingPlay' => 'Spela',
'settings.continueWatchingDetails' => 'Öppna detaljer',
'settings.useGlobalHubs' => 'Använd startlayout',
'settings.useGlobalHubsDescription' => 'Visa enhetliga startsideshubbar. Annars används biblioteksrekommendationer.',
'settings.showServerNameOnHubs' => 'Visa servernamn på hubbar',
@@ -2259,8 +2267,8 @@ extension on TranslationsSv {
'mediaMenu.markAsWatched' => 'Markera som sedd',
'mediaMenu.markAsUnwatched' => 'Markera som osedd',
'mediaMenu.removeFromContinueWatching' => 'Ta bort från Fortsätt titta',
'mediaMenu.viewDetails' => 'Visa detaljer',
'mediaMenu.goToSeries' => 'Gå till serie',
'mediaMenu.goToSeason' => 'Gå till säsong',
'mediaMenu.shufflePlay' => 'Blanda uppspelning',
'mediaMenu.shuffleNotAvailableOffline' => 'Blandad uppspelning är inte tillgänglig offline',
'mediaMenu.fileInfo' => 'Filinformation',
@@ -2392,7 +2400,6 @@ extension on TranslationsSv {
'messages.fileInfoNotAvailable' => 'Filinformation inte tillgänglig',
'messages.errorLoadingFileInfo' => ({required Object error}) => 'Fel vid laddning av filinformation: ${error}',
'messages.errorLoadingSeries' => 'Fel vid laddning av serie',
'messages.errorLoadingSeason' => 'Fel vid laddning av säsong',
'messages.musicNotSupported' => 'Musikuppspelning stöds inte ännu',
'messages.noDescriptionAvailable' => 'Ingen beskrivning tillgänglig',
'messages.noProfilesAvailable' => 'Inga profiler tillgängliga',
@@ -2428,11 +2435,11 @@ extension on TranslationsSv {
'subtitlingStyling.border' => 'Kantlinje',
'subtitlingStyling.background' => 'Bakgrund',
'subtitlingStyling.fontSize' => 'Teckenstorlek',
_ => null,
} ?? switch (path) {
'subtitlingStyling.textColor' => 'Textfärg',
'subtitlingStyling.borderSize' => 'Kantstorlek',
'subtitlingStyling.borderColor' => 'Kantfärg',
_ => null,
} ?? switch (path) {
'subtitlingStyling.backgroundOpacity' => 'Bakgrundsopacitet',
'subtitlingStyling.backgroundColor' => 'Bakgrundsfärg',
'subtitlingStyling.position' => 'Position',
@@ -2615,6 +2622,7 @@ extension on TranslationsSv {
'libraries.sortLabels.rating' => 'Betyg',
'libraries.sortLabels.communityRating' => 'Användarbetyg',
'libraries.sortLabels.criticRating' => 'Kritikerbetyg',
'libraries.sortLabels.userRating' => 'Användarbetyg',
'libraries.sortLabels.lastPlayed' => 'Senast spelad',
'libraries.sortLabels.datePlayed' => 'Speldatum',
'libraries.sortLabels.playCount' => 'Antal spelningar',
@@ -2941,12 +2949,12 @@ extension on TranslationsSv {
'companionRemote.remote.menu' => 'Meny',
'companionRemote.remote.tabNavigation' => 'Fliknavigering',
'companionRemote.remote.tabDiscover' => 'Upptäck',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabLibraries' => 'Bibliotek',
'companionRemote.remote.tabSearch' => 'Sök',
'companionRemote.remote.tabDownloads' => 'Nedladdningar',
'companionRemote.remote.tabSettings' => 'Inställningar',
_ => null,
} ?? switch (path) {
'companionRemote.remote.previous' => 'Föregående',
'companionRemote.remote.playPause' => 'Spela/Pausa',
'companionRemote.remote.next' => 'Nästa',
+16 -8
View File
@@ -162,6 +162,7 @@ class _TranslationsCommonZh extends TranslationsCommonEn {
@override String get ok => '确定';
@override String get off => '关闭';
@override String seasonNumber({required Object number}) => '第${number}季';
@override String episodeNumberTitle({required Object number, required Object title}) => '第${number}集 - ${title}';
@override String chapterNumber({required Object number}) => '章节 ${number}';
@override String get reconnect => '重新连接';
@override String get exit => '退出';
@@ -244,6 +245,9 @@ class _TranslationsSettingsZh extends TranslationsSettingsEn {
@override String get gridView => '网格视图';
@override String get listView => '列表视图';
@override String get showHeroSection => '显示主要精选区';
@override String get continueWatchingAction => '继续观看操作';
@override String get continueWatchingPlay => '播放';
@override String get continueWatchingDetails => '打开详情';
@override String get useGlobalHubs => '使用主页布局';
@override String get useGlobalHubsDescription => '显示统一主页中心。否则使用资料库推荐。';
@override String get showServerNameOnHubs => '在推荐栏显示服务器名称';
@@ -491,8 +495,8 @@ class _TranslationsMediaMenuZh extends TranslationsMediaMenuEn {
@override String get markAsWatched => '标记为已观看';
@override String get markAsUnwatched => '标记为未观看';
@override String get removeFromContinueWatching => '从继续观看中移除';
@override String get viewDetails => '查看详情';
@override String get goToSeries => '转到系列';
@override String get goToSeason => '转到季';
@override String get shufflePlay => '随机播放';
@override String get shuffleNotAvailableOffline => '离线时无法随机播放';
@override String get fileInfo => '文件信息';
@@ -672,7 +676,6 @@ class _TranslationsMessagesZh extends TranslationsMessagesEn {
@override String get fileInfoNotAvailable => '文件信息不可用';
@override String errorLoadingFileInfo({required Object error}) => '加载文件信息时出错: ${error}';
@override String get errorLoadingSeries => '加载系列时出错';
@override String get errorLoadingSeason => '加载季时出错';
@override String get musicNotSupported => '尚不支持播放音乐';
@override String get noDescriptionAvailable => '暂无描述';
@override String get noProfilesAvailable => '没有可用的用户';
@@ -1740,6 +1743,7 @@ class _TranslationsLibrariesSortLabelsZh extends TranslationsLibrariesSortLabels
@override String get rating => '评分';
@override String get communityRating => '社区评分';
@override String get criticRating => '影评人评分';
@override String get userRating => '用户评分';
@override String get lastPlayed => '最近播放';
@override String get datePlayed => '播放日期';
@override String get playCount => '播放次数';
@@ -1969,6 +1973,7 @@ extension on TranslationsZh {
'common.ok' => '确定',
'common.off' => '关闭',
'common.seasonNumber' => ({required Object number}) => '第${number}季',
'common.episodeNumberTitle' => ({required Object number, required Object title}) => '第${number}集 - ${title}',
'common.chapterNumber' => ({required Object number}) => '章节 ${number}',
'common.reconnect' => '重新连接',
'common.exit' => '退出',
@@ -2024,6 +2029,9 @@ extension on TranslationsZh {
'settings.gridView' => '网格视图',
'settings.listView' => '列表视图',
'settings.showHeroSection' => '显示主要精选区',
'settings.continueWatchingAction' => '继续观看操作',
'settings.continueWatchingPlay' => '播放',
'settings.continueWatchingDetails' => '打开详情',
'settings.useGlobalHubs' => '使用主页布局',
'settings.useGlobalHubsDescription' => '显示统一主页中心。否则使用资料库推荐。',
'settings.showServerNameOnHubs' => '在推荐栏显示服务器名称',
@@ -2259,8 +2267,8 @@ extension on TranslationsZh {
'mediaMenu.markAsWatched' => '标记为已观看',
'mediaMenu.markAsUnwatched' => '标记为未观看',
'mediaMenu.removeFromContinueWatching' => '从继续观看中移除',
'mediaMenu.viewDetails' => '查看详情',
'mediaMenu.goToSeries' => '转到系列',
'mediaMenu.goToSeason' => '转到季',
'mediaMenu.shufflePlay' => '随机播放',
'mediaMenu.shuffleNotAvailableOffline' => '离线时无法随机播放',
'mediaMenu.fileInfo' => '文件信息',
@@ -2392,7 +2400,6 @@ extension on TranslationsZh {
'messages.fileInfoNotAvailable' => '文件信息不可用',
'messages.errorLoadingFileInfo' => ({required Object error}) => '加载文件信息时出错: ${error}',
'messages.errorLoadingSeries' => '加载系列时出错',
'messages.errorLoadingSeason' => '加载季时出错',
'messages.musicNotSupported' => '尚不支持播放音乐',
'messages.noDescriptionAvailable' => '暂无描述',
'messages.noProfilesAvailable' => '没有可用的用户',
@@ -2428,11 +2435,11 @@ extension on TranslationsZh {
'subtitlingStyling.border' => '边框',
'subtitlingStyling.background' => '背景',
'subtitlingStyling.fontSize' => '字号',
_ => null,
} ?? switch (path) {
'subtitlingStyling.textColor' => '文本颜色',
'subtitlingStyling.borderSize' => '边框大小',
'subtitlingStyling.borderColor' => '边框颜色',
_ => null,
} ?? switch (path) {
'subtitlingStyling.backgroundOpacity' => '背景不透明度',
'subtitlingStyling.backgroundColor' => '背景颜色',
'subtitlingStyling.position' => '位置',
@@ -2615,6 +2622,7 @@ extension on TranslationsZh {
'libraries.sortLabels.rating' => '评分',
'libraries.sortLabels.communityRating' => '社区评分',
'libraries.sortLabels.criticRating' => '影评人评分',
'libraries.sortLabels.userRating' => '用户评分',
'libraries.sortLabels.lastPlayed' => '最近播放',
'libraries.sortLabels.datePlayed' => '播放日期',
'libraries.sortLabels.playCount' => '播放次数',
@@ -2941,12 +2949,12 @@ extension on TranslationsZh {
'companionRemote.remote.menu' => '菜单',
'companionRemote.remote.tabNavigation' => '标签导航',
'companionRemote.remote.tabDiscover' => '发现',
_ => null,
} ?? switch (path) {
'companionRemote.remote.tabLibraries' => '媒体库',
'companionRemote.remote.tabSearch' => '搜索',
'companionRemote.remote.tabDownloads' => '下载',
'companionRemote.remote.tabSettings' => '设置',
_ => null,
} ?? switch (path) {
'companionRemote.remote.previous' => '上一个',
'companionRemote.remote.playPause' => '播放/暂停',
'companionRemote.remote.next' => '下一个',
+6 -2
View File
@@ -54,6 +54,7 @@
"ok": "OK",
"off": "Av",
"seasonNumber": "Säsong ${number}",
"episodeNumberTitle": "Avsnitt ${number} - ${title}",
"chapterNumber": "Kapitel ${number}",
"reconnect": "Återanslut",
"exit": "Avsluta",
@@ -115,6 +116,9 @@
"gridView": "Rutnät",
"listView": "Lista",
"showHeroSection": "Visa hjältesektion",
"continueWatchingAction": "Åtgärd för Fortsätt titta",
"continueWatchingPlay": "Spela",
"continueWatchingDetails": "Öppna detaljer",
"useGlobalHubs": "Använd startlayout",
"useGlobalHubsDescription": "Visa enhetliga startsideshubbar. Annars används biblioteksrekommendationer.",
"showServerNameOnHubs": "Visa servernamn på hubbar",
@@ -360,8 +364,8 @@
"markAsWatched": "Markera som sedd",
"markAsUnwatched": "Markera som osedd",
"removeFromContinueWatching": "Ta bort från Fortsätt titta",
"viewDetails": "Visa detaljer",
"goToSeries": "Gå till serie",
"goToSeason": "Gå till säsong",
"shufflePlay": "Blanda uppspelning",
"shuffleNotAvailableOffline": "Blandad uppspelning är inte tillgänglig offline",
"fileInfo": "Filinformation",
@@ -507,7 +511,6 @@
"fileInfoNotAvailable": "Filinformation inte tillgänglig",
"errorLoadingFileInfo": "Fel vid laddning av filinformation: ${error}",
"errorLoadingSeries": "Fel vid laddning av serie",
"errorLoadingSeason": "Fel vid laddning av säsong",
"musicNotSupported": "Musikuppspelning stöds inte ännu",
"noDescriptionAvailable": "Ingen beskrivning tillgänglig",
"noProfilesAvailable": "Inga profiler tillgängliga",
@@ -751,6 +754,7 @@
"rating": "Betyg",
"communityRating": "Användarbetyg",
"criticRating": "Kritikerbetyg",
"userRating": "Användarbetyg",
"lastPlayed": "Senast spelad",
"datePlayed": "Speldatum",
"playCount": "Antal spelningar",
+6 -2
View File
@@ -54,6 +54,7 @@
"ok": "确定",
"off": "关闭",
"seasonNumber": "第${number}季",
"episodeNumberTitle": "第${number}集 - ${title}",
"chapterNumber": "章节 ${number}",
"reconnect": "重新连接",
"exit": "退出",
@@ -115,6 +116,9 @@
"gridView": "网格视图",
"listView": "列表视图",
"showHeroSection": "显示主要精选区",
"continueWatchingAction": "继续观看操作",
"continueWatchingPlay": "播放",
"continueWatchingDetails": "打开详情",
"useGlobalHubs": "使用主页布局",
"useGlobalHubsDescription": "显示统一主页中心。否则使用资料库推荐。",
"showServerNameOnHubs": "在推荐栏显示服务器名称",
@@ -360,8 +364,8 @@
"markAsWatched": "标记为已观看",
"markAsUnwatched": "标记为未观看",
"removeFromContinueWatching": "从继续观看中移除",
"viewDetails": "查看详情",
"goToSeries": "转到系列",
"goToSeason": "转到季",
"shufflePlay": "随机播放",
"shuffleNotAvailableOffline": "离线时无法随机播放",
"fileInfo": "文件信息",
@@ -507,7 +511,6 @@
"fileInfoNotAvailable": "文件信息不可用",
"errorLoadingFileInfo": "加载文件信息时出错: ${error}",
"errorLoadingSeries": "加载系列时出错",
"errorLoadingSeason": "加载季时出错",
"musicNotSupported": "尚不支持播放音乐",
"noDescriptionAvailable": "暂无描述",
"noProfilesAvailable": "没有可用的用户",
@@ -751,6 +754,7 @@
"rating": "评分",
"communityRating": "社区评分",
"criticRating": "影评人评分",
"userRating": "用户评分",
"lastPlayed": "最近播放",
"datePlayed": "播放日期",
"playCount": "播放次数",
+4 -4
View File
@@ -51,7 +51,7 @@ 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_overlay_provider.dart';
import 'providers/watch_state_store.dart';
import 'providers/companion_remote_provider.dart';
import 'providers/shader_provider.dart';
import 'utils/snackbar_helper.dart';
@@ -775,10 +775,10 @@ class _MainAppState extends State<MainApp> with WidgetsBindingObserver {
return provider;
},
),
ChangeNotifierProxyProvider2<ActiveProfileProvider, MultiServerProvider, WatchStateOverlayProvider>(
create: (_) => WatchStateOverlayProvider(),
ChangeNotifierProxyProvider2<ActiveProfileProvider, MultiServerProvider, WatchStateStore>(
create: (_) => WatchStateStore(),
update: (_, activeProfile, multiServer, previous) {
final provider = previous ?? WatchStateOverlayProvider();
final provider = previous ?? WatchStateStore();
provider.setActiveProfileId(activeProfile.activeId);
provider.setActiveClientScopesByServer({
for (final serverId in multiServer.serverManager.serverIds)
+47 -2
View File
@@ -65,10 +65,52 @@ MediaItem? defaultPlaybackSeason(List<MediaItem> seasons) {
return season.kind == MediaKind.season ? season : null;
}
/// Index of the first season that still has unwatched episodes, preferring
/// regular seasons over specials (mirrors [defaultPlaybackSeasonIndex]). Uses
/// leafCount/viewedLeafCount, so no episodes need to be fetched. Returns null
/// when every season is fully watched (or counts are unavailable).
int? firstUnwatchedSeasonIndex(List<MediaItem> seasons) {
int? firstSpecial;
for (var i = 0; i < seasons.length; i++) {
final season = seasons[i];
if (season.kind != MediaKind.season) continue;
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
firstSpecial ??= i; // specials only count as a last resort
}
return firstSpecial;
}
/// First episode that is unwatched or still in progress, in list order.
/// Same predicate as [_collectPlayable]'s `unwatchedOnly` filter, returned in
/// the order the episodes are displayed so the highlight matches the list.
MediaItem? firstUnwatchedEpisode(List<MediaItem> episodes) {
for (final episode in episodes) {
if (episode.kind != MediaKind.episode) continue;
if (episode.isWatched && !episode.hasActiveProgress) continue;
return episode;
}
return null;
}
/// Find the season index matching an explicit navigation target or on-deck
/// episode, then fall back to [defaultPlaybackSeasonIndex].
int preferredSeasonIndex(List<MediaItem> seasons, {int? initialSeasonIndex, MediaItem? onDeckEpisode}) {
/// episode. With neither, fall back to the first season that still has
/// unwatched episodes (so a partially-watched show removed from Continue
/// Watching still opens on the right season), then [defaultPlaybackSeasonIndex].
int preferredSeasonIndex(
List<MediaItem> seasons, {
String? initialSeasonId,
int? initialSeasonIndex,
MediaItem? onDeckEpisode,
}) {
if (seasons.isEmpty) return 0;
if (initialSeasonId != null) {
final idx = seasons.indexWhere((season) => season.kind == MediaKind.season && season.id == initialSeasonId);
if (idx != -1) return idx;
}
if (initialSeasonIndex != null) {
final idx = seasons.indexWhere((season) => season.kind == MediaKind.season && season.index == initialSeasonIndex);
if (idx != -1) return idx;
@@ -88,6 +130,9 @@ int preferredSeasonIndex(List<MediaItem> seasons, {int? initialSeasonIndex, Medi
}
}
final unwatched = firstUnwatchedSeasonIndex(seasons);
if (unwatched != null) return unwatched;
return defaultPlaybackSeasonIndex(seasons);
}
+1 -1
View File
@@ -56,7 +56,7 @@ class MediaDisplayCriteria {
bool get hasDisplayMetadata =>
(doviProfile ?? 0) > 0 || _hasValue(transfer) || _hasValue(primaries) || _hasValue(matrix);
bool get canPrimeNativeDisplayCriteria => hasDimensions && hasDisplayMetadata;
bool get canPrimeNativeDisplayCriteria => hasDimensions && (hasDisplayMetadata || hasFrameRate);
bool get isHdr {
if ((doviProfile ?? 0) > 0 && doviCompatibilityId != 2) return true;
+24 -2
View File
@@ -10,6 +10,7 @@ import 'media_backend.dart';
import 'media_kind.dart';
import 'media_role.dart';
import 'media_version.dart';
import 'season_title.dart';
part 'media_item.freezed.dart';
part 'media_item.g.dart';
@@ -364,6 +365,11 @@ sealed class MediaItem with _$MediaItem {
/// `[seasonId, showId]`. For a season: `[showId]`. For a movie: `[]`.
List<String> get parentChain => [?parentId, ?grandparentId];
/// Recency used to order the Continue Watching / On Deck shelf: when the item
/// was last watched, falling back to when it was added for never-watched rows.
/// Shared by the per-client merge and the cross-server sort so they agree.
int get recencySortKey => lastViewedAt ?? addedAt ?? 0;
/// Whether this item has started but not finished playback.
bool get hasActiveProgress {
if (durationMs == null || viewOffsetMs == null) return false;
@@ -383,6 +389,16 @@ sealed class MediaItem with _$MediaItem {
return viewCount != null && viewCount! > 0;
}
/// Copy with the watched flag applied so [isWatched] reflects it for every
/// kind: containers need their leaf counts patched, not just [viewCount].
MediaItem withWatchedFlag(bool isWatched) {
var updated = copyWith(viewCount: isWatched ? 1 : 0);
if (leafCount != null || viewedLeafCount != null) {
updated = updated.copyWith(viewedLeafCount: isWatched ? (leafCount ?? viewedLeafCount ?? 1) : 0);
}
return updated;
}
/// Display-friendly title that prefers the show name for episodes/seasons.
String get displayTitle {
if ((kind == MediaKind.episode || kind == MediaKind.season) && grandparentTitle != null) {
@@ -396,8 +412,14 @@ sealed class MediaItem with _$MediaItem {
/// Subtitle line shown below [displayTitle] for episodes/seasons.
String? get displaySubtitle {
if (kind == MediaKind.episode || kind == MediaKind.season) {
if (grandparentTitle != null || (kind == MediaKind.season && parentTitle != null)) {
if (kind == MediaKind.season) {
if (grandparentTitle != null || parentTitle != null) {
// Re-localize a server's generic English "Season N" (see #1271).
final label = localizedSeasonLabel(title: title, index: index);
return label.isNotEmpty ? label : title;
}
} else if (kind == MediaKind.episode) {
if (grandparentTitle != null) {
return title;
}
}
+6
View File
@@ -1,5 +1,6 @@
import 'media_item.dart';
import 'media_kind.dart';
import 'season_title.dart';
/// Convenience type-check getters and spoiler helpers on [MediaItem]. These
/// give consumers a Plex-style fluent API (e.g. `item.isShow`) while keeping
@@ -27,4 +28,9 @@ extension MediaItemTypes on MediaItem {
/// Non-spoiler art path for episodes (show/season background).
String? get spoilerSafeArt => grandparentArtPath ?? artPath;
/// Localized season label for this item. Re-localizes a server's generic
/// English "Season N" to the app locale (see [localizedSeasonLabel]); falls
/// back to [displayTitle] when there is no usable title or index.
String get localizedSeasonTitle => localizedSeasonLabel(title: title, index: index, fallback: displayTitle);
}
+33 -2
View File
@@ -5,6 +5,7 @@ import '../services/playback_initialization_types.dart';
import '../utils/app_logger.dart';
import '../utils/media_server_http_client.dart' show AbortController, MediaServerResponse;
import '../utils/external_ids.dart';
import '../utils/watch_state_notifier.dart';
import 'download_resolution.dart';
import 'ids.dart';
import 'library_filter_result.dart';
@@ -22,6 +23,9 @@ import 'media_playlist.dart';
import 'playback_report_metadata.dart';
import 'server_capabilities.dart';
/// Default number of items requested for horizontal hub previews.
const int defaultHubPreviewLimit = 20;
/// Backend-neutral client for a single media server (Plex or Jellyfin).
///
/// Each implementation wraps the per-backend HTTP layer and exposes the same
@@ -225,7 +229,7 @@ abstract class MediaServerClient {
/// Curated home-screen hubs across all libraries (Plex Discover; Jellyfin
/// synthesizes `Latest` plus optional `Resume` + `NextUp`).
Future<List<MediaHub>> fetchGlobalHubs({int limit = 10, bool includePlaybackHubs = true});
Future<List<MediaHub>> fetchGlobalHubs({int limit = defaultHubPreviewLimit, bool includePlaybackHubs = true});
/// Hubs scoped to a single library section. [libraryName] is baked into
/// the title of synthetic hubs (Jellyfin) so per-library "Recently Added"
@@ -236,7 +240,7 @@ abstract class MediaServerClient {
Future<List<MediaHub>> fetchLibraryHubs(
String libraryId, {
required String libraryName,
int limit = 10,
int limit = defaultHubPreviewLimit,
bool includePlaybackHubs = true,
MediaKind? libraryKind,
});
@@ -472,6 +476,17 @@ abstract class MediaServerClient {
/// one and returns a fixed 0.9.
double get watchedThreshold;
/// Whether a playback-stopped report past [watchedThreshold] already marks
/// the item played server-side. When true, in-player auto-scrobble must NOT
/// also call [markWatched]: the server marks it played from the stop report,
/// and the extra `/UserPlayedItems` toggle double-scrobbles through
/// integrations that watch both the played-state change and the
/// playback-stop — e.g. Jellyfin's Trakt plugin fires once on `TogglePlayed`
/// and again on `PlayedToCompletion` (#1287). Plex returns false: its
/// timeline stop doesn't reliably mark watched without an active play
/// session, so the explicit call is still required.
bool get marksWatchedOnPlaybackStopped;
/// First playback signal for [itemId]. Plex sends a `/:/timeline?state=playing`
/// heartbeat; Jellyfin opens a `/Sessions/Playing` session row. Subsequent
/// ticks must call [reportPlaybackProgress] (Jellyfin distinguishes session
@@ -570,6 +585,22 @@ extension MediaServerClientScope on MediaServerClient {
ScopedMediaServerClient(:final scopedServerId) => scopedServerId,
_ => serverId,
};
/// Mark [item] watched because it crossed [watchedThreshold] during playback,
/// when a playback-stopped report is/was also sent for the same playback.
/// Backends that mark played from the stop report
/// ([marksWatchedOnPlaybackStopped]) only emit the local watch event —
/// issuing [markWatched] too would double-scrobble via the Jellyfin Trakt
/// plugin (#1287). The local event still keeps the UI and Plezy's own Trakt
/// sync (which key on `watched` events, not progress) in sync; the stop
/// report syncs the server.
Future<void> markWatchedFromPlaybackStop(MediaItem item) async {
if (marksWatchedOnPlaybackStopped) {
WatchStateNotifier().notifyWatched(item: item, isNowWatched: true, cacheServerId: cacheServerId);
} else {
await markWatched(item);
}
}
}
/// Cache-aware fetch helpers shared by both backends so the offline-first /
+26
View File
@@ -0,0 +1,26 @@
import '../i18n/strings.g.dart';
/// Matches a media server's generic English season title, e.g. "Season 1".
///
/// Plex and Jellyfin return this verbatim when they have no localized name for a
/// season (or when the request language resolves to English), which leaks
/// untranslated "Season N" labels into otherwise-localized UI (see #1271).
final RegExp _genericSeasonTitle = RegExp(r'^season\s+(\d+)$', caseSensitive: false);
/// Localized season label.
///
/// Replaces a generic English "Season N" (or an empty title) with the app-locale
/// `t.common.seasonNumber`, while preserving custom names ("Specials", …) and
/// titles the server already localized ("Saison 1").
///
/// Prefers [index] for the number; falls back to the digits parsed from a
/// generic title, then to [fallback] when there is nothing usable to show.
String localizedSeasonLabel({String? title, int? index, String? fallback}) {
final raw = title?.trim() ?? '';
final match = _genericSeasonTitle.firstMatch(raw);
final number = index ?? (match != null ? int.tryParse(match.group(1)!) : null);
if ((match != null || raw.isEmpty) && number != null) {
return t.common.seasonNumber(number: number);
}
return raw.isNotEmpty ? raw : (fallback ?? '');
}
+32 -12
View File
@@ -13,6 +13,11 @@ class PlayerAndroid extends PlayerBase {
bool _tunnelingEnabled = true;
String _dvConversionMode = 'auto';
/// The native plugin switched from ExoPlayer to its mpv fallback for this
/// session. Sticky for the instance lifetime, mirroring the native flag
/// (which resets only on initialize/dispose).
bool _usingMpvFallback = false;
String? _hiddenSubtitleTrackId;
@override
@@ -30,12 +35,32 @@ 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).
@override
bool get attachesExternalSubtitlesAtOpen => !_usingMpvFallback;
// The fallback runs mpv over MediaCodec — the same display-switch decoder
// constraint as PlayerNative on Android. The whole startup-gate chain
// (setVideoFrameRate, playback-restart, seek/drop-buffers refresh,
// open-paused) already routes per-core natively.
@override
bool get needsDecoderRefreshAfterDisplaySwitch => _usingMpvFallback;
@override
bool get detectsFpsAfterRender => true;
@override
bool get providesNativeStats => true;
@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.
_usingMpvFallback = true;
clearTracks();
backendSwitchedController.add(null);
return;
@@ -70,17 +95,7 @@ class PlayerAndroid extends PlayerBase {
// Register property observers before flipping `initialized` so partial
// failures don't leave us in a half-initialized state that the memoized
// future would falsely treat as ready.
await observeProperty('time-pos', 'double');
await observeProperty('duration', 'double');
await observeProperty('seekable', 'flag');
await observeProperty('pause', 'flag');
await observeProperty('paused-for-cache', 'flag');
await observeProperty('track-list', 'string');
await observeProperty('eof-reached', 'flag');
await observeProperty('volume', 'double');
await observeProperty('speed', 'double');
await observeProperty('aid', 'string');
await observeProperty('sid', 'string');
await observeCoreProperties(trackListFormat: 'string');
await observeProperty('demuxer-cache-time', 'double');
initialized = true;
@@ -283,6 +298,7 @@ class PlayerAndroid extends PlayerBase {
}
}
@override
Future<Map<String, dynamic>> getStats() async {
if (disposed) return {};
try {
@@ -303,7 +319,8 @@ class PlayerAndroid extends PlayerBase {
}
}
Future<String> getPlayerType() async {
@override
Future<String> runtimePlayerType() async {
if (disposed) return 'unknown';
try {
final result = await invoke<String>('getPlayerType');
@@ -352,6 +369,7 @@ class PlayerAndroid extends PlayerBase {
///
/// For non-ASS subtitles, applies CaptionStyleCompat (color, border, background).
/// For ASS subtitles, applies font scale via libass setFontScale().
@override
Future<void> setSubtitleStyle({
required double fontSize,
required String textColor,
@@ -379,12 +397,14 @@ class PlayerAndroid extends PlayerBase {
/// Apply the box-fit mode to the native ExoPlayer layer.
/// Maps to AspectRatioFrameLayout resize mode: 0=FIT, 1=ZOOM, 2=FILL.
@override
Future<void> setBoxFitMode(int mode) async {
if (disposed || !initialized) return;
await invoke('setBoxFitMode', {'mode': mode});
}
/// Apply custom zoom to the native ExoPlayer layer.
@override
Future<void> setVideoZoom(double scale) async {
if (disposed || !initialized) return;
await invoke('setVideoZoom', {'scale': scale});
+70 -2
View File
@@ -99,6 +99,28 @@ abstract class Player {
/// Whether this player backend supports secondary subtitle tracks.
bool get supportsSecondarySubtitles;
/// Whether this backend ingests external subtitles in [open] (single
/// prepare(), safe to auto-play immediately). Backends returning false
/// need external subtitles added after open via [addSubtitleTrack] while
/// paused, and the caller resumes once the tracks are selected.
bool get attachesExternalSubtitlesAtOpen;
/// Whether the backend detects container fps from rendered frame
/// timestamps, so `container-fps` only becomes available a few frames
/// after playback starts (retry the property read instead of giving up).
bool get detectsFpsAfterRender;
/// Whether the video decoder must be refreshed (seek-in-place or
/// drop-buffers) after a display mode switch. True for mpv on Android,
/// where MediaCodec can stall against the reconfigured surface.
bool get needsDecoderRefreshAfterDisplaySwitch;
/// Whether [getStats] aggregates performance stats natively for the
/// active backend (the Android plugin covers both ExoPlayer and its mpv
/// fallback). Backends returning false are sampled via mpv property
/// reads instead.
bool get providesNativeStats;
/// Add an external subtitle track.
///
/// [uri] - URL or path to the subtitle file.
@@ -156,7 +178,10 @@ abstract class Player {
/// Prime native display matching from server metadata before the decoder
/// emits stream properties. Unsupported platforms ignore this.
Future<void> setDisplayCriteria(MediaDisplayCriteria? criteria);
///
/// [extraDelayMs] is added after a native display-switch completion event,
/// for TVs or AVRs that need extra HDMI settle time.
Future<void> setDisplayCriteria(MediaDisplayCriteria? criteria, {int extraDelayMs = 0});
/// Configure subtitle fonts for libass rendering.
///
@@ -215,6 +240,46 @@ abstract class Player {
/// On other platforms, this is a no-op.
Future<void> clearVideoFrameRate();
/// Apply subtitle styling to the native rendering layer.
///
/// ExoPlayer renders subtitles natively (CaptionStyleCompat for text subs,
/// libass font scale for ASS), so styling must be pushed after [open].
/// No-op on mpv backends, which style subtitles via `sub-*` properties.
Future<void> setSubtitleStyle({
required double fontSize,
required String textColor,
required double borderSize,
required String borderColor,
required String bgColor,
required int bgOpacity,
int subtitlePosition = 100,
bool bold = false,
bool italic = false,
});
/// Apply the box-fit mode to the native video layer
/// (0=FIT, 1=ZOOM/cover, 2=FILL/stretch).
///
/// ExoPlayer scales via AspectRatioFrameLayout; mpv backends are a no-op
/// here and scale via `panscan`/`video-aspect-override` properties instead.
Future<void> setBoxFitMode(int mode);
/// Apply custom zoom to the native video layer. No-op on mpv backends,
/// which zoom via the `video-zoom` property.
Future<void> setVideoZoom(double scale);
/// Aggregated native playback stats (codecs, dimensions, dropped frames…).
///
/// Returns an empty map on backends without native stats aggregation;
/// query mpv properties directly there instead.
Future<Map<String, dynamic>> getStats();
/// The backend actually playing right now, resolved from the native side.
///
/// Unlike [playerType] (the configured backend), this reflects runtime
/// fallbacks — e.g. 'mpv' after ExoPlayer hit an unsupported format.
Future<String> runtimePlayerType();
/// Request audio focus before starting playback.
///
/// On Android, this notifies the system that the app wants to play audio,
@@ -237,8 +302,11 @@ abstract class Player {
/// Dispose of the player and release resources.
///
/// [preserveDisplayMode] keeps any native display-mode hint active while a
/// replacement video route is being opened. Use false when leaving playback.
///
/// After calling this, the player instance should not be used.
Future<void> dispose();
Future<void> dispose({bool preserveDisplayMode = false});
/// Creates a new player instance.
///
+74 -3
View File
@@ -98,6 +98,35 @@ abstract class PlayerBase with PlayerStreamControllersMixin implements Player {
);
}
/// The (name, format) registrations every backend makes at init — the
/// properties [handlePropertyChange] needs for core [PlayerState].
/// `track-list` is registered separately because mpv uses node format on
/// Apple platforms; backend-specific extras (mpv: secondary-sid /
/// demuxer-cache-state / audio-device*; ExoPlayer: demuxer-cache-time)
/// are appended by the subclasses.
static const List<(String, String)> corePropertyObservations = [
('time-pos', 'double'),
('duration', 'double'),
('seekable', 'flag'),
('pause', 'flag'),
('paused-for-cache', 'flag'),
('eof-reached', 'flag'),
('volume', 'double'),
('speed', 'double'),
('aid', 'string'),
('sid', 'string'),
];
/// Register [corePropertyObservations] plus `track-list` in the
/// backend's preferred format. Called from each subclass's initialize.
@protected
Future<void> observeCoreProperties({required String trackListFormat}) async {
for (final (name, format) in corePropertyObservations) {
await observeProperty(name, format);
}
await observeProperty('track-list', trackListFormat);
}
@protected
Future<void> observeProperty(String name, String format) async {
final propId = _nextPropId++;
@@ -543,7 +572,7 @@ abstract class PlayerBase with PlayerStreamControllersMixin implements Player {
}
@override
Future<void> setDisplayCriteria(MediaDisplayCriteria? criteria) async {}
Future<void> setDisplayCriteria(MediaDisplayCriteria? criteria, {int extraDelayMs = 0}) async {}
@override
Future<bool> setVisible(bool visible, {bool restoreOnWindowVisible = false}) async {
@@ -568,6 +597,34 @@ abstract class PlayerBase with PlayerStreamControllersMixin implements Player {
// ignore: no-empty-block - base no-op, overridden by platform subclasses
Future<void> clearVideoFrameRate() async {}
@override
// ignore: no-empty-block - base no-op, ExoPlayer styles subtitles natively
Future<void> setSubtitleStyle({
required double fontSize,
required String textColor,
required double borderSize,
required String borderColor,
required String bgColor,
required int bgOpacity,
int subtitlePosition = 100,
bool bold = false,
bool italic = false,
}) async {}
@override
// ignore: no-empty-block - base no-op, mpv scales via panscan/aspect-override
Future<void> setBoxFitMode(int mode) async {}
@override
// ignore: no-empty-block - base no-op, mpv zooms via the video-zoom property
Future<void> setVideoZoom(double scale) async {}
@override
Future<Map<String, dynamic>> getStats() async => const {};
@override
Future<String> runtimePlayerType() async => playerType;
@override
Future<bool> requestAudioFocus() async {
// Default returns true, overridden by Android
@@ -585,6 +642,18 @@ abstract class PlayerBase with PlayerStreamControllersMixin implements Player {
@override
bool get supportsSecondarySubtitles => true;
@override
bool get attachesExternalSubtitlesAtOpen => false;
@override
bool get detectsFpsAfterRender => false;
@override
bool get needsDecoderRefreshAfterDisplaySwitch => false;
@override
bool get providesNativeStats => false;
@override
// ignore: no-empty-block - base no-op, overridden by platform subclasses
Future<void> selectSecondarySubtitleTrack(SubtitleTrack track) async {}
@@ -669,13 +738,15 @@ abstract class PlayerBase with PlayerStreamControllersMixin implements Player {
}
@override
Future<void> dispose() async {
Future<void> dispose({bool preserveDisplayMode = false}) async {
if (_disposed) return;
_disposed = true;
await _eventSubscription?.cancel();
await _logSubscription?.cancel();
await methodChannel.invokeMethod('dispose'); // Direct call — already guarded by _disposed check above
await methodChannel.invokeMethod('dispose', {
'preserveDisplayMode': preserveDisplayMode,
}); // Direct call — already guarded by _disposed check above
await closeStreamControllers();
}
}
+17 -13
View File
@@ -112,17 +112,7 @@ class PlayerNative extends PlayerBase {
// Subscribe to MPV properties before flipping `initialized` so partial
// failures don't leave us in a half-initialized state that the memoized
// future would falsely treat as ready.
await observeProperty('time-pos', 'double');
await observeProperty('duration', 'double');
await observeProperty('seekable', 'flag');
await observeProperty('pause', 'flag');
await observeProperty('paused-for-cache', 'flag');
await observeProperty('track-list', _nodeFormat);
await observeProperty('eof-reached', 'flag');
await observeProperty('volume', 'double');
await observeProperty('speed', 'double');
await observeProperty('aid', 'string');
await observeProperty('sid', 'string');
await observeCoreProperties(trackListFormat: _nodeFormat);
await observeProperty('secondary-sid', 'string');
await observeProperty('demuxer-cache-state', _nodeFormat);
await observeProperty('audio-device-list', _nodeFormat);
@@ -195,6 +185,14 @@ class PlayerNative extends PlayerBase {
}
await command(['loadfile', uri, 'replace']);
// mpv's pause property survives loadfile; in-place reloads pause the old
// file before resolving, so explicitly unpause for the replacement. Set
// after loadfile so the paused old file never audibly unpauses
// pre-replace.
if (play) {
await setProperty('pause', 'no');
}
}
@override
@@ -295,10 +293,16 @@ class PlayerNative extends PlayerBase {
}
@override
Future<void> setDisplayCriteria(MediaDisplayCriteria? criteria) async {
bool get needsDecoderRefreshAfterDisplaySwitch => Platform.isAndroid;
@override
Future<void> setDisplayCriteria(MediaDisplayCriteria? criteria, {int extraDelayMs = 0}) async {
if (disposed || !Platform.isIOS) return;
await _ensureInitialized();
await invoke('setDisplayCriteria', {'criteria': _effectiveDisplayCriteria(criteria)?.toJson()});
await invoke('setDisplayCriteria', {
'criteria': _effectiveDisplayCriteria(criteria)?.toJson(),
'extraDelayMs': extraDelayMs,
});
}
@override
-12
View File
@@ -14,9 +14,6 @@ class PlayerState {
final double rate;
final Tracks tracks;
final TrackSelection track;
final double audioDelay;
final double subtitleDelay;
final bool audioPassthrough;
final AudioDevice audioDevice;
final List<AudioDevice> audioDevices;
final List<BufferRange> bufferRanges;
@@ -33,9 +30,6 @@ class PlayerState {
this.rate = 1.0,
this.tracks = const Tracks(),
this.track = const TrackSelection(),
this.audioDelay = 0.0,
this.subtitleDelay = 0.0,
this.audioPassthrough = false,
this.audioDevice = AudioDevice.auto,
this.audioDevices = const [],
this.bufferRanges = const [],
@@ -53,9 +47,6 @@ class PlayerState {
double? rate,
Tracks? tracks,
TrackSelection? track,
double? audioDelay,
double? subtitleDelay,
bool? audioPassthrough,
AudioDevice? audioDevice,
List<AudioDevice>? audioDevices,
List<BufferRange>? bufferRanges,
@@ -72,9 +63,6 @@ class PlayerState {
rate: rate ?? this.rate,
tracks: tracks ?? this.tracks,
track: track ?? this.track,
audioDelay: audioDelay ?? this.audioDelay,
subtitleDelay: subtitleDelay ?? this.subtitleDelay,
audioPassthrough: audioPassthrough ?? this.audioPassthrough,
audioDevice: audioDevice ?? this.audioDevice,
audioDevices: audioDevices ?? this.audioDevices,
bufferRanges: bufferRanges ?? this.bufferRanges,
@@ -1,127 +0,0 @@
import 'dart:async';
import '../media/ids.dart';
import 'package:flutter/foundation.dart';
import '../media/media_item.dart';
import '../mixins/disposable_change_notifier_mixin.dart';
import '../services/watch_state_resolver.dart';
import '../utils/global_key_utils.dart';
import '../utils/watch_state_notifier.dart';
@immutable
class WatchStateOverlayPatch {
final bool? isWatched;
final bool hasViewOffsetMs;
final int? viewOffsetMs;
const WatchStateOverlayPatch({this.isWatched, this.hasViewOffsetMs = false, this.viewOffsetMs});
factory WatchStateOverlayPatch.fromSnapshot(WatchStateSnapshot snapshot) => WatchStateOverlayPatch(
isWatched: snapshot.isWatched,
hasViewOffsetMs: snapshot.hasViewOffsetMs,
viewOffsetMs: snapshot.viewOffsetMs,
);
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is WatchStateOverlayPatch &&
other.isWatched == isWatched &&
other.hasViewOffsetMs == hasViewOffsetMs &&
other.viewOffsetMs == viewOffsetMs;
@override
int get hashCode => Object.hash(isWatched, hasViewOffsetMs, viewOffsetMs);
}
class _WatchStateOverlayEntry {
final WatchStateOverlayPatch patch;
final int sequence;
const _WatchStateOverlayEntry(this.patch, this.sequence);
}
/// Session-local watch-state overlay for immediate UI freshness.
///
/// Server fetches remain the source of truth; this only patches stale
/// [MediaItem] snapshots while a screen waits for its next refresh.
class WatchStateOverlayProvider extends ChangeNotifier with DisposableChangeNotifierMixin {
WatchStateOverlayProvider() {
_subscription = WatchStateNotifier().stream.listen(_onWatchStateEvent);
}
StreamSubscription<WatchStateEvent>? _subscription;
final Map<String, _WatchStateOverlayEntry> _patches = {};
String? _activeProfileId;
Map<String, String?> _activeClientScopesByServer = const {};
int _sequence = 0;
WatchStateOverlayPatch? patchForGlobalKey(String globalKey) {
_WatchStateOverlayEntry? scopedEntry;
final parsed = parseGlobalKey(globalKey);
if (parsed != null) {
final scoped = _activeClientScopesByServer[parsed.serverId];
if (scoped != null && scoped.isNotEmpty) {
scopedEntry = _patches[buildGlobalKey(ServerId(scoped), parsed.ratingKey)];
}
}
final unscopedEntry = _patches[globalKey];
if (scopedEntry == null) return unscopedEntry?.patch;
if (unscopedEntry == null) return scopedEntry.patch;
return scopedEntry.sequence >= unscopedEntry.sequence ? scopedEntry.patch : unscopedEntry.patch;
}
WatchStateOverlayPatch? patchForItem(MediaItem item) => patchForGlobalKey(item.globalKey);
MediaItem apply(MediaItem item) {
return applyPatch(item, patchForItem(item));
}
static MediaItem applyPatch(MediaItem item, WatchStateOverlayPatch? patch) {
if (patch == null) return item;
return WatchStateSnapshot(
isWatched: patch.isWatched,
hasViewOffsetMs: patch.hasViewOffsetMs,
viewOffsetMs: patch.viewOffsetMs,
).apply(item);
}
void setActiveProfileId(String? profileId) {
if (_activeProfileId == profileId) return;
_activeProfileId = profileId;
if (_patches.isEmpty) return;
_patches.clear();
safeNotifyListeners();
}
void setActiveClientScopesByServer(Map<String, String?> scopes) {
final normalized = <String, String?>{
for (final entry in scopes.entries)
if (entry.value != null && entry.value!.isNotEmpty && entry.value != entry.key) entry.key: entry.value,
};
if (mapEquals(_activeClientScopesByServer, normalized)) return;
_activeClientScopesByServer = Map.unmodifiable(normalized);
if (_patches.isNotEmpty) safeNotifyListeners();
}
void _onWatchStateEvent(WatchStateEvent event) {
final snapshot = WatchStateResolver.fromEvent(event);
if (snapshot.isEmpty) return;
final patch = WatchStateOverlayPatch.fromSnapshot(snapshot);
final cacheServerId = event.cacheServerId;
final key = cacheServerId != null && cacheServerId.isNotEmpty && cacheServerId != event.serverId
? buildGlobalKey(ServerId(cacheServerId), event.itemId)
: event.globalKey;
_patches[key] = _WatchStateOverlayEntry(patch, ++_sequence);
safeNotifyListeners();
}
@override
void dispose() {
_subscription?.cancel();
_subscription = null;
super.dispose();
}
}
+185
View File
@@ -0,0 +1,185 @@
import 'dart:async';
import '../media/ids.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:provider/provider.dart';
import '../media/media_item.dart';
import '../mixins/disposable_change_notifier_mixin.dart';
import '../services/watch_state_resolver.dart';
import '../utils/global_key_utils.dart';
import '../utils/watch_state_notifier.dart';
@immutable
class WatchStatePatch {
final bool? isWatched;
final bool hasViewOffsetMs;
final int? viewOffsetMs;
const WatchStatePatch({this.isWatched, this.hasViewOffsetMs = false, this.viewOffsetMs});
factory WatchStatePatch.fromSnapshot(WatchStateSnapshot snapshot) => WatchStatePatch(
isWatched: snapshot.isWatched,
hasViewOffsetMs: snapshot.hasViewOffsetMs,
viewOffsetMs: snapshot.viewOffsetMs,
);
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is WatchStatePatch &&
other.isWatched == isWatched &&
other.hasViewOffsetMs == hasViewOffsetMs &&
other.viewOffsetMs == viewOffsetMs;
@override
int get hashCode => Object.hash(isWatched, hasViewOffsetMs, viewOffsetMs);
}
class _WatchStatePatchEntry {
final WatchStatePatch patch;
final int sequence;
const _WatchStatePatchEntry(this.patch, this.sequence);
}
/// The single session-local layer for watch-state freshness.
///
/// Server fetches remain the source of truth; [MediaItem] snapshots are never
/// hand-mutated to reflect watch events. Instead, every watch event lands here
/// as a patch, and consumers resolve items at point of use ([apply] /
/// [patchForItem]). Resolution is hierarchy-aware: an item's effective patch
/// is the newest among its own and its [MediaItem.parentChain] ancestors', so
/// marking a show/season reaches every descendant, while a later per-item
/// event still overrides an older container mark.
class WatchStateStore extends ChangeNotifier with DisposableChangeNotifierMixin {
WatchStateStore() {
_subscription = WatchStateNotifier().stream.listen(_onWatchStateEvent);
}
StreamSubscription<WatchStateEvent>? _subscription;
final Map<String, _WatchStatePatchEntry> _patches = {};
String? _activeProfileId;
Map<String, String?> _activeClientScopesByServer = const {};
int _sequence = 0;
_WatchStatePatchEntry? _entryFor(String globalKey) {
_WatchStatePatchEntry? scopedEntry;
final parsed = parseGlobalKey(globalKey);
if (parsed != null) {
final scoped = _activeClientScopesByServer[parsed.serverId];
if (scoped != null && scoped.isNotEmpty) {
scopedEntry = _patches[buildGlobalKey(ServerId(scoped), parsed.ratingKey)];
}
}
final unscopedEntry = _patches[globalKey];
if (scopedEntry == null) return unscopedEntry;
if (unscopedEntry == null) return scopedEntry;
return scopedEntry.sequence >= unscopedEntry.sequence ? scopedEntry : unscopedEntry;
}
WatchStatePatch? patchForGlobalKey(String globalKey) => _entryFor(globalKey)?.patch;
WatchStatePatch? patchForItem(MediaItem item) {
var best = _entryFor(item.globalKey);
if (item.parentChain.isNotEmpty) {
final serverId = serverIdOrNull(item.serverId);
for (final parentId in item.parentChain) {
// Mirror MediaItem.globalKey's bare-id fallback when serverId is missing.
final entry = _entryFor(serverId != null ? buildGlobalKey(serverId, parentId) : parentId);
if (entry != null && (best == null || entry.sequence > best.sequence)) best = entry;
}
}
return best?.patch;
}
MediaItem apply(MediaItem item) {
return applyPatch(item, patchForItem(item));
}
List<MediaItem> applyAll(List<MediaItem> items) {
if (_patches.isEmpty) return items;
return [for (final item in items) apply(item)];
}
static MediaItem applyPatch(MediaItem item, WatchStatePatch? patch) {
if (patch == null) return item;
return WatchStateSnapshot(
isWatched: patch.isWatched,
hasViewOffsetMs: patch.hasViewOffsetMs,
viewOffsetMs: patch.viewOffsetMs,
).apply(item);
}
void setActiveProfileId(String? profileId) {
if (_activeProfileId == profileId) return;
_activeProfileId = profileId;
if (_patches.isEmpty) return;
_patches.clear();
safeNotifyListeners();
}
void setActiveClientScopesByServer(Map<String, String?> scopes) {
final normalized = <String, String?>{
for (final entry in scopes.entries)
if (entry.value != null && entry.value!.isNotEmpty && entry.value != entry.key) entry.key: entry.value,
};
if (mapEquals(_activeClientScopesByServer, normalized)) return;
_activeClientScopesByServer = Map.unmodifiable(normalized);
if (_patches.isNotEmpty) safeNotifyListeners();
}
void _onWatchStateEvent(WatchStateEvent event) {
final snapshot = WatchStateResolver.fromEvent(event);
if (snapshot.isEmpty) return;
final patch = WatchStatePatch.fromSnapshot(snapshot);
final cacheServerId = event.cacheServerId;
final key = cacheServerId != null && cacheServerId.isNotEmpty && cacheServerId != event.serverId
? buildGlobalKey(ServerId(cacheServerId), event.itemId)
: event.globalKey;
_patches[key] = _WatchStatePatchEntry(patch, ++_sequence);
safeNotifyListeners();
}
@override
void dispose() {
_subscription?.cancel();
_subscription = null;
super.dispose();
}
}
/// Point-of-use watch-state resolution. All fall back to the item as-is when
/// no [WatchStateStore] is in the tree (tests, isolated subtrees).
extension WatchStateResolution on BuildContext {
/// Build-time resolution: subscribes this context to the item's effective
/// patch, so the widget rebuilds when a newer event lands for it (or an
/// ancestor). Use in `build`.
MediaItem withFreshWatchState(MediaItem item) {
try {
final patch = select<WatchStateStore, WatchStatePatch?>((store) => store.patchForItem(item));
return WatchStateStore.applyPatch(item, patch);
} on ProviderNotFoundException {
return item;
}
}
/// Point-in-time resolution for handlers and non-build code paths.
MediaItem readFreshWatchState(MediaItem item) {
try {
return read<WatchStateStore>().apply(item);
} on ProviderNotFoundException {
return item;
}
}
List<MediaItem> readFreshWatchStateAll(List<MediaItem> items) {
try {
return read<WatchStateStore>().applyAll(items);
} on ProviderNotFoundException {
return items;
}
}
}
+124 -82
View File
@@ -14,6 +14,7 @@ import '../focus/key_event_utils.dart';
import '../utils/global_key_utils.dart';
import 'package:cached_network_image_ce/cached_network_image.dart';
import '../services/apple_tv_remote_touch_service.dart';
import '../services/image_cache_service.dart';
import '../media/media_item.dart';
import '../media/media_item_types.dart';
@@ -26,6 +27,7 @@ import '../providers/multi_server_provider.dart';
import '../providers/hidden_libraries_provider.dart';
import '../providers/libraries_provider.dart';
import '../providers/playback_state_provider.dart';
import '../providers/watch_state_store.dart';
import '../widgets/hub_section.dart';
import '../widgets/app_menu.dart';
import '../widgets/clickable_cursor.dart';
@@ -57,6 +59,7 @@ import '../utils/app_logger.dart';
import '../utils/dialogs.dart';
import '../utils/formatters.dart';
import '../utils/media_hub_ordering.dart';
import '../utils/media_navigation_helper.dart';
import '../utils/provider_extensions.dart';
import '../utils/video_player_navigation.dart';
import '../utils/layout_constants.dart';
@@ -147,6 +150,8 @@ class _DiscoverScreenState extends State<DiscoverScreen>
LibrariesProvider? _librariesProvider;
Set<String> _lastSeenHiddenKeys = {};
List<String> _lastSeenLibraryOrderKeys = const [];
Future<void>? _systemShelfSyncFuture;
List<MediaItem>? _pendingSystemShelfItems;
// WatchStateAware: watch on-deck items and their parent shows/seasons
@override
@@ -212,6 +217,7 @@ class _DiscoverScreenState extends State<DiscoverScreen>
// Hero and app bar focus
late FocusNode _heroFocusNode;
final _actionBarKey = GlobalKey<FocusableActionBarState>();
final _serverActivitiesButtonKey = GlobalKey<ServerActivitiesButtonState>();
final _userMenuKey = GlobalKey<AppMenuButtonState<String>>();
/// Backend-neutral hero client lookup. Returns the actual
@@ -533,7 +539,7 @@ class _DiscoverScreenState extends State<DiscoverScreen>
},
onSelect: () {
if (_onDeck.isNotEmpty && _currentHeroIndex < _onDeck.length) {
navigateToVideoPlayer(context, metadata: _onDeck[_currentHeroIndex]);
navigateToMediaItem(context, _onDeck[_currentHeroIndex], playDirectly: true);
}
},
)(node, event);
@@ -546,6 +552,7 @@ class _DiscoverScreenState extends State<DiscoverScreen>
WidgetsBinding.instance.removeObserver(this);
_autoScrollTimer?.cancel();
_indicatorTimer?.cancel();
_pendingSystemShelfItems = null;
_indicatorProgress.dispose();
_heroController.dispose();
_scrollController.dispose();
@@ -900,14 +907,36 @@ class _DiscoverScreenState extends State<DiscoverScreen>
/// Sync Continue Watching items to the platform launcher shelf.
Future<void> _syncSystemShelf(List<MediaItem> onDeck) async {
_pendingSystemShelfItems = List<MediaItem>.unmodifiable(onDeck);
if (_systemShelfSyncFuture != null) {
await _systemShelfSyncFuture;
return;
}
final syncFuture = _drainSystemShelfSyncQueue();
_systemShelfSyncFuture = syncFuture;
await syncFuture;
}
Future<void> _drainSystemShelfSyncQueue() async {
try {
await SystemShelfService().syncFromContinueWatching(
onDeck,
(serverId) => context.getMediaClientWithFallback(serverId),
hideSpoilers: context.settingsRead(SettingsService.hideSpoilers),
);
} catch (e) {
appLogger.w('Failed to sync system shelf', error: e);
while (_pendingSystemShelfItems != null) {
final onDeck = _pendingSystemShelfItems!;
_pendingSystemShelfItems = null;
if (!mounted) return;
try {
await SystemShelfService().syncFromContinueWatching(
onDeck,
(serverId) => context.getMediaClientWithFallback(serverId),
hideSpoilers: context.settingsRead(SettingsService.hideSpoilers),
);
} catch (e) {
appLogger.w('Failed to sync system shelf', error: e);
}
}
} finally {
_systemShelfSyncFuture = null;
}
}
@@ -1334,7 +1363,10 @@ class _DiscoverScreenState extends State<DiscoverScreen>
// a permanently empty popover.
if (PlatformDetector.isDesktop(context) &&
context.select<MultiServerProvider, bool>((p) => p.hasOnlinePlexServers))
const FocusableAction(child: ServerActivitiesButton()),
FocusableAction(
onPressed: () => _serverActivitiesButtonKey.currentState?.togglePanel(),
child: ServerActivitiesButton(key: _serverActivitiesButtonKey),
),
// User menu — profiles + sign out
_buildUserMenuAction(context),
],
@@ -1611,6 +1643,9 @@ class _DiscoverScreenState extends State<DiscoverScreen>
onNavigateToSidebar: _navigateToSidebar,
tallPosterScale: TvBrowseRailLayout.compactTallPosterScale,
backgroundBleedLeft: sidebarBleed,
selectSuppressionGestureSignal: PlatformDetector.isAppleTV()
? AppleTvRemoteTouchService.instance.touchActiveListenable
: null,
),
),
SideNavigationBleedBuilder(
@@ -1785,8 +1820,8 @@ class _DiscoverScreenState extends State<DiscoverScreen>
child: ClickableCursor(
child: GestureDetector(
onTap: () {
appLogger.d('Navigating to VideoPlayerScreen for: ${heroItem.title}');
navigateToVideoPlayer(context, metadata: heroItem);
appLogger.d('Activating hero item: ${heroItem.title}');
navigateToMediaItem(context, heroItem, playDirectly: true);
},
child: Stack(
fit: StackFit.expand,
@@ -2049,84 +2084,91 @@ class _DiscoverScreenState extends State<DiscoverScreen>
);
}
Widget _buildSmartPlayButton(MediaItem heroItem) {
final hasProgress = heroItem.hasActiveProgress;
final isTv = PlatformDetector.isTV();
Widget _buildSmartPlayButton(MediaItem rawHeroItem) {
return Builder(
builder: (context) {
// The on-deck snapshot refetches shortly after a watch event; the store
// patch bridges the gap so "minutes left" never lags.
final heroItem = context.withFreshWatchState(rawHeroItem);
final hasProgress = heroItem.hasActiveProgress;
final isTv = PlatformDetector.isTV();
final minutesLeft = hasProgress ? ((heroItem.durationMs! - heroItem.viewOffsetMs!) / 60_000).round() : 0;
final minutesLeft = hasProgress ? ((heroItem.durationMs! - heroItem.viewOffsetMs!) / 60_000).round() : 0;
final progress = hasProgress ? heroItem.viewOffsetMs! / heroItem.durationMs! : 0.0;
final progress = hasProgress ? heroItem.viewOffsetMs! / heroItem.durationMs! : 0.0;
return ListenableBuilder(
listenable: _heroFocusNode,
builder: (context, _) {
final showFocus = isTv && _heroFocusNode.hasFocus && InputModeTracker.isKeyboardMode(context);
final colorScheme = Theme.of(context).colorScheme;
final backgroundColor = showFocus ? colorScheme.primary : Colors.white;
final foregroundColor = showFocus ? colorScheme.onPrimary : Colors.black;
return InkWell(
onTap: () {
appLogger.d('Playing: ${heroItem.title}');
navigateToVideoPlayer(context, metadata: heroItem);
},
borderRadius: BorderRadius.all(Radius.circular(isTv ? 32 : 24)),
child: AnimatedContainer(
duration: const Duration(milliseconds: 150),
curve: Curves.easeOutCubic,
padding: .symmetric(horizontal: isTv ? 34 : 24, vertical: isTv ? 16 : 12),
decoration: BoxDecoration(
color: backgroundColor,
return ListenableBuilder(
listenable: _heroFocusNode,
builder: (context, _) {
final showFocus = isTv && _heroFocusNode.hasFocus && InputModeTracker.isKeyboardMode(context);
final colorScheme = Theme.of(context).colorScheme;
final backgroundColor = showFocus ? colorScheme.primary : Colors.white;
final foregroundColor = showFocus ? colorScheme.onPrimary : Colors.black;
return InkWell(
onTap: () {
appLogger.d('Playing: ${heroItem.title}');
navigateToVideoPlayer(context, metadata: heroItem);
},
borderRadius: BorderRadius.all(Radius.circular(isTv ? 32 : 24)),
boxShadow: showFocus
? [BoxShadow(color: colorScheme.primary.withValues(alpha: 0.35), blurRadius: 28, spreadRadius: 4)]
: null,
),
child: Row(
mainAxisSize: .min,
children: [
AppIcon(Symbols.play_arrow_rounded, fill: 1, size: isTv ? 28 : 20, color: foregroundColor),
SizedBox(width: isTv ? 12 : 8),
if (hasProgress) ...[
// Progress bar
Container(
width: isTv ? 56 : 40,
height: isTv ? 8 : 6,
decoration: BoxDecoration(
color: foregroundColor.withValues(alpha: 0.25),
borderRadius: BorderRadius.all(Radius.circular(isTv ? 4 : 3)),
),
child: FractionallySizedBox(
alignment: .centerLeft,
widthFactor: progress,
child: Container(
child: AnimatedContainer(
duration: const Duration(milliseconds: 150),
curve: Curves.easeOutCubic,
padding: .symmetric(horizontal: isTv ? 34 : 24, vertical: isTv ? 16 : 12),
decoration: BoxDecoration(
color: backgroundColor,
borderRadius: BorderRadius.all(Radius.circular(isTv ? 32 : 24)),
boxShadow: showFocus
? [BoxShadow(color: colorScheme.primary.withValues(alpha: 0.35), blurRadius: 28, spreadRadius: 4)]
: null,
),
child: Row(
mainAxisSize: .min,
children: [
AppIcon(Symbols.play_arrow_rounded, fill: 1, size: isTv ? 28 : 20, color: foregroundColor),
SizedBox(width: isTv ? 12 : 8),
if (hasProgress) ...[
// Progress bar
Container(
width: isTv ? 56 : 40,
height: isTv ? 8 : 6,
decoration: BoxDecoration(
color: foregroundColor,
borderRadius: BorderRadius.all(Radius.circular(isTv ? 3 : 2)),
color: foregroundColor.withValues(alpha: 0.25),
borderRadius: BorderRadius.all(Radius.circular(isTv ? 4 : 3)),
),
child: FractionallySizedBox(
alignment: .centerLeft,
widthFactor: progress,
child: Container(
decoration: BoxDecoration(
color: foregroundColor,
borderRadius: BorderRadius.all(Radius.circular(isTv ? 3 : 2)),
),
),
),
),
),
),
SizedBox(width: isTv ? 12 : 8),
Text(
t.discover.minutesLeft(minutes: minutesLeft),
style: TextStyle(
color: foregroundColor,
fontSize: isTv ? 18 : 14,
fontWeight: isTv ? FontWeight.w700 : FontWeight.w600,
),
),
] else
Text(
t.common.play,
style: TextStyle(
color: foregroundColor,
fontSize: isTv ? 18 : 14,
fontWeight: isTv ? FontWeight.w700 : FontWeight.w600,
),
),
],
),
),
SizedBox(width: isTv ? 12 : 8),
Text(
t.discover.minutesLeft(minutes: minutesLeft),
style: TextStyle(
color: foregroundColor,
fontSize: isTv ? 18 : 14,
fontWeight: isTv ? FontWeight.w700 : FontWeight.w600,
),
),
] else
Text(
t.common.play,
style: TextStyle(
color: foregroundColor,
fontSize: isTv ? 18 : 14,
fontWeight: isTv ? FontWeight.w700 : FontWeight.w600,
),
),
],
),
),
);
},
);
},
);
+5 -6
View File
@@ -14,6 +14,7 @@ import '../widgets/settings_builder.dart';
import '../utils/app_logger.dart';
import '../utils/grid_size_calculator.dart';
import '../utils/platform_detector.dart';
import '../utils/plex_library_section_utils.dart';
import '../utils/provider_extensions.dart';
import '../widgets/focusable_media_card.dart';
import '../widgets/ios_status_bar_tap_scroll_to_top.dart';
@@ -130,20 +131,18 @@ class _HubDetailScreenState extends State<HubDetailScreen>
// Hub ids can have various formats:
// - /hubs/sections/1/... (Plex)
// - /library/sections/1/all?... (Plex)
// - /hubs/home/recentlyAdded?type=2&sectionID=1 (Plex home hubs — id in query)
// - home.recent / library.<id>.continue (Jellyfin synthesized)
final hubKey = widget.hub.id;
appLogger.d('Hub key: $hubKey');
RegExpMatch? match = RegExp(r'/hubs/sections/(\d+)').firstMatch(hubKey);
match ??= RegExp(r'/library/sections/(\d+)').firstMatch(hubKey);
match ??= RegExp(r'sections/(\d+)').firstMatch(hubKey);
final sectionId = plexLibrarySectionIdFromString(hubKey);
if (match != null) {
final sectionId = match.group(1)!;
if (sectionId != null) {
appLogger.d('Loading sorts for section: $sectionId');
final client = context.tryGetMediaClientForServer(ServerId(serverId));
final sorts = client == null ? const <MediaSort>[] : await client.fetchSortOptions(sectionId);
final sorts = client == null ? const <MediaSort>[] : await client.fetchSortOptions('$sectionId');
appLogger.d('Loaded ${sorts.length} sorts');
@@ -5,6 +5,7 @@ import 'package:flutter/material.dart';
import 'package:plezy/widgets/app_icon.dart';
import 'package:material_symbols_icons/symbols.dart';
import '../../focus/focusable_button.dart';
import '../../providers/watch_state_store.dart';
import '../../focus/focusable_wrapper.dart';
import '../../media/media_item.dart';
import '../../media/media_item_types.dart';
@@ -72,6 +73,8 @@ class FolderTreeItem extends StatelessWidget {
return item.displayTitle;
}
MediaItem _effectiveItem(BuildContext context) => context.withFreshWatchState(item);
String? _dedupeSubtitle(String? subtitle) {
final value = subtitle?.trim();
if (value == null || value.isEmpty || value == _rowTitle()) return null;
@@ -271,6 +274,8 @@ class FolderTreeItem extends StatelessWidget {
}
Widget _buildWatchOverlay(BuildContext context, bool showUnwatchedCount) {
// Shadows the field with the session-fresh view; everything below reads it.
final item = _effectiveItem(context);
final hasActiveProgress = item.hasActiveProgress;
return Stack(
@@ -7,6 +7,7 @@ import 'package:material_symbols_icons/symbols.dart';
import '../../../i18n/strings.g.dart';
import '../../../media/media_hub.dart';
import '../../../media/media_item.dart';
import '../../../media/media_server_client.dart';
import '../../../mixins/item_updatable.dart';
import '../../../mixins/watch_state_aware.dart';
import '../../../services/settings_service.dart';
@@ -185,7 +186,7 @@ class _LibraryRecommendedTabState extends BaseLibraryTabState<MediaHub, LibraryR
await client.fetchLibraryHubs(
widget.library.id,
libraryName: widget.library.title,
limit: 12,
limit: defaultHubPreviewLimit,
libraryKind: widget.library.kind,
),
);
+248 -285
View File
@@ -26,6 +26,7 @@ import '../media/media_hub.dart';
import '../utils/provider_extensions.dart';
import '../utils/plex_season_display.dart';
import '../media/media_item.dart';
import '../media/season_title.dart';
import '../media/episode_collection.dart';
import '../media/media_item_types.dart';
import '../media/media_kind.dart';
@@ -52,6 +53,7 @@ import '../utils/grid_size_calculator.dart';
import '../utils/layout_constants.dart';
import '../providers/download_provider.dart';
import '../providers/offline_watch_provider.dart';
import '../providers/watch_state_store.dart';
import '../theme/mono_tokens.dart';
import '../utils/app_logger.dart';
import '../utils/formatters.dart';
@@ -180,22 +182,6 @@ class _SeasonEpisodePager {
if (changed) _states[entry.key] = entry.value.replaceItems(next);
}
}
void patchWhere(bool Function(String seasonId, MediaItem episode) test, MediaItem Function(MediaItem episode) patch) {
for (final entry in _states.entries.toList()) {
var changed = false;
final next = <MediaItem>[];
for (final episode in entry.value.items) {
if (test(entry.key, episode)) {
changed = true;
next.add(patch(episode));
} else {
next.add(episode);
}
}
if (changed) _states[entry.key] = entry.value.replaceItems(next);
}
}
}
class MediaDetailScreen extends StatefulWidget {
@@ -205,15 +191,36 @@ class MediaDetailScreen extends StatefulWidget {
/// If provided, auto-selects this season index when the screen loads.
/// Used when navigating to a show from a season context.
final int? initialSeasonIndex;
final String? initialSeasonId;
final String? initialEpisodeId;
const MediaDetailScreen({super.key, required this.metadata, this.isOffline = false, this.initialSeasonIndex});
const MediaDetailScreen({
super.key,
required this.metadata,
this.isOffline = false,
this.initialSeasonIndex,
this.initialSeasonId,
this.initialEpisodeId,
});
@override
State<MediaDetailScreen> createState() => _MediaDetailScreenState();
}
PageRoute<bool> mediaDetailRoute({required MediaItem metadata, bool isOffline = false, int? initialSeasonIndex}) {
final page = MediaDetailScreen(metadata: metadata, isOffline: isOffline, initialSeasonIndex: initialSeasonIndex);
PageRoute<bool> mediaDetailRoute({
required MediaItem metadata,
bool isOffline = false,
int? initialSeasonIndex,
String? initialSeasonId,
String? initialEpisodeId,
}) {
final page = MediaDetailScreen(
metadata: metadata,
isOffline: isOffline,
initialSeasonIndex: initialSeasonIndex,
initialSeasonId: initialSeasonId,
initialEpisodeId: initialEpisodeId,
);
if (!PlatformDetector.isTV()) return MaterialPageRoute<bool>(builder: (_) => page);
return PageRouteBuilder<bool>(
@@ -245,7 +252,6 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
bool _showEpisodesDirectly = false;
MediaItem? _fullMetadata;
MediaItem? _onDeckEpisode;
final Map<String, int> _localProgressById = {};
bool _isLoadingMetadata = true;
List<MediaItem>? _extras;
List<MediaHub> _relatedHubs = [];
@@ -300,8 +306,12 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
final ScrollController _seasonTabsScrollController = ScrollController();
final FocusNode _firstEpisodeFocusNode = FocusNode(debugLabel: 'first_episode');
final FocusNode _lastEpisodeFocusNode = FocusNode(debugLabel: 'last_episode');
final FocusNode _initialEpisodeFocusNode = FocusNode(debugLabel: 'initial_episode');
String? _lastEpisodeFocusPinnedKey;
bool _suppressNextLastEpisodeFocusLoad = false;
bool _initialDetailFocusApplied = false;
bool _initialEpisodePagingInFlight = false;
bool _initialEpisodePagingDone = false;
static const int _episodesPageSize = 200;
// Sentinel at the end of the inline episode list; its viewport position drives
// lazy paging (the list is shrink-wrapped, so it can't self-detect near-end).
@@ -378,25 +388,14 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
@override
void onWatchStateChanged(WatchStateEvent event) {
_watchStateChanged = true;
final epIndex = _episodes.indexWhere((e) => e.id == event.itemId);
if (event.changeType == WatchStateChangeType.removedFromContinueWatching) return;
if (event.changeType == WatchStateChangeType.removedFromContinueWatching) {
return;
}
// Lists keep their server snapshots untouched; cards and the hero resolve
// them against [WatchStateStore] at build, so a rebuild is all the
// visuals need.
setStateIfMounted(() {});
if (event.changeType == WatchStateChangeType.progressUpdate) {
if (event.viewOffset != null) {
_patchLocalProgress(event.itemId, event.viewOffset!, epIndex: epIndex);
}
if (event.isNowWatched != true) return;
}
_localProgressById.remove(event.itemId);
_patchWatchedStateFromEvent(
event,
epIndex: epIndex,
clearWatchedProgress: !widget.isOffline || event.changeType == WatchStateChangeType.progressUpdate,
);
if (event.changeType == WatchStateChangeType.progressUpdate && event.isNowWatched != true) return;
if (widget.isOffline) {
if (_metadata.isShow) {
@@ -407,190 +406,22 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
// Online: refresh server-derived counters and on-deck state. A watched
// episode can change the hero play target even when the episode row itself
// was already visible and patched locally.
// was already visible.
unawaited(_refreshWatchState());
}
void _patchWatchedStateFromEvent(WatchStateEvent event, {required int epIndex, required bool clearWatchedProgress}) {
final isWatched = event.isNowWatched;
if (isWatched == null) return;
/// Session-fresh view of [item]: server snapshot + newest watch-state patch.
MediaItem _fresh(MediaItem item) => context.readFreshWatchState(item);
setStateIfMounted(() {
final base = _fullMetadata ?? widget.metadata;
final episodeDelta = epIndex == -1 ? 0 : _watchStateDelta(_episodes[epIndex], isWatched);
if (base.id == event.itemId) {
_fullMetadata = _withWatchedPatch(base, isWatched, clearWatchedProgress: clearWatchedProgress);
}
final onDeckEpisode = _onDeckEpisode;
if (onDeckEpisode != null && onDeckEpisode.id == event.itemId) {
_onDeckEpisode = _withWatchedPatch(onDeckEpisode, isWatched, clearWatchedProgress: clearWatchedProgress);
}
_patchWatchedInListWhere(
_seasons,
(item) => item.id == event.itemId,
isWatched,
clearWatchedProgress: clearWatchedProgress,
);
_patchWatchedInListWhere(
_episodes,
(item) => item.id == event.itemId,
isWatched,
clearWatchedProgress: clearWatchedProgress,
);
_seasonEpisodePager.patchWhere(
(_, item) => item.id == event.itemId,
(item) => _withWatchedPatch(item, isWatched, clearWatchedProgress: clearWatchedProgress),
);
final extras = _extras;
if (extras != null) {
_patchWatchedInListWhere(
extras,
(item) => item.id == event.itemId,
isWatched,
clearWatchedProgress: clearWatchedProgress,
);
}
_relatedHubs = _patchWatchedInHubs(
_relatedHubs,
(item) => item.id == event.itemId,
isWatched,
clearWatchedProgress: clearWatchedProgress,
);
if (base.id == event.itemId || _seasons.any((season) => season.id == event.itemId)) {
_patchLoadedDescendantsOf(event.itemId, isWatched, clearWatchedProgress: clearWatchedProgress);
} else if (episodeDelta != 0) {
_adjustParentWatchCounts(event.parentChain, episodeDelta);
}
_syncFlattenEpisodeState();
});
}
MediaItem _withWatchedPatch(MediaItem item, bool isWatched, {required bool clearWatchedProgress}) {
final viewOffsetMs = isWatched && !clearWatchedProgress ? null : 0;
var updated = item.copyWith(viewCount: isWatched ? 1 : 0);
if (item.leafCount != null || item.viewedLeafCount != null) {
updated = updated.copyWith(viewedLeafCount: isWatched ? (item.leafCount ?? item.viewedLeafCount ?? 1) : 0);
}
return viewOffsetMs == null ? updated : updated.copyWith(viewOffsetMs: viewOffsetMs);
}
int _watchStateDelta(MediaItem item, bool isWatched) {
if (item.isWatched == isWatched) return 0;
return isWatched ? 1 : -1;
}
void _patchWatchedInListWhere(
List<MediaItem> items,
bool Function(MediaItem item) test,
bool isWatched, {
required bool clearWatchedProgress,
}) {
for (var i = 0; i < items.length; i++) {
if (test(items[i])) {
items[i] = _withWatchedPatch(items[i], isWatched, clearWatchedProgress: clearWatchedProgress);
}
}
}
List<MediaHub> _patchWatchedInHubs(
List<MediaHub> hubs,
bool Function(MediaItem item) test,
bool isWatched, {
required bool clearWatchedProgress,
}) {
var changed = false;
final updatedHubs = <MediaHub>[];
for (final hub in hubs) {
var hubChanged = false;
final items = List<MediaItem>.of(hub.items);
_patchWatchedInListWhere(
items,
(item) {
final matches = test(item);
hubChanged = hubChanged || matches;
return matches;
},
isWatched,
clearWatchedProgress: clearWatchedProgress,
);
changed = changed || hubChanged;
updatedHubs.add(hubChanged ? hub.copyWith(items: items) : hub);
}
return changed ? updatedHubs : hubs;
}
void _patchLoadedDescendantsOf(String parentId, bool isWatched, {required bool clearWatchedProgress}) {
bool isDescendant(MediaItem item) => item.parentChain.contains(parentId);
_patchWatchedInListWhere(_seasons, isDescendant, isWatched, clearWatchedProgress: clearWatchedProgress);
_patchWatchedInListWhere(_episodes, isDescendant, isWatched, clearWatchedProgress: clearWatchedProgress);
_seasonEpisodePager.patchWhere(
(seasonId, item) => seasonId == parentId || isDescendant(item),
(item) => _withWatchedPatch(item, isWatched, clearWatchedProgress: clearWatchedProgress),
);
}
void _adjustParentWatchCounts(List<String> parentIds, int delta) {
if (parentIds.isEmpty) return;
final parentIdSet = parentIds.toSet();
final base = _fullMetadata ?? widget.metadata;
if (parentIdSet.contains(base.id)) {
_fullMetadata = _withAdjustedViewedLeafCount(base, delta);
}
for (var i = 0; i < _seasons.length; i++) {
if (parentIdSet.contains(_seasons[i].id)) {
_seasons[i] = _withAdjustedViewedLeafCount(_seasons[i], delta);
}
}
}
MediaItem _withAdjustedViewedLeafCount(MediaItem item, int delta) {
final viewedLeafCount = item.viewedLeafCount;
if (viewedLeafCount == null) return item;
final max = item.leafCount ?? (1 << 30);
final next = (viewedLeafCount + delta).clamp(0, max).toInt();
return item.copyWith(viewedLeafCount: next);
}
void _patchLocalProgress(String itemId, int viewOffset, {int? epIndex}) {
_localProgressById[itemId] = viewOffset;
setStateIfMounted(() {
final base = _fullMetadata ?? widget.metadata;
if (base.id == itemId) {
_fullMetadata = base.copyWith(viewOffsetMs: viewOffset);
}
final onDeckEpisode = _onDeckEpisode;
if (onDeckEpisode != null && onDeckEpisode.id == itemId) {
_onDeckEpisode = onDeckEpisode.copyWith(viewOffsetMs: viewOffset);
}
final index = epIndex ?? _episodes.indexWhere((e) => e.id == itemId);
if (index != -1) {
final updated = _episodes[index].copyWith(viewOffsetMs: viewOffset);
_episodes[index] = updated;
_syncEpisodeToCache(index, updated);
}
});
}
MediaItem _applyLocalProgress(MediaItem item) {
if (!_localProgressById.containsKey(item.id)) return item;
return item.copyWith(viewOffsetMs: _localProgressById[item.id]!);
}
List<MediaItem> _freshAll(List<MediaItem> items) => context.readFreshWatchStateAll(items);
MediaItem _normalizeRefreshedItem(MediaItem item, MediaItem fallback) {
return _applyLocalProgress(
_withFallbackLibrary(
item.copyWith(
serverId: item.serverId ?? fallback.serverId ?? _metadata.serverId,
serverName: item.serverName ?? fallback.serverName ?? _metadata.serverName,
),
fallback,
return _withFallbackLibrary(
item.copyWith(
serverId: item.serverId ?? fallback.serverId ?? _metadata.serverId,
serverName: item.serverName ?? fallback.serverName ?? _metadata.serverName,
),
fallback,
);
}
@@ -780,19 +611,15 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
final metadata = result.item;
final onDeckEpisode = result.onDeckEpisode;
if (metadata != null) {
final refreshedMetadata = _applyLocalProgress(
_withFallbackLibrary(
metadata.copyWith(serverId: serverId, serverName: serverName ?? metadata.serverName),
_metadata,
),
final refreshedMetadata = _withFallbackLibrary(
metadata.copyWith(serverId: serverId, serverName: serverName ?? metadata.serverName),
_metadata,
);
final refreshedOnDeck = onDeckEpisode == null
? null
: _applyLocalProgress(
_withFallbackLibrary(
onDeckEpisode.copyWith(serverId: serverId, serverName: serverName ?? onDeckEpisode.serverName),
refreshedMetadata,
),
: _withFallbackLibrary(
onDeckEpisode.copyWith(serverId: serverId, serverName: serverName ?? onDeckEpisode.serverName),
refreshedMetadata,
);
setStateIfMounted(() {
_fullMetadata = refreshedMetadata;
@@ -963,6 +790,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
_firstEpisodeFocusNode.dispose();
_lastEpisodeFocusNode.removeListener(_onLastEpisodeFocusChanged);
_lastEpisodeFocusNode.dispose();
_initialEpisodeFocusNode.dispose();
super.dispose();
}
@@ -1424,7 +1252,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
: await context.read<DownloadProvider>().lookupOfflineMetadata(serverId, _metadata.id);
if (!mounted) return;
setState(() {
_fullMetadata = _applyLocalProgress(cachedMetadata ?? _metadata);
_fullMetadata = cachedMetadata ?? _metadata;
_isLoadingMetadata = false;
_hasLoadedExtras = true;
_hasLoadedRelatedHubs = true;
@@ -1452,7 +1280,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
// Truly orphaned item (server gone) — fall back to widget metadata
// and let downstream loaders no-op gracefully.
setState(() {
_fullMetadata = _applyLocalProgress(_metadata);
_fullMetadata = _metadata;
_isLoadingMetadata = false;
_hasLoadedSeasons = true;
_hasLoadedEpisodes = true;
@@ -1472,22 +1300,18 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
final serverId = _metadata.serverId;
final serverName = _metadata.serverName;
final source = metadata ?? _metadata;
final base = _applyLocalProgress(
_withFallbackLibrary(
source.copyWith(serverId: serverId ?? source.serverId, serverName: serverName ?? source.serverName),
_metadata,
),
final base = _withFallbackLibrary(
source.copyWith(serverId: serverId ?? source.serverId, serverName: serverName ?? source.serverName),
_metadata,
);
final onDeckWithServerId = onDeckEpisode == null
? null
: _applyLocalProgress(
_withFallbackLibrary(
onDeckEpisode.copyWith(
serverId: serverId ?? onDeckEpisode.serverId,
serverName: serverName ?? onDeckEpisode.serverName,
),
base,
: _withFallbackLibrary(
onDeckEpisode.copyWith(
serverId: serverId ?? onDeckEpisode.serverId,
serverName: serverName ?? onDeckEpisode.serverName,
),
base,
);
setState(() {
@@ -1512,7 +1336,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
// Fallback to passed metadata on error
if (!mounted) return;
setState(() {
_fullMetadata = _applyLocalProgress(_metadata);
_fullMetadata = _metadata;
_isLoadingMetadata = false;
_hasLoadedExtras = true;
_hasLoadedRelatedHubs = true;
@@ -1604,13 +1428,16 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
if (shouldShowEpisodesDirectly) {
await _fetchAllEpisodes();
_ensureFallbackOnDeckEpisode();
} else if (seasonsWithServerId.isNotEmpty) {
// Load only the on-deck season's first page; other seasons load lazily
// when focused (strict on-demand — no whole-show pre-warm).
// when focused (strict on-demand — no whole-show pre-warm). Once the
// on-deck season is loaded, synthesize on-deck if the backend omitted it.
final fetchOnDeckSeason = _fetchSeasonEpisodes(onDeckSeasonIndex).then((_) => _ensureFallbackOnDeckEpisode());
if (PlatformDetector.isTV()) {
await _fetchSeasonEpisodes(onDeckSeasonIndex);
await fetchOnDeckSeason;
} else {
unawaited(_fetchSeasonEpisodes(onDeckSeasonIndex));
unawaited(fetchOnDeckSeason);
}
}
} catch (e, st) {
@@ -1666,7 +1493,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
id: seasonId,
backend: _metadata.backend,
kind: MediaKind.season,
title: firstEp.parentTitle ?? t.common.seasonNumber(number: entry.key),
title: localizedSeasonLabel(title: firstEp.parentTitle, index: entry.key),
index: entry.key,
leafCount: entry.value.length,
thumbPath: firstEp.parentThumbPath,
@@ -1683,8 +1510,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
for (final entry in seasonMap.entries) {
final seasonRatingKey = entry.value.first.parentId ?? '';
final sortedEpisodes = entry.value..sort((a, b) => (a.index ?? 0).compareTo(b.index ?? 0));
final episodesWithProgress = sortedEpisodes.map(_applyLocalProgress).toList();
_seasonEpisodePager.completeFirstPage(seasonRatingKey, episodesWithProgress, episodesWithProgress.length);
_seasonEpisodePager.completeFirstPage(seasonRatingKey, sortedEpisodes, sortedEpisodes.length);
}
final onDeckSeasonIndex = _findOnDeckSeasonIndex(seasons);
@@ -1714,8 +1540,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
..sort((a, b) => (a.index ?? 0).compareTo(b.index ?? 0));
setState(() {
final episodes = seasonEpisodes.map(_applyLocalProgress).toList();
_allEpisodes = _allEpisodes.completeInitialLoad(episodes, episodes.length);
_allEpisodes = _allEpisodes.completeInitialLoad(seasonEpisodes, seasonEpisodes.length);
_episodes = _allEpisodes.items;
_hasLoadedEpisodes = true;
});
@@ -1735,7 +1560,12 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
/// Find the season index matching the initial selection or on-deck episode,
/// then fall back to the same season the Play button would use.
int _findOnDeckSeasonIndex(List<MediaItem> seasons) {
return preferredSeasonIndex(seasons, initialSeasonIndex: widget.initialSeasonIndex, onDeckEpisode: _onDeckEpisode);
return preferredSeasonIndex(
seasons,
initialSeasonId: widget.initialSeasonId,
initialSeasonIndex: widget.initialSeasonIndex,
onDeckEpisode: _onDeckEpisode,
);
}
/// Fetch episodes for a specific season by index, using cache when available
@@ -1751,8 +1581,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
// demand) and clear any prior per-season loading/error state.
final cached = _seasonEpisodePager.stateFor(seasonId);
if (_seasonEpisodePager.hasState(seasonId) && !cached.isInitialLoading && !cached.initialLoadFailed) {
final episodes = cached.items.map(_applyLocalProgress).toList();
_seasonEpisodePager.completeFirstPage(seasonId, episodes, cached.totalCount);
_seasonEpisodePager.completeFirstPage(seasonId, cached.items, cached.totalCount);
setStateIfMounted(() {
if (_isSelectedSeason(seasonIndex, seasonId)) {
_episodes = List.of(_seasonEpisodePager.stateFor(seasonId).items);
@@ -1785,12 +1614,11 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
final allEpisodes = downloadProvider.getDownloadedEpisodesForShow(_metadata.id);
final seasonEpisodes = allEpisodes.where((ep) => ep.parentIndex == season.index).toList()
..sort((a, b) => (a.index ?? 0).compareTo(b.index ?? 0));
final episodes = seasonEpisodes.map(_applyLocalProgress).toList();
_completeSeasonEpisodesLoad(
seasonIndex: seasonIndex,
seasonId: seasonId,
episodes: episodes,
total: episodes.length,
episodes: seasonEpisodes,
total: seasonEpisodes.length,
generation: generation,
);
} else {
@@ -1818,7 +1646,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
_completeSeasonEpisodesLoad(
seasonIndex: seasonIndex,
seasonId: seasonId,
episodes: page.items.map(_applyLocalProgress).toList(),
episodes: page.items,
total: page.totalCount,
generation: generation,
);
@@ -1866,11 +1694,10 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
if (!mounted || _showEpisodesDirectly || seasonIndex >= _seasons.length || _seasons[seasonIndex].id != seasonId) {
return;
}
final episodes = page.items.map(_applyLocalProgress).toList();
setStateIfMounted(() {
final current = _seasonEpisodePager.stateFor(seasonId);
if (_seasonEpisodePager.hasState(seasonId) && !(current.isInitialLoading && !current.hasItems)) return;
_seasonEpisodePager.completeFirstPage(seasonId, episodes, page.totalCount);
_seasonEpisodePager.completeFirstPage(seasonId, page.items, page.totalCount);
if (_isSelectedSeason(seasonIndex, seasonId)) {
_episodes = List.of(_seasonEpisodePager.stateFor(seasonId).items);
}
@@ -1925,9 +1752,13 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
size: _episodesPageSize,
);
if (!mounted || generation != _episodesLoadGeneration) return;
final more = page.items.map(_applyLocalProgress).toList();
setStateIfMounted(() {
_seasonEpisodePager.completeMoreLoad(seasonId, expectedOffset: loaded, episodes: more, total: page.totalCount);
_seasonEpisodePager.completeMoreLoad(
seasonId,
expectedOffset: loaded,
episodes: page.items,
total: page.totalCount,
);
if (_isSelectedSeason(seasonIndex, seasonId)) _episodes = List.of(_seasonEpisodePager.stateFor(seasonId).items);
});
} catch (e, st) {
@@ -2117,6 +1948,93 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
scrollContextToCenter(key.currentContext);
}
bool get _hasInitialDetailFocusTarget =>
widget.initialEpisodeId != null || widget.initialSeasonId != null || widget.initialSeasonIndex != null;
bool get _episodesContainInitialTarget {
final targetEpisodeId = widget.initialEpisodeId;
return targetEpisodeId != null && _episodes.any((episode) => episode.id == targetEpisodeId);
}
void _scheduleInitialMobileDetailFocus(MediaItem metadata) {
if (_initialDetailFocusApplied || PlatformDetector.isTV() || !_hasInitialDetailFocusTarget) return;
if (widget.initialEpisodeId != null) {
if (_episodesContainInitialTarget) {
_applyInitialMobileFocus(_initialTargetEpisodeFocusNode(), _seasonsSectionKey);
return;
}
_maybeLoadMoreForInitialEpisode();
// Target never materialized (stale/deleted id) — fall back to the
// season anchors below instead of retrying forever.
if (!_initialEpisodePagingDone) return;
}
if (metadata.isShow &&
!_showEpisodesDirectly &&
_seasons.isNotEmpty &&
_seasonTabFocusNodes.length > _selectedSeasonIndex) {
_applyInitialMobileFocus(_seasonTabFocusNodes[_selectedSeasonIndex], _seasonsSectionKey);
return;
}
if (((metadata.isShow && _showEpisodesDirectly) || metadata.isSeason) && _episodes.isNotEmpty) {
_applyInitialMobileFocus(_firstEpisodeFocusNode, _seasonsSectionKey);
}
}
void _applyInitialMobileFocus(FocusNode node, GlobalKey sectionKey) {
_initialDetailFocusApplied = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
node.requestFocus();
_scrollSectionIntoView(sectionKey);
});
}
void _maybeLoadMoreForInitialEpisode() {
if (_initialEpisodePagingDone || _initialEpisodePagingInFlight) return;
if (_episodesContainInitialTarget) {
_initialEpisodePagingDone = true;
return;
}
final hasMore = _isFlattenEpisodeList ? _allEpisodes.hasMore : _selectedSeasonHasMore;
final pageError = _isFlattenEpisodeList ? _allEpisodesPageError : _seasonEpisodesPageError;
if (!hasMore || pageError) {
// All pages loaded (or paging failed) without the target appearing.
_initialEpisodePagingDone = true;
return;
}
if (_isFlattenEpisodeList ? _isLoadingAllEpisodes : _isLoadingMoreSeasonEpisodes) return;
_initialEpisodePagingInFlight = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || _episodesContainInitialTarget) {
_initialEpisodePagingInFlight = false;
return;
}
Future<void>? load;
if (_isFlattenEpisodeList) {
if (_allEpisodes.hasMore && !_isLoadingAllEpisodes && !_allEpisodesPageError) {
load = _loadMoreAllEpisodes();
}
} else if (_selectedSeasonHasMore && !_isLoadingMoreSeasonEpisodes && !_seasonEpisodesPageError) {
load = _loadMoreSeasonEpisodes();
}
if (load == null) {
_initialEpisodePagingInFlight = false;
return;
}
// The loaders setState on success and failure, so the resulting rebuild
// re-enters this method for the next page (or marks paging done).
unawaited(load.whenComplete(() => _initialEpisodePagingInFlight = false));
});
}
/// Focus the first available section above the primary action row.
void _focusAboveActionRow() {
if (PlatformDetector.isTV()) return;
@@ -2332,7 +2250,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
onSecondaryTapDown: (details) => tapPosition = details.globalPosition,
onSecondaryTap: () => _showSeasonTabContextMenu(index, position: tapPosition),
child: FocusableTabChip(
label: season.title!,
label: season.localizedSeasonTitle,
isSelected: index == _selectedSeasonIndex,
topImage: topImage,
focusNode: _seasonTabFocusNodes.length > index ? _seasonTabFocusNodes[index] : null,
@@ -2631,9 +2549,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
/// Build episode list directly when the library hides seasons for single-season shows
Widget _buildEpisodesList() {
final client = _getMediaClientForMetadata(context);
final pinnedLastEpisodeKey = _lastEpisodeFocusPinnedKey;
final hasPinnedLastEpisode =
pinnedLastEpisodeKey != null && _episodes.any((episode) => episode.globalKey == pinnedLastEpisodeKey);
final hasPinnedLastEpisode = _hasPinnedLastEpisodeInList;
return ListView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
@@ -2654,15 +2570,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
client: client,
isOffline: widget.isOffline,
autofocus: false,
focusNode: index == 0
? _firstEpisodeFocusNode
: _shouldUseLastEpisodeFocusNode(
episode: episode,
index: index,
hasPinnedLastEpisode: hasPinnedLastEpisode,
)
? _lastEpisodeFocusNode
: null,
focusNode: _episodeListFocusNode(episode: episode, index: index, hasPinnedLastEpisode: hasPinnedLastEpisode),
onNavigateUp: index == 0
? () {
if (!_showEpisodesDirectly) {
@@ -2686,9 +2594,8 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
final refreshed = await client?.fetchItem(episode.id);
if (refreshed != null) {
setStateIfMounted(() {
final updated = _applyLocalProgress(refreshed);
_episodes[index] = updated;
_syncEpisodeToCache(index, updated);
_episodes[index] = refreshed;
_syncEpisodeToCache(index, refreshed);
});
}
},
@@ -2711,6 +2618,39 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
return index == _episodes.length - 1;
}
bool get _hasPinnedLastEpisodeInList {
final pinnedKey = _lastEpisodeFocusPinnedKey;
return pinnedKey != null && _episodes.any((episode) => episode.globalKey == pinnedKey);
}
/// Resolve the focus node for an inline episode list item. Role nodes
/// (first/last) take priority so their consumers always find them attached;
/// the initial navigation target only claims a node when no role applies.
FocusNode? _episodeListFocusNode({
required MediaItem episode,
required int index,
required bool hasPinnedLastEpisode,
}) {
if (index == 0) return _firstEpisodeFocusNode;
if (_shouldUseLastEpisodeFocusNode(episode: episode, index: index, hasPinnedLastEpisode: hasPinnedLastEpisode)) {
return _lastEpisodeFocusNode;
}
if (widget.initialEpisodeId == episode.id) return _initialEpisodeFocusNode;
return null;
}
/// The node the initial target episode's card actually holds.
FocusNode _initialTargetEpisodeFocusNode() {
final index = _episodes.indexWhere((episode) => episode.id == widget.initialEpisodeId);
if (index == -1) return _initialEpisodeFocusNode;
return _episodeListFocusNode(
episode: _episodes[index],
index: index,
hasPinnedLastEpisode: _hasPinnedLastEpisodeInList,
) ??
_initialEpisodeFocusNode;
}
/// Tail of the inline episode list: a retry tile when a page failed, otherwise
/// a spinner. Carries [_episodeTailKey] so the scroll listener can detect when
/// it nears the viewport and page the next batch in.
@@ -2814,9 +2754,11 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
}
List<MediaItem> _enrichPlayableEpisodes(List<MediaItem> episodes, ServerId serverId) {
// Enrich each episode with serverId/serverName/grandparent fields —
// Jellyfin's recursive query doesn't always populate them, and the copy is
// a no-op for Plex where the mapper already does.
// Enrich each episode with serverId/serverName/parent fields — backends
// don't always populate them on recursive queries, and hierarchy-aware
// watch-state resolution needs the parentChain intact. The copy is a no-op
// where the mapper already did.
final fallbackParentId = _metadata.isSeason ? _metadata.id : null;
final fallbackGrandparentId = _metadata.isSeason ? (_metadata.grandparentId ?? _metadata.parentId) : _metadata.id;
final fallbackGrandparentTitle = _metadata.isSeason
? (_metadata.grandparentTitle ?? _metadata.parentTitle)
@@ -2827,13 +2769,13 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
e.copyWith(
serverId: serverId,
serverName: _metadata.serverName ?? e.serverName,
parentId: e.parentId ?? fallbackParentId,
grandparentId: e.grandparentId ?? fallbackGrandparentId,
grandparentTitle: e.grandparentTitle ?? fallbackGrandparentTitle,
),
_metadata,
),
)
.map(_applyLocalProgress)
.toList();
}
@@ -2921,7 +2863,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
final nextEpisode = await offlineWatchProvider.getNextUnwatchedEpisode(_metadata.id);
setStateIfMounted(() {
_onDeckEpisode = nextEpisode == null ? null : _applyLocalProgress(nextEpisode);
_onDeckEpisode = nextEpisode;
});
if (nextEpisode != null) {
@@ -2929,6 +2871,21 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
}
}
/// Online counterpart to [_loadOfflineOnDeckEpisode]: when the backend
/// omitted an on-deck episode (e.g. the show was removed from Continue
/// Watching) synthesize one from the on-deck season's already-loaded episodes
/// so the next unwatched episode is highlighted/focused and the Play button
/// resumes it. No-op once a backend on-deck episode exists, or when every
/// loaded episode is watched (keep the default S1E1 for a rewatch).
void _ensureFallbackOnDeckEpisode() {
if (_onDeckEpisode != null) return;
final next = firstUnwatchedEpisode(_freshAll(_episodes));
if (next == null) return;
setStateIfMounted(() {
_onDeckEpisode = next;
});
}
Future<void> _playFirstEpisode() async {
try {
// If seasons aren't loaded yet, wait for them or load them
@@ -3024,8 +2981,9 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
@override
Widget build(BuildContext context) {
// Use full metadata if loaded, otherwise use passed metadata
final metadata = _fullMetadata ?? _metadata;
// Session-fresh hero: server snapshot resolved against the watch-state
// store (onWatchStateChanged rebuilds on relevant events).
final metadata = _fresh(_fullMetadata ?? _metadata);
final isShow = metadata.isShow;
final isMobile = PlatformDetector.isMobile(context);
final isTv = PlatformDetector.isTV();
@@ -3061,6 +3019,8 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
return _buildTvDetailScreen(context, metadata, _handleMediaDetailBackKey);
}
_scheduleInitialMobileDetailFocus(metadata);
final blockSystemBack = Platform.isAndroid && InputModeTracker.isKeyboardMode(context);
final content = PrimaryScrollController(
controller: _scrollController,
@@ -3298,6 +3258,9 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
) {
final size = MediaQuery.sizeOf(context);
final detailHubs = _tvDetailHubs(metadata);
if (widget.initialEpisodeId != null && !_initialEpisodePagingDone) {
_maybeLoadMoreForInitialEpisode();
}
final hideSpoilers = SettingsService.instance.read(SettingsService.hideSpoilers);
final detailScale = TvLayoutConstants.scaleForSize(size);
final spotlightTop = (size.height * 0.08).clamp(44.0 * detailScale, 110.0 * detailScale).toDouble();
@@ -3721,7 +3684,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
hubs.add(
MediaHub(
id: '$_tvDetailSeasonHubIdPrefix$i',
title: season.title?.isNotEmpty == true ? season.title! : (season.displaySubtitle ?? season.displayTitle),
title: season.localizedSeasonTitle,
type: 'episode',
items: episodes,
size: total,
@@ -3784,6 +3747,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
}
String? _tvDetailInitialItemId(MediaItem metadata) {
if (widget.initialEpisodeId != null) return widget.initialEpisodeId;
if (!metadata.isShow) return null;
return _onDeckEpisode?.id;
}
@@ -3888,8 +3852,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
}
if (hasLoadedState) {
final episodes = state.items.map(_applyLocalProgress).toList();
_seasonEpisodePager.completeFirstPage(season.id, episodes, state.totalCount);
_seasonEpisodePager.completeFirstPage(season.id, state.items, state.totalCount);
setStateIfMounted(() {
_selectedSeasonIndex = seasonIndex;
_episodes = List.of(_seasonEpisodePager.stateFor(season.id).items);
@@ -4364,7 +4327,7 @@ class _MediaDetailScreenState extends State<MediaDetailScreen>
// For TV shows
if (metadata.isShow) {
if (_onDeckEpisode != null) {
final episode = _onDeckEpisode!;
final episode = _fresh(_onDeckEpisode!);
// Check if episode has been partially watched
if (episode.viewOffsetMs != null && episode.viewOffsetMs! > 0) {
return Symbols.resume_rounded; // Resume icon
+2 -12
View File
@@ -2,11 +2,10 @@ import 'package:flutter/material.dart';
import '../../media/ids.dart';
import 'package:plezy/widgets/app_icon.dart';
import 'package:material_symbols_icons/symbols.dart';
import 'package:provider/provider.dart';
import '../../media/media_item.dart';
import '../../media/media_kind.dart';
import '../../mixins/context_menu_tap_mixin.dart';
import '../../providers/watch_state_overlay_provider.dart';
import '../../providers/watch_state_store.dart';
import '../../utils/formatters.dart';
import '../../utils/provider_extensions.dart';
import '../../i18n/strings.g.dart';
@@ -47,16 +46,7 @@ class PlaylistItemCard extends StatefulWidget {
}
class _PlaylistItemCardState extends State<PlaylistItemCard> with ContextMenuTapMixin<PlaylistItemCard> {
MediaItem _effectiveItem(BuildContext context) {
try {
final patch = context.select<WatchStateOverlayProvider, WatchStateOverlayPatch?>(
(provider) => provider.patchForGlobalKey(widget.item.globalKey),
);
return WatchStateOverlayProvider.applyPatch(widget.item, patch);
} on ProviderNotFoundException {
return widget.item;
}
}
MediaItem _effectiveItem(BuildContext context) => context.withFreshWatchState(widget.item);
@override
Widget build(BuildContext context) {
+35
View File
@@ -12,6 +12,7 @@ import '../mixins/mounted_set_state_mixin.dart';
import '../mixins/refreshable.dart';
import '../providers/multi_server_provider.dart';
import '../utils/app_logger.dart';
import '../utils/platform_detector.dart';
import '../utils/snackbar_helper.dart';
import '../widgets/desktop_app_bar.dart';
import '../widgets/loading_indicator_box.dart';
@@ -44,6 +45,7 @@ class _SearchScreenState extends State<SearchScreen>
bool _hasSearched = false;
late final Debounce _searchDebounce;
String _lastSearchedQuery = '';
String? _focusResultsForQuery;
@override
void initState() {
@@ -69,6 +71,7 @@ class _SearchScreenState extends State<SearchScreen>
if (query.trim().isEmpty) {
_searchDebounce.cancel();
_focusResultsForQuery = null;
setStateIfMounted(() {
_searchResults = [];
_hasSearched = false;
@@ -117,8 +120,10 @@ class _SearchScreenState extends State<SearchScreen>
_isSearching = false;
_lastSearchedQuery = query.trim();
});
_maybeFocusResultsAfterSubmit(query, neutral);
}
} catch (e) {
_focusResultsForQuery = null;
if (mounted) {
setStateIfMounted(() {
_isSearching = false;
@@ -128,6 +133,34 @@ class _SearchScreenState extends State<SearchScreen>
}
}
/// OSK "Search" / hardware Enter on TV: jump to results, or force the
/// search to run now and focus results when it lands.
void _handleSearchSubmit() {
final query = _searchController.text.trim();
if (query.isEmpty) return;
if (_searchResults.isNotEmpty && !_isSearching && query == _lastSearchedQuery.trim()) {
_firstResultFocusNode.requestFocus();
return;
}
_focusResultsForQuery = query;
if (_searchDebounce.isPending || !_isSearching) {
_searchDebounce.cancel();
_performSearch(query);
}
// else: the in-flight search already covers the current text; its
// completion focuses the results.
}
void _maybeFocusResultsAfterSubmit(String query, List<MediaItem> results) {
if (_focusResultsForQuery == null || _focusResultsForQuery != query.trim()) return;
_focusResultsForQuery = null;
if (results.isEmpty) return;
if (_searchController.text.trim() != query.trim()) return; // user kept editing
FocusUtils.requestFocusAfterBuild(this, _firstResultFocusNode);
}
@override
void refresh() {
if (!mounted) return;
@@ -163,6 +196,7 @@ class _SearchScreenState extends State<SearchScreen>
appLogger.d('SearchScreen.fullRefresh() called - clearing search and reloading');
// Clear search results and search text for new profile
_searchController.clear();
_focusResultsForQuery = null;
setStateIfMounted(() {
_searchResults.clear();
_isSearching = false;
@@ -228,6 +262,7 @@ class _SearchScreenState extends State<SearchScreen>
onNavigateDown: _searchResults.isNotEmpty && !_isSearching
? _firstResultFocusNode.requestFocus
: null,
onEditingComplete: PlatformDetector.isTV() ? _handleSearchSubmit : null,
onBack: () {
if (_searchController.text.isNotEmpty) {
_searchController.clear();
@@ -63,6 +63,7 @@ class AppearanceSettingsScreen extends StatelessWidget {
title: t.settings.showHeroSection,
subtitle: t.settings.showHeroSectionDescription,
),
_continueWatchingActionSelector(),
SettingSwitchTile(
pref: SettingsService.useGlobalHubs,
icon: Symbols.home_rounded,
@@ -252,6 +253,18 @@ class AppearanceSettingsScreen extends StatelessWidget {
encode: (v) => v,
);
Widget _continueWatchingActionSelector() => SettingSegmentedTile<ContinueWatchingAction, ContinueWatchingAction>(
pref: SettingsService.continueWatchingAction,
icon: Symbols.play_circle_rounded,
title: t.settings.continueWatchingAction,
segments: [
ButtonSegment(value: ContinueWatchingAction.play, label: Text(t.settings.continueWatchingPlay)),
ButtonSegment(value: ContinueWatchingAction.details, label: Text(t.settings.continueWatchingDetails)),
],
decode: (v) => v,
encode: (v) => v,
);
// Sections offered as a startup destination, in display order. Live TV is
// always listed; if no server provides it, startup falls back to Home.
static const _startupSectionOptions = [
@@ -284,6 +284,7 @@ class _PlaybackSettingsScreenState extends State<PlaybackSettingsScreen> {
builder: (context) {
final svc = SettingsService.instance;
final shouldShow =
PlatformDetector.isAppleTV() ||
(Platform.isWindows &&
(svc.read(SettingsService.matchRefreshRate) || svc.read(SettingsService.matchDynamicRange))) ||
(Platform.isAndroid && svc.read(SettingsService.matchContentFrameRate));
@@ -0,0 +1,77 @@
/// What a position tick means for the end-of-video prompt flow.
enum CompletionLatchSignal {
/// Nothing to do.
none,
/// Playback just entered the end-of-video window and the latch is clear —
/// the caller should run its completion handling (which latches on
/// success via [CompletionLatch.latch]).
completed,
/// Playback moved back out of the end region and the latch re-armed.
rearmed,
}
/// End-of-video latch with rearm hysteresis for the Play Next / completion
/// prompts.
///
/// The prompt fires when playback enters the last [triggerWindowMs] of the
/// item and must not re-fire on every subsequent position tick — the latch
/// stays set while playback is parked inside the end region. It re-arms only
/// once playback moves back out past [rearmWindowMs] (a larger window, so a
/// position oscillating at the boundary can't flap), and never while a
/// prompt is visible or an auto-play countdown owns the screen.
///
/// Latching is the *caller's* move ([latch]), not [classifyPosition]'s: the
/// completion handler has its own bail-outs (live TV, in-flight media swap)
/// and a tick that bails must stay un-latched so the next tick retries.
class CompletionLatch {
CompletionLatch({required this.triggerWindowMs, required this.rearmWindowMs})
: assert(rearmWindowMs > triggerWindowMs, 'rearm window must exceed trigger window for hysteresis');
/// Fire when within this many ms of the end.
final int triggerWindowMs;
/// Re-arm only after moving back out past this many ms from the end.
final int rearmWindowMs;
bool _triggered = false;
/// Whether the end-of-video handling already ran for this approach to
/// the end region.
bool get triggered => _triggered;
/// Mark the completion handling as done for this approach to the end.
void latch() => _triggered = true;
/// Clear unconditionally — new media was loaded.
void reset() => _triggered = false;
/// Re-arm so the prompt can fire again — but only when no prompt is
/// visible and no auto-play countdown is running, so an active dialog is
/// never clobbered. Callers decide *when* re-arming is safe (media
/// reloaded, or playback moved back out of the end region).
void rearmIfClear({required bool promptVisible, required bool countdownActive}) {
if (_triggered && !promptVisible && !countdownActive) _triggered = false;
}
/// Classify a position tick against the trigger/rearm windows.
CompletionLatchSignal classifyPosition({
required int positionMs,
required int durationMs,
required bool promptVisible,
required bool countdownActive,
}) {
if (durationMs <= 0) return CompletionLatchSignal.none;
if (positionMs >= durationMs - triggerWindowMs) {
if (!promptVisible && !_triggered) return CompletionLatchSignal.completed;
return CompletionLatchSignal.none;
}
if (positionMs < durationMs - rearmWindowMs) {
final wasLatched = _triggered;
rearmIfClear(promptVisible: promptVisible, countdownActive: countdownActive);
if (wasLatched && !_triggered) return CompletionLatchSignal.rearmed;
}
return CompletionLatchSignal.none;
}
}
@@ -0,0 +1,41 @@
/// Per-screen state for Android display frame-rate matching: the retry
/// counter for backends that detect fps only after rendering, whether a
/// switch was already applied for the current item, and the MediaSession
/// pause-suppression window armed around HDMI renegotiations.
///
/// One instance lives on the player screen; the open/reload pipelines call
/// [resetForNewItem] before each open and the display-matching paths flip
/// [applied]/[retries] as they negotiate.
class FrameRateMatcher {
/// Retries left for late fps detection (ExoPlayer reports container fps
/// only after ~8 rendered frames).
int retries = 0;
/// Whether a display switch was already applied for the current item —
/// the post-first-frame path bails instead of switching twice.
bool applied = false;
bool _suppressMediaPause = false;
/// Whether a MediaSession PauseEvent should be ignored right now because
/// the display is (or may still be) renegotiating HDMI. Fire Stick (and
/// similar Android TV devices) send onPause() through the MediaSession
/// callback when the display mode changes for frame rate matching.
bool get suppressesMediaPause => _suppressMediaPause;
/// Arm the pause-suppression window around an HDMI renegotiation. The
/// window outlasts the switch by a safety margin on top of the user's
/// configured extra delay.
void beginSuppressWindow(int delaySec) {
_suppressMediaPause = true;
Future.delayed(Duration(seconds: 2 + delaySec + 1), () {
_suppressMediaPause = false;
});
}
/// Reset the per-item negotiation state before opening new media.
void resetForNewItem() {
retries = 0;
applied = false;
}
}
@@ -0,0 +1,41 @@
import '../../media/media_server_client.dart';
import '../../models/livetv_channel.dart';
/// Launch parameters for a live TV session. A [VideoPlayerScreen] plays live
/// TV iff it was constructed with one of these — the type encodes the
/// "these fields travel together" invariant the nine separate nullable
/// constructor parameters used to leave implicit.
class LiveTvSessionArgs {
final String? channelName;
/// Pre-resolved stream URL (Jellyfin always provides one; Plex tunes
/// in-player when null).
final String? streamUrl;
final List<LiveTvChannel>? channels;
final int? currentChannelIndex;
final String? dvrKey;
/// Backend-neutral client typing. The four in-player live ops branch on
/// `client is PlexClient` / `client is JellyfinClient` at their use sites:
/// Plex tunes a transcode session and gets capture-buffer updates;
/// Jellyfin uses its `/Sessions/Playing*` endpoints for progress reporting
/// and re-opens [streamUrl] for retry. Tune (Plex-only by protocol)
/// and seek (Plex-only — Jellyfin live channels aren't seekable) gate
/// explicitly on `client is PlexClient`.
final MediaServerClient? client;
final String? sessionIdentifier;
final String? sessionPath;
const LiveTvSessionArgs({
this.channelName,
this.streamUrl,
this.channels,
this.currentChannelIndex,
this.dvrKey,
this.client,
this.sessionIdentifier,
this.sessionPath,
});
}
@@ -0,0 +1,76 @@
import 'dart:async';
import '../../media/media_server_client.dart';
import '../../models/livetv_capture_buffer.dart';
import '../../services/jellyfin_client.dart';
import '../../services/live_session_tracker.dart';
import 'live_tv_session_args.dart';
/// Mutable state for one live TV playback session: tune/session identity,
/// the timeline heartbeat machinery, the capture buffer used for
/// time-shifting, and the retry/fallback ladder.
///
/// One instance lives on the player screen (inert when the screen plays
/// VOD); the live-TV part file owns all the logic and reads/writes through
/// this object so the session state has a single boundary and lifetime.
class LiveTvSessionState {
LiveTvSessionState(LiveTvSessionArgs? args, {required this.itemId})
: channelIndex = args?.currentChannelIndex ?? -1,
channelName = args?.channelName,
client = args?.client,
dvrKey = args?.dvrKey,
streamUrl = args?.streamUrl,
sessionIdentifier = args?.sessionIdentifier,
sessionPath = args?.sessionPath,
jellyfin = args?.client is JellyfinClient && args?.sessionIdentifier != null
? JellyfinLiveSessionTracker(playSessionId: args?.sessionIdentifier)
: JellyfinLiveSessionTracker();
int channelIndex;
String? channelName;
MediaServerClient? client;
String? dvrKey;
String? streamUrl;
/// The channel/program item progress reports are attributed to; updated
/// on channel switches.
String itemId;
String? sessionIdentifier;
String? sessionPath;
Timer? timelineTimer;
int timelineGeneration = 0;
DateTime? playbackStartTime;
String? programId;
int? durationMs;
/// Jellyfin live TV heartbeat state machine. The Plex live branch keeps
/// its bespoke capture-buffer flow inline; this tracker only collapses
/// the Jellyfin started/progress/stopped transition.
JellyfinLiveSessionTracker jellyfin;
CaptureBuffer? captureBuffer;
int? programBeginsAt;
double streamStartEpoch = 0;
bool atLiveEdge = true;
String? transcodeSessionId;
/// Fallback level for live TV stream errors (mirrors Plex web client
/// behavior). 0 = directStream+directStreamAudio, 1 = no directStream,
/// 2 = no DS + no DS audio.
int fallbackLevel = 0;
bool retrying = false;
/// Whether the timeline heartbeat should restart when the app resumes
/// from the background (it is suspended on hide).
bool resumeTimelineOnResume = false;
/// The stream just (re)started at the live edge — align the epoch
/// bookkeeping every restart flow shares (retry, channel zap).
void markStreamRestartedAtLiveEdge() {
final now = DateTime.now();
playbackStartTime = now;
streamStartEpoch = now.millisecondsSinceEpoch / 1000.0;
atLiveEdge = true;
}
}
+10 -10
View File
@@ -47,7 +47,7 @@ extension _VideoPlayerBuildMethods on VideoPlayerScreenState {
});
}
int? _selectedSourceSubtitleStreamId(List<MediaSubtitleTrack> tracks) {
int? _selectedSourceSubtitleStreamIdForControls(List<MediaSubtitleTrack> tracks) {
if (tracks.isEmpty) return null;
for (final track in tracks) {
if (track.selected) return track.id;
@@ -248,7 +248,6 @@ extension _VideoPlayerBuildMethods on VideoPlayerScreenState {
onPrevious: onPrevious,
availableVersions: _availableVersions,
selectedMediaIndex: _effectiveSelectedMediaIndex,
selectedMediaSourceId: widget.selectedMediaSourceId,
selectedQualityPreset: _selectedQualityPreset,
serverSupportsTranscoding: _serverSupportsTranscoding,
isTranscoding: _isTranscoding,
@@ -256,8 +255,9 @@ extension _VideoPlayerBuildMethods on VideoPlayerScreenState {
sourceAudioTracks: sourceAudioTracks,
selectedAudioStreamId: _selectedAudioStreamId,
sourceSubtitleTracks: sourceSubtitleTracks,
selectedSubtitleStreamId: _selectedSourceSubtitleStreamId(sourceSubtitleTracks),
selectedSubtitleStreamId: _selectedSourceSubtitleStreamIdForControls(sourceSubtitleTracks),
sourcePartId: _currentMediaInfo?.partId,
onPlaybackSourceChanged: _switchPlaybackSource,
onTogglePIPMode: _togglePIPMode,
boxFitMode: _videoFilterManager?.boxFitMode ?? 0,
videoZoomScale: _videoFilterManager?.zoomScale ?? 1.0,
@@ -285,14 +285,14 @@ extension _VideoPlayerBuildMethods on VideoPlayerScreenState {
onShaderChanged: () => _setPlayerState(() {}),
thumbnailDataBuilder: _scrubPreviewSource?.isAvailable == true ? _getThumbnailData : null,
isLive: widget.isLive,
liveChannelName: _liveChannelName,
captureBuffer: _captureBuffer,
isAtLiveEdge: _isAtLiveEdge,
streamStartEpoch: _streamStartEpoch,
liveChannelName: _live.channelName,
captureBuffer: _live.captureBuffer,
isAtLiveEdge: _live.atLiveEdge,
streamStartEpoch: _live.streamStartEpoch,
currentPositionEpoch: widget.isLive ? _currentPositionEpoch : null,
onLiveSeek: _captureBuffer != null ? _seekLiveToEpoch : null,
onLiveSeekBy: _captureBuffer != null ? _liveSeek.seekBy : null,
onJumpToLive: _captureBuffer != null && !_isAtLiveEdge ? _jumpToLiveEdge : null,
onLiveSeek: _live.captureBuffer != null ? _seekLiveToEpoch : null,
onLiveSeekBy: _live.captureBuffer != null ? _liveSeek.seekBy : null,
onJumpToLive: _live.captureBuffer != null && !_live.atLiveEdge ? _jumpToLiveEdge : null,
isAmbientLightingEnabled: _ambientLightingService?.isEnabled ?? false,
onToggleAmbientLighting: _ambientLightingService?.isSupported == true
? _toggleAmbientLighting
@@ -16,7 +16,7 @@ extension _VideoPlayerCompanionRemoteMethods on VideoPlayerScreenState {
if (player == null) return;
final settings = await SettingsService.getInstance();
final seekSeconds = settings.read(SettingsService.seekTimeSmall);
if (widget.isLive && _captureBuffer != null) {
if (widget.isLive && _live.captureBuffer != null) {
_liveSeek.seekBy(seekSeconds);
return;
}
@@ -27,7 +27,7 @@ extension _VideoPlayerCompanionRemoteMethods on VideoPlayerScreenState {
if (player == null) return;
final settings = await SettingsService.getInstance();
final seekSeconds = settings.read(SettingsService.seekTimeSmall);
if (widget.isLive && _captureBuffer != null) {
if (widget.isLive && _live.captureBuffer != null) {
_liveSeek.seekBy(-seekSeconds);
return;
}
@@ -3,7 +3,7 @@ part of '../../video_player_screen.dart';
extension _VideoPlayerDisplayMatchingMethods on VideoPlayerScreenState {
Future<void> _applyFrameRateMatching() async {
if (player == null || !Platform.isAndroid) return;
if (_frameRateMatchingApplied) return;
if (_frameRate.applied) return;
try {
final fpsStr = await player!.getProperty('container-fps');
@@ -11,8 +11,8 @@ extension _VideoPlayerDisplayMatchingMethods on VideoPlayerScreenState {
if (fps == null || fps <= 0) {
// ExoPlayer detects FPS from frame timestamps after ~8 rendered frames.
// STATE_READY fires before frames render, so retry until detection completes.
if (player is PlayerAndroid && _frameRateRetries < 10) {
_frameRateRetries++;
if (player!.detectsFpsAfterRender && _frameRate.retries < 10) {
_frameRate.retries++;
Future.delayed(const Duration(milliseconds: 500), () {
if (mounted && player != null) _applyFrameRateMatching();
});
@@ -22,19 +22,10 @@ extension _VideoPlayerDisplayMatchingMethods on VideoPlayerScreenState {
return;
}
_frameRateRetries = 0;
_frameRateMatchingApplied = true;
_frameRate.retries = 0;
_frameRate.applied = true;
final durationMs = player!.state.duration.inMilliseconds;
final settingsService = await SettingsService.getInstance();
final delaySec = settingsService.read(SettingsService.displaySwitchDelay);
// Suppress spurious PauseEvent from MediaSession during HDMI renegotiation.
// Fire Stick (and similar Android TV devices) send onPause() through the
// MediaSession callback when the display mode changes for frame rate matching.
_suppressMediaPauseDuringFrameRateSwitch = true;
Future.delayed(Duration(seconds: 2 + delaySec + 1), () {
_suppressMediaPauseDuringFrameRateSwitch = false;
});
// Pause so the playback clock doesn't advance while the TV renegotiates
// HDMI. The native setVideoFrameRate call below awaits the real display
@@ -46,7 +37,12 @@ extension _VideoPlayerDisplayMatchingMethods on VideoPlayerScreenState {
appLogger.w('Failed to pause before frame rate switch', error: e);
}
final didSwitch = await player!.setVideoFrameRate(fps, durationMs, extraDelayMs: delaySec * 1000);
final didSwitch = await _switchDisplayFrameRateForOpen(
player: player!,
settingsService: settingsService,
fps: fps,
durationMs: durationMs,
);
if (didSwitch) {
await _refreshAndroidMpvDecoderAfterFrameRateSwitch(reason: 'post-first-frame display switch');
}
@@ -57,10 +53,7 @@ extension _VideoPlayerDisplayMatchingMethods on VideoPlayerScreenState {
unawaited(
Sentry.addBreadcrumb(
Breadcrumb(
message: 'Frame rate matching: ${fps}fps, switched=$didSwitch, delay=${delaySec}s',
category: 'player',
),
Breadcrumb(message: 'Frame rate matching: ${fps}fps, switched=$didSwitch', category: 'player'),
),
);
appLogger.d('Frame rate matching: Set display to ${fps}fps (duration: ${durationMs}ms, switched=$didSwitch)');
@@ -71,7 +64,7 @@ extension _VideoPlayerDisplayMatchingMethods on VideoPlayerScreenState {
Future<void> _refreshAndroidMpvDecoderAfterFrameRateSwitch({required String reason}) async {
final p = player;
if (!mounted || !Platform.isAndroid || p == null || p is PlayerAndroid) return;
if (!mounted || p == null || !p.needsDecoderRefreshAfterDisplaySwitch) return;
final isLive = widget.isLive;
final targetPosition = p.state.position;
@@ -108,19 +101,6 @@ extension _VideoPlayerDisplayMatchingMethods on VideoPlayerScreenState {
}
}
/// Clear frame rate matching and restore default display mode
Future<void> _clearFrameRateMatching() async {
if (player == null || !Platform.isAndroid) return;
try {
await player!.clearVideoFrameRate();
unawaited(Sentry.addBreadcrumb(Breadcrumb(message: 'Frame rate matching cleared', category: 'player')));
appLogger.d('Frame rate matching: Cleared, restored default display mode');
} catch (e) {
appLogger.d('Failed to clear frame rate matching', error: e);
}
}
/// Apply Windows display mode matching (refresh rate, HDR).
Future<void> _applyWindowsDisplayMatching() async {
if (player == null || _displayModeService == null) return;
@@ -1,6 +1,26 @@
part of '../../video_player_screen.dart';
extension _VideoPlayerEpisodeNavigationMethods on VideoPlayerScreenState {
void _clearEpisodeLoadingFlags() {
if (!_isLoadingNext && !_isLoadingPrevious) return;
_setPlayerState(() {
_isLoadingNext = false;
_isLoadingPrevious = false;
});
}
/// Old screen-swap parity: after an in-place item change (or its failed
/// rollback), surface the chrome and re-anchor focus on play/pause. The
/// control that drove the swap (next button, queue item, play-next prompt)
/// may have unmounted or unfocused by now — without a fresh route's
/// autofocus, dpad navigation would be stranded until the chrome is hidden
/// and re-shown. Focusing play/pause is invisible in pointer mode (focus
/// visuals are keyboard/dpad-gated).
void _showChromeForSwappedItem() {
if (!mounted) return;
_chromeController.show(focusTarget: PlayerChromeFocusTarget.playPause);
}
Future<void> _playNext() async {
if (!mounted) return;
if (_nextEpisode == null || _isLoadingNext) return;
@@ -46,7 +66,7 @@ extension _VideoPlayerEpisodeNavigationMethods on VideoPlayerScreenState {
_setPlayerState(() {
_showPlayNextDialog = false;
_completionTriggered = false;
_completionLatch.reset();
});
final target = clampSeekPosition(currentPlayer, Duration.zero);
@@ -57,92 +77,171 @@ extension _VideoPlayerEpisodeNavigationMethods on VideoPlayerScreenState {
_updateMediaControlsPlaybackState();
}
/// Navigates to a new episode, preserving playback state and track selections.
/// When PiP is active, swaps the media source in-place to keep the PiP window alive.
Future<void> _navigateToEpisode(MediaItem episodeMetadata) async {
// PiP active: swap media in-place to keep the PiP window alive. The
// swap path threads the neutral [MediaServerClient] through
// [PlaybackInitializationService] and the lifecycle services, so it
// works for both Plex and Jellyfin sessions.
if (PipService().isPipActive.value && player != null) {
await _swapEpisodeInPip(episodeMetadata);
return;
}
// Set flag to skip orientation restoration in dispose()
_isReplacingWithVideo = true;
unawaited(DiscordRPCService.instance.stopPlayback());
unawaited(TraktScrobbleService.instance.stopPlayback());
unawaited(TrackerCoordinator.instance.stopPlayback());
if (player == null) {
if (mounted) {
unawaited(
navigateToVideoPlayer(
context,
metadata: episodeMetadata,
usePushReplacement: true,
isOffline: widget.isOffline,
),
);
}
return;
}
// Capture current state atomically to avoid race conditions
final currentPlayer = player;
if (currentPlayer == null) {
if (mounted) {
unawaited(
navigateToVideoPlayer(
context,
metadata: episodeMetadata,
usePushReplacement: true,
isOffline: widget.isOffline,
),
);
}
return;
}
final currentAudioTrack = currentPlayer.state.track.audio;
final currentSubtitleTrack = currentPlayer.state.track.subtitle;
final currentSecondarySubtitleTrack = currentPlayer.state.track.secondarySubtitle;
unawaited(currentPlayer.pause());
await _sendStoppedProgressOnce();
_progressTracker?.stopTracking();
await disposePlayerForNavigation();
if (mounted) {
unawaited(
navigateToVideoPlayer(
context,
metadata: episodeMetadata,
preferredAudioTrack: currentAudioTrack,
preferredSubtitleTrack: currentSubtitleTrack,
preferredSecondarySubtitleTrack: currentSecondarySubtitleTrack,
usePushReplacement: true,
isOffline: widget.isOffline,
),
/// Replace this screen with a fresh player route — the fallback for flows
/// the in-place reload cannot serve. Marks the screen as being replaced so
/// dispose skips the app-level player-exit side effects the replacement
/// route takes over (WT host-exit notify, sleep timer, system UI restore,
/// display mode).
Future<void> _replaceScreenWithPlayer(MediaItem metadata) async {
_isReplacingWithVideo = true; // before any await — dispose can run mid-helper
try {
await navigateToVideoPlayer(
context,
metadata: metadata,
usePushReplacement: true,
isOffline: _offlineLibraryMode,
);
} finally {
// Still mounted ⇒ no push happened (external-player branch or a
// throw): this screen stays, so restore normal-exit semantics.
if (mounted) {
_isReplacingWithVideo = false;
_clearEpisodeLoadingFlags();
}
}
}
/// Swap to a new episode while keeping the player alive for PiP continuity.
/// Reuses the existing mpv instance (and its Metal layer in PiP) and only
/// reloads the media source + resets Dart-side services.
Future<void> _swapEpisodeInPip(MediaItem episodeMetadata) async {
_isSwappingEpisode = true;
final currentPlayer = player!;
final playbackGeneration = _beginPlaybackGeneration(isEpisodeSwap: true);
final previousMetadata = _currentMetadata;
/// Navigates to a new episode by reusing the current player whenever possible.
Future<void> _navigateToEpisode(MediaItem episodeMetadata) async {
if (player == null) {
if (mounted) unawaited(_replaceScreenWithPlayer(episodeMetadata));
return;
}
final currentAudioTrack = currentPlayer.state.track.audio;
final currentSubtitleTrack = currentPlayer.state.track.subtitle;
final currentSecondarySubtitleTrack = currentPlayer.state.track.secondarySubtitle;
await _reloadMediaInPlace(
metadata: episodeMetadata,
selectedMediaIndex: _effectiveSelectedMediaIndex,
selectedMediaSourceId: null,
qualityPreset: _selectedQualityPreset,
// Stream ids are per-part: the previous episode's audio id is
// meaningless on the new item, so let preferences pick the track.
useCurrentAudioStreamSelection: false,
preserveCurrentTrackSelection: true,
reason: 'episode navigation',
);
}
Future<void> _switchPlaybackSource({
int? newMediaIndex,
TranscodeQualityPreset? newPreset,
int? newAudioStreamId,
int? newSubtitleStreamId,
}) async {
final currentPlayer = player;
if (!mounted || currentPlayer == null || _playbackTransition != _PlaybackTransition.idle) return;
final effectiveMediaIndex = newMediaIndex ?? _effectiveSelectedMediaIndex;
final effectivePreset = newPreset ?? _selectedQualityPreset;
final effectiveAudioStreamId = newAudioStreamId ?? _selectedAudioStreamId;
final currentSubtitleStreamId = _selectedSourceSubtitleStreamIdForControls(_sourceSubtitleTracksForControls());
final effectiveSubtitleStreamId = newSubtitleStreamId ?? currentSubtitleStreamId;
final effectiveMediaSourceId = newMediaIndex != null
? PlaybackSession.mediaSourceIdForIndex(_availableVersions, effectiveMediaIndex) ?? _selectedMediaSourceId
: _selectedMediaSourceId;
final isVersionChange =
effectiveMediaIndex != _effectiveSelectedMediaIndex ||
(_selectedMediaSourceId != null && effectiveMediaSourceId != _selectedMediaSourceId);
final isPresetChange = effectivePreset != _selectedQualityPreset;
final isAudioChange = effectiveAudioStreamId != _selectedAudioStreamId;
final isSubtitleChange = newSubtitleStreamId != null && effectiveSubtitleStreamId != currentSubtitleStreamId;
if (!isVersionChange && !isPresetChange && !isAudioChange && !isSubtitleChange) return;
// Read the client before any await — context across an async gap. A
// missing client leaves this null and the guard below reports it.
final serverId = _currentMetadata.serverId;
PlexClient? subtitleClient;
if (isSubtitleChange && serverId != null) {
try {
subtitleClient = context.getPlexClientForServer(ServerId(serverId));
} catch (_) {}
}
try {
if (isVersionChange) {
await saveMediaVersionIndexFor(_currentMetadata, effectiveMediaIndex);
}
if (isSubtitleChange) {
final partId = _currentMediaInfo?.partId;
if (subtitleClient == null || partId == null || effectiveSubtitleStreamId == null) {
throw StateError('No Plex part available for subtitle stream selection');
}
final saved = await subtitleClient.selectStreams(
partId,
subtitleStreamID: effectiveSubtitleStreamId,
allParts: true,
);
if (!saved) {
throw StateError('Failed to select subtitle stream');
}
}
await _reloadMediaInPlace(
metadata: _currentMetadata.copyWith(viewOffsetMs: currentPlayer.state.position.inMilliseconds),
selectedMediaIndex: effectiveMediaIndex,
selectedMediaSourceId: effectiveMediaSourceId,
qualityPreset: effectivePreset,
// A version change selects a different part, and stream ids are
// per-part — only same-part switches may carry the current id.
selectedAudioStreamId: isVersionChange ? newAudioStreamId : effectiveAudioStreamId,
useCurrentAudioStreamSelection: !isVersionChange,
resumePosition: currentPlayer.state.position,
preserveCurrentTrackSelection: false,
reason: 'source switch',
);
} catch (e) {
if (mounted) {
showErrorSnackBar(context, t.messages.errorLoading(error: e.toString()));
}
}
}
/// Reload a VOD item/source while keeping the route, player instance, and
/// native renderer alive. This is the common path for episode navigation,
/// queue item jumps, Watch Together media switches, and source changes.
Future<bool> _reloadMediaInPlace({
required MediaItem metadata,
int? selectedMediaIndex,
String? selectedMediaSourceId,
TranscodeQualityPreset? qualityPreset,
int? selectedAudioStreamId,
Duration? resumePosition,
bool preserveCurrentTrackSelection = false,
bool useCurrentAudioStreamSelection = true,
String reason = 'media reload',
}) async {
if (widget.isLive) {
_clearEpisodeLoadingFlags();
return false;
}
final existingPlayer = player;
if (!mounted || existingPlayer == null || _playbackTransition != _PlaybackTransition.idle) {
if (mounted) _clearEpisodeLoadingFlags();
return false;
}
_playbackTransition = _PlaybackTransition.reloadingMedia;
final currentPlayer = player!;
final attempt = _beginPlaybackAttempt(currentPlayer, isMediaReload: true);
bool isCurrentReload() => attempt.isCurrent;
// The session itself swaps atomically at the open boundary, so the only
// rollback state is the eagerly-set identity (shown by the loading UI)
// and the first-frame flag.
final previousMetadata = _currentMetadata;
final previousMediaIndex = _effectiveSelectedMediaIndex;
final previousPartId = _currentMediaInfo?.partId;
final previousHasFirstFrame = _hasFirstFrame.value;
final isItemChange = previousMetadata.globalKey != metadata.globalKey;
final currentAudioTrack = preserveCurrentTrackSelection ? currentPlayer.state.track.audio : null;
final currentSubtitleTrack = preserveCurrentTrackSelection ? currentPlayer.state.track.subtitle : null;
final currentSecondarySubtitleTrack = preserveCurrentTrackSelection
? currentPlayer.state.track.secondarySubtitle
: null;
final wasPlayingBeforeReload = currentPlayer.state.playing;
var didOpenReplacement = false;
// Capture context-dependent values before async gaps. The neutral
// [PlaybackInitializationService] consumes [mediaClient] regardless of
@@ -154,39 +253,61 @@ extension _VideoPlayerEpisodeNavigationMethods on VideoPlayerScreenState {
final playbackState = context.read<PlaybackStateProvider>();
final database = context.read<AppDatabase>();
final serverManager = context.read<MultiServerProvider>().serverManager;
// Sync readiness (playerReady/deferredPlay/firstPlay handshake) is
// per-item: cycle the Watch Together attachment across item changes, the
// same reset the old screen-swap flow got from dispose + re-attach.
// Same-item source switches keep the attachment (and readiness) intact.
final watchTogether = _activeWatchTogetherSession();
final watchTogetherWasAttached = watchTogether?.syncManager?.hasPlayer ?? false;
final cycleWatchTogetherAttachment = watchTogetherWasAttached && isItemChange;
await _sendStoppedProgressOnce();
_progressTracker?.stopTracking();
_progressTracker?.dispose();
_progressTracker = null;
unawaited(DiscordRPCService.instance.stopPlayback());
unawaited(TraktScrobbleService.instance.stopPlayback());
unawaited(TrackerCoordinator.instance.stopPlayback());
if (!isCurrentReload()) return true;
if (!_isCurrentPlaybackGeneration(playbackGeneration, currentPlayer)) return;
final requestedMediaIndex = _effectiveSelectedMediaIndex;
_currentMetadata = episodeMetadata;
VideoPlayerScreenState._activeId = episodeMetadata.id;
VideoPlayerScreenState._activeMediaIndex = requestedMediaIndex;
final targetMediaIndex = selectedMediaIndex ?? _effectiveSelectedMediaIndex;
final targetQualityPreset = qualityPreset ?? _selectedQualityPreset;
final targetAudioStreamId = useCurrentAudioStreamSelection
? selectedAudioStreamId ?? _selectedAudioStreamId
: selectedAudioStreamId;
// Eager identity-only: the loading UI shows the new title immediately,
// while the selection/source state flips with the session commit at the
// open boundary.
_currentMetadata = metadata;
VideoPlayerScreenState._activeId = metadata.id;
VideoPlayerScreenState._activeMediaIndex = targetMediaIndex;
_unfocusPlayNextPrompt();
_showPlayNextDialog = false;
_autoPlayTimer?.cancel();
_hasFirstFrame.value = false;
try {
// Detach before pausing so the reload's internal pause can't broadcast
// a party-wide pause; the finally below restores the attachment.
if (cycleWatchTogetherAttachment) {
watchTogether!.detachPlayer();
}
try {
await currentPlayer.pause();
} catch (e) {
appLogger.w('Failed to pause before $reason', error: e);
}
if (!isCurrentReload()) return true;
// Overlap the old item's stop report with the resolve round-trip; it
// is awaited again right before the open below.
final stoppedProgressFuture = _sendStoppedProgressOnce();
final playbackResolver = PlaybackSourceResolver(serverManager: serverManager, database: database);
final playbackContext = await playbackResolver.resolve(
metadata: episodeMetadata,
selectedMediaIndex: requestedMediaIndex,
selectedMediaSourceId: widget.selectedMediaSourceId,
offlineLibraryMode: widget.isOffline,
qualityPreset: _selectedQualityPreset,
selectedAudioStreamId: _selectedAudioStreamId,
metadata: metadata,
selectedMediaIndex: targetMediaIndex,
selectedMediaSourceId: selectedMediaSourceId,
offlineLibraryMode: _offlineLibraryMode,
qualityPreset: targetQualityPreset,
selectedAudioStreamId: targetAudioStreamId,
sessionIdentifier: _playbackSessionIdentifier,
transcodeSessionId: _playbackTranscodeSessionId,
);
if (!_isCurrentPlaybackGeneration(playbackGeneration, currentPlayer)) return;
if (!isCurrentReload()) return true;
final result = playbackContext.result;
final mediaClient = playbackContext.reportingClient;
final plexClient = mediaClient is PlexClient ? mediaClient : null;
@@ -196,106 +317,145 @@ extension _VideoPlayerEpisodeNavigationMethods on VideoPlayerScreenState {
throw PlaybackException('No video URL available');
}
Duration? resumePosition;
_isTranscoding = result.isTranscoding;
_effectiveIsOffline = result.isOffline;
_playbackContext = playbackContext;
_streamHeaders = streamHeaders;
_playbackPlaySessionId = result.playSessionId;
_playbackPlayMethod = result.playMethod;
_selectedAudioStreamId = result.activeAudioStreamId;
_effectiveSelectedMediaIndex = result.selectedMediaIndex;
if (result.fallbackReason != null && !_selectedQualityPreset.isOriginal) {
if (mounted) {
showErrorSnackBar(context, t.videoControls.transcodeUnavailableFallback);
}
_selectedQualityPreset = TranscodeQualityPreset.original;
// Build the replacement session now, commit it only once open()
// succeeds — until then every session-derived getter still describes
// the item that is actually playing.
final session = PlaybackSession.fromContext(
playbackContext,
requestedQualityPreset: targetQualityPreset,
requestedMediaSourceId: selectedMediaSourceId,
);
if (result.fallbackReason != null && !targetQualityPreset.isOriginal && mounted) {
showErrorSnackBar(context, t.videoControls.transcodeUnavailableFallback);
}
if (_isOfflinePlayback) {
final localOffset = await offlineWatchService.getLocalViewOffset(episodeMetadata.globalKey);
if (!_isCurrentPlaybackGeneration(playbackGeneration, currentPlayer)) return;
if (localOffset != null && localOffset > 0) {
resumePosition = Duration(milliseconds: localOffset);
}
}
resumePosition ??= episodeMetadata.viewOffsetMs != null
? Duration(milliseconds: episodeMetadata.viewOffsetMs!)
: null;
final openResumePosition = await _resolveOpenResumePosition(
metadata: metadata,
isOffline: _offlineLibraryMode || result.isOffline,
offlineWatchService: offlineWatchService,
requested: resumePosition,
);
if (!isCurrentReload()) return true;
final hasExternalSubs = result.externalSubtitles.isNotEmpty;
final isExoPlayer = player is PlayerAndroid;
final attachesSubsAtOpen = currentPlayer.attachesExternalSubtitlesAtOpen;
final displayCriteria = result.mediaInfo?.displayCriteria;
await currentPlayer.setDisplayCriteria(
!result.isTranscoding && displayCriteria?.canPrimeNativeDisplayCriteria == true ? displayCriteria : null,
final settingsService = await SettingsService.getInstance();
if (!isCurrentReload()) return true;
// Same pre-open frame-rate orchestration as the initial start flow —
// including the Android MPV startup decoder refresh, whose gate is
// armed before open and released after track setup below.
final frameRatePlan = await _prepareFrameRateForOpen(
currentPlayer: currentPlayer,
settingsService: settingsService,
preKnownFps: displayCriteria?.fps,
hasVideoUrl: true,
ensureAudioFocus: () => currentPlayer.requestAudioFocus(),
);
if (!_isCurrentPlaybackGeneration(playbackGeneration, currentPlayer)) return;
final openTiming = _playbackOpenTiming(
backend: episodeMetadata.backend,
if (frameRatePlan == null || !isCurrentReload()) return true;
_frameRate.resetForNewItem();
if (frameRatePlan.countsAsApplied) _frameRate.applied = true;
await _primeDisplayCriteria(
player: currentPlayer,
settingsService: settingsService,
displayCriteria: displayCriteria,
isTranscoding: result.isTranscoding,
resumePosition: resumePosition,
durationMs: episodeMetadata.durationMs,
);
await currentPlayer.setProperty('force-seekable', result.isTranscoding ? 'yes' : 'no');
if (!_isCurrentPlaybackGeneration(playbackGeneration, currentPlayer)) return;
await currentPlayer.open(
Media(result.videoUrl!, start: openTiming.mediaStart, headers: result.usesLocalMedia ? null : streamHeaders),
play: isExoPlayer || !hasExternalSubs,
externalSubtitles: isExoPlayer && hasExternalSubs ? result.externalSubtitles : null,
timelineOffset: openTiming.timelineOffset,
timelineDuration: openTiming.timelineDuration,
if (!isCurrentReload()) return true;
final openTiming = _playbackOpenTiming(
backend: metadata.backend,
isTranscoding: result.isTranscoding,
resumePosition: openResumePosition,
durationMs: metadata.durationMs,
);
await stoppedProgressFuture;
_progressTracker?.stopTracking();
_progressTracker?.dispose();
_progressTracker = null;
unawaited(DiscordRPCService.instance.stopPlayback());
unawaited(TraktScrobbleService.instance.stopPlayback());
unawaited(TrackerCoordinator.instance.stopPlayback());
if (!isCurrentReload()) return true;
if (!_isCurrentPlaybackGeneration(playbackGeneration, currentPlayer)) return;
_completionTriggered = false;
_isSwappingEpisode = false;
frameRatePlan.armStartupRefreshGate(currentPlayer);
final didOpen = await _openMediaOnPlayer(
player: currentPlayer,
settingsService: settingsService,
videoUrl: result.videoUrl!,
isTranscoding: result.isTranscoding,
timing: openTiming,
headers: result.usesLocalMedia ? null : streamHeaders,
play: !frameRatePlan.holdPlaybackStart && (attachesSubsAtOpen || !hasExternalSubs),
externalSubtitlesAtOpen: attachesSubsAtOpen && hasExternalSubs ? result.externalSubtitles : null,
shouldContinue: isCurrentReload,
onOpened: () {
// The player now owns the new file — publish the session at the
// same boundary so identity and source state flip together.
didOpenReplacement = true;
_commitPlaybackSession(session);
},
);
if (!didOpen || !isCurrentReload()) return true;
_completionLatch.reset();
_scrubPreviewSource?.dispose();
_setPlayerState(() {
_availableVersions = result.availableVersions;
_currentMediaInfo = result.mediaInfo;
_scrubPreviewSource = null;
_isLoadingNext = false;
});
// Versions/mediaInfo come from the committed session; rebuild so the
// controls pick them up. Same-part switches (quality/audio/subtitle)
// keep the scrub-preview source — BIF/trickplay is per part, so a
// reset would re-download identical bytes.
final reusesScrubPreview =
previousMetadata.globalKey == metadata.globalKey &&
previousPartId != null &&
previousPartId == result.mediaInfo?.partId;
if (reusesScrubPreview) {
_setPlayerState(() {});
} else {
_resetScrubPreviewForNewItem(metadata: metadata, mediaInfo: result.mediaInfo, mediaClient: mediaClient);
}
_clearEpisodeLoadingFlags();
if (isItemChange) _showChromeForSwappedItem();
_trackManager?.dispose();
final trackManager = TrackManager(
player: currentPlayer,
isActive: () => mounted && player != null,
// Plex writes track changes immediately. Jellyfin persists selected
// indexes through playback progress reports.
persistTrackPreference: plexClient != null ? _plexTrackPersister(() => plexClient) : null,
final trackManager = _buildTrackManager(
forPlayer: currentPlayer,
metadata: metadata,
plexClient: plexClient,
getProfileSettings: () => userProfileProvider.profileSettings,
waitForProfileSettings: _waitForProfileSettingsIfNeeded,
metadata: episodeMetadata,
mediaInfo: _currentMediaInfo,
preferredAudioTrack: currentAudioTrack,
preferredSubtitleTrack: currentSubtitleTrack,
preferredSecondarySubtitleTrack: currentSecondarySubtitleTrack,
showMessage: (message, {duration}) {
if (mounted) showAppSnackBar(context, message, duration: duration);
},
);
_trackManager = trackManager;
trackManager.cacheExternalSubtitles(result.externalSubtitles);
if (player is! PlayerAndroid && hasExternalSubs) {
trackManager.waitingForExternalSubsTrackSelection = true;
try {
await trackManager.addExternalSubtitles(result.externalSubtitles);
} finally {
await trackManager.resumeAfterSubtitleLoad();
}
if (!_isCurrentPlaybackGeneration(playbackGeneration, currentPlayer)) return;
} else {
trackManager.applyTrackSelectionWhenReady();
}
if (!_isCurrentPlaybackGeneration(playbackGeneration, currentPlayer)) return;
await _applyTracksAfterOpen(
forPlayer: currentPlayer,
trackManager: trackManager,
externalSubtitles: result.externalSubtitles,
// Same guard as the start path: don't resume a player a newer flow
// owns, and let a pending startup gate own the resume instead.
shouldResumeAfterSubtitleLoad: () => !frameRatePlan.holdPlaybackStart && mounted && player == currentPlayer,
);
if (!isCurrentReload()) return true;
await _releaseFrameRateStartupGate(
currentPlayer: currentPlayer,
settingsService: settingsService,
plan: frameRatePlan,
resumeAfterStartupGate: (reason) => _resumeAfterFrameRateStartupGate(
currentPlayer: currentPlayer,
attachesSubsAtOpen: attachesSubsAtOpen,
hasExternalSubs: hasExternalSubs,
reason: reason,
),
);
if (!isCurrentReload()) return true;
// Same helper as the initial start flow, so any future change lands in
// both paths together.
_wirePerItemPlaybackServices(
metadata: episodeMetadata,
metadata: metadata,
mediaClient: mediaClient,
offlineWatchService: offlineWatchService,
playSessionId: _playbackPlaySessionId,
@@ -304,24 +464,80 @@ extension _VideoPlayerEpisodeNavigationMethods on VideoPlayerScreenState {
);
try {
playbackState.setCurrentItem(episodeMetadata);
playbackState.setCurrentItem(metadata);
} catch (e) {
appLogger.d('playbackState.setCurrentItem failed', error: e);
}
await _loadAdjacentEpisodes();
if (!_isCurrentPlaybackGeneration(playbackGeneration, currentPlayer)) return;
unawaited(_loadAdjacentEpisodes(metadata: metadata, attempt: attempt));
if (!isCurrentReload()) return true;
if (_autoPipEnabled) {
unawaited(_videoPIPManager?.updateAutoPipState(isPlaying: currentPlayer.state.playing));
}
return true;
} catch (e) {
if (!_isCurrentPlaybackGeneration(playbackGeneration, currentPlayer)) return;
_isSwappingEpisode = false;
_completionTriggered = false;
_currentMetadata = previousMetadata;
VideoPlayerScreenState._activeId = previousMetadata.id;
appLogger.e('Failed to swap episode in PiP', error: e);
if (!isCurrentReload()) return true;
_completionLatch.reset();
if (!didOpenReplacement) {
// Nothing was opened: the previous session is still committed, so
// only the eagerly-set identity needs restoring before resuming.
_currentMetadata = previousMetadata;
VideoPlayerScreenState._activeId = previousMetadata.id;
VideoPlayerScreenState._activeMediaIndex = previousMediaIndex;
_hasFirstFrame.value = previousHasFirstFrame;
// If the stop report already went out, un-latch the tracker so the
// resumed session keeps reporting (and its eventual real stop sends).
_progressTracker?.resumeAfterStoppedReport();
if (wasPlayingBeforeReload && mounted && player == currentPlayer) {
unawaited(currentPlayer.play());
}
} else if (_progressTracker == null && player == currentPlayer) {
// The new file is playing and its session is committed — keep the
// new identity and make sure progress reporting is wired to the
// item actually on screen (the failure may have hit before
// _wirePerItemPlaybackServices ran).
_wirePerItemPlaybackServices(
metadata: metadata,
mediaClient: _playbackSession?.reportingClient,
offlineWatchService: offlineWatchService,
playSessionId: _playbackPlaySessionId,
playMethod: _playbackPlayMethod,
mediaInfo: _currentMediaInfo,
);
}
// Unconditional setState — beyond the flags this also publishes the
// rolled-back identity (_clearEpisodeLoadingFlags skips the rebuild
// when no loading flags are set).
_setPlayerState(() {
_isLoadingNext = false;
_isLoadingPrevious = false;
});
if (isItemChange) _showChromeForSwappedItem();
appLogger.e('Failed to reload media in-place during $reason', error: e);
if (mounted) {
showErrorSnackBar(context, t.messages.errorLoading(error: e.toString()));
}
return true;
} finally {
// Release the reload transition unless a newer flow already took
// ownership (a non-reload attempt force-idles it; a newer reload can
// then re-acquire it).
if (attempt.isCurrent && _playbackTransition == _PlaybackTransition.reloadingMedia) {
_playbackTransition = _PlaybackTransition.idle;
}
// Restore Watch Together sync on every exit: after a successful item
// change (readiness re-handshakes for the new item), after a failed
// reload (the still-playing old item must stay synced), and when the
// manager auto-detached itself on a mid-reload remote-action failure.
if (watchTogetherWasAttached &&
watchTogether != null &&
watchTogether.isInSession &&
mounted &&
player == currentPlayer &&
!(watchTogether.syncManager?.hasPlayer ?? true)) {
watchTogether.attachPlayer(currentPlayer);
}
}
}
}
@@ -6,7 +6,7 @@ extension _VideoPlayerEpisodeQueueMethods on VideoPlayerScreenState {
if (!mounted) return;
// Download/offline library mode uses the local downloaded queue instead.
if (widget.isOffline) return;
if (_offlineLibraryMode) return;
// Skip play queue for live TV (would interfere with tuner session)
if (widget.isLive) return;
@@ -77,10 +77,12 @@ extension _VideoPlayerEpisodeQueueMethods on VideoPlayerScreenState {
}
}
Future<void> _loadAdjacentEpisodes() async {
Future<void> _loadAdjacentEpisodes({MediaItem? metadata, _PlaybackAttempt? attempt}) async {
if (!mounted || widget.isLive) return;
if (widget.isOffline) {
final targetMetadata = metadata ?? _currentMetadata;
if (_offlineLibraryMode) {
// Offline mode: find next/previous from downloaded episodes
_loadAdjacentEpisodesOffline();
return;
@@ -89,10 +91,10 @@ extension _VideoPlayerEpisodeQueueMethods on VideoPlayerScreenState {
try {
final adjacentEpisodes = await _episodeNavigation.loadAdjacentEpisodes(
context: context,
metadata: _currentMetadata,
metadata: targetMetadata,
);
if (mounted) {
if (mounted && _currentMetadata.globalKey == targetMetadata.globalKey && (attempt == null || attempt.isCurrent)) {
_setPlayerState(() {
_nextEpisode = adjacentEpisodes.next;
_previousEpisode = adjacentEpisodes.previous;
+5 -5
View File
@@ -22,11 +22,11 @@ extension _VideoPlayerErrorMethods on VideoPlayerScreenState {
// Live TV: retry with progressively degraded stream settings
// (mirrors Plex web client fallback chain).
if (widget.isLive && _liveStreamFallbackLevel < 2 && !_isRetryingLiveStream) {
_liveStreamFallbackLevel++;
_isRetryingLiveStream = true;
appLogger.w('Live stream failed, retrying with fallback level $_liveStreamFallbackLevel');
_retryLiveStream().whenComplete(() => _isRetryingLiveStream = false);
if (widget.isLive && _live.fallbackLevel < 2 && !_live.retrying) {
_live.fallbackLevel++;
_live.retrying = true;
appLogger.w('Live stream failed, retrying with fallback level $_live.fallbackLevel');
_retryLiveStream().whenComplete(() => _live.retrying = false);
return;
}
@@ -59,14 +59,14 @@ extension _VideoPlayerLifecycleMethods on VideoPlayerScreenState {
}
void _suspendLiveTimelineForBackground() {
_resumeLiveTimelineOnResume = _liveTimelineTimer != null;
_live.resumeTimelineOnResume = _live.timelineTimer != null;
_stopLiveTimelineUpdates();
}
void _resumeLiveTimelineAfterBackgroundIfNeeded() {
final shouldResume = _resumeLiveTimelineOnResume;
_resumeLiveTimelineOnResume = false;
if (shouldResume && _liveSessionIdentifier != null) {
final shouldResume = _live.resumeTimelineOnResume;
_live.resumeTimelineOnResume = false;
if (shouldResume && _live.sessionIdentifier != null) {
_startLiveTimelineUpdates();
}
}
+132 -122
View File
@@ -3,10 +3,10 @@ part of '../../video_player_screen.dart';
extension _VideoPlayerLiveTvMethods on VideoPlayerScreenState {
/// Start periodic timeline heartbeats for live TV transcode session.
void _startLiveTimelineUpdates() {
final generation = ++_liveTimelineGeneration;
_liveTimelineTimer?.cancel();
_liveTimelineTimer = Timer.periodic(const Duration(seconds: 10), (_) {
if (generation != _liveTimelineGeneration) return;
final generation = ++_live.timelineGeneration;
_live.timelineTimer?.cancel();
_live.timelineTimer = Timer.periodic(const Duration(seconds: 10), (_) {
if (generation != _live.timelineGeneration) return;
final state = player?.state.playing == true ? 'playing' : 'paused';
_sendLiveTimeline(state);
});
@@ -14,7 +14,7 @@ extension _VideoPlayerLiveTvMethods on VideoPlayerScreenState {
// Sending time=0 immediately after player.open() causes the server
// to spawn a duplicate transcode job with offset=-1 that 404s.
Future.delayed(const Duration(seconds: 3), () {
if (_liveTimelineTimer != null && generation == _liveTimelineGeneration) {
if (_live.timelineTimer != null && generation == _live.timelineGeneration) {
final state = player?.state.playing == true ? 'playing' : 'paused';
_sendLiveTimeline(state);
}
@@ -22,30 +22,30 @@ extension _VideoPlayerLiveTvMethods on VideoPlayerScreenState {
}
void _stopLiveTimelineUpdates() {
_liveTimelineGeneration++;
_liveTimelineTimer?.cancel();
_liveTimelineTimer = null;
_live.timelineGeneration++;
_live.timelineTimer?.cancel();
_live.timelineTimer = null;
}
Future<void> _sendLiveTimeline(String state) async {
final client = _liveClient;
final playbackTime = _livePlaybackStartTime != null
? DateTime.now().difference(_livePlaybackStartTime!).inMilliseconds
final client = _live.client;
final playbackTime = _live.playbackStartTime != null
? DateTime.now().difference(_live.playbackStartTime!).inMilliseconds
: 0;
if (client is PlexClient) {
final sessionId = _liveSessionIdentifier;
final sessionPath = _liveSessionPath;
final sessionId = _live.sessionIdentifier;
final sessionPath = _live.sessionPath;
if (sessionId == null || sessionPath == null) return;
try {
// Use the program ratingKey from tune metadata, not the channel key
final ratingKey = _liveProgramId ?? _liveItemId ?? widget.metadata.id;
final ratingKey = _live.programId ?? _live.itemId;
// For live TV, player position/duration are unreliable (often 0).
// Use playbackTime as time, and program duration from tune metadata.
// Plex rejects timeline pings where time > duration; grow duration to
// match — otherwise Tunarr-style short synthetic programs 400 mid-stream.
final time = playbackTime;
final duration = max(_liveDurationMs ?? 0, time);
final duration = max(_live.durationMs ?? 0, time);
final updatedBuffer = await client.updateLiveTimeline(
ratingKey: ratingKey,
sessionPath: sessionPath,
@@ -57,8 +57,8 @@ extension _VideoPlayerLiveTvMethods on VideoPlayerScreenState {
);
if (updatedBuffer != null && mounted) {
_setPlayerState(() {
_captureBuffer = updatedBuffer;
_isAtLiveEdge =
_live.captureBuffer = updatedBuffer;
_live.atLiveEdge =
(_currentPositionEpoch >=
updatedBuffer.seekableEndEpoch - VideoPlayerScreenState._liveEdgeThresholdSeconds);
});
@@ -70,12 +70,12 @@ extension _VideoPlayerLiveTvMethods on VideoPlayerScreenState {
}
if (client is JellyfinClient) {
await _jellyfinLiveSession.report(
await _live.jellyfin.report(
client: client,
itemId: _liveItemId ?? widget.metadata.id,
itemId: _live.itemId,
state: state,
position: Duration(milliseconds: playbackTime),
duration: Duration(milliseconds: _liveDurationMs ?? 0),
duration: Duration(milliseconds: _live.durationMs ?? 0),
);
return;
}
@@ -89,14 +89,16 @@ extension _VideoPlayerLiveTvMethods on VideoPlayerScreenState {
/// that URL — degradation knobs apply only to the Plex transcoder branch.
Future<void> _retryLiveStream() async {
_liveSeek.cancel();
final client = _liveClient;
final ds = _liveStreamFallbackLevel < 1;
final dsa = _liveStreamFallbackLevel < 2;
final currentPlayer = player;
if (!mounted || currentPlayer == null) return;
final client = _live.client;
final ds = _live.fallbackLevel < 1;
final dsa = _live.fallbackLevel < 2;
if (client is PlexClient) {
final channels = widget.liveChannels;
final channelIndex = _liveChannelIndex;
final dvrKey = _liveDvrKey;
final channels = widget.live?.channels;
final channelIndex = _live.channelIndex;
final dvrKey = _live.dvrKey;
if (channels == null || channelIndex < 0 || channelIndex >= channels.length || dvrKey == null) {
appLogger.w('Cannot retry live stream — missing session info');
showGlobalErrorSnackBar(_redactPlayerError(_lastLogError ?? t.liveTv.liveStreamFailed));
@@ -108,48 +110,50 @@ extension _VideoPlayerLiveTvMethods on VideoPlayerScreenState {
// Re-tune to get a fresh capture session — the previous one is dead.
final tuneResult = await client.tuneChannel(dvrKey, channel.key);
if (tuneResult == null || !mounted) {
if (!mounted || player != currentPlayer) return;
if (tuneResult == null) {
showGlobalErrorSnackBar(_redactPlayerError(_lastLogError ?? t.liveTv.liveStreamFailed));
unawaited(_handleBackButton());
return;
}
_liveSessionIdentifier = tuneResult.sessionIdentifier;
_liveSessionPath = tuneResult.sessionPath;
_transcodeSessionId = generateSessionIdentifier();
_live.sessionIdentifier = tuneResult.sessionIdentifier;
_live.sessionPath = tuneResult.sessionPath;
_live.transcodeSessionId = generateSessionIdentifier();
final streamPath = await client.buildLiveStreamPath(
sessionPath: tuneResult.sessionPath,
sessionIdentifier: tuneResult.sessionIdentifier,
transcodeSessionId: _transcodeSessionId!,
transcodeSessionId: _live.transcodeSessionId!,
directStream: ds,
directStreamAudio: dsa,
);
if (streamPath == null || !mounted) {
if (!mounted || player != currentPlayer) return;
if (streamPath == null) {
showGlobalErrorSnackBar(_redactPlayerError(_lastLogError ?? t.liveTv.liveStreamFailed));
unawaited(_handleBackButton());
return;
}
final streamUrl = client.buildLiveStreamUrl(streamPath);
_liveStreamUrl = streamUrl;
_livePlaybackStartTime = DateTime.now();
_streamStartEpoch = DateTime.now().millisecondsSinceEpoch / 1000.0;
_isAtLiveEdge = true;
_live.streamUrl = streamUrl;
_live.markStreamRestartedAtLiveEdge();
await _setLiveStreamOptions();
await player!.open(Media(streamUrl, headers: const {'Accept-Language': 'en'}), play: true, isLive: true);
await _setLiveStreamOptions(currentPlayer);
await currentPlayer.open(Media(streamUrl, headers: const {'Accept-Language': 'en'}), play: true, isLive: true);
return;
}
final liveStreamUrl = _liveStreamUrl;
final liveStreamUrl = _live.streamUrl;
if (client is JellyfinClient && liveStreamUrl != null) {
appLogger.i('Retrying Jellyfin live stream by re-opening URL');
_livePlaybackStartTime = DateTime.now();
_streamStartEpoch = DateTime.now().millisecondsSinceEpoch / 1000.0;
_isAtLiveEdge = true;
await _setLiveStreamOptions();
await player!.open(Media(liveStreamUrl, headers: const {'Accept-Language': 'en'}), play: true, isLive: true);
_live.markStreamRestartedAtLiveEdge();
await _setLiveStreamOptions(currentPlayer);
await currentPlayer.open(
Media(liveStreamUrl, headers: const {'Accept-Language': 'en'}),
play: true,
isLive: true,
);
return;
}
@@ -161,18 +165,16 @@ extension _VideoPlayerLiveTvMethods on VideoPlayerScreenState {
/// Configure MPV options for live streaming.
/// The official Plex Media Player does not set client-side reconnect options —
/// reconnection is handled by the server's transcoder on the input side.
Future<void> _setLiveStreamOptions() async {
await player!.setProperty('force-seekable', 'no');
}
Future<void> _setLiveStreamOptions(Player player) => player.setProperty('force-seekable', 'no');
/// The raw live playback position as an absolute epoch second
/// (`_streamStartEpoch + player position`).
int get _rawPositionEpoch => (_streamStartEpoch + (player?.state.position.inSeconds ?? 0)).round();
/// (`_live.streamStartEpoch + player position`).
int get _rawPositionEpoch => (_live.streamStartEpoch + (player?.state.position.inSeconds ?? 0)).round();
/// The current playback position as an absolute epoch second (for live TV time-shift).
///
/// While a relative skip is pending/settling, this returns the accumulator's
/// target rather than the raw sum. During a live re-open `_streamStartEpoch`
/// target rather than the raw sum. During a live re-open `_live.streamStartEpoch`
/// is advanced to the target before the new stream's position resets to ~0,
/// so the raw sum transiently overshoots; pinning to the pending target keeps
/// seek accumulation and the live-edge heartbeat ([_sendLiveTimeline]) correct
@@ -196,47 +198,53 @@ extension _VideoPlayerLiveTvMethods on VideoPlayerScreenState {
/// Seek the live TV stream to an absolute epoch second.
/// Creates a new transcode session at the target offset.
Future<void> _seekLivePosition(int targetEpochSeconds) async {
if (_captureBuffer == null ||
_liveSessionPath == null ||
_liveSessionIdentifier == null ||
_transcodeSessionId == null) {
final currentPlayer = player;
if (currentPlayer == null) return;
if (_live.captureBuffer == null ||
_live.sessionPath == null ||
_live.sessionIdentifier == null ||
_live.transcodeSessionId == null) {
return;
}
final clamped = targetEpochSeconds.clamp(_captureBuffer!.seekableStartEpoch, _captureBuffer!.seekableEndEpoch);
final clamped = targetEpochSeconds.clamp(
_live.captureBuffer!.seekableStartEpoch,
_live.captureBuffer!.seekableEndEpoch,
);
final offsetSeconds = clamped - _captureBuffer!.startedAt.round();
final offsetSeconds = clamped - _live.captureBuffer!.startedAt.round();
// Live seek requires a transcode session — Plex-only by protocol. The
// Plex path populates _captureBuffer; the Jellyfin path never does, so
// Plex path populates _live.captureBuffer; the Jellyfin path never does, so
// the early-return above already covers Jellyfin in practice. This
// explicit guard keeps the contract obvious.
final client = _liveClient;
final client = _live.client;
if (client is! PlexClient) return;
final streamPath = await client.buildLiveStreamPath(
sessionPath: _liveSessionPath!,
sessionIdentifier: _liveSessionIdentifier!,
transcodeSessionId: _transcodeSessionId!,
sessionPath: _live.sessionPath!,
sessionIdentifier: _live.sessionIdentifier!,
transcodeSessionId: _live.transcodeSessionId!,
offsetSeconds: offsetSeconds,
);
if (streamPath == null || !mounted) return;
if (streamPath == null || !mounted || player != currentPlayer) return;
final streamUrl = client.buildLiveStreamUrl(streamPath);
_streamStartEpoch = _captureBuffer!.startedAt + offsetSeconds;
_isAtLiveEdge = (clamped >= _captureBuffer!.seekableEndEpoch - VideoPlayerScreenState._liveEdgeThresholdSeconds);
_livePlaybackStartTime = DateTime.now();
_live.streamStartEpoch = _live.captureBuffer!.startedAt + offsetSeconds;
_live.atLiveEdge =
(clamped >= _live.captureBuffer!.seekableEndEpoch - VideoPlayerScreenState._liveEdgeThresholdSeconds);
_live.playbackStartTime = DateTime.now();
await _setLiveStreamOptions();
await player!.open(Media(streamUrl, headers: const {'Accept-Language': 'en'}), play: true, isLive: true);
await _setLiveStreamOptions(currentPlayer);
await currentPlayer.open(Media(streamUrl, headers: const {'Accept-Language': 'en'}), play: true, isLive: true);
if (mounted) _setPlayerState(() {});
}
/// Current seekable epoch window for [_liveSeek], or null when there is no
/// live capture buffer.
LiveSeekBounds? _liveSeekBounds() {
final buffer = _captureBuffer;
final buffer = _live.captureBuffer;
if (buffer == null) return null;
return (start: buffer.seekableStartEpoch, end: buffer.seekableEndEpoch);
}
@@ -246,10 +254,10 @@ extension _VideoPlayerLiveTvMethods on VideoPlayerScreenState {
void _onLiveSeekTargetChanged() {
if (!mounted) return;
final pending = _liveSeek.pendingEpoch;
final buffer = _captureBuffer;
final buffer = _live.captureBuffer;
_setPlayerState(() {
if (pending != null && buffer != null) {
_isAtLiveEdge = pending >= buffer.seekableEndEpoch - VideoPlayerScreenState._liveEdgeThresholdSeconds;
_live.atLiveEdge = pending >= buffer.seekableEndEpoch - VideoPlayerScreenState._liveEdgeThresholdSeconds;
}
});
}
@@ -279,19 +287,21 @@ extension _VideoPlayerLiveTvMethods on VideoPlayerScreenState {
/// Jump to the live edge of the capture buffer.
Future<void> _jumpToLiveEdge() async {
if (_captureBuffer == null) return;
await _seekLiveToEpoch(_captureBuffer!.seekableEndEpoch);
if (_live.captureBuffer == null) return;
await _seekLiveToEpoch(_live.captureBuffer!.seekableEndEpoch);
}
Future<void> _switchLiveChannel(int delta) async {
final channels = widget.liveChannels;
final channels = widget.live?.channels;
if (channels == null || channels.isEmpty) return;
if (_isSwitchingChannel) return; // debounce concurrent switches
if (_playbackTransition != _PlaybackTransition.idle) return; // debounce concurrent switches
final newIndex = _liveChannelIndex + delta;
final newIndex = _live.channelIndex + delta;
if (newIndex < 0 || newIndex >= channels.length) return;
final currentPlayer = player;
if (currentPlayer == null) return;
_isSwitchingChannel = true;
_playbackTransition = _PlaybackTransition.switchingChannel;
_liveSeek.cancel();
// Stop old session heartbeats and notify server
@@ -313,27 +323,30 @@ extension _VideoPlayerLiveTvMethods on VideoPlayerScreenState {
final genericClient = multiServer.getClientForServer(ServerId(serverInfo.serverId));
final resolution = await genericClient?.liveTv.resolveStreamUrl(channel.key, dvrKey: serverInfo.dvrKey);
if (!mounted || player != currentPlayer) return;
if (resolution != null) {
// Jellyfin: pre-resolved negotiated URL.
await _setLiveStreamOptions();
await player!.open(Media(resolution.url, headers: const {'Accept-Language': 'en'}), play: true, isLive: true);
_liveClient = genericClient;
_liveDvrKey = serverInfo.dvrKey;
_liveStreamUrl = resolution.url;
_liveItemId = channel.key;
_liveSessionIdentifier = resolution.playSessionId;
_jellyfinLiveSession = JellyfinLiveSessionTracker(playSessionId: resolution.playSessionId);
_livePlaybackStartTime = DateTime.now();
_captureBuffer = null;
_programBeginsAt = null;
_liveProgramId = null;
_liveDurationMs = null;
_streamStartEpoch = DateTime.now().millisecondsSinceEpoch / 1000.0;
_isAtLiveEdge = true;
await _setLiveStreamOptions(currentPlayer);
await currentPlayer.open(
Media(resolution.url, headers: const {'Accept-Language': 'en'}),
play: true,
isLive: true,
);
_live.client = genericClient;
_live.dvrKey = serverInfo.dvrKey;
_live.streamUrl = resolution.url;
_live.itemId = channel.key;
_live.sessionIdentifier = resolution.playSessionId;
_live.jellyfin = JellyfinLiveSessionTracker(playSessionId: resolution.playSessionId);
_live.captureBuffer = null;
_live.programBeginsAt = null;
_live.programId = null;
_live.durationMs = null;
_live.markStreamRestartedAtLiveEdge();
if (!mounted) return;
_setPlayerState(() {
_liveChannelIndex = newIndex;
_liveChannelName = channel.displayName;
_live.channelIndex = newIndex;
_live.channelName = channel.displayName;
});
_startLiveTimelineUpdates();
return;
@@ -344,43 +357,41 @@ extension _VideoPlayerLiveTvMethods on VideoPlayerScreenState {
if (client == null) return;
final tuneResult = await client.tuneChannel(serverInfo.dvrKey, channel.key);
if (tuneResult == null || !mounted) return;
if (tuneResult == null || !mounted || player != currentPlayer) return;
_transcodeSessionId = generateSessionIdentifier();
_liveStreamFallbackLevel = 0;
_live.transcodeSessionId = generateSessionIdentifier();
_live.fallbackLevel = 0;
final streamPath = await client.buildLiveStreamPath(
sessionPath: tuneResult.sessionPath,
sessionIdentifier: tuneResult.sessionIdentifier,
transcodeSessionId: _transcodeSessionId!,
transcodeSessionId: _live.transcodeSessionId!,
);
if (streamPath == null || !mounted) return;
if (streamPath == null || !mounted || player != currentPlayer) return;
final streamUrl = client.buildLiveStreamUrl(streamPath);
await _setLiveStreamOptions();
await player!.open(Media(streamUrl, headers: const {'Accept-Language': 'en'}), play: true, isLive: true);
await _setLiveStreamOptions(currentPlayer);
await currentPlayer.open(Media(streamUrl, headers: const {'Accept-Language': 'en'}), play: true, isLive: true);
_liveClient = client;
_liveDvrKey = serverInfo.dvrKey;
_liveStreamUrl = streamUrl;
_liveItemId = channel.key;
_livePlaybackStartTime = DateTime.now();
_liveProgramId = tuneResult.metadata.ratingKey;
_liveDurationMs = tuneResult.metadata.duration;
_live.client = client;
_live.dvrKey = serverInfo.dvrKey;
_live.streamUrl = streamUrl;
_live.itemId = channel.key;
_live.programId = tuneResult.metadata.ratingKey;
_live.durationMs = tuneResult.metadata.duration;
// Reset time-shift state for new channel
_captureBuffer = tuneResult.captureBuffer;
_programBeginsAt = tuneResult.beginsAt;
_streamStartEpoch = DateTime.now().millisecondsSinceEpoch / 1000.0;
_isAtLiveEdge = true;
_live.captureBuffer = tuneResult.captureBuffer;
_live.programBeginsAt = tuneResult.beginsAt;
_live.markStreamRestartedAtLiveEdge();
if (!mounted) return;
_setPlayerState(() {
_liveChannelIndex = newIndex;
_liveChannelName = channel.displayName;
_liveSessionIdentifier = tuneResult.sessionIdentifier;
_liveSessionPath = tuneResult.sessionPath;
_live.channelIndex = newIndex;
_live.channelName = channel.displayName;
_live.sessionIdentifier = tuneResult.sessionIdentifier;
_live.sessionPath = tuneResult.sessionPath;
});
// Restart timeline heartbeats for the new session
@@ -389,15 +400,14 @@ extension _VideoPlayerLiveTvMethods on VideoPlayerScreenState {
appLogger.e('Failed to switch channel', error: e);
if (mounted) showErrorSnackBar(context, e.toString());
} finally {
_isSwitchingChannel = false;
_playbackTransition = _PlaybackTransition.idle;
}
}
bool get _hasNextChannel =>
widget.isLive &&
widget.liveChannels != null &&
_liveChannelIndex >= 0 &&
_liveChannelIndex < (widget.liveChannels!.length - 1);
bool get _hasNextChannel {
final channels = widget.live?.channels;
return channels != null && _live.channelIndex >= 0 && _live.channelIndex < channels.length - 1;
}
bool get _hasPreviousChannel => widget.isLive && widget.liveChannels != null && _liveChannelIndex > 0;
bool get _hasPreviousChannel => widget.live?.channels != null && _live.channelIndex > 0;
}
+2 -6
View File
@@ -37,18 +37,14 @@ extension _VideoPlayerPipMethods on VideoPlayerScreenState {
if (needsVideoFilter && _videoFilterManager == null && settings != null) {
_videoFilterManager = VideoFilterManager(
player: currentPlayer,
availableVersions: _availableVersions,
selectedMediaIndex: _effectiveSelectedMediaIndex,
initialBoxFitMode: settings.read(SettingsService.defaultBoxFitMode),
initialPlayerSize: initialPlayerSize,
onBoxFitModeChanged: (mode) => settings.write(SettingsService.defaultBoxFitMode, mode),
);
_videoFilterManager!.updateVideoFilter();
unawaited(_videoFilterManager!.updateVideoFilter());
}
if (_videoPIPManager == null) {
_videoPIPManager = VideoPIPManager(player: currentPlayer, initialPlayerSize: initialPlayerSize);
}
_videoPIPManager ??= VideoPIPManager(player: currentPlayer, initialPlayerSize: initialPlayerSize);
_videoPIPManager!.onBeforeEnterPip = _preparePipFiltersForEntry;
_attachPipStateListener();
}
@@ -0,0 +1,417 @@
part of '../../video_player_screen.dart';
/// Outcome of the Android pre-open frame-rate negotiation for the initial
/// start flow: which pre-switch ran, whether playback must open paused
/// behind a startup gate, and which post-open follow-up (fallback switch
/// or mpv decoder refresh) releases it.
class _FrameRateStartupPlan {
_FrameRateStartupPlan({required this.fps});
final double? fps;
bool attemptedMpvPreLoad = false;
bool didPreLoadSwitch = false;
bool preOpenExoHandled = false;
bool needsPostOpenSwitch = false;
bool needsStartupRefresh = false;
Future<bool>? _startupFrameReady;
/// Whether playback must open paused behind a startup gate that
/// [_releaseFrameRateStartupGate] resumes.
bool get holdPlaybackStart => needsPostOpenSwitch || needsStartupRefresh;
/// Whether the pre-open negotiation already counts as the per-item
/// switch — keeps the post-first-frame fallback from double-switching
/// while a planned follow-up is still pending.
bool get countsAsApplied => didPreLoadSwitch || attemptedMpvPreLoad || preOpenExoHandled;
/// Subscribe to the first rendered frame *before* open() so the startup
/// decoder refresh can't miss a synchronously-fast restart event.
void armStartupRefreshGate(Player player) {
if (!needsStartupRefresh) return;
appLogger.d('Frame rate matching: opening Android MPV paused for startup decoder refresh');
_startupFrameReady = player.streams.playbackRestart.first
.then((_) => true)
.timeout(
const Duration(seconds: 15),
onTimeout: () {
appLogger.w('Timed out waiting for Android MPV startup frame before decoder refresh');
return false;
},
);
}
}
/// Shared building blocks for opening media on the live player.
///
/// The initial start flow ([_startPlayback]), the in-place reload flow
/// ([_reloadMediaInPlace]), and the transcode-restart seek
/// ([_restartPlexTranscodeAt]) all route through these helpers so per-open
/// behavior (display priming, frame-rate suppression windows, native
/// subtitle styling, the open sequence itself) cannot drift between paths.
/// This is also the only place that reads
/// [SettingsService.displaySwitchDelay].
extension _VideoPlayerOpenMethods on VideoPlayerScreenState {
/// Prime native display matching (tvOS HDMI mode) from server metadata
/// before the decoder emits stream properties. The native side resolves
/// only after any resulting display-mode switch has settled, plus the
/// user-configured extra delay on Apple TV.
Future<void> _primeDisplayCriteria({
required Player player,
required SettingsService settingsService,
required MediaDisplayCriteria? displayCriteria,
required bool isTranscoding,
}) {
return player.setDisplayCriteria(
!isTranscoding && displayCriteria?.canPrimeNativeDisplayCriteria == true ? displayCriteria : null,
extraDelayMs: PlatformDetector.isAppleTV() ? settingsService.read(SettingsService.displaySwitchDelay) * 1000 : 0,
);
}
/// Ask the platform to renegotiate the display refresh rate for [fps],
/// arming the MediaSession pause-suppression window first. The native call
/// returns only after the real display-change event (+ settle + the
/// user-configured delay). Returns whether a switch was initiated.
Future<bool> _switchDisplayFrameRateForOpen({
required Player player,
required SettingsService settingsService,
required double fps,
required int durationMs,
}) {
final delaySec = settingsService.read(SettingsService.displaySwitchDelay);
_frameRate.beginSuppressWindow(delaySec);
return player.setVideoFrameRate(fps, durationMs, extraDelayMs: delaySec * 1000);
}
/// Whether the Android pre-open frame-rate negotiation applies: the user
/// opted into per-content refresh-rate matching and metadata already told
/// us the target fps. Shared by the start and reload flows so the
/// eligibility rule cannot drift between them.
bool _shouldAutoSwitchFrameRateForOpen(SettingsService settingsService, double? fps) {
return Platform.isAndroid && settingsService.read(SettingsService.matchContentFrameRate) && fps != null && fps > 0;
}
/// Resolve where a fresh open should start: explicit request → locally
/// tracked offline progress → server view offset.
Future<Duration?> _resolveOpenResumePosition({
required MediaItem metadata,
required bool isOffline,
required OfflineWatchSyncService offlineWatchService,
Duration? requested,
}) async {
if (requested != null) return requested;
// In offline mode, prefer locally tracked progress over the cached server
// value since the user may have watched further since downloading.
if (isOffline) {
final localOffset = await offlineWatchService.getLocalViewOffset(metadata.globalKey);
if (localOffset != null && localOffset > 0) {
appLogger.d('Resuming offline playback from local progress: ${localOffset}ms');
return Duration(milliseconds: localOffset);
}
}
return metadata.viewOffsetMs != null ? Duration(milliseconds: metadata.viewOffsetMs!) : null;
}
/// Run the Android pre-open frame-rate strategy for the initial start:
/// mpv switches before load (its decoder must start after the mode change,
/// then gets a startup refresh); ExoPlayer switches before open (after
/// audio focus, so AudioTrack passthrough survives the renegotiation);
/// anything that could not switch up front falls back to a post-open
/// switch that holds playback start. Returns null when the screen/player
/// went stale mid-switch and the caller must bail.
Future<_FrameRateStartupPlan?> _prepareFrameRateForOpen({
required Player currentPlayer,
required SettingsService settingsService,
required double? preKnownFps,
required bool hasVideoUrl,
required Future<void> Function() ensureAudioFocus,
}) async {
final plan = _FrameRateStartupPlan(fps: preKnownFps);
final willAutoSwitch = _shouldAutoSwitchFrameRateForOpen(settingsService, preKnownFps);
// willAutoSwitch is Android-only, so the strategy fork below is between
// the two Android backends: mpv needs its decoder refreshed after a
// display switch (pre-load path), ExoPlayer switches pre-open instead.
final isAndroidMpv = currentPlayer.needsDecoderRefreshAfterDisplaySwitch;
final needsMpvPreLoad = willAutoSwitch && isAndroidMpv && hasVideoUrl;
final needsExoPreOpen = willAutoSwitch && !isAndroidMpv && hasVideoUrl;
plan.needsPostOpenSwitch = willAutoSwitch && !needsMpvPreLoad && !needsExoPreOpen;
plan.attemptedMpvPreLoad = needsMpvPreLoad;
// MPV on Android can decode and present its first paused frame before a
// post-open display switch settles. Switch first when metadata already
// gives us the FPS so MediaCodec starts after the display mode change.
if (needsMpvPreLoad) {
final durationMs = _currentMetadata.durationMs ?? currentPlayer.state.duration.inMilliseconds;
try {
appLogger.d('Frame rate matching: pre-load MPV switch to ${preKnownFps}fps (duration: ${durationMs}ms)');
plan.didPreLoadSwitch = await _switchDisplayFrameRateForOpen(
player: currentPlayer,
settingsService: settingsService,
fps: preKnownFps!,
durationMs: durationMs,
);
if (!mounted || player != currentPlayer) return null;
if (plan.didPreLoadSwitch) {
_frameRate.applied = true;
plan.needsStartupRefresh = true;
}
appLogger.d(
'Frame rate matching: pre-load MPV switch complete '
'(switched=${plan.didPreLoadSwitch}, startupRefresh=${plan.needsStartupRefresh})',
);
} catch (e) {
appLogger.w('Failed to apply pre-load MPV frame rate matching', error: e);
plan.needsPostOpenSwitch = true;
plan.needsStartupRefresh = false;
}
}
// ExoPlayer prepares AudioTrack during open() even when opened paused.
// On Shield/AVR chains, switching HDMI refresh rate after that can break
// direct passthrough, so switch before ExoPlayer creates renderers.
if (needsExoPreOpen) {
final durationMs = _currentMetadata.durationMs ?? currentPlayer.state.duration.inMilliseconds;
try {
await ensureAudioFocus();
if (!mounted || player != currentPlayer) return null;
appLogger.d('Frame rate matching: pre-open ExoPlayer switch to ${preKnownFps}fps (duration: ${durationMs}ms)');
final didSwitch = await _switchDisplayFrameRateForOpen(
player: currentPlayer,
settingsService: settingsService,
fps: preKnownFps!,
durationMs: durationMs,
);
if (!mounted || player != currentPlayer) return null;
plan.preOpenExoHandled = true;
appLogger.d('Frame rate matching: pre-open ExoPlayer switch complete (switched=$didSwitch)');
} catch (e) {
appLogger.w('Failed to apply pre-open ExoPlayer frame rate matching', error: e);
plan.needsPostOpenSwitch = true;
plan.preOpenExoHandled = false;
}
}
return plan;
}
/// Release the startup gate a [_FrameRateStartupPlan] held playback
/// behind: run the post-open fallback switch, or wait for the first
/// rendered frame and refresh the mpv decoder, then resume via
/// [resumeAfterStartupGate].
Future<void> _releaseFrameRateStartupGate({
required Player currentPlayer,
required SettingsService settingsService,
required _FrameRateStartupPlan plan,
required Future<void> Function(String reason) resumeAfterStartupGate,
}) async {
// Fallback refresh-rate path. The player was opened paused;
// setVideoFrameRate awaits the real display-change event (+ settle +
// user delay) before returning, then we start playback.
if (plan.needsPostOpenSwitch && mounted && player == currentPlayer) {
_frameRate.applied = true;
final durationMs = _currentMetadata.durationMs ?? currentPlayer.state.duration.inMilliseconds;
bool didSwitch = false;
try {
didSwitch = await _switchDisplayFrameRateForOpen(
player: currentPlayer,
settingsService: settingsService,
fps: plan.fps!,
durationMs: durationMs,
);
if (!mounted || player != currentPlayer) return;
if (didSwitch) {
await _refreshAndroidMpvDecoderAfterFrameRateSwitch(reason: 'post-open frame rate switch');
}
} catch (e) {
appLogger.w('Failed to apply pre-playback frame rate matching', error: e);
}
// Always resume — either the switch completed and we want to play,
// or no switch was needed and we need to start playback now that the
// preparation gate has been cleared.
await resumeAfterStartupGate('post-open frame rate switch');
unawaited(
Sentry.addBreadcrumb(
Breadcrumb(message: 'Pre-playback frame rate: ${plan.fps}fps, switched=$didSwitch', category: 'player'),
),
);
} else if (plan.needsStartupRefresh && mounted && player == currentPlayer) {
appLogger.d('Frame rate matching: waiting for Android MPV startup frame before decoder refresh');
final startupFrameReady = plan._startupFrameReady;
final startupReady = startupFrameReady == null ? false : await startupFrameReady;
if (mounted && player == currentPlayer) {
if (startupReady) {
await Future<void>.delayed(const Duration(milliseconds: 100));
await _refreshAndroidMpvDecoderAfterFrameRateSwitch(reason: 'pre-load frame rate startup');
await resumeAfterStartupGate('startup decoder refresh');
} else {
appLogger.w('Frame rate matching: skipping Android MPV decoder refresh because startup frame timed out');
await resumeAfterStartupGate('startup frame timeout');
}
}
unawaited(
Sentry.addBreadcrumb(
Breadcrumb(
message: 'Android MPV startup decoder refresh after pre-load frame-rate switch',
category: 'player',
),
),
);
}
}
/// Resume playback once a frame-rate startup gate releases: a pending
/// post-open external-subtitle load resumes through the track manager
/// (which also arms selection), everything else plays directly. Shared by
/// the start and reload flows.
Future<void> _resumeAfterFrameRateStartupGate({
required Player currentPlayer,
required bool attachesSubsAtOpen,
required bool hasExternalSubs,
required String reason,
}) async {
if (!mounted || player != currentPlayer) return;
final trackManager = _trackManager;
if (trackManager == null) return;
appLogger.d('Frame rate matching: resuming playback after $reason');
if (!attachesSubsAtOpen && hasExternalSubs) {
await trackManager.resumeAfterSubtitleLoad();
} else {
await currentPlayer.play();
}
}
/// Push the user's subtitle style to the native rendering layer (no-op on
/// mpv backends, which style via `sub-*` properties). Must run after
/// open() since that's when ExoPlayer initializes its subtitle views.
Future<void> _applyNativeSubtitleStyle(Player player, SettingsService settingsService) {
return player.setSubtitleStyle(
fontSize: settingsService.read(SettingsService.subtitleFontSize).toDouble(),
textColor: settingsService.read(SettingsService.subtitleTextColor),
borderSize: settingsService.read(SettingsService.subtitleBorderSize).toDouble(),
borderColor: settingsService.read(SettingsService.subtitleBorderColor),
bgColor: settingsService.read(SettingsService.subtitleBackgroundColor),
bgOpacity: settingsService.read(SettingsService.subtitleBackgroundOpacity),
subtitlePosition: settingsService.read(SettingsService.subtitlePosition),
bold: settingsService.read(SettingsService.subtitleBold),
italic: settingsService.read(SettingsService.subtitleItalic),
);
}
/// Build the per-item [TrackManager] for a freshly opened source. The
/// start and reload flows construct it identically apart from where the
/// preferred tracks and profile settings come from.
TrackManager _buildTrackManager({
required Player forPlayer,
required MediaItem metadata,
required PlexClient? plexClient,
required MediaServerUserProfile? Function() getProfileSettings,
AudioTrack? preferredAudioTrack,
SubtitleTrack? preferredSubtitleTrack,
SubtitleTrack? preferredSecondarySubtitleTrack,
}) {
return TrackManager(
player: forPlayer,
isActive: () => mounted && player == forPlayer,
// Plex writes track changes immediately. Jellyfin persists selected
// indexes through playback progress reports.
persistTrackPreference: plexClient != null ? _plexTrackPersister(() => plexClient) : null,
getProfileSettings: getProfileSettings,
waitForProfileSettings: _waitForProfileSettingsIfNeeded,
metadata: metadata,
mediaInfo: _currentMediaInfo,
preferredAudioTrack: preferredAudioTrack,
preferredSubtitleTrack: preferredSubtitleTrack,
preferredSecondarySubtitleTrack: preferredSecondarySubtitleTrack,
showMessage: (message, {duration}) {
if (mounted) showAppSnackBar(context, message, duration: duration);
},
);
}
/// Apply track selection for a freshly opened source: mpv backends get
/// external subtitles via the post-open sub-add dance (opened paused to
/// avoid the issue #226 race), others arm selection directly.
/// [shouldResumeAfterSubtitleLoad] lets a startup gate own the resume.
/// [applySelectionWhenResumeSkipped] is for flows that legitimately stay
/// paused (e.g. a transcode restart while paused): selection is still
/// armed and the waiting flag cleared instead of leaving both dangling.
Future<void> _applyTracksAfterOpen({
required Player forPlayer,
required TrackManager trackManager,
required List<SubtitleTrack> externalSubtitles,
required bool Function() shouldResumeAfterSubtitleLoad,
bool applySelectionWhenResumeSkipped = false,
}) async {
if (!forPlayer.attachesExternalSubtitlesAtOpen && externalSubtitles.isNotEmpty) {
trackManager.waitingForExternalSubsTrackSelection = true;
try {
await trackManager.addExternalSubtitles(externalSubtitles);
} finally {
if (shouldResumeAfterSubtitleLoad()) {
await trackManager.resumeAfterSubtitleLoad();
} else if (applySelectionWhenResumeSkipped) {
trackManager.waitingForExternalSubsTrackSelection = false;
trackManager.applyTrackSelectionWhenReady();
}
}
} else {
// Subs attached at open time (ExoPlayer) or none: apply once tracks
// are available.
trackManager.applyTrackSelectionWhenReady();
}
}
/// Drop the previous item's scrub-preview source and kick off the async
/// thumbnail load for the new one.
void _resetScrubPreviewForNewItem({
required MediaItem metadata,
required MediaSourceInfo? mediaInfo,
required MediaServerClient? mediaClient,
}) {
_scrubPreviewSource?.dispose();
_setPlayerState(() => _scrubPreviewSource = null);
_queueScrubPreviewLoad(metadata: metadata, mediaInfo: mediaInfo, mediaClient: mediaClient);
}
/// Open [videoUrl] on [player]: force-seekable hint → open → native
/// subtitle style.
///
/// [shouldContinue] is re-checked between the awaits so stale generations
/// stop without touching the player further. [onOpened] fires immediately
/// after open() returns (before styling) so callers can flip rollback
/// bookkeeping at the exact ownership boundary.
///
/// Returns false if [shouldContinue] stopped the sequence before open;
/// true once open() has been issued (even if styling was skipped).
Future<bool> _openMediaOnPlayer({
required Player player,
required SettingsService settingsService,
required String videoUrl,
required bool isTranscoding,
required _PlaybackOpenTiming timing,
Map<String, String>? headers,
required bool play,
List<SubtitleTrack>? externalSubtitlesAtOpen,
bool Function()? shouldContinue,
void Function()? onOpened,
}) async {
// Transcode streams can be seekable even when MPV cannot prove it
// from response headers. Reset non-transcodes so live/direct/offline
// streams keep native seekability detection.
await player.setProperty('force-seekable', isTranscoding ? 'yes' : 'no');
if (shouldContinue != null && !shouldContinue()) return false;
await player.open(
Media(videoUrl, start: timing.mediaStart, headers: headers),
play: play,
externalSubtitles: externalSubtitlesAtOpen,
timelineOffset: timing.timelineOffset,
timelineDuration: timing.timelineDuration,
);
onOpened?.call();
if (shouldContinue != null && !shouldContinue()) return true;
await _applyNativeSubtitleStyle(player, settingsService);
return true;
}
}
@@ -6,8 +6,9 @@ extension _VideoPlayerPlaybackPromptMethods on VideoPlayerScreenState {
// inter-segment gaps in the chunked MKV transcode stream.
if (widget.isLive) return;
if (!completed) return;
// Ignore spurious EOF from the old file during in-place episode swap
if (_isSwappingEpisode) return;
// Ignore spurious EOF from the old file during an in-place media-source
// transition (episode swap, transcode restart, channel switch).
if (_playbackTransition != _PlaybackTransition.idle) return;
// mpv does not flip the `pause` property on EOF, so _onPlayingStateChanged
// never fires false. Normalize all playback-dependent state.
@@ -28,14 +29,14 @@ extension _VideoPlayerPlaybackPromptMethods on VideoPlayerScreenState {
// End-of-video sleep timer takes precedence over autoplay / next-episode
// dialogs: the user explicitly asked to stop after this item.
final sleepTimerService = SleepTimerService();
if (sleepTimerService.isEndOfVideoMode && !_completionTriggered) {
_completionTriggered = true;
if (sleepTimerService.isEndOfVideoMode && !_completionLatch.triggered) {
_completionLatch.latch();
sleepTimerService.notifyVideoCompleted();
return;
}
if (_nextEpisode != null && !_showPlayNextDialog && !_showStillWatchingPrompt && !_completionTriggered) {
_completionTriggered = true;
if (_nextEpisode != null && !_showPlayNextDialog && !_showStillWatchingPrompt && !_completionLatch.triggered) {
_completionLatch.latch();
// PiP: skip dialog (user can't interact), auto-play immediately
if (PipService().isPipActive.value) {
@@ -72,8 +73,8 @@ extension _VideoPlayerPlaybackPromptMethods on VideoPlayerScreenState {
if (autoPlayEnabled) {
_startAutoPlayTimer();
}
} else if (_nextEpisode == null && !_completionTriggered) {
_completionTriggered = true;
} else if (_nextEpisode == null && !_completionLatch.triggered) {
_completionLatch.latch();
unawaited(_handleBackButton());
}
}
@@ -108,14 +109,15 @@ extension _VideoPlayerPlaybackPromptMethods on VideoPlayerScreenState {
});
}
/// Re-arm the end-of-video latch so Play Next can fire again — but only when no
/// prompt is visible and no auto-play countdown is running, so we never clobber
/// an active dialog. Callers decide *when* it is safe to re-arm (media reloaded,
/// or playback moved back out of the end region).
/// Re-arm the end-of-video latch so Play Next can fire again. Callers
/// decide *when* it is safe to re-arm (media reloaded, or playback moved
/// back out of the end region); the latch itself refuses while a prompt
/// or countdown is active.
void _rearmCompletionLatch() {
if (_completionTriggered && !_showPlayNextDialog && _autoPlayTimer?.isActive != true) {
_completionTriggered = false;
}
_completionLatch.rearmIfClear(
promptVisible: _showPlayNextDialog,
countdownActive: _autoPlayTimer?.isActive == true,
);
}
void _showStillWatchingDialog() {
@@ -1,11 +1,42 @@
part of '../../video_player_screen.dart';
extension _VideoPlayerPlaybackServiceMethods on VideoPlayerScreenState {
void _queueScrubPreviewLoad({
required MediaItem metadata,
required MediaSourceInfo? mediaInfo,
required MediaServerClient? mediaClient,
}) {
if (mediaInfo == null || _isOfflinePlayback || mediaClient == null) return;
final mediaInfoAtStart = mediaInfo;
final metadataAtStart = metadata;
unawaited(
mediaClient
.createScrubPreviewSource(item: metadataAtStart, mediaSource: mediaInfoAtStart)
.then((service) {
if (service == null) return;
// Keyed on item + part rather than session identity: the preview
// is per part, so a load that outlives a same-part source switch
// (quality/audio) still applies.
if (mounted &&
_currentMetadata.globalKey == metadataAtStart.globalKey &&
_currentMediaInfo?.partId == mediaInfoAtStart.partId) {
_setPlayerState(() => _scrubPreviewSource = service);
} else {
service.dispose();
}
})
.catchError((e, st) {
appLogger.w('Scrub preview load failed', error: e, stackTrace: st);
}),
);
}
/// Wire the per-item playback services that need to (re)bind whenever
/// the active media item changes: [PlaybackProgressTracker],
/// [MediaControlsManager.updateMetadata], and the
/// Discord/Trakt/Tracker scrobblers. Both [_initializeServices] and
/// [_swapEpisodeInPip] call this so the two flows can't drift.
/// [_reloadMediaInPlace] call this so the two flows can't drift.
///
/// The caller is responsible for ensuring `player != null` and (if the
/// media-controls metadata refresh should run) for having created
@@ -21,8 +52,53 @@ extension _VideoPlayerPlaybackServiceMethods on VideoPlayerScreenState {
final currentPlayer = player;
if (currentPlayer == null) return;
// Progress tracker — local media still reports live when its server is
// online; only queue locally when no reporting client is reachable.
_rebindProgressTracker(
metadata: metadata,
mediaClient: mediaClient,
offlineWatchService: offlineWatchService,
playSessionId: playSessionId,
playMethod: playMethod,
mediaInfo: mediaInfo,
);
// Media controls metadata. Fire-and-forget — the OS plugin downloads
// the poster synchronously inside `setMetadata` (~270 ms); the
// controls populate a beat after first frame which is fine.
if (_mediaControlsManager != null) {
unawaited(
_mediaControlsManager!.updateMetadata(
metadata: metadata,
client: mediaClient,
duration: metadata.durationMs != null ? Duration(milliseconds: metadata.durationMs!) : null,
),
);
}
// Scrobblers — Discord RPC, Trakt, unified tracker. All accept the
// neutral [MediaServerClient]; null short-circuits cleanly.
if (mediaClient != null) {
unawaited(DiscordRPCService.instance.startPlayback(metadata, mediaClient));
unawaited(TraktScrobbleService.instance.startPlayback(metadata, mediaClient, isLive: widget.isLive));
unawaited(TrackerCoordinator.instance.startPlayback(metadata, mediaClient, isLive: widget.isLive));
}
}
/// (Re)create the [PlaybackProgressTracker] for the current play session.
/// Session-keyed only — a transcode restart rebinds just this, while item
/// changes go through [_wirePerItemPlaybackServices] for the full set.
void _rebindProgressTracker({
required MediaItem metadata,
required MediaServerClient? mediaClient,
required OfflineWatchSyncService? offlineWatchService,
String? playSessionId,
String? playMethod,
MediaSourceInfo? mediaInfo,
}) {
final currentPlayer = player;
if (currentPlayer == null) return;
// Local media still reports live when its server is online; only queue
// locally when no reporting client is reachable.
if (mediaClient != null) {
_progressTracker = PlaybackProgressTracker(
client: mediaClient,
@@ -45,27 +121,6 @@ extension _VideoPlayerPlaybackServiceMethods on VideoPlayerScreenState {
);
_progressTracker!.startTracking();
}
// Media controls metadata. Fire-and-forget — the OS plugin downloads
// the poster synchronously inside `setMetadata` (~270 ms); the
// controls populate a beat after first frame which is fine.
if (_mediaControlsManager != null) {
unawaited(
_mediaControlsManager!.updateMetadata(
metadata: metadata,
client: mediaClient,
duration: metadata.durationMs != null ? Duration(milliseconds: metadata.durationMs!) : null,
),
);
}
// Scrobblers — Discord RPC, Trakt, unified tracker. All accept the
// neutral [MediaServerClient]; null short-circuits cleanly.
if (mediaClient != null) {
unawaited(DiscordRPCService.instance.startPlayback(metadata, mediaClient));
unawaited(TraktScrobbleService.instance.startPlayback(metadata, mediaClient, isLive: widget.isLive));
unawaited(TrackerCoordinator.instance.startPlayback(metadata, mediaClient, isLive: widget.isLive));
}
}
/// Initialize the service layer
@@ -122,7 +177,7 @@ extension _VideoPlayerPlaybackServiceMethods on VideoPlayerScreenState {
_wasPlayingBeforeInactive = false;
_updateMediaControlsPlaybackState();
} else if (event is PauseEvent) {
if (_suppressMediaPauseDuringFrameRateSwitch) {
if (_frameRate.suppressesMediaPause) {
appLogger.d('Media control: Pause event suppressed (frame rate switch in progress)');
return;
}
@@ -152,7 +207,7 @@ extension _VideoPlayerPlaybackServiceMethods on VideoPlayerScreenState {
});
// Wire progress tracker, media-controls metadata, and the
// Discord/Trakt/Tracker scrobblers. Shared with [_swapEpisodeInPip]
// Discord/Trakt/Tracker scrobblers. Shared with [_reloadMediaInPlace]
// so the two flows can't drift.
_wirePerItemPlaybackServices(
metadata: _currentMetadata,
+122 -353
View File
@@ -4,71 +4,71 @@ extension _VideoPlayerPlaybackStartMethods on VideoPlayerScreenState {
Future<void> _startPlayback() async {
final currentPlayer = player;
if (!mounted || currentPlayer == null) return;
final playbackGeneration = _beginPlaybackGeneration();
final attempt = _beginPlaybackAttempt(currentPlayer);
// Live TV mode: bypass standard playback initialization
if (widget.isLive) {
try {
_hasFirstFrame.value = false;
await currentPlayer.requestAudioFocus();
await _setLiveStreamOptions();
if (!_isCurrentPlaybackGeneration(playbackGeneration, currentPlayer)) return;
await _setLiveStreamOptions(currentPlayer);
if (!attempt.isCurrent) return;
String streamUrl;
if (_liveStreamUrl != null) {
streamUrl = _liveStreamUrl!;
_streamStartEpoch = DateTime.now().millisecondsSinceEpoch / 1000.0;
_isAtLiveEdge = true;
if (_live.streamUrl != null) {
streamUrl = _live.streamUrl!;
_live.streamStartEpoch = DateTime.now().millisecondsSinceEpoch / 1000.0;
_live.atLiveEdge = true;
} else {
// Tune channel inside the player (shows loading spinner while tuning)
final channels = widget.liveChannels;
final channelIndex = _liveChannelIndex;
final channels = widget.live?.channels;
final channelIndex = _live.channelIndex;
if (channels == null || channelIndex < 0 || channelIndex >= channels.length) {
throw Exception('No channel to tune');
}
final channel = channels[channelIndex];
appLogger.d('Tune: dvrKey=$_liveDvrKey channelKey=${channel.key}');
final client = _liveClient;
appLogger.d('Tune: dvrKey=$_live.dvrKey channelKey=${channel.key}');
final client = _live.client;
if (client is! PlexClient) {
throw StateError(
'In-player live tuning is Plex-only; got ${client?.runtimeType ?? 'null'}. '
'Jellyfin live TV must pass a pre-resolved liveStreamUrl via LiveTvSupport.resolveStreamUrl.',
);
}
final dvrKey = _liveDvrKey;
final dvrKey = _live.dvrKey;
if (dvrKey == null) throw Exception('No DVR to tune');
final tuneResult = await client.tuneChannel(dvrKey, channel.key);
if (tuneResult == null) throw Exception('Failed to tune channel');
_liveSessionIdentifier = tuneResult.sessionIdentifier;
_liveSessionPath = tuneResult.sessionPath;
_liveProgramId = tuneResult.metadata.ratingKey;
_liveDurationMs = tuneResult.metadata.duration;
_captureBuffer = tuneResult.captureBuffer;
_programBeginsAt = tuneResult.beginsAt;
_transcodeSessionId = generateSessionIdentifier();
_live.sessionIdentifier = tuneResult.sessionIdentifier;
_live.sessionPath = tuneResult.sessionPath;
_live.programId = tuneResult.metadata.ratingKey;
_live.durationMs = tuneResult.metadata.duration;
_live.captureBuffer = tuneResult.captureBuffer;
_live.programBeginsAt = tuneResult.beginsAt;
_live.transcodeSessionId = generateSessionIdentifier();
// Show "Watch from Start" dialog when an existing capture session has >60s of history.
// On a fresh tune (no active recording), the buffer is empty so this won't trigger.
int? offsetSeconds;
if (_captureBuffer != null && _programBeginsAt != null) {
if (_live.captureBuffer != null && _live.programBeginsAt != null) {
final nowEpoch = DateTime.now().millisecondsSinceEpoch ~/ 1000;
final offsetProgramStart = _programBeginsAt! - _captureBuffer!.startedAt.round();
final offsetProgramStart = _live.programBeginsAt! - _live.captureBuffer!.startedAt.round();
// If a session recording started after current program start, offset of program start at will be negative.
// If a session recording started before current program start, offset of program start will be positive.
// If guide data is not available, program start will be equal to current time.
final useProgramStart = offsetProgramStart > 0 && nowEpoch - _programBeginsAt! > 60;
final effectiveStart = useProgramStart ? _programBeginsAt! : _captureBuffer!.seekableStartEpoch;
final useProgramStart = offsetProgramStart > 0 && nowEpoch - _live.programBeginsAt! > 60;
final effectiveStart = useProgramStart ? _live.programBeginsAt! : _live.captureBuffer!.seekableStartEpoch;
final elapsed = nowEpoch - effectiveStart;
appLogger.d(
'Time-shift: buffer=${_captureBuffer!.seekableDurationSeconds}s, '
'beginsAt=$_programBeginsAt, elapsed=${elapsed}s (need >60 for dialog)',
'Time-shift: buffer=${_live.captureBuffer!.seekableDurationSeconds}s, '
'beginsAt=$_live.programBeginsAt, elapsed=${elapsed}s (need >60 for dialog)',
);
if (elapsed > 60) {
final watchFromStart = await _showWatchFromStartDialog(effectiveStart, nowEpoch);
if (!mounted) return;
if (watchFromStart == true) {
offsetSeconds = useProgramStart ? offsetProgramStart : _captureBuffer!.seekStartSeconds.round();
offsetSeconds = useProgramStart ? offsetProgramStart : _live.captureBuffer!.seekStartSeconds.round();
}
}
}
@@ -77,28 +77,28 @@ extension _VideoPlayerPlaybackStartMethods on VideoPlayerScreenState {
final streamPath = await client.buildLiveStreamPath(
sessionPath: tuneResult.sessionPath,
sessionIdentifier: tuneResult.sessionIdentifier,
transcodeSessionId: _transcodeSessionId!,
transcodeSessionId: _live.transcodeSessionId!,
offsetSeconds: offsetSeconds,
);
if (streamPath == null || !mounted) throw Exception('Failed to build stream path');
streamUrl = client.buildLiveStreamUrl(streamPath);
_liveStreamUrl = streamUrl;
_live.streamUrl = streamUrl;
// Track stream start epoch for position calculations
if (offsetSeconds != null) {
_streamStartEpoch = _captureBuffer!.startedAt + offsetSeconds;
_isAtLiveEdge = false;
_live.streamStartEpoch = _live.captureBuffer!.startedAt + offsetSeconds;
_live.atLiveEdge = false;
} else {
_streamStartEpoch = DateTime.now().millisecondsSinceEpoch / 1000.0;
_isAtLiveEdge = true;
_live.streamStartEpoch = DateTime.now().millisecondsSinceEpoch / 1000.0;
_live.atLiveEdge = true;
}
}
_livePlaybackStartTime = DateTime.now();
_live.playbackStartTime = DateTime.now();
await currentPlayer.setProperty('force-seekable', 'no');
await currentPlayer.open(Media(streamUrl, headers: const {'Accept-Language': 'en'}), play: true, isLive: true);
if (!_isCurrentPlaybackGeneration(playbackGeneration, currentPlayer)) return;
if (!attempt.isCurrent) return;
_trackManager?.cacheExternalSubtitles(const []);
@@ -106,9 +106,9 @@ extension _VideoPlayerPlaybackStartMethods on VideoPlayerScreenState {
if (!mounted || player != currentPlayer) return;
if (mounted) {
// Live TV never commits a PlaybackSession, so the session-derived
// versions/mediaInfo getters already read empty here.
_setPlayerState(() {
_availableVersions = [];
_currentMediaInfo = null;
_isPlayerInitialized = true;
});
_trackManager?.mediaInfo = null;
@@ -128,91 +128,64 @@ extension _VideoPlayerPlaybackStartMethods on VideoPlayerScreenState {
final offlineWatchService = context.read<OfflineWatchSyncService>();
try {
PlaybackInitializationResult result;
PlaybackContext playbackContext;
Map<String, String>? streamHeaders;
if (widget.isOffline) {
if (_offlineLibraryMode) {
final playbackResolver = PlaybackSourceResolver(
serverManager: context.read<MultiServerProvider>().serverManager,
database: context.read<AppDatabase>(),
);
playbackContext = await playbackResolver.resolve(
metadata: _currentMetadata,
selectedMediaIndex: widget.selectedMediaIndex,
selectedMediaSourceId: widget.selectedMediaSourceId,
selectedMediaIndex: _effectiveSelectedMediaIndex,
selectedMediaSourceId: _selectedMediaSourceId,
offlineLibraryMode: true,
qualityPreset: _selectedQualityPreset,
selectedAudioStreamId: _selectedAudioStreamId,
sessionIdentifier: _playbackSessionIdentifier,
transcodeSessionId: _playbackTranscodeSessionId,
);
result = playbackContext.result;
if (result.videoUrl == null) {
if (playbackContext.result.videoUrl == null) {
throw PlaybackException(t.messages.fileInfoNotAvailable);
}
streamHeaders = playbackContext.streamHeaders;
_isTranscoding = result.isTranscoding;
_effectiveIsOffline = result.isOffline;
_playbackPlaySessionId = result.playSessionId;
_playbackPlayMethod = result.playMethod;
_selectedAudioStreamId = result.activeAudioStreamId;
} else {
// Online path: `_playbackDataFuture` was kicked off in `_initializePlayer`
// in parallel with MPV setup. Quality preset + server capabilities +
// headers were resolved there too. Just await the result.
streamHeaders = _streamHeaders;
final playbackDataFuture = _playbackDataFuture;
if (playbackDataFuture == null) {
throw StateError('Playback data was not prepared before playback start');
}
playbackContext = await playbackDataFuture;
result = playbackContext.result;
if (!mounted || player != currentPlayer) return;
streamHeaders = playbackContext.streamHeaders;
_isTranscoding = result.isTranscoding;
_effectiveIsOffline = result.isOffline;
_playbackPlaySessionId = result.playSessionId;
_playbackPlayMethod = result.playMethod;
_selectedAudioStreamId = result.activeAudioStreamId;
if (result.fallbackReason != null && !_selectedQualityPreset.isOriginal) {
if (playbackContext.result.fallbackReason != null && !_selectedQualityPreset.isOriginal) {
if (mounted) {
showErrorSnackBar(context, t.videoControls.transcodeUnavailableFallback);
}
// Reset the preset so the UI reflects what's actually playing.
_selectedQualityPreset = TranscodeQualityPreset.original;
}
}
_effectiveSelectedMediaIndex = result.selectedMediaIndex;
_playbackContext = playbackContext;
_streamHeaders = streamHeaders;
final result = playbackContext.result;
final streamHeaders = playbackContext.streamHeaders;
// Initial start has no previous session to protect, so commit as soon
// as the resolve lands (reload-style flows commit at the open
// boundary instead).
_commitPlaybackSession(
PlaybackSession.fromContext(
playbackContext,
requestedQualityPreset: _selectedQualityPreset,
requestedMediaSourceId: _selectedMediaSourceId,
),
);
// Primary refresh-rate path: when metadata provides FPS, Android players
// can switch before creating decoders. MPV still needs a startup refresh
// when MediaCodec has already produced its first paused frame.
final settingsService = await SettingsService.getInstance();
if (!_isCurrentPlaybackGeneration(playbackGeneration, currentPlayer)) return;
if (!attempt.isCurrent) return;
final displayCriteria = result.mediaInfo?.displayCriteria;
final preKnownFps = displayCriteria?.fps;
final willAutoSwitch =
Platform.isAndroid &&
settingsService.read(SettingsService.matchContentFrameRate) &&
preKnownFps != null &&
preKnownFps > 0;
final isExoPlayer = currentPlayer is PlayerAndroid;
final isAndroidMpv = Platform.isAndroid && !isExoPlayer;
final needsExoPlayerFrameRateStartup = willAutoSwitch && isExoPlayer && result.videoUrl != null;
final needsAndroidMpvFrameRateStartup = willAutoSwitch && isAndroidMpv && result.videoUrl != null;
var didPreLoadFrameRateSwitch = false;
var didPreOpenExoFrameRateSwitch = false;
var preOpenExoFrameRateHandled = false;
var needsPostOpenFrameRateSwitch =
willAutoSwitch && !needsAndroidMpvFrameRateStartup && !needsExoPlayerFrameRateStartup;
var needsAndroidMpvStartupRefresh = false;
final attachesSubsAtOpen = currentPlayer.attachesExternalSubtitlesAtOpen;
final hasExternalSubs = result.externalSubtitles.isNotEmpty;
Future<bool>? androidMpvStartupReady;
var audioFocusReady = false;
Future<void> ensureAudioFocus() async {
@@ -227,89 +200,23 @@ extension _VideoPlayerPlaybackStartMethods on VideoPlayerScreenState {
audioFocusReady = true;
}
// MPV on Android can decode and present its first paused frame before a
// post-open display switch settles. Switch first when metadata already
// gives us the FPS so MediaCodec starts after the display mode change.
if (needsAndroidMpvFrameRateStartup) {
final delaySec = settingsService.read(SettingsService.displaySwitchDelay);
final durationMs = _currentMetadata.durationMs ?? currentPlayer.state.duration.inMilliseconds;
_suppressMediaPauseDuringFrameRateSwitch = true;
Future.delayed(Duration(seconds: 2 + delaySec + 1), () {
_suppressMediaPauseDuringFrameRateSwitch = false;
});
try {
appLogger.d(
'Frame rate matching: pre-load MPV switch to ${preKnownFps}fps '
'(duration: ${durationMs}ms, delay=${delaySec}s)',
);
didPreLoadFrameRateSwitch = await currentPlayer.setVideoFrameRate(
preKnownFps,
durationMs,
extraDelayMs: delaySec * 1000,
);
if (!mounted || player != currentPlayer) return;
if (didPreLoadFrameRateSwitch) {
_frameRateMatchingApplied = true;
needsAndroidMpvStartupRefresh = true;
}
appLogger.d(
'Frame rate matching: pre-load MPV switch complete '
'(switched=$didPreLoadFrameRateSwitch, delay=${delaySec}s, '
'startupRefresh=$needsAndroidMpvStartupRefresh)',
);
} catch (e) {
appLogger.w('Failed to apply pre-load MPV frame rate matching', error: e);
needsPostOpenFrameRateSwitch = true;
needsAndroidMpvStartupRefresh = false;
}
}
// ExoPlayer prepares AudioTrack during open() even when opened paused.
// On Shield/AVR chains, switching HDMI refresh rate after that can break
// direct passthrough, so switch before ExoPlayer creates renderers.
if (needsExoPlayerFrameRateStartup) {
final delaySec = settingsService.read(SettingsService.displaySwitchDelay);
final durationMs = _currentMetadata.durationMs ?? currentPlayer.state.duration.inMilliseconds;
_suppressMediaPauseDuringFrameRateSwitch = true;
Future.delayed(Duration(seconds: 2 + delaySec + 1), () {
_suppressMediaPauseDuringFrameRateSwitch = false;
});
try {
await ensureAudioFocus();
if (!mounted || player != currentPlayer) return;
appLogger.d(
'Frame rate matching: pre-open ExoPlayer switch to ${preKnownFps}fps '
'(duration: ${durationMs}ms, delay=${delaySec}s)',
);
didPreOpenExoFrameRateSwitch = await currentPlayer.setVideoFrameRate(
preKnownFps,
durationMs,
extraDelayMs: delaySec * 1000,
);
if (!mounted || player != currentPlayer) return;
preOpenExoFrameRateHandled = true;
appLogger.d(
'Frame rate matching: pre-open ExoPlayer switch complete '
'(switched=$didPreOpenExoFrameRateSwitch, delay=${delaySec}s)',
);
} catch (e) {
appLogger.w('Failed to apply pre-open ExoPlayer frame rate matching', error: e);
needsPostOpenFrameRateSwitch = true;
preOpenExoFrameRateHandled = false;
}
}
final shouldHoldPlaybackStart = needsPostOpenFrameRateSwitch || needsAndroidMpvStartupRefresh;
Duration? resumePosition;
final frameRatePlan = await _prepareFrameRateForOpen(
currentPlayer: currentPlayer,
settingsService: settingsService,
preKnownFps: displayCriteria?.fps,
hasVideoUrl: result.videoUrl != null,
ensureAudioFocus: ensureAudioFocus,
);
if (frameRatePlan == null) return;
final shouldHoldPlaybackStart = frameRatePlan.holdPlaybackStart;
// Open video through Player
if (result.videoUrl != null) {
// Reset first frame flag and frame rate retry counter for new video
_hasFirstFrame.value = false;
_frameRateRetries = 0;
_frameRateMatchingApplied = false;
if (didPreLoadFrameRateSwitch || needsAndroidMpvFrameRateStartup || preOpenExoFrameRateHandled) {
_frameRateMatchingApplied = true;
_frameRate.resetForNewItem();
if (frameRatePlan.countsAsApplied) {
_frameRate.applied = true;
}
// Request audio focus before starting playback (Android)
@@ -317,23 +224,14 @@ extension _VideoPlayerPlaybackStartMethods on VideoPlayerScreenState {
// Fired in parallel with MPV setup in `_initializePlayer`; we await
// the in-flight future here (usually already resolved).
await ensureAudioFocus();
if (!_isCurrentPlaybackGeneration(playbackGeneration, currentPlayer)) return;
if (!attempt.isCurrent) return;
// Pass resume position if available.
// In offline mode, prefer locally tracked progress over the cached server value
// since the user may have watched further since downloading.
if (_isOfflinePlayback) {
final globalKey = _currentMetadata.globalKey;
final localOffset = await offlineWatchService.getLocalViewOffset(globalKey);
if (!mounted || player != currentPlayer) return;
if (localOffset != null && localOffset > 0) {
resumePosition = Duration(milliseconds: localOffset);
appLogger.d('Resuming offline playback from local progress: ${localOffset}ms');
}
}
resumePosition ??= _currentMetadata.viewOffsetMs != null
? Duration(milliseconds: _currentMetadata.viewOffsetMs!)
: null;
final resumePosition = await _resolveOpenResumePosition(
metadata: _currentMetadata,
isOffline: _isOfflinePlayback,
offlineWatchService: offlineWatchService,
);
if (!mounted || player != currentPlayer) return;
// Enable FFmpeg auto-reconnect for VOD streams (covers network drops
// up to 10 min). Forwarded to the Kotlin layer on Android so MPV
@@ -346,23 +244,15 @@ extension _VideoPlayerPlaybackStartMethods on VideoPlayerScreenState {
);
}
await currentPlayer.setDisplayCriteria(
!result.isTranscoding && displayCriteria?.canPrimeNativeDisplayCriteria == true ? displayCriteria : null,
await _primeDisplayCriteria(
player: currentPlayer,
settingsService: settingsService,
displayCriteria: displayCriteria,
isTranscoding: result.isTranscoding,
);
final shouldAutoPlay = !shouldHoldPlaybackStart && (isExoPlayer || !hasExternalSubs);
if (needsAndroidMpvStartupRefresh) {
appLogger.d('Frame rate matching: opening Android MPV paused for startup decoder refresh');
androidMpvStartupReady = currentPlayer.streams.playbackRestart.first
.then((_) => true)
.timeout(
const Duration(seconds: 15),
onTimeout: () {
appLogger.w('Timed out waiting for Android MPV startup frame before decoder refresh');
return false;
},
);
}
final shouldAutoPlay = !shouldHoldPlaybackStart && (attachesSubsAtOpen || !hasExternalSubs);
frameRatePlan.armStartupRefreshGate(currentPlayer);
// ExoPlayer: attach external subs at open time so it discovers
// them in a single prepare() — no media reload needed for selection.
@@ -373,34 +263,18 @@ extension _VideoPlayerPlaybackStartMethods on VideoPlayerScreenState {
resumePosition: resumePosition,
durationMs: _currentMetadata.durationMs,
);
// Transcode streams can be seekable even when MPV cannot prove it
// from response headers. Reset non-transcodes so live/direct/offline
// streams keep native seekability detection.
await currentPlayer.setProperty('force-seekable', result.isTranscoding ? 'yes' : 'no');
await currentPlayer.open(
Media(result.videoUrl!, start: openTiming.mediaStart, headers: streamHeaders),
final didOpen = await _openMediaOnPlayer(
player: currentPlayer,
settingsService: settingsService,
videoUrl: result.videoUrl!,
isTranscoding: result.isTranscoding,
timing: openTiming,
headers: streamHeaders,
play: shouldAutoPlay,
externalSubtitles: isExoPlayer && hasExternalSubs ? result.externalSubtitles : null,
timelineOffset: openTiming.timelineOffset,
timelineDuration: openTiming.timelineDuration,
externalSubtitlesAtOpen: attachesSubsAtOpen && hasExternalSubs ? result.externalSubtitles : null,
shouldContinue: () => attempt.isCurrent,
);
if (!_isCurrentPlaybackGeneration(playbackGeneration, currentPlayer)) return;
// Apply subtitle styling to ExoPlayer native layer (CaptionStyleCompat + libass font scale)
// Must be called after open() since that's when ExoPlayer initializes
if (currentPlayer is PlayerAndroid) {
await currentPlayer.setSubtitleStyle(
fontSize: settingsService.read(SettingsService.subtitleFontSize).toDouble(),
textColor: settingsService.read(SettingsService.subtitleTextColor),
borderSize: settingsService.read(SettingsService.subtitleBorderSize).toDouble(),
borderColor: settingsService.read(SettingsService.subtitleBorderColor),
bgColor: settingsService.read(SettingsService.subtitleBackgroundColor),
bgOpacity: settingsService.read(SettingsService.subtitleBackgroundOpacity),
subtitlePosition: settingsService.read(SettingsService.subtitlePosition),
bold: settingsService.read(SettingsService.subtitleBold),
italic: settingsService.read(SettingsService.subtitleItalic),
);
}
if (!didOpen || !attempt.isCurrent) return;
// Attach player to Watch Together session for sync (if in session)
if (mounted && !_isOfflinePlayback) {
@@ -409,41 +283,14 @@ extension _VideoPlayerPlaybackStartMethods on VideoPlayerScreenState {
}
}
// Update available versions from the playback data
// Versions/mediaInfo come from the committed session; rebuild so the
// controls pick them up.
if (mounted) {
_setPlayerState(() {
_availableVersions = result.availableVersions;
_currentMediaInfo = result.mediaInfo;
_scrubPreviewSource?.dispose();
_scrubPreviewSource = null;
});
// Backend-neutral scrub-thumbnail load. The factory dispatches to
// BIF (Plex) or trickplay sprite sheets (Jellyfin) and returns null
// when the inputs aren't sufficient. Guard against media-change
// races during the async load.
final mediaClient = context.tryGetMediaClientForServer(serverIdOrNull(_currentMetadata.serverId));
final mediaInfoAtStart = _currentMediaInfo;
if (mediaInfoAtStart != null && !_isOfflinePlayback && mediaClient != null) {
unawaited(
mediaClient
.createScrubPreviewSource(item: _currentMetadata, mediaSource: mediaInfoAtStart)
.then((service) {
if (service == null) return;
if (mounted && identical(_currentMediaInfo, mediaInfoAtStart)) {
_setPlayerState(() => _scrubPreviewSource = service);
} else {
service.dispose();
}
})
.catchError((e, st) {
appLogger.w('Scrub preview load failed', error: e, stackTrace: st);
}),
);
}
_resetScrubPreviewForNewItem(metadata: _currentMetadata, mediaInfo: result.mediaInfo, mediaClient: mediaClient);
await _initVideoFilterAndPip();
if (!_isCurrentPlaybackGeneration(playbackGeneration, currentPlayer)) return;
if (!attempt.isCurrent) return;
if (player == currentPlayer) {
// Auto-PiP: set up callback for API 26-30 path and initial state
@@ -474,122 +321,44 @@ extension _VideoPlayerPlaybackStartMethods on VideoPlayerScreenState {
await _restoreAmbientLighting();
}
}
if (!_isCurrentPlaybackGeneration(playbackGeneration, currentPlayer)) return;
if (!attempt.isCurrent) return;
// Track manager: owns track selection, external subtitle loading, and Plex
// immediate stream writes. Jellyfin persists selected stream indexes through
// playback progress reports instead.
final plexTrackClient = mediaClient is PlexClient ? mediaClient : null;
_trackManager = TrackManager(
player: currentPlayer,
isActive: () => mounted && player == currentPlayer,
persistTrackPreference: plexTrackClient != null ? _plexTrackPersister(() => plexTrackClient) : null,
getProfileSettings: () => context.read<UserProfileProvider>().profileSettings,
waitForProfileSettings: _waitForProfileSettingsIfNeeded,
_trackManager = _buildTrackManager(
forPlayer: currentPlayer,
metadata: _currentMetadata,
mediaInfo: _currentMediaInfo,
preferredAudioTrack: widget.preferredAudioTrack,
preferredSubtitleTrack: widget.preferredSubtitleTrack,
preferredSecondarySubtitleTrack: widget.preferredSecondarySubtitleTrack,
showMessage: (message, {duration}) {
if (mounted) showAppSnackBar(context, message, duration: duration);
},
plexClient: mediaClient is PlexClient ? mediaClient : null,
getProfileSettings: () => context.read<UserProfileProvider>().profileSettings,
preferredAudioTrack: _preferredAudioTrack,
preferredSubtitleTrack: _preferredSubtitleTrack,
preferredSecondarySubtitleTrack: _preferredSecondarySubtitleTrack,
);
// Store external subtitles for re-use after backend fallback
_trackManager!.cacheExternalSubtitles(result.externalSubtitles);
Future<void> resumeAfterStartupGate(String reason) async {
if (!mounted || player != currentPlayer) return;
final trackManager = _trackManager;
if (trackManager == null) return;
appLogger.d('Frame rate matching: resuming playback after $reason');
if (currentPlayer is! PlayerAndroid && hasExternalSubs) {
await trackManager.resumeAfterSubtitleLoad();
} else {
await currentPlayer.play();
}
}
await _applyTracksAfterOpen(
forPlayer: currentPlayer,
trackManager: _trackManager!,
externalSubtitles: result.externalSubtitles,
// When a startup gate below owns the resume, skip this one to
// avoid a double-play.
shouldResumeAfterSubtitleLoad: () => !shouldHoldPlaybackStart && mounted && player == currentPlayer,
);
// MPV with external subs: add after open via sub-add,
// opened paused to avoid race condition (issue #226)
if (currentPlayer is! PlayerAndroid && result.externalSubtitles.isNotEmpty) {
_hasFirstFrame.value = false;
_trackManager!.waitingForExternalSubsTrackSelection = true;
try {
await _trackManager!.addExternalSubtitles(result.externalSubtitles);
} finally {
// When a startup gate below owns the resume,
// skip this one to avoid a double-play.
if (!shouldHoldPlaybackStart && mounted && player == currentPlayer) {
await _trackManager!.resumeAfterSubtitleLoad();
}
}
} else {
// Android (subs attached at open time) or no external subs:
// apply once tracks are available
_trackManager!.applyTrackSelectionWhenReady();
}
// Fallback refresh-rate path. The player was opened paused;
// setVideoFrameRate awaits the real display-change event (+ settle +
// user delay) before returning, then we start playback.
if (needsPostOpenFrameRateSwitch && mounted && player == currentPlayer) {
_frameRateMatchingApplied = true;
final delaySec = settingsService.read(SettingsService.displaySwitchDelay);
final durationMs = _currentMetadata.durationMs ?? currentPlayer.state.duration.inMilliseconds;
_suppressMediaPauseDuringFrameRateSwitch = true;
Future.delayed(Duration(seconds: 2 + delaySec + 1), () {
_suppressMediaPauseDuringFrameRateSwitch = false;
});
bool didSwitch = false;
try {
didSwitch = await currentPlayer.setVideoFrameRate(preKnownFps!, durationMs, extraDelayMs: delaySec * 1000);
if (!mounted || player != currentPlayer) return;
if (didSwitch) {
await _refreshAndroidMpvDecoderAfterFrameRateSwitch(reason: 'post-open frame rate switch');
}
} catch (e) {
appLogger.w('Failed to apply pre-playback frame rate matching', error: e);
}
// Always resume — either the switch completed and we want to play,
// or no switch was needed and we need to start playback now that the
// preparation gate has been cleared.
await resumeAfterStartupGate('post-open frame rate switch');
unawaited(
Sentry.addBreadcrumb(
Breadcrumb(
message: 'Pre-playback frame rate: ${preKnownFps}fps, switched=$didSwitch, delay=${delaySec}s',
category: 'player',
),
),
);
} else if (needsAndroidMpvStartupRefresh && mounted && player == currentPlayer) {
appLogger.d('Frame rate matching: waiting for Android MPV startup frame before decoder refresh');
final startupReady = androidMpvStartupReady == null ? false : await androidMpvStartupReady;
if (mounted && player == currentPlayer) {
if (startupReady) {
await Future<void>.delayed(const Duration(milliseconds: 100));
await _refreshAndroidMpvDecoderAfterFrameRateSwitch(reason: 'pre-load frame rate startup');
await resumeAfterStartupGate('startup decoder refresh');
} else {
appLogger.w('Frame rate matching: skipping Android MPV decoder refresh because startup frame timed out');
await resumeAfterStartupGate('startup frame timeout');
}
}
unawaited(
Sentry.addBreadcrumb(
Breadcrumb(
message: 'Android MPV startup decoder refresh after pre-load frame-rate switch',
category: 'player',
),
),
);
}
await _releaseFrameRateStartupGate(
currentPlayer: currentPlayer,
settingsService: settingsService,
plan: frameRatePlan,
resumeAfterStartupGate: (reason) => _resumeAfterFrameRateStartupGate(
currentPlayer: currentPlayer,
attachesSubsAtOpen: attachesSubsAtOpen,
hasExternalSubs: hasExternalSubs,
reason: reason,
),
);
}
} on PlaybackException catch (e, st) {
appLogger.w('Playback initialization failed', error: e, stackTrace: st);
+74 -50
View File
@@ -39,91 +39,115 @@ extension _VideoPlayerSeekingMethods on VideoPlayerScreenState {
}
Future<void> _restartPlexTranscodeAt(Duration target) async {
if (_isRestartingTranscodeSeek) return;
if (_playbackTransition != _PlaybackTransition.idle) return;
appLogger.d('Restarting Plex transcode at ${target.inSeconds}s');
_isRestartingTranscodeSeek = true;
_playbackTransition = _PlaybackTransition.restartingTranscode;
_chromeController.show();
final currentPlayer = player;
if (currentPlayer == null) {
_isRestartingTranscodeSeek = false;
_playbackTransition = _PlaybackTransition.idle;
return;
}
final replacementMetadata = _currentMetadata.copyWith(viewOffsetMs: target.inMilliseconds);
final wasPlaying = currentPlayer.state.playing;
final nextTranscodeSessionId = generateSessionIdentifier();
final offlineWatchService = context.read<OfflineWatchSyncService>();
final playbackResolver = PlaybackSourceResolver(
serverManager: context.read<MultiServerProvider>().serverManager,
database: context.read<AppDatabase>(),
);
try {
final mediaClient = _getMediaServerClient(context);
if (mediaClient == null) {
throw StateError('No client registered for ${replacementMetadata.serverId}');
}
_playbackTranscodeSessionId = nextTranscodeSessionId;
final playbackService = PlaybackInitializationService(client: mediaClient, database: context.read<AppDatabase>());
final result = await playbackService.getPlaybackData(
final playbackContext = await playbackResolver.resolve(
metadata: replacementMetadata,
selectedMediaIndex: _effectiveSelectedMediaIndex,
selectedMediaSourceId: widget.selectedMediaSourceId,
preferOffline: false,
selectedMediaSourceId: _selectedMediaSourceId,
offlineLibraryMode: false,
qualityPreset: _selectedQualityPreset,
selectedAudioStreamId: _selectedAudioStreamId,
sessionIdentifier: _playbackSessionIdentifier,
transcodeSessionId: _playbackTranscodeSessionId,
// A transcode restart must stay on the server stream even when the
// preset would normally prefer a downloaded copy.
preferOffline: false,
);
if (!mounted || player != currentPlayer) return;
final result = playbackContext.result;
if (result.videoUrl == null) {
throw PlaybackException(t.messages.fileInfoNotAvailable);
}
_currentMetadata = replacementMetadata;
_isTranscoding = result.isTranscoding;
_effectiveIsOffline = result.isOffline;
_playbackPlaySessionId = result.playSessionId;
_playbackPlayMethod = result.playMethod;
_selectedAudioStreamId = result.activeAudioStreamId;
_effectiveSelectedMediaIndex = result.selectedMediaIndex;
_availableVersions = result.availableVersions;
_currentMediaInfo = result.mediaInfo;
final isExoPlayer = currentPlayer is PlayerAndroid;
final hasExternalSubs = result.externalSubtitles.isNotEmpty;
final shouldAutoPlay = wasPlaying && (isExoPlayer || !hasExternalSubs);
final timelineDuration = _currentMetadata.durationMs != null
? Duration(milliseconds: _currentMetadata.durationMs!)
: null;
await currentPlayer.setProperty('force-seekable', result.isTranscoding ? 'yes' : 'no');
await currentPlayer.open(
Media(result.videoUrl!, start: result.isTranscoding ? null : target, headers: _streamHeaders),
play: shouldAutoPlay,
externalSubtitles: isExoPlayer && hasExternalSubs ? result.externalSubtitles : null,
timelineOffset: result.isTranscoding ? target : Duration.zero,
timelineDuration: result.isTranscoding ? timelineDuration : null,
final session = PlaybackSession.fromContext(
playbackContext,
requestedQualityPreset: _selectedQualityPreset,
requestedMediaSourceId: _selectedMediaSourceId,
);
if (!mounted || player != currentPlayer) return;
final attachesSubsAtOpen = currentPlayer.attachesExternalSubtitlesAtOpen;
final hasExternalSubs = result.externalSubtitles.isNotEmpty;
final shouldAutoPlay = wasPlaying && (attachesSubsAtOpen || !hasExternalSubs);
final didOpen = await _openMediaOnPlayer(
player: currentPlayer,
settingsService: SettingsService.instance,
videoUrl: result.videoUrl!,
isTranscoding: result.isTranscoding,
timing: _playbackOpenTiming(
backend: replacementMetadata.backend,
isTranscoding: result.isTranscoding,
resumePosition: target,
durationMs: replacementMetadata.durationMs,
),
headers: playbackContext.streamHeaders,
play: shouldAutoPlay,
externalSubtitlesAtOpen: attachesSubsAtOpen && hasExternalSubs ? result.externalSubtitles : null,
shouldContinue: () => mounted && player == currentPlayer,
onOpened: () {
// A pre-open failure leaves the previous session (and ids)
// committed; the swap happens only once the player owns the
// restarted stream.
_currentMetadata = replacementMetadata;
_commitPlaybackSession(session);
},
);
if (!didOpen || !mounted || player != currentPlayer) return;
_setPlayerState(() {});
// The play session changed with the restarted transcode — rebind the
// progress tracker so reports don't keep flowing against the dead
// session ids. The item itself is unchanged, so the item-keyed
// services (media-controls metadata, scrobblers) stay as they are.
_progressTracker?.stopTracking();
_progressTracker?.dispose();
_progressTracker = null;
_rebindProgressTracker(
metadata: _currentMetadata,
mediaClient: session.reportingClient,
offlineWatchService: offlineWatchService,
playSessionId: _playbackPlaySessionId,
playMethod: _playbackPlayMethod,
mediaInfo: _currentMediaInfo,
);
final trackManager = _trackManager;
if (trackManager != null) {
trackManager.metadata = _currentMetadata;
trackManager.mediaInfo = _currentMediaInfo;
trackManager.cacheExternalSubtitles(result.externalSubtitles);
if (currentPlayer is! PlayerAndroid && result.externalSubtitles.isNotEmpty) {
trackManager.waitingForExternalSubsTrackSelection = true;
await trackManager.addExternalSubtitles(result.externalSubtitles);
if (wasPlaying && mounted && player == currentPlayer) {
await trackManager.resumeAfterSubtitleLoad();
} else {
trackManager.waitingForExternalSubsTrackSelection = false;
trackManager.applyTrackSelectionWhenReady();
}
} else {
trackManager.applyTrackSelectionWhenReady();
}
await _applyTracksAfterOpen(
forPlayer: currentPlayer,
trackManager: trackManager,
externalSubtitles: result.externalSubtitles,
// A restart while paused must stay paused — selection is still
// applied through the resume-skipped branch.
shouldResumeAfterSubtitleLoad: () => wasPlaying && mounted && player == currentPlayer,
applySelectionWhenResumeSkipped: true,
);
}
_updateMediaControlsPlaybackState();
@@ -133,7 +157,7 @@ extension _VideoPlayerSeekingMethods on VideoPlayerScreenState {
showErrorSnackBar(context, t.messages.errorLoading(error: e.toString()));
}
} finally {
_isRestartingTranscodeSeek = false;
_playbackTransition = _PlaybackTransition.idle;
}
}
}
@@ -36,6 +36,17 @@ extension _VideoPlayerWatchTogetherMethods on VideoPlayerScreenState {
}
}
/// The active Watch Together session, or null when not in one (or the
/// provider is unavailable).
WatchTogetherProvider? _activeWatchTogetherSession() {
try {
final watchTogether = _watchTogetherProvider ?? context.read<WatchTogetherProvider>();
return watchTogether.isInSession ? watchTogether : null;
} catch (_) {
return null;
}
}
/// Check if episode navigation controls should be enabled
/// Returns true if not in Watch Together session, or if user is the host
bool _canNavigateEpisodes() {
@@ -75,8 +86,7 @@ extension _VideoPlayerWatchTogetherMethods on VideoPlayerScreenState {
}
}
/// Handle media switch from host (guest only)
/// Uses VideoPlayerScreen's context for proper navigation (pushReplacement)
/// Handle media switch from host (guest only) using the in-place reload path.
Future<void> _handlePlayerMediaSwitch(String ratingKey, ServerId serverId, String title) async {
if (!mounted) return;
@@ -102,12 +112,22 @@ extension _VideoPlayerWatchTogetherMethods on VideoPlayerScreenState {
return;
}
// Detach and dispose current player before switching to avoid sync calls on a disposed instance
_isReplacingWithVideo = true;
await disposePlayerForNavigation();
if (!mounted) return;
if (player == null || widget.isLive) {
unawaited(_replaceScreenWithPlayer(metadata));
return;
}
// Use same navigation as local episode change (pushReplacement from player context)
unawaited(navigateToVideoPlayer(context, metadata: metadata, usePushReplacement: true));
final handled = await _reloadMediaInPlace(
metadata: metadata,
selectedMediaIndex: await savedMediaVersionIndexFor(metadata) ?? 0,
selectedMediaSourceId: null,
qualityPreset: _selectedQualityPreset,
preserveCurrentTrackSelection: false,
useCurrentAudioStreamSelection: false,
reason: 'watch together media switch',
);
if (!handled && mounted && player == null) {
unawaited(_replaceScreenWithPlayer(metadata));
}
}
}
+147 -195
View File
@@ -17,6 +17,8 @@ import '../mpv/player/platform/player_android.dart';
import '../services/scrub_preview_source.dart';
import '../media/media_backend.dart';
import '../media/media_display_criteria.dart';
import '../media/media_server_user_profile.dart';
import '../media/media_item.dart';
import '../media/media_item_types.dart';
import '../media/media_server_client.dart';
@@ -27,8 +29,6 @@ import '../services/plex_client.dart';
import '../utils/session_identifier.dart';
import '../database/app_database.dart';
import '../media/media_version.dart';
import '../models/livetv_capture_buffer.dart';
import '../models/livetv_channel.dart';
import '../models/transcode_quality_preset.dart';
import '../media/media_source_info.dart';
import '../mixins/mounted_set_state_mixin.dart';
@@ -48,6 +48,7 @@ import '../services/apple_tv_remote_touch_service.dart';
import '../services/media_controls_manager.dart';
import '../services/playback_initialization_service.dart';
import '../services/playback_context.dart';
import '../services/playback_session.dart';
import '../services/playback_progress_tracker.dart';
import '../services/playback_source_resolver.dart';
import '../services/offline_watch_sync_service.dart';
@@ -74,6 +75,10 @@ import '../utils/platform_detector.dart';
import '../utils/provider_extensions.dart';
import '../utils/snackbar_helper.dart';
import '../utils/video_player_navigation.dart';
import 'video_player/completion_latch.dart';
import 'video_player/frame_rate_matcher.dart';
import 'video_player/live_tv_session_args.dart';
import 'video_player/live_tv_session_state.dart';
import 'video_player/widgets/player_prompt_overlays.dart';
import '../widgets/overlay_sheet.dart';
import '../widgets/video_controls/player_chrome_controller.dart';
@@ -96,6 +101,7 @@ part 'video_player/parts/live_tv.dart';
part 'video_player/parts/media_controls.dart';
part 'video_player/parts/pip.dart';
part 'video_player/parts/shader.dart';
part 'video_player/parts/playback_open.dart';
part 'video_player/parts/playback_prompts.dart';
part 'video_player/parts/playback_services.dart';
part 'video_player/parts/playback_start.dart';
@@ -120,6 +126,25 @@ Future<void> _setWakelock(bool enabled) async {
}
}
/// The in-place media-source transitions a [VideoPlayerScreenState] can run.
/// They are mutually exclusive by construction — entry points bail while a
/// transition is in flight.
enum _PlaybackTransition { idle, reloadingMedia, restartingTranscode, switchingChannel }
/// Handle for one playback attempt (initial start, in-place reload,
/// transcode restart). Async continuations check [isCurrent] after every
/// await: it holds while the screen is mounted, the captured player is
/// still the active one, and no newer attempt has bumped the generation.
class _PlaybackAttempt {
_PlaybackAttempt._(this._owner, this.generation, this.player);
final VideoPlayerScreenState _owner;
final int generation;
final Player player;
bool get isCurrent => _owner._isCurrentPlaybackGeneration(generation, player);
}
class _PlaybackOpenTiming {
final Duration? mediaStart;
final Duration timelineOffset;
@@ -194,29 +219,11 @@ class VideoPlayerScreen extends StatefulWidget {
/// Plex audio track (fallback: first).
final int? selectedAudioStreamId;
/// Session identifiers forwarded across quality/version/audio switches so
/// the server-side transcode session is preserved.
final String? reusedSessionIdentifier;
final String? reusedTranscodeSessionId;
/// Present iff this screen plays live TV; carries the whole live launch
/// state (see [LiveTvSessionArgs]).
final LiveTvSessionArgs? live;
// Live TV fields
final bool isLive;
final String? liveChannelName;
final String? liveStreamUrl;
final List<LiveTvChannel>? liveChannels;
final int? liveCurrentChannelIndex;
final String? liveDvrKey;
/// Backend-neutral client typing. The four in-player live ops branch on
/// `client is PlexClient` / `client is JellyfinClient` at their use sites:
/// Plex tunes a transcode session and gets capture-buffer updates;
/// Jellyfin uses its `/Sessions/Playing*` endpoints for progress reporting
/// and re-opens [liveStreamUrl] for retry. Tune (Plex-only by protocol)
/// and seek (Plex-only — Jellyfin live channels aren't seekable) gate
/// explicitly on `client is PlexClient`.
final MediaServerClient? liveClient;
final String? liveSessionIdentifier;
final String? liveSessionPath;
bool get isLive => live != null;
const VideoPlayerScreen({
super.key,
@@ -229,17 +236,7 @@ class VideoPlayerScreen extends StatefulWidget {
this.isOffline = false,
this.selectedQualityPreset,
this.selectedAudioStreamId,
this.reusedSessionIdentifier,
this.reusedTranscodeSessionId,
this.isLive = false,
this.liveChannelName,
this.liveStreamUrl,
this.liveChannels,
this.liveCurrentChannelIndex,
this.liveDvrKey,
this.liveClient,
this.liveSessionIdentifier,
this.liveSessionPath,
this.live,
});
@override
@@ -264,31 +261,38 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
MediaItem? _previousEpisode;
bool _isLoadingNext = false;
bool _isLoadingPrevious = false;
bool _isSwappingEpisode = false;
// In-flight media-source transition. At most one can run at a time: the
// entry guards make reload / transcode-restart / channel-switch mutually
// exclusive instead of relying on three independent booleans.
_PlaybackTransition _playbackTransition = _PlaybackTransition.idle;
bool _showPlayNextDialog = false;
bool _isPhone = false;
List<MediaVersion> _availableVersions = [];
MediaSourceInfo? _currentMediaInfo;
late int _effectiveSelectedMediaIndex;
String? _selectedMediaSourceId;
bool get _offlineLibraryMode => widget.isOffline;
// Transcode / quality state
late TranscodeQualityPreset _selectedQualityPreset;
int? _selectedAudioStreamId;
bool _isTranscoding = false;
bool _effectiveIsOffline = false;
AudioTrack? _preferredAudioTrack;
SubtitleTrack? _preferredSubtitleTrack;
SubtitleTrack? _preferredSecondarySubtitleTrack;
bool _serverSupportsTranscoding = false;
// Kicked off early in `_initializePlayer` for online non-live playback so
// the metadata fetch (and transcode-decision HTTP, if non-original preset)
// overlaps with MPV property configuration. Awaited inside `_startPlayback`
// immediately before `player.open()` needs the video URL.
Future<PlaybackContext>? _playbackDataFuture;
PlaybackContext? _playbackContext;
// The item currently loaded in the player: resolver output + effective
// selections, swapped atomically by [_commitPlaybackSession]. Null until
// the first resolve lands and always null for live TV (which tunes
// through its own path). The getters below denormalize it for the many
// existing read sites.
PlaybackSession? _playbackSession;
int _playbackGeneration = 0;
// HTTP headers attached to the player's `Media` request — `X-Plex-Token`
// for Plex, empty for Jellyfin (token rides in the URL there). Sourced
// from `MediaServerClient.streamHeaders` so the player code path stays
// backend-neutral.
Map<String, String>? _streamHeaders;
// Fired in parallel with MPV setup so the OS audio-focus negotiation
// (~90ms on Android) doesn't sit on the critical path. Awaited before
// `player.open()` so the semantics are unchanged — we just eat the cost
@@ -296,8 +300,6 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
Future<void>? _audioFocusFuture;
late final String _playbackSessionIdentifier;
late String _playbackTranscodeSessionId;
String? _playbackPlaySessionId;
String? _playbackPlayMethod;
StreamSubscription<PlayerError>? _errorSubscription;
StreamSubscription<bool>? _playingSubscription;
StreamSubscription<bool>? _completedSubscription;
@@ -307,7 +309,6 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
StreamSubscription<Duration>? _positionSubscription;
StreamSubscription<void>? _playbackRestartSubscription;
StreamSubscription<void>? _backendSwitchedSubscription;
bool _isRestartingTranscodeSeek = false;
TrackManager? _trackManager;
StreamSubscription<PlayerLog>? _logSubscription;
StreamSubscription<void>? _sleepTimerSubscription;
@@ -316,35 +317,17 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
StreamSubscription<double>? _mediaControlsRateSubscription;
StreamSubscription<bool>? _mediaControlsSeekableSubscription;
StreamSubscription<Map<String, bool>>? _serverStatusSubscription;
bool _isReplacingWithVideo = false;
bool _isDisposingForNavigation = false;
bool _isHandlingBack = false;
/// Set just before this screen replaces itself with another player route
/// (the fallback pushReplacement paths). Dispose then skips the app-level
/// player-exit side effects because the replacement continues the session.
bool _isReplacingWithVideo = false;
ScrubPreviewSource? _scrubPreviewSource;
int _liveChannelIndex = -1;
String? _liveChannelName;
MediaServerClient? _liveClient;
String? _liveDvrKey;
String? _liveStreamUrl;
String? _liveItemId;
String? _liveSessionIdentifier;
String? _liveSessionPath;
Timer? _liveTimelineTimer;
int _liveTimelineGeneration = 0;
DateTime? _livePlaybackStartTime;
String? _liveProgramId;
int? _liveDurationMs;
// Jellyfin live TV heartbeat state machine. The Plex live branch keeps
// its bespoke capture-buffer flow inline; this tracker only collapses
// the Jellyfin started/progress/stopped transition.
JellyfinLiveSessionTracker _jellyfinLiveSession = JellyfinLiveSessionTracker();
CaptureBuffer? _captureBuffer;
int? _programBeginsAt;
double _streamStartEpoch = 0;
bool _isAtLiveEdge = true;
String? _transcodeSessionId;
/// Live TV session state (tune identity, heartbeats, capture buffer,
/// retry ladder) — inert for VOD screens. See [LiveTvSessionState].
late final LiveTvSessionState _live = LiveTvSessionState(widget.live, itemId: widget.metadata.id);
/// Coalesces rapid relative live-TV skips into a single transcode re-open so
/// mashing skip-forward can't compound into an overshoot to live (#1253).
@@ -357,21 +340,13 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
onChanged: _onLiveSeekTargetChanged,
);
/// Fallback level for live TV stream errors (mirrors Plex web client behavior).
/// 0 = directStream+directStreamAudio, 1 = no directStream, 2 = no DS + no DS audio.
int _liveStreamFallbackLevel = 0;
bool _isRetryingLiveStream = false;
Timer? _autoPlayTimer;
int _autoPlayCountdown = 5;
bool _completionTriggered = false;
// End-of-video Play Next thresholds. Fire the prompt within _kPlayNextTriggerMs
// of the end; re-arm (allow it to fire again) only once playback is more than
// _kPlayNextRearmMs from the end. The gap is hysteresis so a position parked at
// the boundary can't oscillate between firing and re-arming.
static const int _kPlayNextTriggerMs = 1000;
static const int _kPlayNextRearmMs = 2000;
// End-of-video Play Next latch. Fires within 1s of the end; re-arms only
// once playback is more than 2s from the end — the gap is hysteresis so a
// position parked at the boundary can't oscillate (see CompletionLatch).
final CompletionLatch _completionLatch = CompletionLatch(triggerWindowMs: 1000, rearmWindowMs: 2000);
late final FocusNode _playNextCancelFocusNode;
late final FocusNode _playNextConfirmFocusNode;
@@ -405,7 +380,6 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
bool _androidAutoPipTransitionInFlight = false;
bool _pipFiltersPrepared = false;
VoidCallback? _autoPipEnteringCallback;
bool _resumeLiveTimelineOnResume = false;
int _rewindOnResume = 0;
Future<void> _lifecycleTransition = Future<void>.value();
String _playerBackendLabel = 'unknown';
@@ -456,17 +430,49 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
return manager.getClient(ServerId(id));
}
// Denormalized views over the committed [PlaybackSession]. Read sites
// keep their historical names; live TV (no session) gets the defaults.
PlaybackContext? get _playbackContext => _playbackSession?.context;
bool get _isTranscoding => _playbackSession?.isTranscoding ?? false;
bool get _effectiveIsOffline => _playbackSession?.isOffline ?? false;
String? get _playbackPlaySessionId => _playbackSession?.playSessionId;
String? get _playbackPlayMethod => _playbackSession?.playMethod;
List<MediaVersion> get _availableVersions => _playbackSession?.availableVersions ?? const [];
MediaSourceInfo? get _currentMediaInfo => _playbackSession?.mediaInfo;
bool get _usesLocalPlaybackSource => _effectiveIsOffline;
bool get _isOfflinePlayback => widget.isOffline || _effectiveIsOffline;
bool get _isOfflinePlayback => _offlineLibraryMode || _effectiveIsOffline;
/// Atomically publish a freshly opened [PlaybackSession] and refine the
/// selection-intent fields from what the backend actually delivered
/// (clamped version index, active audio stream, post-fallback preset).
///
/// Reload-style flows call this from the open boundary: a failure before
/// the commit leaves the previous session — and everything derived from
/// it — untouched, so there is nothing to roll back.
void _commitPlaybackSession(PlaybackSession session) {
_playbackSession = session;
_effectiveSelectedMediaIndex = session.mediaIndex;
_selectedMediaSourceId = session.mediaSourceId;
_selectedQualityPreset = session.qualityPreset;
_selectedAudioStreamId = session.audioStreamId;
}
ScrubFrame? _getThumbnailData(Duration time) => _scrubPreviewSource?.getFrame(time);
int _beginPlaybackGeneration({bool isEpisodeSwap = false}) {
if (!isEpisodeSwap) _isSwappingEpisode = false;
int _beginPlaybackGeneration({bool isMediaReload = false}) {
if (!isMediaReload) _playbackTransition = _PlaybackTransition.idle;
return ++_playbackGeneration;
}
/// Start a new playback attempt: bumps the generation and captures the
/// owning player so async continuations can check [_PlaybackAttempt.isCurrent]
/// uniformly instead of threading (generation, player) pairs around.
_PlaybackAttempt _beginPlaybackAttempt(Player currentPlayer, {bool isMediaReload = false}) {
return _PlaybackAttempt._(this, _beginPlaybackGeneration(isMediaReload: isMediaReload), currentPlayer);
}
bool _isCurrentPlaybackGeneration(int generation, Player currentPlayer) {
return mounted && player == currentPlayer && _playbackGeneration == generation;
}
@@ -484,27 +490,18 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
_activeId = widget.metadata.id;
_activeMediaIndex = widget.selectedMediaIndex;
_effectiveSelectedMediaIndex = widget.selectedMediaIndex;
_selectedMediaSourceId = widget.selectedMediaSourceId;
// Reused across quality/version/audio switches so the server-side
// transcode session is preserved.
_playbackSessionIdentifier = widget.reusedSessionIdentifier ?? generateSessionIdentifier();
_playbackTranscodeSessionId = widget.reusedTranscodeSessionId ?? generateSessionIdentifier();
// Reused across in-place quality/version/audio switches so the
// server-side transcode session is preserved.
_playbackSessionIdentifier = generateSessionIdentifier();
_playbackTranscodeSessionId = generateSessionIdentifier();
_selectedAudioStreamId = widget.selectedAudioStreamId;
_effectiveIsOffline = false;
_preferredAudioTrack = widget.preferredAudioTrack;
_preferredSubtitleTrack = widget.preferredSubtitleTrack;
_preferredSecondarySubtitleTrack = widget.preferredSecondarySubtitleTrack;
_selectedQualityPreset = widget.selectedQualityPreset ?? TranscodeQualityPreset.original;
_liveChannelIndex = widget.liveCurrentChannelIndex ?? -1;
_liveChannelName = widget.liveChannelName;
_liveClient = widget.liveClient;
_liveDvrKey = widget.liveDvrKey;
_liveStreamUrl = widget.liveStreamUrl;
_liveItemId = widget.metadata.id;
_liveSessionIdentifier = widget.liveSessionIdentifier;
_liveSessionPath = widget.liveSessionPath;
if (widget.liveClient is JellyfinClient && widget.liveSessionIdentifier != null) {
_jellyfinLiveSession = JellyfinLiveSessionTracker(playSessionId: widget.liveSessionIdentifier);
}
_playNextCancelFocusNode = FocusNode(debugLabel: 'PlayNextCancel');
_playNextConfirmFocusNode = FocusNode(debugLabel: 'PlayNextConfirm');
@@ -516,16 +513,16 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
_screenFocusNode = FocusNode(debugLabel: 'VideoPlayerScreen');
_screenFocusNode.addListener(_onScreenFocusChanged);
appLogger.d('VideoPlayerScreen initialized for: ${widget.metadata.title}');
if (widget.preferredAudioTrack != null) {
appLogger.d('VideoPlayerScreen initialized for: ${_currentMetadata.title}');
if (_preferredAudioTrack != null) {
appLogger.d(
'Preferred audio track: ${widget.preferredAudioTrack!.title ?? widget.preferredAudioTrack!.id} (${widget.preferredAudioTrack!.language ?? "unknown"})',
'Preferred audio track: ${_preferredAudioTrack!.title ?? _preferredAudioTrack!.id} (${_preferredAudioTrack!.language ?? "unknown"})',
);
}
if (widget.preferredSubtitleTrack != null) {
final subtitleDesc = widget.preferredSubtitleTrack!.id == "no"
if (_preferredSubtitleTrack != null) {
final subtitleDesc = _preferredSubtitleTrack!.id == "no"
? "OFF"
: "${widget.preferredSubtitleTrack!.title ?? widget.preferredSubtitleTrack!.id} (${widget.preferredSubtitleTrack!.language ?? "unknown"})";
: "${_preferredSubtitleTrack!.title ?? _preferredSubtitleTrack!.id} (${_preferredSubtitleTrack!.language ?? "unknown"})";
appLogger.d('Preferred subtitle track: $subtitleDesc');
}
@@ -541,7 +538,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
// synthetic ids tracked in the provider). For genuine standalone
// playback (continue-watching, direct episode tap with no queue
// launcher) clear any stale queue so prev/next stays consistent.
final meta = widget.metadata;
final meta = _currentMetadata;
if (playbackState.isItemInActiveQueue(meta)) {
playbackState.setCurrentItem(meta);
} else {
@@ -659,7 +656,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
// no async gaps invalidate it before the calls below read it.
// Skipped for live TV (has its own tune path) and offline (its own
// branch in _startPlayback).
if (!widget.isLive && !widget.isOffline && mounted) {
if (!widget.isLive && !_offlineLibraryMode && mounted) {
// Backend-neutral lookup so Jellyfin items also flow through here.
// Plex-specific transcoder caching is gated on capabilities below;
// Jellyfin's `streamHeaders` is empty because it embeds api_key in
@@ -668,7 +665,6 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
if (genericClient == null) {
throw StateError('No client registered for ${_currentMetadata.serverId}');
}
_streamHeaders = genericClient.streamHeaders;
// Single source of truth for showing quality controls and applying the
// saved startup quality. Backends that cannot transcode always start at
// Original even if the user picked a lower default quality.
@@ -686,8 +682,8 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
);
_playbackDataFuture = playbackResolver.resolve(
metadata: _currentMetadata,
selectedMediaIndex: widget.selectedMediaIndex,
selectedMediaSourceId: widget.selectedMediaSourceId,
selectedMediaIndex: _effectiveSelectedMediaIndex,
selectedMediaSourceId: _selectedMediaSourceId,
offlineLibraryMode: false,
qualityPreset: _selectedQualityPreset,
selectedAudioStreamId: _selectedAudioStreamId,
@@ -912,7 +908,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
if (!done) {
final durMs = currentPlayer.state.duration.inMilliseconds;
final posMs = currentPlayer.state.position.inMilliseconds;
if (durMs <= 0 || posMs < durMs - _kPlayNextRearmMs) {
if (durMs <= 0 || posMs < durMs - _completionLatch.rearmWindowMs) {
_rearmCompletionLatch();
}
}
@@ -938,7 +934,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
// When server comes back online while buffering, force mpv to reconnect
// immediately instead of waiting for ffmpeg's exponential backoff
if (!_isOfflinePlayback && !widget.isLive) {
final serverId = widget.metadata.serverId;
final serverId = _currentMetadata.serverId;
if (serverId != null) {
if (!mounted) return;
final serverManager = context.read<MultiServerProvider>().serverManager;
@@ -959,7 +955,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
if (!mounted || player != currentPlayer) return;
_lastLogError = null;
_sawServer500 = false;
_liveStreamFallbackLevel = 0;
_live.fallbackLevel = 0;
if (!_hasFirstFrame.value) {
_hasFirstFrame.value = true;
unawaited(Sentry.addBreadcrumb(Breadcrumb(message: 'First frame ready', category: 'player')));
@@ -1000,17 +996,17 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
}
final duration = activePlayer.state.duration;
if (duration.inMilliseconds > 0) {
if (position.inMilliseconds >= duration.inMilliseconds - _kPlayNextTriggerMs &&
!_showPlayNextDialog &&
!_completionTriggered) {
_onVideoCompleted(true);
} else if (position.inMilliseconds < duration.inMilliseconds - _kPlayNextRearmMs) {
// Seeked back out of the end region after dismissing Play Next — re-arm
// so the prompt can fire again if the user returns to the end.
_rearmCompletionLatch();
}
final signal = _completionLatch.classifyPosition(
positionMs: position.inMilliseconds,
durationMs: duration.inMilliseconds,
promptVisible: _showPlayNextDialog,
countdownActive: _autoPlayTimer?.isActive == true,
);
if (signal == CompletionLatchSignal.completed) {
_onVideoCompleted(true);
}
// CompletionLatchSignal.rearmed needs no action here: the latch
// re-armed itself once playback seeked back out of the end region.
});
// Services init must finish before first frame so Discord / Trakt /
@@ -1041,14 +1037,9 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
/// Windows display mode matching service.
DisplayModeService? _displayModeService;
/// Apply frame rate matching on Android by setting the display refresh rate
/// to match the video content's frame rate.
int _frameRateRetries = 0;
bool _suppressMediaPauseDuringFrameRateSwitch = false;
// True once a frame-rate switch has been requested for the current playback
// session — either via the pre-playback primary path (Plex metadata fps) or
// via the post-`playbackRestart` fallback. Prevents double-switching.
bool _frameRateMatchingApplied = false;
/// Android display frame-rate matching state (retry counter, applied
/// latch, MediaSession pause-suppression window) — see [FrameRateMatcher].
final FrameRateMatcher _frameRate = FrameRateMatcher();
/// Handle back button press
/// For non-host participants in Watch Together, shows leave session confirmation
@@ -1130,10 +1121,10 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
_cleanupCompanionRemoteCallbacks();
// Notify Watch Together guests that host is exiting the player
// Use stored reference since context.read() may fail in dispose
// Skip if replacing with another video (episode navigation)
if (!_isReplacingWithVideo &&
// Notify Watch Together guests that host is exiting the player.
// Use stored reference since context.read() may fail in dispose.
final isReplacingWithVideo = _isReplacingWithVideo;
if (!isReplacingWithVideo &&
_watchTogetherProvider != null &&
_watchTogetherProvider!.isHost &&
_watchTogetherProvider!.isInSession) {
@@ -1167,8 +1158,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
_scrubPreviewSource?.dispose();
// Mark sleep timer for restart if truly exiting (not episode transition)
if (!_isReplacingWithVideo) {
if (!isReplacingWithVideo) {
SleepTimerService().markNeedsRestart();
}
@@ -1216,7 +1206,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
if (Platform.isWindows && _displayModeService != null) {
FullscreenStateManager().removeListener(_onFullscreenChanged);
}
if (!_isReplacingWithVideo &&
if (!isReplacingWithVideo &&
Platform.isWindows &&
_displayModeService != null &&
_displayModeService!.anyChangeApplied) {
@@ -1228,15 +1218,19 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
// Clear frame rate matching and abandon audio focus before disposing player (Android only)
if (Platform.isAndroid && player != null) {
player!.clearVideoFrameRate();
// Native dispose deliberately leaves the display mode for Dart to clear
// (ExoPlayerCore.releasePending) — skip it during a player→player
// replacement, the Android analog of preserveDisplayMode below.
if (!isReplacingWithVideo) {
player!.clearVideoFrameRate();
}
player!.abandonAudioFocus();
}
unawaited(_setWakelock(false));
appLogger.d('Wakelock disabled');
// Restore system UI and orientation preferences (skip if navigating to another video)
if (!_isReplacingWithVideo) {
if (!isReplacingWithVideo) {
unawaited(_restoreSystemUiAndOrientation());
}
@@ -1244,7 +1238,9 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
final playerToDispose = player;
player = null;
if (playerToDispose != null) {
unawaited(playerToDispose.dispose());
// Keep the native display mode (tvOS HDMI criteria) across a
// player→player handoff; the replacement screen primes its own.
unawaited(playerToDispose.dispose(preserveDisplayMode: isReplacingWithVideo));
}
if (_activeId == _currentMetadata.id) {
_activeId = null;
@@ -1332,8 +1328,6 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
void _setPlayerState(VoidCallback fn) => setStateIfMounted(fn);
bool _isSwitchingChannel = false;
/// Wait briefly for profile settings to load in offline mode.
/// This prevents default-track fallback when playback starts before
/// UserProfileProvider finishes initialization.
@@ -1365,17 +1359,6 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
void _onSecondarySubtitleTrackChanged(SubtitleTrack track) => _trackManager?.onSecondarySubtitleTrackChanged(track);
/// Set flag to skip orientation restoration when replacing with another video
void setReplacingWithVideo() {
_isReplacingWithVideo = true;
}
/// Session identifiers owned by this screen, forwarded to a replacement
/// [VideoPlayerScreen] during quality/version/audio switches so the Plex
/// transcode session is continued rather than restarted.
String get playbackSessionIdentifier => _playbackSessionIdentifier;
String get playbackTranscodeSessionId => _playbackTranscodeSessionId;
Future<void> _sendStoppedProgressOnce({Duration? positionOverride}) {
final tracker = _progressTracker;
if (tracker == null) return Future<void>.value();
@@ -1385,37 +1368,6 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
});
}
/// Dispose the player before replacing the video to avoid race conditions
Future<void> disposePlayerForNavigation() async {
if (_isDisposingForNavigation) return;
_isDisposingForNavigation = true;
_isExiting.value = true; // Show black overlay during transition
try {
_detachFromWatchTogetherSession();
await _sendStoppedProgressOnce();
_progressTracker?.stopTracking();
_detachPipStateListener();
_videoPIPManager?.onBeforeEnterPip = null;
unawaited(_videoPIPManager?.disableAutoPip());
_clearAutoPipEnteringCallback();
// Clear frame rate matching before disposing (Android only)
await _clearFrameRateMatching();
// Restore Windows display mode before disposing
if (!_isReplacingWithVideo) {
await _restoreWindowsDisplayMode();
}
await _positionSubscription?.cancel();
_positionSubscription = null;
await player?.dispose();
} catch (e) {
appLogger.d('Error disposing player before navigation', error: e);
} finally {
player = null;
_isPlayerInitialized = false;
}
}
@override
Widget build(BuildContext context) {
final isCurrentRoute = ModalRoute.of(context)?.isCurrent ?? true;
@@ -1,5 +1,6 @@
import 'dart:async';
import 'package:flutter/foundation.dart' show ValueListenable;
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
@@ -44,6 +45,7 @@ class AppleTvRemoteTouchService {
bool _listening = false;
bool _nativeKeyHandlerRegistered = false;
bool _touchActive = false;
final ValueNotifier<bool> _touchActiveNotifier = ValueNotifier<bool>(false);
double _startX = 0;
double _startY = 0;
double _anchorX = 0;
@@ -83,6 +85,14 @@ class AppleTvRemoteTouchService {
Stream<AppleTvRemotePlayPauseAction> get playPauseActions => _playPauseController.stream;
/// Whether a Siri-remote touch gesture is currently in progress (finger down).
/// Cleared when the touch ends or cancels. tvOS-only; `false` elsewhere.
bool get isTouchActive => _touchActive;
/// Listenable mirror of [isTouchActive] so widgets can react when the active
/// touch gesture ends (used to extend Home-rail select suppression).
ValueListenable<bool> get touchActiveListenable => _touchActiveNotifier;
void start() {
if (_listening) return;
_channel.setMessageHandler(handleMessage);
@@ -179,6 +189,7 @@ class AppleTvRemoteTouchService {
void _startTouch(double x, double y) {
_touchActive = true;
_touchActiveNotifier.value = true;
_startX = x;
_startY = y;
_anchorX = x;
@@ -412,6 +423,7 @@ class AppleTvRemoteTouchService {
void _resetTouch() {
_touchActive = false;
_touchActiveNotifier.value = false;
_lastSwipeAxis = null;
_lastSwipeAt = null;
}
+7 -8
View File
@@ -84,12 +84,10 @@ class DataAggregationService {
}).toList();
}
// Sort by most recently viewed, falling back to addedAt for unwatched items
filteredOnDeck.sort((a, b) {
final aTime = a.lastViewedAt ?? a.addedAt ?? 0;
final bTime = b.lastViewedAt ?? b.addedAt ?? 0;
return bTime.compareTo(aTime); // Descending (most recent first)
});
// Sort by most recently viewed, falling back to addedAt for unwatched items.
// Same key as JellyfinClient's continue-watching merge (MediaItem.recencySortKey)
// so per-server and cross-server ordering can't drift apart.
filteredOnDeck.sort((a, b) => b.recencySortKey.compareTo(a.recencySortKey));
filteredOnDeck = await _deduplicateContinueWatching(filteredOnDeck);
@@ -265,11 +263,12 @@ class DataAggregationService {
try {
final serverLibraries = libraries?[serverId];
final shouldUseGlobalHubs = useGlobalHubs && client.capabilities.richHubs;
final hubItemLimit = limit ?? defaultHubPreviewLimit;
final hubs = shouldUseGlobalHubs
? await client.fetchGlobalHubs(limit: limit ?? 10, includePlaybackHubs: includePlaybackHubs)
? await client.fetchGlobalHubs(limit: hubItemLimit, includePlaybackHubs: includePlaybackHubs)
: await _fetchLibraryHubsForClient(
client,
limit: limit ?? 10,
limit: hubItemLimit,
hiddenLibraryKeys: hiddenLibraryKeys,
includePlaybackHubs: includePlaybackHubs,
libraries: useGlobalHubs ? serverLibraries : null,
@@ -7,12 +7,10 @@ import 'package:provider/provider.dart';
import '../media/media_item.dart';
import '../media/media_item_types.dart';
import '../media/play_queue.dart';
import '../mpv/mpv.dart';
import '../providers/multi_server_provider.dart';
import '../providers/playback_state_provider.dart';
import '../services/multi_server_manager.dart';
import '../utils/app_logger.dart';
import '../utils/video_player_navigation.dart';
/// Result of loading adjacent episodes
class AdjacentEpisodes {
@@ -146,50 +144,6 @@ class EpisodeNavigationService {
appLogger.d('Local episode queue (${allEpisodes.length} episodes, anchor: $anchorIdx)');
}
/// Navigate to the next or previous episode
///
/// Preserves the current audio track, subtitle track, and playback rate
/// selections when transitioning between episodes.
Future<void> navigateToEpisode({
required BuildContext context,
required MediaItem episode,
required Player? player,
bool usePushReplacement = true,
}) async {
if (!context.mounted) return;
// Capture current player state before navigation
AudioTrack? currentAudioTrack;
SubtitleTrack? currentSubtitleTrack;
SubtitleTrack? currentSecondarySubtitleTrack;
double? currentPlaybackRate;
if (player != null) {
currentAudioTrack = player.state.track.audio;
currentSubtitleTrack = player.state.track.subtitle;
currentSecondarySubtitleTrack = player.state.track.secondarySubtitle;
currentPlaybackRate = player.state.rate;
appLogger.d(
'Navigating to episode with preserved settings - Audio: ${currentAudioTrack?.id}, Subtitle: ${currentSubtitleTrack?.id}, Rate: ${currentPlaybackRate}x',
);
}
// Navigate to the new episode
if (context.mounted) {
unawaited(
navigateToVideoPlayer(
context,
metadata: episode,
preferredAudioTrack: currentAudioTrack,
preferredSubtitleTrack: currentSubtitleTrack,
preferredSecondarySubtitleTrack: currentSecondarySubtitleTrack,
usePushReplacement: usePushReplacement,
),
);
}
}
/// LRU-touching read: re-inserts the entry so it becomes the most recent.
/// Returns null on miss.
List<MediaItem>? _readSeriesCache(String seriesId) {
+5 -1
View File
@@ -208,7 +208,11 @@ class ExternalPlayerService {
if (position.inMilliseconds / duration.inMilliseconds >= client.watchedThreshold) {
try {
await client.markWatched(metadata);
// reportPlaybackStopped above marks the item played on backends that
// support it (Jellyfin); markWatchedFromPlaybackStop then only emits the
// local watch event there to avoid double-scrobbling via the Trakt
// plugin (#1287). Plex still issues the explicit server call.
await client.markWatchedFromPlaybackStop(metadata);
unawaited(TrackerCoordinator.instance.markWatched(metadata, client));
} catch (e) {
appLogger.w('Failed to mark external playback watched for ${metadata.id}', error: e);
+7
View File
@@ -242,6 +242,13 @@ class JellyfinClient
@override
double get watchedThreshold => 0.9;
/// Jellyfin marks an item played from `/Sessions/Playing/Stopped` itself
/// (server `MaxResumePct`, default 90%), so the in-player auto-scrobble must
/// not also `POST /UserPlayedItems` — that double-scrobbles via the Trakt
/// plugin (#1287). Manual mark-watched still hits `/UserPlayedItems`.
@override
bool get marksWatchedOnPlaybackStopped => true;
@override
void close() => _http.close();
+95 -16
View File
@@ -45,6 +45,12 @@ const _queueFields = 'UserData';
/// bounded while still returning the full series queue.
const _episodeQueuePageSize = 200;
/// How many recently played episodes to scan when stamping `/Shows/NextUp`
/// rows with their series' last-watched date (see [_attachSeriesLastPlayed]).
/// Mirrors [_episodeQueuePageSize]; covers far more distinct series than the
/// Next Up list ever returns, while keeping the response bounded.
const _continueWatchingSeriesLookback = 200;
const _childrenPageSize = 500;
const _pagedListPageSize = 200;
const _playableDescendantTypes = 'Movie,Episode';
@@ -887,13 +893,13 @@ mixin _JellyfinBrowseMethods on MediaServerCacheMixin {
return _mergeContinueWatchingAndNextUp(
resume: _mapItems(results.first),
nextUp: _mapItems(results[1]),
nextUp: await _attachSeriesLastPlayed(_mapItems(results[1])),
limit: count,
);
}
@override
Future<List<MediaHub>> fetchGlobalHubs({int limit = 10, bool includePlaybackHubs = true}) async {
Future<List<MediaHub>> fetchGlobalHubs({int limit = defaultHubPreviewLimit, bool includePlaybackHubs = true}) async {
// Jellyfin doesn't expose a single "hubs" endpoint, so we synthesise the
// home rows from Latest plus optional playback rows. The richer Plex Discover surface
// is intentionally left untranslated — see ServerCapabilities.richHubs.
@@ -913,6 +919,7 @@ mixin _JellyfinBrowseMethods on MediaServerCacheMixin {
title: t.discover.recentlyAdded,
type: 'mixed',
items: latest,
previewLimit: limit,
serverId: serverId,
serverName: serverName,
),
@@ -947,6 +954,7 @@ mixin _JellyfinBrowseMethods on MediaServerCacheMixin {
title: t.discover.continueWatching,
type: 'mixed',
items: results[1],
previewLimit: limit,
serverId: serverId,
serverName: serverName,
),
@@ -956,6 +964,7 @@ mixin _JellyfinBrowseMethods on MediaServerCacheMixin {
title: t.discover.nextUp,
type: 'episode',
items: results[2],
previewLimit: limit,
serverId: serverId,
serverName: serverName,
),
@@ -965,6 +974,7 @@ mixin _JellyfinBrowseMethods on MediaServerCacheMixin {
title: t.discover.recentlyAdded,
type: 'mixed',
items: results.first,
previewLimit: limit,
serverId: serverId,
serverName: serverName,
),
@@ -975,7 +985,7 @@ mixin _JellyfinBrowseMethods on MediaServerCacheMixin {
Future<List<MediaHub>> fetchLibraryHubs(
String libraryId, {
required String libraryName,
int limit = 10,
int limit = defaultHubPreviewLimit,
bool includePlaybackHubs = true,
MediaKind? libraryKind,
}) async {
@@ -1001,6 +1011,7 @@ mixin _JellyfinBrowseMethods on MediaServerCacheMixin {
title: t.discover.recentlyAddedIn(library: libraryName),
type: 'mixed',
items: latest,
previewLimit: limit,
serverId: serverId,
serverName: serverName,
),
@@ -1040,6 +1051,7 @@ mixin _JellyfinBrowseMethods on MediaServerCacheMixin {
title: t.discover.continueWatchingIn(library: libraryName),
type: 'mixed',
items: results[1],
previewLimit: limit,
serverId: serverId,
serverName: serverName,
),
@@ -1049,6 +1061,7 @@ mixin _JellyfinBrowseMethods on MediaServerCacheMixin {
title: t.discover.nextUpIn(library: libraryName),
type: 'episode',
items: results[2],
previewLimit: limit,
serverId: serverId,
serverName: serverName,
),
@@ -1058,6 +1071,7 @@ mixin _JellyfinBrowseMethods on MediaServerCacheMixin {
title: t.discover.recentlyAddedIn(library: libraryName),
type: 'mixed',
items: results.first,
previewLimit: limit,
serverId: serverId,
serverName: serverName,
),
@@ -1252,6 +1266,67 @@ mixin _JellyfinBrowseMethods on MediaServerCacheMixin {
return extras;
}
/// Jellyfin's `/Shows/NextUp` returns the *next* (unwatched) episode for each
/// series, so those rows have no `LastPlayedDate` of their own and a Series DTO
/// doesn't expose an aggregated one. To let the Continue Watching shelf
/// interleave Next Up with resume items by recency, stamp each Next Up episode
/// with its series' last-watched date, read from the most recently played
/// episode of that series.
Future<List<MediaItem>> _attachSeriesLastPlayed(List<MediaItem> nextUp) async {
final pendingSeriesIds = <String>{
for (final item in nextUp)
if (item.kind == MediaKind.episode && item.lastViewedAt == null && item.grandparentId != null)
item.grandparentId!,
};
if (pendingSeriesIds.isEmpty) return nextUp;
// One lightweight pass over the most recently played episodes server-wide,
// ordered DatePlayed-descending so the first time we see a series is its
// newest play. We deliberately do NOT filter on the Played flag: Jellyfin's
// own NextUp ranks series by MAX(LastPlayedDate) across every episode, and an
// episode can carry a LastPlayedDate while Played==false (started but not
// finished, or later marked unwatched). Filtering to IsPlayed would miss
// those and leave such series un-dated. Null dates sort last, so the limit
// still captures the genuinely-recent episodes; a series whose last play
// falls beyond the window keeps a null date and degrades to its addedAt in
// the sort — it would rank near the bottom anyway, being least-recent.
final rawPlayed = await _safeFetchItemsArray('/Items', {
'userId': connection.userId,
'IncludeItemTypes': 'Episode',
'Recursive': 'true',
'SortBy': 'DatePlayed',
'SortOrder': 'Descending',
'Fields': _queueFields,
'Limit': _continueWatchingSeriesLookback.toString(),
'EnableImages': 'false',
'EnableTotalRecordCount': 'false',
});
final lastPlayedBySeries = <String, int>{};
for (final episode in _mapItems(rawPlayed)) {
final seriesId = episode.grandparentId;
final playedAt = episode.lastViewedAt;
if (seriesId == null || playedAt == null) continue;
if (!pendingSeriesIds.contains(seriesId)) continue;
lastPlayedBySeries.putIfAbsent(seriesId, () => playedAt);
}
if (lastPlayedBySeries.isEmpty) return nextUp;
return [
for (final item in nextUp)
if (item.lastViewedAt == null && lastPlayedBySeries[item.grandparentId] != null)
item.copyWith(lastViewedAt: lastPlayedBySeries[item.grandparentId])
else
item,
];
}
/// Merge Jellyfin's two continue-watching sources into one recency-ordered
/// shelf. Resume items are deduped first so an in-progress episode wins over
/// the same series' Next Up entry, then the combined list is ordered by
/// [MediaItem.recencySortKey] (matching `DataAggregationService`) before the
/// limit is applied — so a recent Next Up episode is never starved by a long
/// run of older resume items.
List<MediaItem> _mergeContinueWatchingAndNextUp({
required List<MediaItem> resume,
required List<MediaItem> nextUp,
@@ -1259,25 +1334,29 @@ mixin _JellyfinBrowseMethods on MediaServerCacheMixin {
}) {
if (limit != null && limit <= 0) return const [];
final result = <MediaItem>[];
final merged = <MediaItem>[];
final seenIds = <String>{};
final seenSeriesIds = <String>{};
void add(MediaItem item) {
if (!seenIds.add(item.id)) return;
// Resume first: first-wins dedup makes an in-progress episode beat the same
// series' Next Up entry.
for (final item in [...resume, ...nextUp]) {
if (!seenIds.add(item.id)) continue;
final seriesId = item.kind == MediaKind.episode ? item.grandparentId : null;
if (seriesId != null && !seenSeriesIds.add(seriesId)) return;
result.add(item);
if (seriesId != null && !seenSeriesIds.add(seriesId)) continue;
merged.add(item);
}
for (final item in resume) {
add(item);
if (limit != null && result.length >= limit) return result;
}
for (final item in nextUp) {
add(item);
if (limit != null && result.length >= limit) return result;
}
// Stable sort by recency: Dart's List.sort isn't stable, so break ties on the
// insertion index to keep ordering deterministic across refreshes.
final ordered = [for (var i = 0; i < merged.length; i++) (item: merged[i], index: i)];
ordered.sort((a, b) {
final byRecency = b.item.recencySortKey.compareTo(a.item.recencySortKey);
return byRecency != 0 ? byRecency : a.index.compareTo(b.index);
});
final result = [for (final entry in ordered) entry.item];
if (limit != null && result.length > limit) return result.sublist(0, limit);
return result;
}
+2 -1
View File
@@ -265,6 +265,7 @@ class JellyfinMappers {
required ServerId serverId,
String? serverName,
MediaItem? Function(Map<String, dynamic>)? mapItem,
int? previewLimit,
}) {
final mapper = mapItem ?? ((it) => mediaItem(it, serverId: serverId, serverName: serverName, absolutizer: null));
final mappedItems = items.map(mapper).whereType<MediaItem>().toList();
@@ -275,7 +276,7 @@ class JellyfinMappers {
type: type,
items: mappedItems,
size: mappedItems.length,
more: items.length >= 20,
more: previewLimit != null && items.length >= previewLimit,
serverId: serverId,
serverName: serverName,
);
+5 -2
View File
@@ -583,9 +583,12 @@ class OfflineWatchSyncService extends ChangeNotifier {
);
}
// If progress exceeded threshold, also mark as watched.
// If progress exceeded threshold, also mark as watched. On backends
// that mark played from the stopped report above (Jellyfin) this only
// emits the local watch event — an explicit markWatched would
// double-scrobble via the Trakt plugin (#1287).
if (action.shouldMarkWatched) {
await client.markWatched(item);
await client.markWatchedFromPlaybackStop(item);
await TrackerCoordinator.instance.markWatched(item, client);
}
break;
+6 -3
View File
@@ -328,9 +328,12 @@ class PlaybackProgressTracker {
if (percent >= threshold) {
_scrobbled = true;
try {
// The neutral markWatched(MediaItem) call emits the watched event
// through WatchStateNotifier itself, so no extra notify here.
await c.markWatched(metadata);
// Backends that mark the item played from the playback-stopped report
// (Jellyfin) only emit the local watch event here — an explicit
// markWatched would double-scrobble via the Trakt plugin (#1287).
// Plex still issues the server call. Either path emits the watched
// event through WatchStateNotifier, so no extra notify is needed.
await c.markWatchedFromPlaybackStop(metadata);
appLogger.d(
'Scrobbled ${metadata.id} (${(percent * 100).toStringAsFixed(0)}% >= ${(threshold * 100).toStringAsFixed(0)}%)',
);
+76
View File
@@ -0,0 +1,76 @@
import '../media/media_item.dart';
import '../media/media_server_client.dart';
import '../media/media_source_info.dart';
import '../media/media_version.dart';
import '../models/transcode_quality_preset.dart';
import 'playback_context.dart';
import 'playback_initialization_types.dart';
/// Immutable snapshot of everything that describes the item currently loaded
/// in the player: the resolver output plus the effective (post-fallback,
/// post-clamping) source selections.
///
/// Built once per resolve and swapped atomically on the screen — failure
/// before the swap means the previous session (and the state derived from
/// it) stays untouched, which replaces the old field-by-field
/// snapshot/rollback bookkeeping.
class PlaybackSession {
final PlaybackContext context;
/// Effective quality preset — the requested preset, downgraded to
/// original when the backend reported a transcode fallback.
final TranscodeQualityPreset qualityPreset;
/// Effective media version id, refined from the resolver's clamped
/// version index when the version list provides one.
final String? mediaSourceId;
const PlaybackSession({required this.context, required this.qualityPreset, this.mediaSourceId});
/// Derives the effective selections from a resolved [context]:
/// quality falls back to original when the backend rejected the requested
/// preset, and the media source id follows the clamped version index.
factory PlaybackSession.fromContext(
PlaybackContext context, {
required TranscodeQualityPreset requestedQualityPreset,
String? requestedMediaSourceId,
}) {
final result = context.result;
final fellBackToOriginal = result.fallbackReason != null && !requestedQualityPreset.isOriginal;
return PlaybackSession(
context: context,
qualityPreset: fellBackToOriginal ? TranscodeQualityPreset.original : requestedQualityPreset,
mediaSourceId:
mediaSourceIdForIndex(result.availableVersions, result.selectedMediaIndex) ?? requestedMediaSourceId,
);
}
static String? mediaSourceIdForIndex(List<MediaVersion> versions, int index) {
if (index < 0 || index >= versions.length) return null;
return versions[index].id;
}
PlaybackInitializationResult get result => context.result;
MediaItem get metadata => context.metadata;
MediaServerClient? get reportingClient => context.reportingClient;
bool get isTranscoding => result.isTranscoding;
bool get isOffline => result.isOffline;
String? get playSessionId => result.playSessionId;
String? get playMethod => result.playMethod;
int? get audioStreamId => result.activeAudioStreamId;
int get mediaIndex => result.selectedMediaIndex;
List<MediaVersion> get availableVersions => result.availableVersions;
MediaSourceInfo? get mediaInfo => result.mediaInfo;
Map<String, String>? get streamHeaders => context.streamHeaders;
}
+5 -1
View File
@@ -14,6 +14,9 @@ class PlaybackSourceResolver {
const PlaybackSourceResolver({required this.serverManager, required this.database});
/// [preferOffline] overrides the default downloaded-copy preference
/// (`offlineLibraryMode || qualityPreset.isOriginal`). Pass false for
/// flows that must stay on the server stream, e.g. a transcode restart.
Future<PlaybackContext> resolve({
required MediaItem metadata,
required int selectedMediaIndex,
@@ -23,6 +26,7 @@ class PlaybackSourceResolver {
int? selectedAudioStreamId,
String? sessionIdentifier,
String? transcodeSessionId,
bool? preferOffline,
}) async {
final reportingClient = _playbackClient(serverIdOrNull(metadata.serverId), offlineLibraryMode: offlineLibraryMode);
final service = PlaybackInitializationService(client: reportingClient, database: database);
@@ -30,7 +34,7 @@ class PlaybackSourceResolver {
metadata: metadata,
selectedMediaIndex: selectedMediaIndex,
selectedMediaSourceId: selectedMediaSourceId,
preferOffline: offlineLibraryMode || qualityPreset.isOriginal,
preferOffline: preferOffline ?? (offlineLibraryMode || qualityPreset.isOriginal),
qualityPreset: qualityPreset,
selectedAudioStreamId: selectedAudioStreamId,
sessionIdentifier: sessionIdentifier,

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