Compare commits

..
12 Commits
Author SHA1 Message Date
edde746 5a7e0966a3 chore: bump version to 2.19.1 2026-09-07 20:50:59 +02:00
edde746 c84b12eacd fix(livetv): allow cold MediaBrowser tuners time to open
Emby and Jellyfin Live TV could fail before playback when opening a cold tuner took longer than ten seconds. Use the existing thirty-second tune timeout only for live PlaybackInfo requests that open a source, preserving other request budgets and transport aborts.

Cover delayed initial tuning and recovery, bounded cancellation without replay, and unchanged VOD and metadata timeouts.

close #2274
2026-09-07 20:32:16 +02:00
edde746 f9b9fbf611 fix(player): restore Android MPV surfaces after screensaver
Paused playback could remain stuck after the screensaver destroyed its video and OSD surfaces, leaving later resume and initialization blocked.

Attach video and OSD surfaces together, drain placeholder frames, and bound surface retirement with explicit failure handling. Preserve native surface ownership through teardown and cover recreation, pause preservation, and disposal.

close #2249
2026-09-07 20:32:16 +02:00
edde746 e727f5bef4 fix(emby): negotiate MPEG-TS HLS for live TV
Emby Live TV can fail to parse fMP4 HLS fragments, and retrying the same negotiated URL cannot change the segment container.

Restrict Emby Live TV negotiation to the existing MPEG-TS profile on initial tune and direct-play recovery. Preserve direct play, stream copy, Jellyfin negotiation, and Emby VOD. Cover transport scoping and recovery with protocol regressions.

close #2273
2026-09-07 20:32:16 +02:00
edde746 3cf412b9c8 fix(player): use native AV1 decoding when Android hardware support is absent
Software MediaCodec AV1 decoding on Pixel fails during ambient lighting and lock/unlock surface transitions, leaving corrupt or black video.

Check hardware AV1 capability before decoder initialization and reuse the per-file software decoding policy to select dav1d with GPU output. Preserve hardware decoding for supported files.

close #2272
2026-09-07 20:32:15 +02:00
edde746 048bf688b2 fix(player): await terminal playback reporting before desktop exit
Closing the app during video playback left the backend session alive until it timed out. Await shared shutdown completion and the terminal video report before closing server clients, while keeping exit bounded when teardown stalls.

close #2275
2026-09-07 20:09:12 +02:00
edde746 8238705d3e fix(android): pin MPV with stable frame scheduling
Android MPV could turn timing jitter into uneven frame presentation without reporting dropped frames.

Pin mpv-build d38d607fd299e106a83f3557e310ac4b8202b39c to consume cadence prediction and refresh-selection hysteresis. Update the unified pin and Apple lock mirrors; only Android binary artifacts change.

Refs #2262
2026-09-07 07:01:09 +02:00
edde746 722c4ddd00 fix(homebrew): migrate cask to postflight steps
Homebrew warns when loading the deprecated postflight hook. Use structured steps with install-time appdir expansion while preserving recursive extended-attribute removal.

close #2259
2026-09-07 07:01:09 +02:00
56b990c04c feat(jellyfin): report the platform in the MediaBrowser client name (#2261)
Jellyfin and Emby sessions expose Client and DeviceName but no platform,
so dashboards and session trackers (Tracearr's normalizeClient, for one)
keyword-match the Client string the way they do for "Jellyfin Android TV"
and "Swiftfin tvOS". Plezy sent Client="Plezy" on every platform, so every
install showed up as platform "Plezy", and an unresolvable device name
became Device="Plezy" as well.

Add jellyfinClientName, which appends the platform ("Plezy Android TV",
"Plezy tvOS", "Plezy iOS", ...), and jellyfinDeviceName, which falls back
through the hardware model and the platform before the app name, and use
both at the two Jellyfin/Emby header call sites. Every emitted client
string was checked against Tracearr's matcher. The Plex headers and the
DisplayPreferences client key are unchanged.


Claude-Session: https://claude.ai/code/session_0134eXvhukgvG6Szg5NTwAim

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-07 01:39:07 +02:00
edde746 b904c11750 fix(network): use default ports for websocket connections
Watch Together could not reach relays when their URLs omitted a port because Dart passes port 0 to custom WebSocket connection factories.

Resolve port 0 to the HTTP/HTTPS default in the Happy Eyeballs factory while preserving explicit destination and proxy ports. Cover portless ws/wss connections with isolated regression tests.

close #2263
2026-09-07 01:30:08 +02:00
edde746 8870852a9e fix(player): reset TrueHD passthrough state after seeks
TrueHD passthrough retains stale muxer timing and partial MAT frames across seeks, including Android's startup decoder refresh. Pin mpv-build d3a1e12c9da054026aa0d546fee29e2ceeae0226, which publishes the upstream SPDIF reset backport for every native platform, and synchronize all Apple and non-Apple locks.

Refs #2262. The timing-warning regression is reproduced and fixed; sustained Fire TV judder still needs reporter confirmation.
2026-09-07 01:18:57 +02:00
github-actions[bot] 6039fde33b chore: update cask to 2.19.0 2026-09-06 21:34:04 +00:00
52 changed files with 1902 additions and 572 deletions
+6 -6
View File
@@ -1,6 +1,6 @@
cask "plezy" do
version "2.18.0"
sha256 "affa0922fb33b6ca79a0d6ce7e5042539097a0ea097f011c9a4cfdbe0e822f94"
version "2.19.0"
sha256 "2b94d7a14ef2771679ed13effce7f23bbaef5796ad8f66d82d1143858ec1b9a0"
url "https://github.com/edde746/plezy/releases/download/#{version}/plezy-macos.dmg"
name "Plezy"
@@ -16,10 +16,10 @@ cask "plezy" do
app "Plezy.app"
postflight do
system_command "/usr/bin/xattr",
args: ["-cr", "#{appdir}/Plezy.app"],
sudo: false
postflight_steps do
run "/usr/bin/xattr",
args: ["-cr", "{{appdir}}/Plezy.app"],
sudo: false
end
uninstall quit: "com.edde746.plezy"
@@ -2,9 +2,13 @@ package com.edde746.plezy.mpv
import android.app.Instrumentation
import android.content.Intent
import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import android.view.ViewGroup
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
@@ -13,6 +17,7 @@ import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
@@ -21,23 +26,64 @@ import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class MpvLifecycleDeviceTest {
@Test
fun repeatedMediaCodecPlaybackCompletesTerminalTeardown() {
fun repeatedMediaCodecPlaybackCompletesTerminalTeardown() = runPlaybackTest(recreateSurfaces = false)
@Test
fun pausedMediaCodecPlaybackSurvivesRepeatedSurfaceRecreation() = runPlaybackTest(recreateSurfaces = true)
@Test
fun pausedGpuPlaybackSurvivesRepeatedSurfaceRecreation() = runPlaybackTest(recreateSurfaces = true, hardwareDecoding = false)
@Test
fun placeholderConsumesFramesWithoutBlockingProducer() {
val placeholder = runBlocking { MpvPlaceholderSurface.create() }
val completed = CountDownLatch(1)
val failure = AtomicReference<Throwable?>()
val producer = Thread {
try {
// More than a BufferQueue can retain without an active consumer.
repeat(16) {
val canvas = placeholder.surface.lockCanvas(null)
canvas.drawColor(Color.BLACK)
placeholder.surface.unlockCanvasAndPost(canvas)
}
} catch (error: Throwable) {
failure.set(error)
} finally {
completed.countDown()
}
}.apply { isDaemon = true }
try {
producer.start()
assertCompletes(completed, "placeholder buffer consumption", 0)
failure.get()?.let { throw AssertionError("Placeholder producer failed", it) }
} finally {
placeholder.close()
producer.join(2_000)
assertTrue("Placeholder producer survived cleanup", !producer.isAlive)
}
}
private fun runPlaybackTest(recreateSurfaces: Boolean, hardwareDecoding: Boolean = true) {
val instrumentation = InstrumentationRegistry.getInstrumentation()
val fixtureBytes = instrumentation.context.assets.open("ffmpeg/mediacodec_teardown.mp4").use { it.readBytes() }
val fixture = copyFixture(fixtureBytes, instrumentation.targetContext.cacheDir)
val activity = instrumentation.startActivitySync(
Intent(instrumentation.targetContext, MpvLifecycleTestActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
) as MpvLifecycleTestActivity
instrumentation.waitForIdleSync()
try {
repeat(CYCLE_COUNT) { cycle ->
runPlaybackCycle(instrumentation, activity, fixture, cycle)
val activity = instrumentation.startActivitySync(
Intent(instrumentation.targetContext, MpvLifecycleTestActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
) as MpvLifecycleTestActivity
try {
instrumentation.waitForIdleSync()
repeat(CYCLE_COUNT) { cycle ->
runPlaybackCycle(instrumentation, activity, fixture, cycle, recreateSurfaces, hardwareDecoding)
}
} finally {
instrumentation.runOnMainSync(activity::finish)
instrumentation.waitForIdleSync()
}
} finally {
instrumentation.runOnMainSync(activity::finish)
instrumentation.waitForIdleSync()
fixture.delete()
}
}
@@ -46,7 +92,9 @@ class MpvLifecycleDeviceTest {
instrumentation: Instrumentation,
activity: MpvLifecycleTestActivity,
fixture: File,
cycle: Int
cycle: Int,
recreateSurfaces: Boolean,
hardwareDecoding: Boolean
) {
val initialized = CountDownLatch(1)
val initializationResult = AtomicReference<Boolean>()
@@ -55,7 +103,7 @@ class MpvLifecycleDeviceTest {
instrumentation.runOnMainSync {
core.set(
MpvPlayerCore(activity, hardwareDecoding = true).also { playerCore ->
MpvPlayerCore(activity, hardwareDecoding = hardwareDecoding).also { playerCore ->
playerCore.delegate = events
playerCore.initialize { success ->
initializationResult.set(success)
@@ -65,30 +113,39 @@ class MpvLifecycleDeviceTest {
)
}
assertCompletes(initialized, "MPV initialization", cycle)
assertTrue("MPV initialization failed in cycle $cycle", initializationResult.get())
setProperty(instrumentation, core.get(), "hwdec", "mediacodec", cycle)
setProperty(instrumentation, core.get(), "aid", "no", cycle)
try {
assertCompletes(initialized, "MPV initialization", cycle)
assertTrue("MPV initialization failed in cycle $cycle", initializationResult.get())
setProperty(instrumentation, core.get(), "hwdec", if (hardwareDecoding) "mediacodec" else "no", cycle)
setProperty(instrumentation, core.get(), "aid", "no", cycle)
if (recreateSurfaces) setProperty(instrumentation, core.get(), "loop-file", "inf", cycle)
val commandCompleted = CountDownLatch(1)
val commandResult = AtomicReference<Boolean>()
instrumentation.runOnMainSync {
core.get().command(arrayOf("loadfile", fixture.absolutePath, "replace")) { success ->
commandResult.set(success)
commandCompleted.countDown()
val commandCompleted = CountDownLatch(1)
val commandResult = AtomicReference<Boolean>()
instrumentation.runOnMainSync {
core.get().command(arrayOf("loadfile", fixture.absolutePath, "replace")) { success ->
commandResult.set(success)
commandCompleted.countDown()
}
}
assertCompletes(commandCompleted, "loadfile command", cycle)
assertTrue("loadfile command failed in cycle $cycle", commandResult.get())
assertCompletes(events.fileLoaded, "file-loaded event", cycle)
assertCompletes(events.playbackRestart, "playback-restart event", cycle)
assertVideoOutput(core.get(), cycle, hardwareDecoding)
if (recreateSurfaces) exerciseSurfaceRecreation(instrumentation, activity, core.get(), cycle, hardwareDecoding)
} finally {
disposeCore(instrumentation, activity, core.get(), cycle)
}
assertCompletes(commandCompleted, "loadfile command", cycle)
assertTrue("loadfile command failed in cycle $cycle", commandResult.get())
assertCompletes(events.fileLoaded, "file-loaded event", cycle)
assertCompletes(events.playbackRestart, "playback-restart event", cycle)
assertEquals("mediacodec", core.get().getProperty("current-vo"))
assertTrue(
"Expected MediaCodec hardware decoding in cycle $cycle",
core.get().getProperty("hwdec-current")?.startsWith("mediacodec") == true
)
}
private fun disposeCore(
instrumentation: Instrumentation,
activity: MpvLifecycleTestActivity,
core: MpvPlayerCore,
cycle: Int
) {
val disposed = CountDownLatch(1)
val nextMainTurn = CountDownLatch(1)
val disposeElapsedMs = AtomicReference<Long>()
@@ -96,19 +153,22 @@ class MpvLifecycleDeviceTest {
val disposeStartedAt = SystemClock.elapsedRealtime()
instrumentation.runOnMainSync {
val synchronousDisposeStartedAt = SystemClock.elapsedRealtime()
core.get().dispose {
core.dispose {
disposeElapsedMs.set(SystemClock.elapsedRealtime() - disposeStartedAt)
disposed.countDown()
}
Handler(Looper.getMainLooper()).post(nextMainTurn::countDown)
synchronousDisposeElapsedMs.set(SystemClock.elapsedRealtime() - synchronousDisposeStartedAt)
}
assertTrue(
"dispose() blocked the main thread for ${synchronousDisposeElapsedMs.get()}ms in cycle $cycle",
synchronousDisposeElapsedMs.get() <= MAX_SYNCHRONOUS_DISPOSE_MS
)
assertCompletes(nextMainTurn, "main-looper turn after dispose", cycle, MAIN_LOOP_TIMEOUT_SECONDS)
assertCompletes(disposed, "terminal teardown", cycle, DISPOSE_TIMEOUT_SECONDS)
try {
assertTrue(
"dispose() blocked the main thread for ${synchronousDisposeElapsedMs.get()}ms in cycle $cycle",
synchronousDisposeElapsedMs.get() <= MAX_SYNCHRONOUS_DISPOSE_MS
)
assertCompletes(nextMainTurn, "main-looper turn after dispose", cycle, MAIN_LOOP_TIMEOUT_SECONDS)
} finally {
assertCompletes(disposed, "terminal teardown", cycle, DISPOSE_TIMEOUT_SECONDS)
}
assertTrue(
"Terminal teardown took ${disposeElapsedMs.get()}ms in cycle $cycle",
disposeElapsedMs.get() <= MAX_DISPOSE_LATENCY_MS
@@ -119,6 +179,123 @@ class MpvLifecycleDeviceTest {
}
}
private fun exerciseSurfaceRecreation(
instrumentation: Instrumentation,
activity: MpvLifecycleTestActivity,
core: MpvPlayerCore,
cycle: Int,
hardwareDecoding: Boolean
) {
val surfaces = mutableListOf<SurfaceView>()
instrumentation.runOnMainSync {
val content = activity.findViewById<ViewGroup>(android.R.id.content)
val container = content.getChildAt(0) as ViewGroup
// The host's first plane only punches out letterboxing; the remaining
// SurfaceViews are the actual video and OSD planes.
for (index in 1 until container.childCount) {
(container.getChildAt(index) as? SurfaceView)?.let(surfaces::add)
}
}
assertEquals("Expected video and optional OSD surfaces", if (hardwareDecoding) 2 else 1, surfaces.size)
// Separate visibility changes and callback latches guarantee both real
// destruction/creation orders, including video returning before the OSD.
val orders = if (hardwareDecoding) listOf(surfaces, surfaces.reversed()) else listOf(surfaces)
for (order in orders) {
setProperty(instrumentation, core, "pause", "yes", cycle)
awaitProperty(core, "pause", "public pause", cycle) { it == "yes" }
for (surface in order) {
changeSurfaceVisibility(instrumentation, surface, visible = false, cycle = cycle)
assertEquals("Surface loss cleared public pause in cycle $cycle", "yes", core.getProperty("pause"))
}
for (surface in order) {
changeSurfaceVisibility(instrumentation, surface, visible = true, cycle = cycle)
assertEquals("Surface restoration cleared public pause in cycle $cycle", "yes", core.getProperty("pause"))
}
val pausedPosition = awaitProperty(core, "time-pos", "paused playback position", cycle) {
it?.toDoubleOrNull() != null
}.toDouble()
setProperty(instrumentation, core, "pause", "no", cycle)
awaitProperty(core, "pause", "public resume", cycle) { it == "no" }
var progressStart = pausedPosition
awaitProperty(core, "time-pos", "playback progress after surface restoration", cycle) { value ->
val position = value?.toDoubleOrNull()
if (position == null) {
false
} else {
// The fixture is two seconds long and loops. Start measuring again
// across a loop boundary rather than mistaking a wrap for a stall.
if (position < progressStart) progressStart = position
position >= progressStart + 0.1
}
}
assertVideoOutput(core, cycle, hardwareDecoding)
}
}
private fun changeSurfaceVisibility(
instrumentation: Instrumentation,
surface: SurfaceView,
visible: Boolean,
cycle: Int
) {
val changed = CountDownLatch(1)
val callback = object : SurfaceHolder.Callback {
override fun surfaceCreated(holder: SurfaceHolder) {
if (visible) changed.countDown()
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) = Unit
override fun surfaceDestroyed(holder: SurfaceHolder) {
if (!visible) changed.countDown()
}
}
try {
instrumentation.runOnMainSync {
surface.holder.addCallback(callback)
surface.visibility = if (visible) View.VISIBLE else View.INVISIBLE
}
assertCompletes(changed, if (visible) "real surface creation" else "real surface destruction", cycle)
instrumentation.runOnMainSync {
assertEquals("Unexpected surface validity in cycle $cycle", visible, surface.holder.surface.isValid)
}
} finally {
instrumentation.runOnMainSync { surface.holder.removeCallback(callback) }
}
}
private fun awaitProperty(
core: MpvPlayerCore,
name: String,
operation: String,
cycle: Int,
matches: (String?) -> Boolean
): String {
val deadline = SystemClock.elapsedRealtime() + TimeUnit.SECONDS.toMillis(OPERATION_TIMEOUT_SECONDS)
var value: String?
do {
value = core.getProperty(name)
if (matches(value)) return requireNotNull(value)
SystemClock.sleep(20)
} while (SystemClock.elapsedRealtime() < deadline)
throw AssertionError("$operation timed out in cycle $cycle; $name=$value")
}
private fun assertVideoOutput(core: MpvPlayerCore, cycle: Int, hardwareDecoding: Boolean) {
if (hardwareDecoding) {
assertEquals("mediacodec", core.getProperty("current-vo"))
assertTrue(
"Expected MediaCodec hardware decoding in cycle $cycle",
core.getProperty("hwdec-current")?.startsWith("mediacodec") == true
)
} else {
assertEquals("gpu", core.getProperty("current-vo"))
assertEquals("no", core.getProperty("hwdec-current"))
}
}
private fun setProperty(
instrumentation: Instrumentation,
core: MpvPlayerCore,
@@ -36,17 +36,22 @@ internal object GpuVoPolicy {
fun needsSoftwareRender(hwdecCurrent: String?): Boolean = !hwdecCurrent.isNullOrBlank() && hwdecCurrent != "mediacodec"
/**
* Whether a video track must be software-decoded up front because the
* bitstream is H.264 High 10 and no hardware decoder advertises the
* profile (#2065). Without this the session still ends up in software —
* MediaCodec refuses the stream, FFmpeg falls back, the 10-bit frames
* cannot enter the video plane and the chain fails — but only after a
* decoder init, a failed video chain and a vo recreation, several seconds
* of black with audio already running. [codec] and [codecProfile] come
* from mpv's track-list; the profile string is FFmpeg's
* (`avcodec_profile_name`: "High 10", "High 10 Intra").
* Select native software decoding before opening a decoder when hardware
* cannot serve the stream. H.264 High 10 needs an advertised profile
* (#2065); AV1 needs an actual hardware decoder (#2272), not a software
* MediaCodec component whose surface/copy paths can fail on VO changes.
* [codec] and [codecProfile] come from mpv's pending video track.
*/
fun needsSoftwareDecode(codec: String?, codecProfile: String?, hardwareHigh10: Boolean): Boolean = !hardwareHigh10 && codec == "h264" && codecProfile?.startsWith("High 10") == true
fun needsSoftwareDecode(
codec: String?,
codecProfile: String?,
hardwareHigh10: Boolean,
hardwareAv1: Boolean
): Boolean = when (codec) {
"h264" -> !hardwareHigh10 && codecProfile?.startsWith("High 10") == true
"av1" -> !hardwareAv1
else -> false
}
/**
* The video track the per-file policies ([needsDvReshaping],
@@ -129,5 +134,5 @@ internal object GpuVoPolicy {
const val REASON_CHAIN_FAILURE = "chain-failure"
const val REASON_HDR_SDR = "hdr-sdr"
const val REASON_SW_DECODE = "sw-decode"
const val REASON_HI10_SW_DECODE = "hi10-sw-decode"
const val REASON_CODEC_SW_DECODE = "codec-sw-decode"
}
@@ -0,0 +1,54 @@
package com.edde746.plezy.mpv
import android.os.Handler
import android.os.HandlerThread
import android.view.Surface
import androidx.media3.common.util.EGLSurfaceTexture
import kotlinx.coroutines.android.asCoroutineDispatcher
import kotlinx.coroutines.withContext
/**
* An offscreen consumer, not an undrained ImageReader queue. MediaCodec and GPU
* output can both keep posting buffers while the real SurfaceViews are absent.
* Media3's common EGL utility consumes each frame on its own GL thread, including
* while the main thread is waiting for MPV to acknowledge a surface handoff.
*/
internal class MpvPlaceholderSurface private constructor(
val surface: Surface,
private val handler: Handler,
private val texture: EGLSurfaceTexture
) : AutoCloseable {
companion object {
/** The caller must retain or close the result even if initialization is canceled. */
suspend fun create(): MpvPlaceholderSurface {
val thread = HandlerThread("MpvPlaceholder").apply { start() }
val handler = Handler(thread.looper)
val texture = EGLSurfaceTexture(handler)
return withContext(handler.asCoroutineDispatcher("MpvPlaceholder")) {
try {
texture.init(EGLSurfaceTexture.SECURE_MODE_NONE)
MpvPlaceholderSurface(Surface(texture.surfaceTexture), handler, texture)
} catch (error: Throwable) {
try {
texture.release()
} finally {
thread.quitSafely()
}
throw error
}
}
}
}
/** Call only after native consumers have retired; destruction stays on the GL thread. */
override fun close() {
handler.post {
try {
surface.release()
texture.release()
} finally {
handler.looper.quitSafely()
}
}
}
}
@@ -3,9 +3,7 @@ package com.edde746.plezy.mpv
import android.app.Activity
import android.app.ActivityManager
import android.content.Context
import android.graphics.PixelFormat
import android.media.AudioAttributes
import android.media.ImageReader
import android.os.Build
import android.os.Handler
import android.os.Looper
@@ -25,10 +23,12 @@ import com.edde746.plezy.shared.MediaCodecQuery
import com.edde746.plezy.shared.PlayerDelegate
import com.edde746.plezy.shared.PlayerSurfaceHost
import com.edde746.plezy.shared.SurfacePlayerCore
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
/**
* mpv playback core. Two modes:
* - Video (default): [context] is the host Activity, which is needed for the
@@ -81,6 +81,7 @@ class MpvPlayerCore private constructor(
companion object {
private const val TAG = "MpvPlayerCore"
private const val SURFACE_HANDOFF_TIMEOUT_MS = 2_000L
/**
* The initial `vo` chain, decided by whether this session will hardware-
@@ -144,8 +145,8 @@ class MpvPlayerCore private constructor(
* chain-failure watchdog. Written under [gpuVoReasons]. */
@Volatile private var activeGpuVoTarget: String? = null
/** Per-file reasons holding hwdec at `no` (DV P5 reshaping, Hi10 without
* a hardware profile); the session's own hwdec value is parked in
/** Per-file reasons holding hwdec at `no` (DV P5 reshaping or unsupported
* hardware decoding); the session's own hwdec value is parked in
* [parkedHwdec] while any is active. Written under itself. */
private val hwdecHoldReasons = LinkedHashSet<String>()
@@ -195,11 +196,12 @@ class MpvPlayerCore private constructor(
private var overlayLayoutListener: ViewTreeObserver.OnGlobalLayoutListener? = null
@Volatile private var disposing: Boolean = false
private var nativeDisposalComplete: CountDownLatch? = null
@Volatile private var pendingSurface: Surface? = null
@Volatile private var attachedSurface: Surface? = null
private var placeholderImageReader: ImageReader? = null
private var placeholder: MpvPlaceholderSurface? = null
@Volatile private var placeholderSurface: Surface? = null
@@ -255,6 +257,8 @@ class MpvPlayerCore private constructor(
@Volatile private var videoOutputRestoring: Boolean = false
@Volatile private var videoOutputFailure: Exception? = null
@Volatile private var deferredResumeRequested: Boolean = false
@Volatile private var resumeBlockedByPublicPause: Boolean = false
@@ -271,7 +275,6 @@ class MpvPlayerCore private constructor(
@Volatile private var videoOutputEpoch: Long = 0L
private val videoOutputMutex = Mutex()
private var pendingVideoOutputDisableJob: Job? = null
private var pendingVideoOutputRefreshJob: Job? = null
private var flutterOverlayApplied = false
@@ -285,14 +288,6 @@ class MpvPlayerCore private constructor(
}
}
private fun ensurePlaceholderSurface() {
if (placeholderSurface?.isValid == true) return
placeholderImageReader?.close()
placeholderImageReader = ImageReader.newInstance(1, 1, PixelFormat.RGBA_8888, 2)
placeholderSurface = placeholderImageReader?.surface
Log.d(TAG, "Created MPV placeholder surface")
}
@Suppress("DEPRECATION")
private fun currentDisplayFpsOverride(): String? {
if (audioOnly) return null
@@ -351,14 +346,13 @@ class MpvPlayerCore private constructor(
attachedToPlaceholder = false
hasAttachedSurface = false
videoOutputRestoring = false
videoOutputFailure = null
deferredResumeRequested = false
synchronized(publicPauseIntentLock) {
publicPauseIntentGeneration += 1L
resumeBlockedByPublicPause = false
}
videoOutputEpoch = 0L
pendingVideoOutputDisableJob?.cancel()
pendingVideoOutputDisableJob = null
lastAppliedSurfaceSize = null
lastKnownSurfaceWidth = 0
lastKnownSurfaceHeight = 0
@@ -385,7 +379,6 @@ class MpvPlayerCore private constructor(
currentDvConversionMode = "auto"
hdrSurfaceDecided = false
hdrDisplayActive = false
if (!audioOnly) ensurePlaceholderSurface()
// Initialize audio focus handling. mpv has none built in, so both modes
// use the shared manager: pause on (transient) loss, auto-resume on
@@ -433,6 +426,18 @@ class MpvPlayerCore private constructor(
scope.launch {
try {
if (!audioOnly) {
// Cancellation must not lose an EGL consumer created on its GL thread.
withContext(NonCancellable) {
val created = MpvPlaceholderSurface.create()
if (disposing) {
created.close()
} else {
placeholder = created
placeholderSurface = created.surface
}
}
}
if (disposing) {
onResult(false)
return@launch
@@ -687,7 +692,6 @@ class MpvPlayerCore private constructor(
val surface = holder.surface
pendingSurface = surface.takeIf { it.isValid }
pendingVideoOutputDisableJob?.cancel()
videoOutputEpoch += 1L
rememberCurrentSurfaceSize()
if (player == null) {
@@ -707,8 +711,12 @@ class MpvPlayerCore private constructor(
override fun surfaceDestroyed(holder: SurfaceHolder) {
Log.d(TAG, "Surface destroyed")
pendingSurface = null
if (player == null || disposing) return
detachSurfaceInternal(reason = "surfaceDestroyed")
if (disposing) {
awaitNativeDisposal()
return
}
if (player == null) return
handoffDestroyedSurface("surfaceDestroyed", videoLost = true)
}
// OSD surface (the vo=mediacodec subtitle/OSD plane)
@@ -718,7 +726,8 @@ class MpvPlayerCore private constructor(
if (disposing) return
pendingOsdSurface = holder.surface.takeIf { it.isValid }
Log.d(TAG, "OSD surface created")
if (player != null && hasAttachedRealSurface()) {
videoOutputEpoch += 1L
if (player != null && currentCandidateSurface() != null) {
refreshVideoOutput("osdSurfaceCreated")
}
}
@@ -728,38 +737,18 @@ class MpvPlayerCore private constructor(
override fun surfaceDestroyed(holder: SurfaceHolder) {
Log.d(TAG, "OSD surface destroyed")
pendingOsdSurface = null
val wasAttached = attachedOsdSurface != null
attachedOsdSurface = null
val p = player ?: return
if (disposing || !wasAttached) return
// Ordered against every other mpv write: a detach that overtook the
// re-attach of a recreated surface would clear the option the attach
// just set, and nothing re-arms it — subtitles would stay dead for the
// rest of the session.
scope.launch(mpvWriteDispatcher) {
try {
p.detachOsdSurface()
} catch (e: Exception) {
Log.w(TAG, "Failed to detach OSD surface", e)
}
if (disposing) {
awaitNativeDisposal()
return
}
if (player == null) return
// Rebuild the VO without this plane before Android invalidates it.
// Keep the video target: hiding the OSD when switching to GPU output
// is not a loss of the video surface and must not pause playback.
handoffDestroyedSurface("osdSurfaceDestroyed", videoLost = false)
}
}
/**
* Hands the OSD Surface to the vo. The vo reads the option when it is
* created, so this has to run before the `vo` or `wid` write that creates
* it, never after.
*/
private fun attachOsdSurfaceIfNeeded(p: MpvPlayer) {
if (!usesMediaCodecVo || activeGpuVoTarget != null) return
val osd = pendingOsdSurface?.takeIf { it.isValid } ?: return
if (osd === attachedOsdSurface) return
p.attachOsdSurface(osd)
attachedOsdSurface = osd
Log.d(TAG, "Attached OSD surface for vo=mediacodec")
}
private fun collectVideoDimensions(p: MpvPlayer) {
scope.launch(start = CoroutineStart.UNDISPATCHED) {
p.observeInt("dwidth").collect { value ->
@@ -816,50 +805,48 @@ class MpvPlayerCore private constructor(
*/
private fun applyGpuVoTarget() {
scope.launch(mpvWriteDispatcher, start = CoroutineStart.ATOMIC) {
val target = synchronized(gpuVoReasons) { activeGpuVoTarget }
runOnMain {
if (disposing) return@runOnMain
if (target == null) {
osdSurfaceView?.visibility = View.VISIBLE
} else {
// The gpu VOs draw their own OSD; a stale subtitle frame must not
// linger on the overlay plane.
osdSurfaceView?.visibility = View.GONE
resetVideoSurfaceToFullContainer()
}
}
try {
// Before the vo write, which recreates the VO: it reads the OSD
// surface option at creation.
val p = player
if (target == null && p != null) attachOsdSurfaceIfNeeded(p)
writeProperty("vo", target ?: "mediacodec")
if (p == null) return@launch
applyRenderTier(p, glVoActive = target != null)
if (target != null) {
// A failed conversion chain makes mpv deselect the video track
// ("Could not initialize video chain" -> vid=no) before the VO
// switch lands. Re-select the explicit track id: mid-file "auto"
// resolves to no selection rather than re-running selection.
if (p.getString("vid").let { it == null || it == "no" }) {
val videoTrackId = videoTracks(p).firstOrNull()?.optLong("id")
if (videoTrackId != null) {
Log.i(TAG, "Re-selecting video track $videoTrackId after chain failure")
writeProperty("vid", videoTrackId.toString())
videoOutputMutex.withLock {
if (disposing || videoOutputFailure != null) return@withLock
val target = synchronized(gpuVoReasons) { activeGpuVoTarget }
runOnMain {
if (disposing) return@runOnMain
if (target == null) {
osdSurfaceView?.visibility = View.VISIBLE
} else {
// GPU output draws its own OSD.
osdSurfaceView?.visibility = View.GONE
resetVideoSurfaceToFullContainer()
}
}
}
applySurfaceSizeInternal(p, force = true)
if (target == null) {
// Refit the surfaces to the aspect rectangle now that the plane
// owns scaling again (the gpu VOs letterboxed within full
// containers).
applyVideoRectLayout()
val p = player
val surface = attachedSurface?.takeIf { it.isValid }
val osd = if (target == null && !attachedToPlaceholder) pendingOsdSurface?.takeIf { it.isValid } else null
if (p != null && surface != null && osd !== attachedOsdSurface) {
p.attachSurfaces(surface, osd)
attachedOsdSurface = osd
}
writeProperty("vo", target ?: "mediacodec")
if (p == null) return@withLock
applyRenderTier(p, glVoActive = target != null)
if (target != null) {
// A failed conversion chain deselects video before this switch.
// Re-select its explicit id; mid-file "auto" resolves to none.
if (p.getString("vid").let { it == null || it == "no" }) {
val videoTrackId = videoTracks(p).firstOrNull()?.optLong("id")
if (videoTrackId != null) {
Log.i(TAG, "Re-selecting video track $videoTrackId after chain failure")
writeProperty("vid", videoTrackId.toString())
}
}
}
applySurfaceSizeInternal(p, force = true)
if (target == null) applyVideoRectLayout()
}
} catch (e: CancellationException) {
Log.d(TAG, "Canceled vo transition write")
} catch (e: Exception) {
Log.w(TAG, "Failed to move the video output to ${target ?: "mediacodec"}", e)
runOnMain { failVideoOutput("VO transition", e) }
}
}
}
@@ -887,24 +874,24 @@ class MpvPlayerCore private constructor(
}
/**
* Per-file Hi10 routing (#2065): an H.264 High 10 stream on hardware that
* advertises no such profile goes straight to software decode on a GL vo,
* instead of letting MediaCodec refuse it and the video chain fail first.
* The profile comes from the container's avcC record (fork patch), so it
* is known inside on_preloaded. Distinct from [GpuVoPolicy.REASON_SW_DECODE]:
* that one follows `hwdec-current`, which is still blank at this point.
* [track] is the pending video track, see [pendingVideoTrack].
* Route unsupported hardware decoding before decoder initialization:
* H.264 High 10 without a hardware profile (#2065), and AV1 without a
* hardware decoder (#2272). Keep the GL requirement for the file, including
* ambient toggles and surface recreation, rather than waiting for failure
* or transient `hwdec-current` observations. [track] is the pending video
* track, see [pendingVideoTrack].
*/
private suspend fun applySoftwareDecodePolicy(p: MpvPlayer, track: org.json.JSONObject?) {
val codec = track?.optString("codec")
val codecProfile = track?.optString("codec-profile")
val hardwareHigh10 = MediaCodecQuery.hardwareAvcHigh10Support()
Log.d(TAG, "Decode routing: codec=$codec profile=$codecProfile hardwareHigh10=$hardwareHigh10")
val needs = GpuVoPolicy.needsSoftwareDecode(codec, codecProfile, hardwareHigh10)
if (holdHwdec(p, GpuVoPolicy.REASON_HI10_SW_DECODE, needs) && needs) {
Log.i(TAG, "H.264 High 10 without a hardware profile: software decode on the GL vo")
val hardwareAv1 = MediaCodecQuery.hardwareAv1Support()
Log.d(TAG, "Decode routing: codec=$codec profile=$codecProfile hardwareHigh10=$hardwareHigh10 hardwareAv1=$hardwareAv1")
val needs = GpuVoPolicy.needsSoftwareDecode(codec, codecProfile, hardwareHigh10, hardwareAv1)
if (holdHwdec(p, GpuVoPolicy.REASON_CODEC_SW_DECODE, needs) && needs) {
Log.i(TAG, "$codec profile=$codecProfile without hardware support: native software decode on the GL vo")
}
setGpuVoRequirement(GpuVoPolicy.REASON_HI10_SW_DECODE, needs)
setGpuVoRequirement(GpuVoPolicy.REASON_CODEC_SW_DECODE, needs)
}
/**
@@ -1116,25 +1103,25 @@ class MpvPlayerCore private constructor(
rememberSurfaceSize(sv.width, sv.height)
}
private fun currentCandidateSurface(): Surface? = surfaceView?.holder?.surface?.takeIf { it.isValid }
?: pendingSurface?.takeIf { it.isValid }
// Only callbacks publish usable surfaces. SurfaceHolder.isValid can still
// be true inside surfaceDestroyed, after we have revoked that surface.
private fun currentCandidateSurface(): Surface? = pendingSurface?.takeIf { it.isValid }
private fun hasAttachedRealSurface(): Boolean = hasAttachedSurface && !attachedToPlaceholder && (attachedSurface?.isValid == true)
// Audio-only mode has no video output to wait for — playback and resume
// paths gated on output readiness must always proceed there.
private fun hasReadyVideoOutput(): Boolean = audioOnly || (hasAttachedRealSurface() && !videoOutputRestoring)
private fun hasReadyVideoOutput(): Boolean = audioOnly || (videoOutputFailure == null && hasAttachedRealSurface() && !videoOutputRestoring)
private fun isCurrentVideoOutputEpoch(epoch: Long): Boolean = !disposing && epoch == videoOutputEpoch
private fun isCurrentVideoOutputEpoch(epoch: Long): Boolean = !disposing && videoOutputFailure == null && epoch == videoOutputEpoch
private fun isVideoOutputRefreshCurrent(epoch: Long): Boolean {
if (disposing) return false
if (epoch != videoOutputEpoch) return false
if (!isCurrentVideoOutputEpoch(epoch)) return false
return hasAttachedRealSurface()
}
private fun refreshVideoOutput(reason: String) {
if (audioOnly || disposing) return
if (audioOnly || disposing || videoOutputFailure != null) return
rememberCurrentSurfaceSize()
val p = player
@@ -1146,18 +1133,12 @@ class MpvPlayerCore private constructor(
}
if (surface == null || !surface.isValid) {
hasAttachedSurface = false
attachedSurface = null
attachedToPlaceholder = false
pendingSurface = null
lastAppliedSurfaceSize = null
videoOutputRestoring = true
Log.d(TAG, "refreshVideoOutput($reason): no valid surface available")
return
}
val refreshEpoch = videoOutputEpoch
pendingVideoOutputDisableJob?.cancel()
videoOutputRestoring = true
flutterOverlayApplied = false
ensureFlutterOverlayOnTop()
@@ -1170,30 +1151,21 @@ class MpvPlayerCore private constructor(
return@withLock
}
if (!surface.isValid) {
hasAttachedSurface = false
attachedSurface = null
attachedToPlaceholder = false
pendingSurface = null
lastAppliedSurfaceSize = null
videoOutputRestoring = true
Log.d(TAG, "Skipping MPV video output refresh with invalid surface ($reason, epoch=$refreshEpoch)")
return@withLock
}
// An unattached OSD Surface forces a wid re-attach: the VO reads the
// OSD surface option at creation, and setting wid recreates the VO.
// Suppressed off the plane, where the GL vo draws its own OSD.
val osdNeedsAttach = activeGpuVoTarget == null && pendingOsdSurface !== attachedOsdSurface
val needsAttach = !hasAttachedSurface || attachedSurface !== surface || osdNeedsAttach
val osd = pendingOsdSurface?.takeIf { usesMediaCodecVo && activeGpuVoTarget == null && it.isValid }
val needsAttach = !hasAttachedSurface || attachedSurface !== surface || osd !== attachedOsdSurface
val wasAttachedToPlaceholder = attachedToPlaceholder
val wasPausedForSurfaceLoss = pausedForSurfaceLoss
if (needsAttach) {
attachOsdSurfaceIfNeeded(p)
p.attachSurface(surface)
p.attachSurfaces(surface, osd)
attachedOsdSurface = osd
attachedSurface = surface
hasAttachedSurface = true
attachedToPlaceholder = false
pendingSurface = null
Log.d(TAG, "refreshVideoOutput($reason): attached surface")
} else {
Log.d(TAG, "refreshVideoOutput($reason): surface already attached, refreshing surface state")
@@ -1222,7 +1194,7 @@ class MpvPlayerCore private constructor(
} catch (e: CancellationException) {
Log.d(TAG, "Canceled pending MPV video output refresh ($reason, epoch=$refreshEpoch)")
} catch (e: Exception) {
Log.w(TAG, "Failed to finalize MPV video output refresh ($reason)", e)
runOnMain { failVideoOutput("refresh ($reason)", e) }
}
}
}
@@ -1254,80 +1226,107 @@ class MpvPlayerCore private constructor(
Log.d(TAG, "Applied MPV surface size $size${if (force) " (forced)" else ""}")
}
private fun schedulePlaceholderSurfaceAttach(
p: MpvPlayer,
reason: String,
epoch: Long
) {
pendingVideoOutputDisableJob?.cancel()
pendingVideoOutputDisableJob = scope.launch(Dispatchers.IO) {
/**
* SurfaceHolder requires consumers to stop using a surface before destruction
* returns. The worker and GL placeholder never need the main looper to finish.
* A timeout is a terminal output failure, not permission to mark it ready or
* release references still held by native code.
*/
private fun handoffDestroyedSurface(reason: String, videoLost: Boolean) {
val p = player ?: return
if (videoOutputFailure != null) return
videoOutputRestoring = true
val epoch = videoOutputEpoch + 1L
videoOutputEpoch = epoch
val completed = CountDownLatch(1)
val failure = AtomicReference<Exception?>()
scope.launch(Dispatchers.IO, start = CoroutineStart.ATOMIC) {
try {
videoOutputMutex.withLock {
if (!isCurrentVideoOutputEpoch(epoch)) {
Log.d(TAG, "Skipping stale MPV placeholder attach ($reason, epoch=$epoch)")
return@withLock
}
publicPauseWriteMutex.withLock {
val wasPaused = try {
p.getFlag("pause") == true
} catch (e: Exception) {
cachedPaused
}
if (!wasPaused) {
try {
if (!isCurrentVideoOutputEpoch(epoch)) return@withLock
val target = if (videoLost) placeholderSurface else currentCandidateSurface() ?: placeholderSurface
check(target != null && target.isValid) { "No valid MPV surface for $reason" }
val isPlaceholder = target === placeholderSurface
if (isPlaceholder && !attachedToPlaceholder) {
publicPauseWriteMutex.withLock {
val wasPaused = p.getFlag("pause") ?: cachedPaused
if (!wasPaused) {
p.setProperty("pause", true)
cachedPaused = true
pausedForSurfaceLoss = true
Log.d(TAG, "Paused MPV for surface loss ($reason, epoch=$epoch)")
} catch (e: Exception) {
pausedForSurfaceLoss = false
Log.w(TAG, "Failed to pause MPV before placeholder attach ($reason)", e)
}
} else {
pausedForSurfaceLoss = false
}
}
val surface = placeholderSurface?.takeIf { it.isValid } ?: run {
Log.w(TAG, "No valid MPV placeholder surface available for $reason")
return@withLock
// Revoke both planes when the video disappears. Otherwise retain
// the currently available video and remove only the destroyed OSD.
val osd = if (isPlaceholder) {
null
} else {
pendingOsdSurface?.takeIf {
usesMediaCodecVo && activeGpuVoTarget == null && it.isValid
}
}
p.attachSurface(surface)
attachedSurface = surface
if (attachedSurface !== target || attachedOsdSurface !== osd) {
p.attachSurfaces(target, osd)
}
attachedSurface = target
attachedOsdSurface = osd
hasAttachedSurface = true
attachedToPlaceholder = true
attachedToPlaceholder = isPlaceholder
lastAppliedSurfaceSize = null
Log.d(TAG, "Attached MPV placeholder surface ($reason, epoch=$epoch)")
if (!isCurrentVideoOutputEpoch(epoch)) return@withLock
videoOutputRestoring = isPlaceholder
if (!isPlaceholder) {
applySurfaceSizeInternal(p, force = true)
if (!isCurrentVideoOutputEpoch(epoch)) return@withLock
applyDeferredResumeIfNeeded(p, reason)
pausedForSurfaceLoss = false
}
Log.d(TAG, "Surface handoff complete ($reason, epoch=$epoch, placeholder=$isPlaceholder)")
}
} catch (e: CancellationException) {
Log.d(TAG, "Canceled pending MPV placeholder attach ($reason, epoch=$epoch)")
} catch (e: Exception) {
Log.w(TAG, "Failed to attach MPV placeholder surface ($reason)", e)
} catch (error: Exception) {
failure.set(error)
} finally {
completed.countDown()
}
}
val acknowledged = try {
completed.await(SURFACE_HANDOFF_TIMEOUT_MS, TimeUnit.MILLISECONDS)
} catch (error: InterruptedException) {
Thread.currentThread().interrupt()
failure.set(error)
false
}
if (!acknowledged || failure.get() != null) {
failVideoOutput(reason, failure.get() ?: MpvException("Surface handoff timed out after ${SURFACE_HANDOFF_TIMEOUT_MS}ms"))
}
}
private fun detachSurfaceInternal(reason: String) {
val hadAttachedSurface = hasAttachedSurface || attachedSurface != null
hasAttachedSurface = false
attachedSurface = null
attachedToPlaceholder = false
private fun failVideoOutput(reason: String, error: Exception) {
if (disposing || videoOutputFailure != null) return
videoOutputFailure = error
videoOutputEpoch += 1L
videoOutputRestoring = true
lastAppliedSurfaceSize = null
val detachEpoch = videoOutputEpoch + 1L
videoOutputEpoch = detachEpoch
val p = player ?: return
if (!hadAttachedSurface) {
Log.d(TAG, "detachSurfaceInternal($reason): no attached surface to clear")
return
}
schedulePlaceholderSurfaceAttach(
p = p,
reason = reason,
epoch = detachEpoch
deferredResumeRequested = false
Log.e(TAG, "MPV video output failed during $reason", error)
// Same terminal playback-error envelope as the other Android player.
// Do not claim that the native call finished or retire its surfaces here.
delegate?.onEvent(
"end-file",
mapOf("reason" to "error", "message" to "Video output failed", "cause" to "$reason: ${error.message}")
)
Log.d(TAG, "Cleared MPV surface attachment ($reason, epoch=$detachEpoch)")
}
private fun awaitNativeDisposal() {
val completed = nativeDisposalComplete ?: return
try {
if (!completed.await(SURFACE_HANDOFF_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
Log.e(TAG, "Native teardown did not release the destroyed surface within ${SURFACE_HANDOFF_TIMEOUT_MS}ms")
}
} catch (error: InterruptedException) {
Thread.currentThread().interrupt()
Log.e(TAG, "Interrupted waiting for native surface retirement", error)
}
}
private fun normalizePauseValue(value: String): Boolean? = when (value.lowercase()) {
@@ -1667,6 +1666,12 @@ class MpvPlayerCore private constructor(
}
val paused = if (name == "pause") normalizePauseValue(value) else null
if (paused == false) {
videoOutputFailure?.let { error ->
runOnMain { onComplete?.invoke(Result.failure(error)) }
return
}
}
val pauseIntent = paused?.let {
synchronized(publicPauseIntentLock) {
PublicPauseIntent(
@@ -2030,10 +2035,10 @@ class MpvPlayerCore private constructor(
check(Looper.myLooper() == Looper.getMainLooper())
Log.d(TAG, "Disposing")
surfaceContainer?.let { container ->
container.visibility = View.INVISIBLE
Log.d(TAG, "Hiding surface container during dispose")
}
val disposalComplete = CountDownLatch(1)
nativeDisposalComplete = disposalComplete
// Hiding a SurfaceView destroys its surface. Keep the views visible until
// native teardown retires both consumers; Flutter's overlay stays above.
handler.removeCallbacksAndMessages(null)
@@ -2048,8 +2053,6 @@ class MpvPlayerCore private constructor(
// Cancel all coroutines
scope.cancel()
pendingVideoOutputDisableJob?.cancel()
pendingVideoOutputDisableJob = null
pendingVideoOutputRefreshJob?.cancel()
pendingVideoOutputRefreshJob = null
@@ -2070,8 +2073,7 @@ class MpvPlayerCore private constructor(
val osdSv = osdSurfaceView
val container = surfaceContainer
val contentView = if (audioOnly) null else activity.findViewById<ViewGroup>(android.R.id.content)
val retiringPlaceholderSurface = placeholderSurface
val retiringPlaceholderImageReader = placeholderImageReader
val retiringPlaceholder = placeholder
surfaceContainer = null
surfaceView = null
@@ -2087,7 +2089,7 @@ class MpvPlayerCore private constructor(
pendingSurface = null
placeholderSurface = null
placeholderImageReader = null
placeholder = null
pausedForSurfaceLoss = false
pausedForAudioFocusLoss = false
attachedToPlaceholder = false
@@ -2099,7 +2101,6 @@ class MpvPlayerCore private constructor(
desiredPaused = true
}
videoOutputEpoch = 0L
pendingVideoOutputDisableJob = null
isInitialized = false
// Close the player on a background thread, then release surfaces and remove views.
@@ -2112,8 +2113,8 @@ class MpvPlayerCore private constructor(
} catch (e: Exception) {
Log.w(TAG, "MPV close failed", e)
}
retiringPlaceholderSurface?.release()
retiringPlaceholderImageReader?.close()
disposalComplete.countDown()
retiringPlaceholder?.close()
player = null
Log.d(TAG, "Disposed (native)")
Handler(Looper.getMainLooper()).post {
@@ -2127,8 +2128,8 @@ class MpvPlayerCore private constructor(
}.start()
} else {
// No player — safe to remove views immediately
retiringPlaceholderSurface?.release()
retiringPlaceholderImageReader?.close()
disposalComplete.countDown()
retiringPlaceholder?.close()
Handler(Looper.getMainLooper()).postAtFrontOfQueue {
sv?.holder?.removeCallback(this)
osdSv?.holder?.removeCallback(osdSurfaceCallback)
@@ -55,6 +55,13 @@ internal object MediaCodecQuery {
} != null
}
/** Software MediaCodec AV1 components are not a hardware decode path (#2272). */
fun hardwareAv1Support(): Boolean = hardwareAv1.value
private val hardwareAv1: Lazy<Boolean> = lazy {
findHardwareDecoder("video/av01") != null
}
fun findHardwareDecoder(
mimeType: String,
codecKind: Int = MediaCodecList.REGULAR_CODECS,
+210 -31
View File
@@ -32,7 +32,9 @@ static int controlled_thread_create(pthread_t* thread, const pthread_attr_t* att
#undef pthread_rwlock_wrlock
#undef pthread_mutex_lock
#include "../../../../libmpv/src/main/cpp/event.cpp"
#define pthread_mutex_lock tracked_mutex_lock
#include "../../../../libmpv/src/main/cpp/render.cpp"
#undef pthread_mutex_lock
struct mpv_handle {
bool initialized = false;
@@ -52,6 +54,8 @@ struct mpv_handle {
jlong callback_session = 0;
jobject video = nullptr;
jobject osd = nullptr;
jobject osd_option = nullptr;
int rebuilds = 0;
mpv_event_hook hook{"on_preloaded", 17};
mpv_event event{};
};
@@ -68,7 +72,16 @@ mpv_handle* active_handle = nullptr;
// fails explicitly rather than depending on allocator reuse or undefined UAF.
std::vector<std::unique_ptr<mpv_handle>> handles;
std::vector<std::unique_ptr<_jstring>> callback_strings;
std::map<jobject, int> global_refs;
// Each NewGlobalRef is a distinct handle, even for the same Java Surface.
std::vector<std::unique_ptr<jobject>> reference_handles;
std::map<jobject, jobject> global_refs;
int fail_ref_after = 0;
std::vector<std::string> option_failures;
bool consume_osd_before_failure = false;
bool hold_wid = false;
bool wid_entered = false;
bool allow_wid = false;
bool surface_waiting = false;
mpv_handle* held_termination = nullptr;
bool allow_termination = false;
bool allow_command = false;
@@ -76,7 +89,7 @@ bool successor_waiting = false;
bool reader_draining = false;
bool fail_thread_create = false;
thread_local mpv_handle* event_handle = nullptr;
enum class Operation { ordinary, successor, replacing_reader };
enum class Operation { ordinary, successor, replacing_reader, surface_handoff };
thread_local Operation operation = Operation::ordinary;
void require(bool condition, const char* message) {
@@ -95,24 +108,45 @@ void require_live(mpv_handle* handle) {
}
void require_surfaces(mpv_handle* handle) {
if (handle->video) require(global_refs[handle->video] == 1, "video Surface released before termination completed");
if (handle->osd) require(global_refs[handle->osd] == 1, "OSD Surface released before termination completed");
for (jobject ref : {handle->video, handle->osd, handle->osd_option}) {
if (ref) require(global_refs.count(ref) == 1, "Surface option/consumer retained a deleted JNI reference");
}
}
jobject new_global_ref(jobject object) {
std::lock_guard<std::mutex> lock(gate);
if (object) ++global_refs[object];
return object;
if (!object) return nullptr;
if (fail_ref_after > 0 && --fail_ref_after == 0) return nullptr;
reference_handles.push_back(std::make_unique<jobject>(object));
jobject ref = reference_handles.back().get();
global_refs.emplace(ref, object);
return ref;
}
void delete_global_ref(jobject object) {
if (!object) return;
std::lock_guard<std::mutex> lock(gate);
require(global_refs[object] > 0, "JNI global reference released more than once");
if (active_handle && (active_handle->video == object || active_handle->osd == object)) {
require(active_handle->terminated, "Surface cleanup preceded native termination");
require(global_refs.count(object) == 1, "JNI global reference released more than once");
if (active_handle &&
(active_handle->video == object || active_handle->osd == object || active_handle->osd_option == object)) {
require(active_handle->terminated, "Surface released while still referenced by MPV");
}
--global_refs[object];
global_refs.erase(object);
}
int live_surface_refs() {
int count = 0;
for (const auto& entry : global_refs) {
if (entry.second != &app_context) ++count;
}
return count;
}
void require_pair(mpv_handle* handle, jobject video, jobject osd) {
require_surfaces(handle);
require(global_refs.at(handle->video) == video, "VO retained the wrong video Surface");
require((handle->osd ? global_refs.at(handle->osd) : nullptr) == osd, "VO retained the wrong OSD Surface");
require(handle->osd_option == handle->osd, "OSD option and active consumer disagree");
}
void detach_event_thread() {
@@ -166,15 +200,25 @@ void initialize_player(jlong session) {
void destroy_player(jlong session) { jni_func_name(nativeDestroy)(&jni, nullptr, session); }
jint attach_surfaces(jlong session, jobject video, jobject osd) {
return jni_func_name(nativeAttachSurfaces)(&jni, nullptr, session, video, osd);
}
void reset_dependencies() {
std::lock_guard<std::mutex> lock(gate);
require(active_handle == nullptr, "previous test left a live MPV instance");
for (const auto& entry : global_refs) {
require(entry.first == &app_context || entry.second == 0, "terminal Surface cleanup leaked a global reference");
}
require(live_surface_refs() == 0, "terminal Surface cleanup leaked a global reference");
handles.clear();
callback_strings.clear();
global_refs.clear();
reference_handles.clear();
fail_ref_after = 0;
option_failures.clear();
consume_osd_before_failure = false;
hold_wid = false;
wid_entered = false;
allow_wid = false;
surface_waiting = false;
held_termination = nullptr;
allow_termination = false;
allow_command = false;
@@ -189,8 +233,7 @@ void rejected_hook_and_successor_retirement() {
const jlong old_session = create_player();
mpv_handle* old = active_handle;
int video, osd;
jni_func_name(nativeAttachSurface)(&jni, nullptr, old_session, &video);
jni_func_name(nativeAttachOsdSurface)(&jni, nullptr, old_session, &osd);
require(attach_surfaces(old_session, &video, &osd) == 0, "initial surface handoff failed");
{
std::lock_guard<std::mutex> lock(gate);
old->hook_pending = true;
@@ -225,8 +268,9 @@ void rejected_hook_and_successor_retirement() {
// without touching the retiring core, surfaces, or a future successor.
require(command(old_session) == MPV_ERROR_UNINITIALIZED, "revoked command was admitted during termination");
jni_func_name(nativeHookContinue)(&jni, nullptr, old_session, old->hook.id);
jni_func_name(nativeDetachSurface)(&jni, nullptr, old_session);
jni_func_name(nativeDetachOsdSurface)(&jni, nullptr, old_session);
require(
attach_surfaces(old_session, nullptr, nullptr) == MPV_ERROR_UNINITIALIZED,
"revoked surface handoff was admitted during termination");
{
std::lock_guard<std::mutex> lock(gate);
require_surfaces(old);
@@ -241,8 +285,7 @@ void rejected_hook_and_successor_retirement() {
std::lock_guard<std::mutex> lock(gate);
successor->hook_pending = true;
}
jni_func_name(nativeAttachSurface)(&jni, nullptr, successor_session, &video);
jni_func_name(nativeAttachOsdSurface)(&jni, nullptr, successor_session, &osd);
require(attach_surfaces(successor_session, &video, &osd) == 0, "successor surface handoff failed");
initialize_player(successor_session);
{
std::unique_lock<std::mutex> lock(gate);
@@ -255,8 +298,9 @@ void rejected_hook_and_successor_retirement() {
jni_func_name(nativeInit)(&jni, nullptr, old_session) == MPV_ERROR_UNINITIALIZED, "stale init reached successor");
require(command(old_session) == MPV_ERROR_UNINITIALIZED, "stale command reached successor");
jni_func_name(nativeHookContinue)(&jni, nullptr, old_session, old->hook.id);
jni_func_name(nativeDetachSurface)(&jni, nullptr, old_session);
jni_func_name(nativeDetachOsdSurface)(&jni, nullptr, old_session);
require(
attach_surfaces(old_session, nullptr, nullptr) == MPV_ERROR_UNINITIALIZED,
"stale surface handoff reached successor");
require(command(successor_session) == 0, "stale teardown retired the successor");
{
std::lock_guard<std::mutex> lock(gate);
@@ -328,18 +372,132 @@ void partial_initialization_can_retire() {
}
}
void paired_surface_replacements() {
reset_dependencies();
const jlong session = create_player();
initialize_player(session);
mpv_handle* handle = active_handle;
int video_a, video_b, osd_a, osd_b;
require(attach_surfaces(session, &video_a, &osd_a) == 0, "initial paired handoff failed");
require_pair(handle, &video_a, &osd_a);
require(attach_surfaces(session, &video_b, &osd_b) == 0, "paired replacement failed");
require_pair(handle, &video_b, &osd_b);
for (jobject next_osd : {static_cast<jobject>(&osd_a), static_cast<jobject>(nullptr), static_cast<jobject>(&osd_b)}) {
const int rebuilds = handle->rebuilds;
require(attach_surfaces(session, &video_b, next_osd) == 0, "OSD-only replacement failed");
require_pair(handle, &video_b, next_osd);
require(handle->rebuilds == rebuilds + 1, "OSD-only change did not rebuild the VO");
require(live_surface_refs() == (next_osd ? 2 : 1), "replacement leaked overwritten Surface references");
}
destroy_player(session);
}
void surface_handoff_failures() {
reset_dependencies();
const jlong session = create_player();
initialize_player(session);
mpv_handle* handle = active_handle;
int video_a, video_b, osd_a, osd_b;
require(attach_surfaces(session, &video_a, &osd_a) == 0, "initial paired handoff failed");
require(
attach_surfaces(session, nullptr, &osd_b) == MPV_ERROR_INVALID_PARAMETER,
"live session admitted a null video Surface");
for (int allocation : {1, 2}) {
fail_ref_after = allocation;
require(
attach_surfaces(session, &video_b, &osd_b) == MPV_ERROR_NOMEM, "global-reference allocation failure was lost");
require_pair(handle, &video_a, &osd_a);
require(live_surface_refs() == 2, "allocation failure leaked a staged Surface");
}
option_failures = {"vo-mediacodec-osd-surface"};
require(attach_surfaces(session, &video_b, &osd_b) == MPV_ERROR_GENERIC, "OSD option failure was lost");
require_pair(handle, &video_a, &osd_a);
require(live_surface_refs() == 2, "rejected OSD option leaked staged references");
option_failures = {"wid"};
require(attach_surfaces(session, &video_b, &osd_b) == MPV_ERROR_GENERIC, "wid option failure was lost");
require_pair(handle, &video_a, &osd_a);
require(attach_surfaces(session, &video_b, &osd_b) == 0, "handoff did not recover from wid failure");
require_pair(handle, &video_b, &osd_b);
require(live_surface_refs() == 2, "successful replacement retained failed handoff references");
// A VO may start between the option writes. Rollback changes only the OSD
// option, so the staged reference must survive even when rollback succeeds.
consume_osd_before_failure = true;
for (bool fail_rollback : {false, true}) {
option_failures = {"wid"};
if (fail_rollback) option_failures.push_back("vo-mediacodec-osd-surface");
require(attach_surfaces(session, &video_a, &osd_a) == MPV_ERROR_GENERIC, "failed handoff reported success");
require(option_failures.empty(), "OSD option rollback was not attempted");
require_surfaces(handle);
}
require(attach_surfaces(session, &video_a, nullptr) == 0, "handoff did not recover from rollback failure");
require_pair(handle, &video_a, nullptr);
require(live_surface_refs() == 1, "successful null-OSD replacement leaked failed handoff references");
option_failures = {"wid", "vo-mediacodec-osd-surface"};
require(attach_surfaces(session, &video_b, &osd_b) < 0, "terminal failed handoff reported success");
destroy_player(session);
require(live_surface_refs() == 0, "termination leaked pending failed-handoff references");
}
void overlapping_handoffs_and_teardown() {
reset_dependencies();
const jlong session = create_player();
initialize_player(session);
mpv_handle* handle = active_handle;
int video_a, video_b, video_c, osd_a, osd_b, osd_c;
require(attach_surfaces(session, &video_a, &osd_a) == 0, "initial paired handoff failed");
hold_wid = true;
jint first_result = MPV_ERROR_GENERIC, second_result = MPV_ERROR_GENERIC;
std::thread first([&] { first_result = attach_surfaces(session, &video_b, &osd_b); });
{
std::unique_lock<std::mutex> lock(gate);
await(lock, [] { return wid_entered; }, "first handoff did not enter synchronous VO rebuild");
require_surfaces(handle);
require(live_surface_refs() == 4, "old Surface references did not survive the wid rebuild");
}
std::thread second([&] {
operation = Operation::surface_handoff;
second_result = attach_surfaces(session, &video_c, &osd_c);
});
{
std::unique_lock<std::mutex> lock(gate);
await(lock, [] { return surface_waiting; }, "overlapping handoff bypassed surface serialization");
require(live_surface_refs() == 4, "waiting handoff mutated active Surface references");
}
std::thread retiring([&] {
operation = Operation::replacing_reader;
destroy_player(session);
});
{
std::unique_lock<std::mutex> lock(gate);
await(lock, [] { return reader_draining; }, "teardown did not drain admitted surface handoffs");
require(!handle->termination_entered, "teardown overtook an admitted surface handoff");
allow_wid = true;
changed.notify_all();
}
first.join();
second.join();
retiring.join();
require(first_result == 0 && second_result == 0, "admitted handoff lost its session during teardown");
require(handle->rebuilds == 3, "overlapping handoffs lost a complete VO rebuild");
require(live_surface_refs() == 0, "overlapping replacement/teardown leaked Surface references");
}
} // namespace
// Observe real contention to arrange overlap without sleeps or a guessed
// scheduling delay. The production guards still acquire the real pthread
// locks; the notification only lets the test release its external MPV gates.
static int tracked_mutex_lock(pthread_mutex_t* mutex) {
if (operation != Operation::successor) return pthread_mutex_lock(mutex);
if (operation != Operation::successor && operation != Operation::surface_handoff) return pthread_mutex_lock(mutex);
const int result = pthread_mutex_trylock(mutex);
if (result != EBUSY) return result;
{
std::lock_guard<std::mutex> lock(gate);
successor_waiting = true;
if (operation == Operation::successor) successor_waiting = true;
if (operation == Operation::surface_handoff) surface_waiting = true;
changed.notify_all();
}
return pthread_mutex_lock(mutex);
@@ -371,9 +529,7 @@ static int controlled_thread_create(pthread_t* thread, const pthread_attr_t* att
extern "C" mpv_handle* mpv_create() {
std::lock_guard<std::mutex> lock(gate);
require(active_handle == nullptr, "successor MPV creation overlapped predecessor termination");
for (const auto& entry : global_refs) {
require(entry.first == &app_context || entry.second == 0, "successor creation preceded retiring Surface cleanup");
}
require(live_surface_refs() == 0, "successor creation preceded retiring Surface cleanup");
handles.push_back(std::make_unique<mpv_handle>());
active_handle = handles.back().get();
return active_handle;
@@ -461,15 +617,35 @@ extern "C" int mpv_request_log_messages(mpv_handle* handle, const char* level) {
}
extern "C" int mpv_set_option(mpv_handle* handle, const char* name, mpv_format format, void* data) {
std::lock_guard<std::mutex> lock(gate);
std::unique_lock<std::mutex> lock(gate);
require_live(handle);
require_surfaces(handle);
require(format == MPV_FORMAT_INT64, "unexpected Surface option format");
jobject object = reinterpret_cast<jobject>(static_cast<intptr_t>(*static_cast<int64_t*>(data)));
if (std::strcmp(name, "wid") == 0) {
handle->video = object;
require(!object || global_refs.count(object) == 1, "option received an invalid JNI reference");
const bool is_wid = std::strcmp(name, "wid") == 0;
if (is_wid && hold_wid) {
wid_entered = true;
changed.notify_all();
await(lock, [] { return allow_wid; }, "test did not release the synchronous wid rebuild");
require_surfaces(handle);
}
if (!option_failures.empty() && option_failures.front() == name) {
option_failures.erase(option_failures.begin());
if (is_wid && consume_osd_before_failure) handle->osd = handle->osd_option;
return MPV_ERROR_GENERIC;
}
if (is_wid) {
// mpv ignores equal option values; changing wid synchronously retires the
// consumers and rebuilds using the OSD option, not the former OSD plane.
if (handle->video != object) {
handle->video = object;
handle->osd = handle->osd_option;
++handle->rebuilds;
}
} else {
require(std::strcmp(name, "vo-mediacodec-osd-surface") == 0, "unexpected Surface option");
handle->osd = object;
handle->osd_option = object;
}
return 0;
}
@@ -515,7 +691,10 @@ int main() {
rejected_hook_and_successor_retirement();
admitted_command_survives_replacement();
partial_initialization_can_retire();
paired_surface_replacements();
surface_handoff_failures();
overlapping_handoffs_and_teardown();
reset_dependencies();
std::puts("MPV lifecycle: callback overlap, reader lifetime, successor isolation and partial init passed");
std::puts("MPV lifecycle: session isolation, paired handoffs, rollback ownership and overlapping teardown passed");
return 0;
}
@@ -82,23 +82,31 @@ class GpuVoPolicyTest {
@Test
fun `High 10 without a hardware profile is software-decoded up front`() {
assertTrue(GpuVoPolicy.needsSoftwareDecode("h264", "High 10", hardwareHigh10 = false))
assertTrue(GpuVoPolicy.needsSoftwareDecode("h264", "High 10 Intra", hardwareHigh10 = false))
assertEquals("gpu", GpuVoPolicy.targetFor(setOf(GpuVoPolicy.REASON_HI10_SW_DECODE)))
assertTrue(GpuVoPolicy.needsSoftwareDecode("h264", "High 10", hardwareHigh10 = false, hardwareAv1 = true))
assertTrue(GpuVoPolicy.needsSoftwareDecode("h264", "High 10 Intra", hardwareHigh10 = false, hardwareAv1 = true))
assertEquals("gpu", GpuVoPolicy.targetFor(setOf(GpuVoPolicy.REASON_CODEC_SW_DECODE)))
}
@Test
fun `Hi10 routing leaves every other stream to the hardware path`() {
fun `hardware supported and unrelated streams retain the configured decoder`() {
// A decoder that advertises the profile gets to try.
assertFalse(GpuVoPolicy.needsSoftwareDecode("h264", "High 10", hardwareHigh10 = true))
assertFalse(GpuVoPolicy.needsSoftwareDecode("h264", "High 10", hardwareHigh10 = true, hardwareAv1 = false))
// 8-bit profiles, other codecs, and streams whose container carries no
// profile (Annex B transport streams) are not routed.
assertFalse(GpuVoPolicy.needsSoftwareDecode("h264", "High", hardwareHigh10 = false))
assertFalse(GpuVoPolicy.needsSoftwareDecode("h264", "Constrained Baseline", hardwareHigh10 = false))
assertFalse(GpuVoPolicy.needsSoftwareDecode("hevc", "Main 10", hardwareHigh10 = false))
assertFalse(GpuVoPolicy.needsSoftwareDecode("h264", null, hardwareHigh10 = false))
assertFalse(GpuVoPolicy.needsSoftwareDecode("h264", "", hardwareHigh10 = false))
assertFalse(GpuVoPolicy.needsSoftwareDecode(null, "High 10", hardwareHigh10 = false))
assertFalse(GpuVoPolicy.needsSoftwareDecode("h264", "High", hardwareHigh10 = false, hardwareAv1 = false))
assertFalse(GpuVoPolicy.needsSoftwareDecode("h264", "Constrained Baseline", hardwareHigh10 = false, hardwareAv1 = false))
assertFalse(GpuVoPolicy.needsSoftwareDecode("hevc", "Main 10", hardwareHigh10 = false, hardwareAv1 = false))
assertFalse(GpuVoPolicy.needsSoftwareDecode("h264", null, hardwareHigh10 = false, hardwareAv1 = false))
assertFalse(GpuVoPolicy.needsSoftwareDecode("h264", "", hardwareHigh10 = false, hardwareAv1 = false))
assertFalse(GpuVoPolicy.needsSoftwareDecode(null, "High 10", hardwareHigh10 = false, hardwareAv1 = false))
}
@Test
fun `AV1 bypasses software MediaCodec even without a reported profile`() {
assertTrue(GpuVoPolicy.needsSoftwareDecode("av1", "Main", hardwareHigh10 = true, hardwareAv1 = false))
assertTrue(GpuVoPolicy.needsSoftwareDecode("av1", null, hardwareHigh10 = true, hardwareAv1 = false))
assertTrue(GpuVoPolicy.needsSoftwareDecode("av1", "", hardwareHigh10 = true, hardwareAv1 = false))
assertFalse(GpuVoPolicy.needsSoftwareDecode("av1", "Main", hardwareHigh10 = false, hardwareAv1 = true))
}
// The per-file policies run inside on_preloaded, before mpv selects a
+67 -53
View File
@@ -1,73 +1,85 @@
#include <jni.h>
#include <mpv/client.h>
#include <new>
#include <vector>
#include "globals.h"
#include "jni_utils.h"
#include "log.h"
extern "C" {
jni_func(void, nativeAttachSurface, jlong session, jobject surface_);
jni_func(void, nativeDetachSurface, jlong session);
jni_func(void, nativeAttachOsdSurface, jlong session, jobject surface_);
jni_func(void, nativeDetachOsdSurface, jlong session);
jni_func(jint, nativeAttachSurfaces, jlong session, jobject surface_, jobject osd_surface_);
};
// Admission (S) precedes this mutex. Teardown drains S before cleanup and
// never takes this mutex, so a waiting handoff cannot outlive its mpv handle.
static pthread_mutex_t surface_lock = PTHREAD_MUTEX_INITIALIZER;
class SurfaceGuard {
public:
SurfaceGuard() { pthread_mutex_lock(&surface_lock); }
~SurfaceGuard() { pthread_mutex_unlock(&surface_lock); }
SurfaceGuard(const SurfaceGuard&) = delete;
SurfaceGuard& operator=(const SurfaceGuard&) = delete;
};
static jobject surface;
jni_func(void, nativeAttachSurface, jlong session, jobject surface_) {
SessionGuard guard(session);
if (!guard.mpv) return;
surface = env->NewGlobalRef(surface_);
if (!surface) {
die("invalid surface provided");
return;
}
int64_t wid = reinterpret_cast<intptr_t>(surface);
int result = mpv_set_option(guard.mpv, "wid", MPV_FORMAT_INT64, &wid);
if (result < 0) ALOGE("mpv_set_option(wid) returned error %s", mpv_error_string(result));
}
jni_func(void, nativeDetachSurface, jlong session) {
SessionGuard guard(session);
if (!guard.mpv) return;
int64_t wid = 0;
int result = mpv_set_option(guard.mpv, "wid", MPV_FORMAT_INT64, &wid);
if (result < 0) ALOGE("mpv_set_option(wid) returned error %s", mpv_error_string(result));
env->DeleteGlobalRef(surface);
surface = NULL;
}
static jobject osd_surface;
// A failed wid update can leave an OSD option/consumer using a staged ref.
// Even a successful option rollback cannot retire a consumer created between
// the two writes. Release these only after a successful wid rebuild or destroy.
static std::vector<jobject> pending_osd_surfaces;
// The OSD plane of vo=mediacodec. Same lifetime rules as the video surface:
// the global ref must outlive the VO, so detach only after vo has been unset.
jni_func(void, nativeAttachOsdSurface, jlong session, jobject surface_) {
jni_func(jint, nativeAttachSurfaces, jlong session, jobject surface_, jobject osd_surface_) {
SessionGuard guard(session);
if (!guard.mpv) return;
if (!guard.mpv) return MPV_ERROR_UNINITIALIZED;
if (!surface_) return MPV_ERROR_INVALID_PARAMETER;
SurfaceGuard lock;
osd_surface = env->NewGlobalRef(surface_);
if (!osd_surface) {
die("invalid osd surface provided");
return;
if (osd_surface_) {
try {
pending_osd_surfaces.reserve(pending_osd_surfaces.size() + 1);
} catch (const std::bad_alloc&) {
return MPV_ERROR_NOMEM;
}
}
jobject next_surface = env->NewGlobalRef(surface_);
if (!next_surface) return MPV_ERROR_NOMEM;
jobject next_osd = osd_surface_ ? env->NewGlobalRef(osd_surface_) : nullptr;
if (osd_surface_ && !next_osd) {
env->DeleteGlobalRef(next_surface);
return MPV_ERROR_NOMEM;
}
int64_t wid = reinterpret_cast<intptr_t>(osd_surface);
int result = mpv_set_option(guard.mpv, "vo-mediacodec-osd-surface", MPV_FORMAT_INT64, &wid);
if (result < 0) ALOGE("mpv_set_option(vo-mediacodec-osd-surface) returned error %s", mpv_error_string(result));
}
jni_func(void, nativeDetachOsdSurface, jlong session) {
SessionGuard guard(session);
if (!guard.mpv || !osd_surface) return;
int64_t osd_wid = reinterpret_cast<intptr_t>(next_osd);
int result = mpv_set_option(guard.mpv, "vo-mediacodec-osd-surface", MPV_FORMAT_INT64, &osd_wid);
if (result < 0) {
env->DeleteGlobalRef(next_surface);
if (next_osd) env->DeleteGlobalRef(next_osd);
return result;
}
if (next_osd) pending_osd_surfaces.push_back(next_osd);
int64_t wid = 0;
int result = mpv_set_option(guard.mpv, "vo-mediacodec-osd-surface", MPV_FORMAT_INT64, &wid);
if (result < 0) ALOGE("mpv_set_option(vo-mediacodec-osd-surface) returned error %s", mpv_error_string(result));
// wid has UPDATE_VO: mpv_set_option synchronously tears down the old VO and
// decoder before rebuilding with both options. A fresh video global ref also
// changes wid when only the Java OSD Surface changed (equal values are ignored).
int64_t wid = reinterpret_cast<intptr_t>(next_surface);
result = mpv_set_option(guard.mpv, "wid", MPV_FORMAT_INT64, &wid);
if (result < 0) {
osd_wid = reinterpret_cast<intptr_t>(osd_surface);
const int rollback = mpv_set_option(guard.mpv, "vo-mediacodec-osd-surface", MPV_FORMAT_INT64, &osd_wid);
if (rollback < 0) ALOGE("OSD surface rollback failed: %s", mpv_error_string(rollback));
env->DeleteGlobalRef(next_surface);
return result;
}
env->DeleteGlobalRef(osd_surface);
osd_surface = NULL;
if (next_osd) pending_osd_surfaces.pop_back();
if (surface) env->DeleteGlobalRef(surface);
if (osd_surface) env->DeleteGlobalRef(osd_surface);
for (jobject pending : pending_osd_surfaces) env->DeleteGlobalRef(pending);
pending_osd_surfaces.clear();
surface = next_surface;
osd_surface = next_osd;
return 0;
}
// Caller holds L after revoking admission, draining JNI readers, joining the
@@ -76,10 +88,12 @@ jni_func(void, nativeDetachOsdSurface, jlong session) {
void render_cleanup(JNIEnv* env) {
if (surface) {
env->DeleteGlobalRef(surface);
surface = NULL;
surface = nullptr;
}
if (osd_surface) {
env->DeleteGlobalRef(osd_surface);
osd_surface = NULL;
osd_surface = nullptr;
}
for (jobject pending : pending_osd_surfaces) env->DeleteGlobalRef(pending);
pending_osd_surfaces.clear();
}
@@ -192,13 +192,7 @@ class MpvPlayer private constructor(
@JvmStatic private external fun nativeSetOptionString(session: Long, name: String, value: String): Int
@JvmStatic private external fun nativeAttachSurface(session: Long, surface: Surface)
@JvmStatic private external fun nativeDetachSurface(session: Long)
@JvmStatic private external fun nativeAttachOsdSurface(session: Long, surface: Surface)
@JvmStatic private external fun nativeDetachOsdSurface(session: Long)
@JvmStatic private external fun nativeAttachSurfaces(session: Long, surface: Surface, osdSurface: Surface?): Int
@JvmStatic private external fun nativeGetPropertyInt(session: Long, name: String): Int?
@@ -306,27 +300,12 @@ class MpvPlayer private constructor(
requestLogMessages(session, level)
}
// Surface — not suspend, called from SurfaceHolder.Callback
fun attachSurface(surface: Surface) {
/** Installs both planes and synchronously rebuilds the VO on the core's ordered IO writer. */
fun attachSurfaces(surface: Surface, osdSurface: Surface?) {
checkNotClosed()
nativeAttachSurface(session, surface)
}
fun detachSurface() {
checkNotClosed()
nativeDetachSurface(session)
}
/** OSD/subtitle plane for `vo=mediacodec`; attach before selecting the VO. */
fun attachOsdSurface(surface: Surface) {
checkNotClosed()
nativeAttachOsdSurface(session, surface)
}
fun detachOsdSurface() {
checkNotClosed()
nativeDetachOsdSurface(session)
checkNotMainThread("MPV surface handoff")
val result = nativeAttachSurfaces(session, surface, osdSurface)
if (result < 0) throw MpvException("Failed to attach MPV surfaces: error $result")
}
// Property getters
+1 -1
View File
@@ -802,7 +802,7 @@
repositoryURL = "https://github.com/edde746/mpv-build";
requirement = {
kind = revision;
revision = 3fd89c259b6ff6ef9a4c25e377d1287fb1407c9a;
revision = d38d607fd299e106a83f3557e310ac4b8202b39c;
};
};
/* End XCRemoteSwiftPackageReference section */
@@ -32,7 +32,7 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/edde746/mpv-build",
"state" : {
"revision" : "3fd89c259b6ff6ef9a4c25e377d1287fb1407c9a"
"revision" : "d38d607fd299e106a83f3557e310ac4b8202b39c"
}
},
{
@@ -32,7 +32,7 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/edde746/mpv-build",
"state" : {
"revision" : "3fd89c259b6ff6ef9a4c25e377d1287fb1407c9a"
"revision" : "d38d607fd299e106a83f3557e310ac4b8202b39c"
}
},
{
+23 -6
View File
@@ -49,6 +49,7 @@ import 'package:path_provider/path_provider.dart';
import 'services/image_cache_service.dart';
import 'services/gamepad_service.dart';
import 'services/trackers/tracker_coordinator.dart';
import 'services/playback_coordinator.dart';
import 'providers/account_preferences_controller.dart';
import 'services/account_preferences_repository.dart';
import 'providers/multi_server_provider.dart';
@@ -1249,7 +1250,7 @@ class _MainAppState extends State<MainApp> with WidgetsBindingObserver {
bool _isAutoDeleteRunning = false;
bool _lastConnectivityWasWifi = false;
bool _lastConnectivityHadNetwork = true;
bool _shutdownStarted = false;
Future<void>? _shutdownFuture;
/// Last time server health probes ran from a resume event (cooldown for desktop)
DateTime _lastResumeProbe = DateTime(0);
@@ -1302,10 +1303,14 @@ class _MainAppState extends State<MainApp> with WidgetsBindingObserver {
);
}
Future<void> _shutdownForExit() async {
if (_shutdownStarted) return;
_shutdownStarted = true;
Future<void> _shutdownForExit() => _shutdownFuture ??= _runShutdownForExit().timeout(
const Duration(seconds: 15),
onTimeout: () {
appLogger.w('Application exit teardown exceeded its deadline');
},
);
Future<void> _runShutdownForExit() async {
// Hide the window before anything else so the exit reads as an instant
// close: the teardown below runs against a still-mounted tree and its
// state churn must never be user-visible. Cmd+Q and OS-initiated exits
@@ -1320,6 +1325,14 @@ class _MainAppState extends State<MainApp> with WidgetsBindingObserver {
}
}
// The player owns the backend session. Flush it while its client and
// native position still exist, before unrelated cleanup can delay exit.
try {
await PlaybackCoordinator.instance.shutdownVideo().timeout(const Duration(seconds: 3));
} catch (e, st) {
appLogger.w('Video shutdown did not complete before exit', error: e, stackTrace: st);
}
_syncDebounce?.cancel();
await _watchStateSubscription?.cancel();
_removeConnectivitySyncListener();
@@ -1330,7 +1343,11 @@ class _MainAppState extends State<MainApp> with WidgetsBindingObserver {
// Quitting straight from the player is a real stop: the trackers that own
// their own watched semantics need the terminal report before the process
// goes away. Bounded — a hung tracker must not hold the app open.
await TrackerCoordinator.instance.stopPlayback().timeout(const Duration(seconds: 3), onTimeout: () {});
try {
await TrackerCoordinator.instance.stopPlayback().timeout(const Duration(seconds: 3));
} catch (e, st) {
appLogger.w('Tracker shutdown did not complete before exit', error: e, stackTrace: st);
}
TrackerCoordinator.instance.cancelInFlight();
await _serverManager.shutdown();
@@ -1349,7 +1366,7 @@ class _MainAppState extends State<MainApp> with WidgetsBindingObserver {
_removeConnectivitySyncListener();
_memoryCheckTimer?.cancel();
_appLifecycleListener.dispose();
if (!_shutdownStarted) {
if (_shutdownFuture == null) {
_libraryEventService.dispose();
_downloadManager.dispose();
_serverManager.dispose();
+6
View File
@@ -125,6 +125,12 @@ enum MediaBrowserDialect {
/// leading codec must be one the dialect is known to emit.
bool get rotatesDisabledTranscodeCodecs => this == MediaBrowserDialect.jellyfin;
/// Restrict Live TV HLS negotiation to MPEG-TS. Emby fMP4 live streams
/// fail with missing initialization metadata in affected setups (#2273),
/// while the same sources play as TS. VOD keeps fMP4; this is a transport
/// compatibility policy, not a restriction on direct play or stream copy.
bool get requiresMpegTsForLiveTv => this == MediaBrowserDialect.emby;
/// `GET /Audio/{id}/Lyrics` (Jellyfin 10.9+). Never call this on Emby: the
/// route resolves to audio streaming with `Lyrics` as the container and
/// spawns an ffmpeg process that fails with a 500.
+16 -8
View File
@@ -371,6 +371,7 @@ class _MainScreenState extends State<MainScreen>
with RouteAware, WindowListener, WidgetsBindingObserver, MountedSetStateMixin {
NavigationTabId _currentTab = NavigationTabId.discover;
String? _selectedLibraryGlobalKey;
Future<void>? _windowCloseFuture;
/// Whether the app is in offline mode (no server connection)
bool _isOffline = false;
@@ -1111,20 +1112,27 @@ class _MainScreenState extends State<MainScreen>
@override
void onWindowClose() {
unawaited(_exitOnWindowClose());
unawaited(
_windowCloseFuture ??= _exitOnWindowClose().whenComplete(() {
_windowCloseFuture = null;
}),
);
}
/// `setPreventClose(true)` hands the window's close button to us, so the app
/// has to shut itself down. A bare `exit(0)` killed the process before the
/// app-level teardown could run — including the terminal playback report that
/// trackers owning their own watched semantics depend on.
/// The root exit observer owns the shutdown deadline. Do not time out its
/// dispatch here or interpret a canceled close as permission to force exit.
Future<void> _exitOnWindowClose() async {
try {
await AppExitService.requestGracefulExit().timeout(const Duration(seconds: 5));
await AppExitService.requestGracefulExit();
} catch (e, st) {
appLogger.w('Graceful window close failed; exiting immediately', error: e, stackTrace: st);
appLogger.w('Graceful window close failed; destroying window', error: e, stackTrace: st);
try {
await windowManager.destroy().timeout(const Duration(seconds: 3));
} catch (fallbackError, fallbackStack) {
appLogger.e('Window destruction failed; forcing exit', error: fallbackError, stackTrace: fallbackStack);
exit(1);
}
}
exit(0);
}
@override
+4 -11
View File
@@ -21,6 +21,7 @@ import '../../profiles/active_profile_binder.dart';
import '../../profiles/active_profile_provider.dart';
import '../../profiles/profile.dart';
import '../../profiles/profile_connection.dart';
import '../../services/jellyfin_auth_header.dart';
import '../../services/jellyfin_auth_service.dart';
import '../../services/jellyfin_endpoint_discovery.dart';
import '../../services/jellyfin_lan_discovery_service.dart';
@@ -447,23 +448,15 @@ class _AddJellyfinScreenState extends State<AddJellyfinScreen>
final authServiceFactory = widget._authServiceFactory;
if (authServiceFactory != null) return await authServiceFactory();
final clientVersion = await resolveJellyfinClientVersion();
final deviceName = await _resolveDeviceName();
final identity = await DeviceIdentityService.resolve();
return JellyfinConnectionAuthService(
clientName: 'Plezy',
clientName: jellyfinClientName(identity),
clientVersion: clientVersion,
deviceName: deviceName,
deviceName: jellyfinDeviceName(identity),
dialect: widget.dialect,
);
}
/// The raw name, not a header-sanitized one: the Jellyfin `MediaBrowser`
/// header percent-encodes it, so the device list shows it verbatim.
Future<String> _resolveDeviceName() async {
final identity = await DeviceIdentityService.resolve();
final name = identity.deviceName?.trim();
return name == null || name.isEmpty ? 'Plezy' : name;
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
@@ -1,3 +1,5 @@
import 'dart:async';
import '../../media/live_tv_support.dart';
/// Sends one live-TV timeline report and commits what it learned only while
@@ -26,3 +28,44 @@ Future<void> runLiveTimelineReport({
}
commit(update);
}
/// Orders reports for one tuned session. Closing the queue synchronously
/// rejects new heartbeats, while the terminal report waits for older HTTP
/// requests so a late playing report cannot resurrect the backend session.
class LiveTimelineReportQueue {
Future<void>? _pending;
Future<void>? _stopped;
Future<void> send({required bool stopped, required Future<void> Function() report}) {
final terminal = _stopped;
if (terminal != null) return terminal;
final previous = _pending;
final completer = Completer<void>();
final operation = completer.future;
_pending = operation;
if (stopped) _stopped = operation;
unawaited(() async {
try {
if (previous != null) {
try {
await previous;
} catch (_) {
// A failed heartbeat must not prevent the final stop attempt.
}
}
// Drop heartbeats queued before the stop but not yet dispatched.
if (!stopped && _stopped != null) {
completer.complete();
return;
}
await report();
completer.complete();
} catch (error, stackTrace) {
completer.completeError(error, stackTrace);
} finally {
if (identical(_pending, operation)) _pending = null;
}
}());
return operation;
}
}
@@ -5,6 +5,7 @@ import '../../media/media_source_info.dart';
import '../../models/livetv_capture_buffer.dart';
import '../../mpv/player/player_streams.dart';
import 'live_tv_session_args.dart';
import 'live_timeline_report.dart';
class _LiveClockOpen {
_LiveClockOpen({required this.generation, required this.targetEpoch});
@@ -50,6 +51,7 @@ class LiveTvSessionState {
Timer? timelineTimer;
int timelineGeneration = 0;
late LiveTimelineReportQueue timelineReports = LiveTimelineReportQueue();
DateTime? playbackStartTime;
/// Current seekable window. Seeded from [session] on adoption, then
@@ -265,6 +267,7 @@ class LiveTvSessionState {
/// snapshot. Every flow that produces a session (start, retry, channel
/// zap) adopts it here, so a field can't be forgotten in one copy.
void adoptSession(LiveTvPlaybackSession newSession) {
if (!identical(session, newSession)) timelineReports = LiveTimelineReportQueue();
session = newSession;
captureBuffer = newSession.captureBuffer;
selectedSubtitle = null;
+13 -10
View File
@@ -10,7 +10,7 @@ extension _VideoPlayerLifecycleMethods on VideoPlayerScreenState {
appLogger.w('Previous lifecycle transition failed', error: error, stackTrace: stackTrace);
})
.then((_) async {
if (!mounted) return;
if (!mounted || _shuttingDown) return;
try {
await transition();
} catch (e, stackTrace) {
@@ -90,7 +90,7 @@ extension _VideoPlayerLifecycleMethods on VideoPlayerScreenState {
appLogger.w('Failed to stop live player while backgrounding', error: e, stackTrace: stackTrace);
}
await stoppedReport;
if (!mounted || currentPlayer != player) return;
if (!mounted || _shuttingDown || currentPlayer != player) return;
await _mediaControls.suspendForTvBackground('hidden_live_stopped');
_recordLifecycleState('hidden', action: 'live_stopped_exit_on_resume');
return;
@@ -139,7 +139,7 @@ extension _VideoPlayerLifecycleMethods on VideoPlayerScreenState {
}
}
if (!mounted || currentPlayer != player) return;
if (!mounted || _shuttingDown || currentPlayer != player) return;
_suspendLiveTimelineForBackground();
@@ -159,6 +159,7 @@ extension _VideoPlayerLifecycleMethods on VideoPlayerScreenState {
}
Future<void> _handleAppResumed() async {
if (_shuttingDown) return;
_recordLifecycleState('resumed', action: 'begin');
_watchTogetherProvider?.setBackgrounded(false);
@@ -182,7 +183,7 @@ extension _VideoPlayerLifecycleMethods on VideoPlayerScreenState {
await currentPlayer.updateFrame();
}
if (!mounted || currentPlayer != player) return;
if (!mounted || _shuttingDown || currentPlayer != player) return;
_hiddenForBackground = false;
_recordLifecycleState('resumed', action: 'render_restored');
@@ -193,7 +194,7 @@ extension _VideoPlayerLifecycleMethods on VideoPlayerScreenState {
// below can act on the stopped player.
if (_tvSuspend.suspended) {
await _restorePlayerAfterTvBackgroundSuspend();
if (!mounted || currentPlayer != player) return;
if (!mounted || _shuttingDown || currentPlayer != player) return;
}
// TV never hides the render layer on background (_handleAppHidden returns
// early without setting _hiddenForBackground), but the screensaver can
@@ -206,12 +207,12 @@ extension _VideoPlayerLifecycleMethods on VideoPlayerScreenState {
currentPlayer != null &&
_isPlayerInitialized) {
await currentPlayer.updateFrame();
if (!mounted || currentPlayer != player) return;
if (!mounted || _shuttingDown || currentPlayer != player) return;
_recordLifecycleState('resumed', action: 'tv_video_output_kick');
}
// Restore media controls and wakelock when app is resumed.
if (_isPlayerInitialized && mounted) {
if (_isPlayerInitialized && mounted && !_shuttingDown) {
_mediaControls.resumeAfterTvBackground('app_resumed');
await _mediaControls.restoreAfterResume();
}
@@ -223,6 +224,7 @@ extension _VideoPlayerLifecycleMethods on VideoPlayerScreenState {
/// Arm the grace timer that releases the native AV pipeline if the app
/// stays backgrounded (Android TV only). Returns whether it was armed.
bool _armTvBackgroundPlayerSuspendTimer() {
if (_shuttingDown) return false;
if (!shouldSuspendPlayerForTvBackground(
isAndroid: Platform.isAndroid,
isTv: PlatformDetector.isTV(),
@@ -253,7 +255,7 @@ extension _VideoPlayerLifecycleMethods on VideoPlayerScreenState {
/// because the reload on restore reads them after the native state is gone.
Future<void> _suspendPlayerForTvBackground() async {
final currentPlayer = player;
if (!mounted || currentPlayer == null || !_isPlayerInitialized) return;
if (!mounted || _shuttingDown || currentPlayer == null || !_isPlayerInitialized) return;
// A live stream's tuned session is also its time-shift buffer. Stopping
// it would force a re-tune at the live edge and discard pause state.
if (widget.isLive) return;
@@ -293,6 +295,7 @@ extension _VideoPlayerLifecycleMethods on VideoPlayerScreenState {
// next paused heartbeat re-opens a server session at the same position
// and the pause stays resumable in place.
await stoppedReport;
if (_shuttingDown) return;
_progressTracker?.resumeAfterStoppedReport();
_progressTracker?.startTracking();
appLogger.w('TV background suspend failed; player left paused', error: e);
@@ -317,7 +320,7 @@ extension _VideoPlayerLifecycleMethods on VideoPlayerScreenState {
for (var attempt = 0; attempt < TvBackgroundSuspendState.stopReportMaxRetries; attempt++) {
await Future<void>.delayed(TvBackgroundSuspendState.stopReportRetryDelay);
final tracker = _progressTracker;
if (!mounted || tracker == null || !_tvSuspend.suspended) return;
if (!mounted || _shuttingDown || tracker == null || !_tvSuspend.suspended) return;
if (tracker.stoppedReportDelivered) return;
await tracker.sendProgress('stopped', positionOverride: position, durationOverride: duration);
}
@@ -336,7 +339,7 @@ extension _VideoPlayerLifecycleMethods on VideoPlayerScreenState {
final restore = _tvSuspend.consumeForRestore();
final currentPlayer = player;
if (!mounted || currentPlayer == null || !_isPlayerInitialized) return;
if (!mounted || _shuttingDown || currentPlayer == null || !_isPlayerInitialized) return;
_recordLifecycleState('resumed', action: 'tv_background_suspend_reload');
final outcome = await _reloadMediaInPlace(
+40 -28
View File
@@ -5,6 +5,7 @@ const _liveClockReadyTimeout = Duration(seconds: 15);
extension _VideoPlayerLiveTvMethods on VideoPlayerScreenState {
/// Start periodic timeline heartbeats for live TV transcode session.
void _startLiveTimelineUpdates() {
if (_shuttingDown) return;
final generation = ++_live.timelineGeneration;
_live.timelineTimer?.cancel();
_live.timelineTimer = Timer.periodic(const Duration(seconds: 10), (_) {
@@ -25,6 +26,7 @@ extension _VideoPlayerLiveTvMethods on VideoPlayerScreenState {
/// Advance the fallback ladder and retry — the error path's entry point.
void _beginLiveLadderRetry() {
if (_shuttingDown) return;
_live.fallbackLevel++;
_live.retrying = true;
appLogger.w('Live stream failed, retrying with fallback level ${_live.fallbackLevel}');
@@ -34,7 +36,7 @@ extension _VideoPlayerLiveTvMethods on VideoPlayerScreenState {
/// Play pressed while the live stream is dead: reuse the ladder retry
/// unless one is already in flight.
Future<void> _retryLiveStreamForPlayIntent() {
if (_live.retrying) return Future.value();
if (_shuttingDown || _live.retrying) return Future.value();
_live.retrying = true;
return _retryLiveStream();
}
@@ -81,6 +83,7 @@ extension _VideoPlayerLiveTvMethods on VideoPlayerScreenState {
}
Future<void> _sendLiveTimeline(String state) async {
if (_shuttingDown && state != 'stopped') return;
final requestSession = _live.session;
if (requestSession == null) return;
final requestGeneration = _live.timelineGeneration;
@@ -93,30 +96,34 @@ extension _VideoPlayerLiveTvMethods on VideoPlayerScreenState {
: 0;
try {
await runLiveTimelineReport(
requestSession: requestSession,
requestGeneration: requestGeneration,
state: state,
positionMs: playbackTime,
currentSession: () => _live.session,
currentGeneration: () => _live.timelineGeneration,
isMounted: () => mounted,
commit: (update) {
_setPlayerState(() {
final playbackStream = update.playbackStream;
if (playbackStream != null &&
_live.adoptPlaybackStreamOrigin(playbackStream, generation: requestStreamGeneration)) {
appLogger.d('Live clock re-anchored on playback transcode origin ${playbackStream.startedAt}');
}
final buffer = update.captureBuffer;
if (buffer != null) _live.captureBuffer = buffer;
final window = _live.captureBuffer;
if (window != null) {
_live.atLiveEdge =
(_currentPositionEpoch >= window.seekableEndEpoch - VideoPlayerScreenState._liveEdgeThresholdSeconds);
}
});
},
await _live.timelineReports.send(
stopped: state == 'stopped',
report: () => runLiveTimelineReport(
requestSession: requestSession,
requestGeneration: requestGeneration,
state: state,
positionMs: playbackTime,
currentSession: () => _live.session,
currentGeneration: () => _live.timelineGeneration,
isMounted: () => mounted,
commit: (update) {
_setPlayerState(() {
final playbackStream = update.playbackStream;
if (playbackStream != null &&
_live.adoptPlaybackStreamOrigin(playbackStream, generation: requestStreamGeneration)) {
appLogger.d('Live clock re-anchored on playback transcode origin ${playbackStream.startedAt}');
}
final buffer = update.captureBuffer;
if (buffer != null) _live.captureBuffer = buffer;
final window = _live.captureBuffer;
if (window != null) {
_live.atLiveEdge =
(_currentPositionEpoch >=
window.seekableEndEpoch - VideoPlayerScreenState._liveEdgeThresholdSeconds);
}
});
},
),
);
} catch (e) {
appLogger.d('Live timeline update failed', error: e);
@@ -163,7 +170,7 @@ extension _VideoPlayerLiveTvMethods on VideoPlayerScreenState {
Future<void> _retryLiveStream() async {
_liveSeek.cancel();
final currentPlayer = player;
if (!mounted || currentPlayer == null) return;
if (!mounted || _shuttingDown || currentPlayer == null) return;
final generation = _transitionGate.generation;
bool isCurrent() => _isCurrentPlaybackGeneration(generation, currentPlayer);
final session = _live.session;
@@ -247,11 +254,13 @@ extension _VideoPlayerLiveTvMethods on VideoPlayerScreenState {
bool? play,
bool applyOptions = true,
}) async {
if (_shuttingDown) return false;
_live.streamGeneration++;
final media = Media(streamUrl, headers: const {'Accept-Language': 'en'});
final playNow = play ?? automotivePlaybackAllowedNow();
if (targetEpoch == null || player is! PlayerNative) {
if (applyOptions) await _setLiveStreamOptions(player);
if (_shuttingDown) return false;
await player.open(media, play: playNow, isLive: true);
return true;
}
@@ -261,6 +270,7 @@ extension _VideoPlayerLiveTvMethods on VideoPlayerScreenState {
final int? sourceId;
try {
if (applyOptions) await _setLiveStreamOptions(player);
if (_shuttingDown) return false;
sourceId = await player.open(media, play: playNow, isLive: true);
} catch (_) {
_live.failClockOpen(clockGeneration);
@@ -317,7 +327,7 @@ extension _VideoPlayerLiveTvMethods on VideoPlayerScreenState {
/// so both guards cover it. Returns whether the rebuilt stream was opened.
Future<bool> _seekLivePosition(int targetEpochSeconds) async {
final currentPlayer = player;
if (currentPlayer == null) return false;
if (_shuttingDown || currentPlayer == null) return false;
final session = _live.session;
final buffer = _live.captureBuffer;
if (session == null || buffer == null) return false;
@@ -326,7 +336,7 @@ extension _VideoPlayerLiveTvMethods on VideoPlayerScreenState {
final offsetSeconds = clamped - buffer.startedAt.round();
final streamUrl = await session.streamUrlAt(offsetSeconds: offsetSeconds, subtitleTrack: _live.selectedSubtitle);
if (streamUrl == null || !mounted || player != currentPlayer) return false;
if (streamUrl == null || !mounted || _shuttingDown || player != currentPlayer) return false;
if (currentPlayer is! PlayerNative) {
_live.streamStartEpoch = buffer.startedAt + offsetSeconds;
@@ -445,6 +455,7 @@ extension _VideoPlayerLiveTvMethods on VideoPlayerScreenState {
}
Future<void> _switchLiveChannel(int delta) async {
if (_shuttingDown) return;
final channels = widget.live?.channels;
if (channels == null || channels.isEmpty) return;
final newIndex = _live.channelIndex + delta;
@@ -456,6 +467,7 @@ extension _VideoPlayerLiveTvMethods on VideoPlayerScreenState {
if (transitionLease == null) return; // debounce concurrent switches
bool isCurrentChannelSwitch() =>
mounted &&
!_shuttingDown &&
player == currentPlayer &&
_transitionGate.owns(transitionLease, expected: PlaybackTransition.switchingChannel);
_liveSeek.cancel();
@@ -195,6 +195,7 @@ extension _VideoPlayerPlaybackPromptMethods on VideoPlayerScreenState {
}
void _cancelAutoPlay() {
if (_shuttingDown) return;
_episode.autoPlayTimer?.cancel();
_unfocusPlayNextPrompt();
_progressTracker?.resumeAfterStoppedReport();
@@ -360,6 +360,7 @@ extension _VideoPlayerReloadMethods on VideoPlayerScreenState {
WatchPlaybackLease? watchTogetherLease,
String reason = 'media reload',
}) async {
if (_shuttingDown) return MediaReloadOutcome.superseded;
if (widget.isLive) {
_clearEpisodeLoadingFlags();
return MediaReloadOutcome.rejected;
@@ -37,7 +37,7 @@ extension _VideoPlayerPlaybackServiceMethods on VideoPlayerScreenState {
}
Future<void> _markFirstFrameReady(Player currentPlayer, SettingsService settingsService) async {
if (!mounted || player != currentPlayer || _firstFrame.rendered || _hasFatalPlaybackError) return;
if (!mounted || _shuttingDown || player != currentPlayer || _firstFrame.rendered || _hasFatalPlaybackError) return;
_firstFrame.markReady();
_http503Watchdog.disarm();
@@ -68,7 +68,7 @@ extension _VideoPlayerPlaybackServiceMethods on VideoPlayerScreenState {
// to _initializeServices in this file and the sleep-timer/Apple TV ones to
// initState; both outlive a re-wire.
await Future.wait<void>(_cancelPlayerStreamSubscriptions(includeMediaControls: false));
if (!mounted || player != currentPlayer) return;
if (!mounted || _shuttingDown || player != currentPlayer) return;
int? lastObservedPositionMs;
_playerStreamSubscriptions.add(currentPlayer.streams.playing.listen(_onPlayingStateChanged));
@@ -328,7 +328,7 @@ extension _VideoPlayerPlaybackServiceMethods on VideoPlayerScreenState {
MediaSourceInfo? mediaInfo,
}) {
final currentPlayer = player;
if (_hasFatalPlaybackError) return;
if (_shuttingDown || _hasFatalPlaybackError) return;
if (currentPlayer == null) return;
@@ -375,7 +375,7 @@ extension _VideoPlayerPlaybackServiceMethods on VideoPlayerScreenState {
MediaSourceInfo? mediaInfo,
}) {
final currentPlayer = player;
if (_hasFatalPlaybackError) return;
if (_shuttingDown || _hasFatalPlaybackError) return;
if (currentPlayer == null) return;
@@ -436,7 +436,7 @@ extension _VideoPlayerPlaybackServiceMethods on VideoPlayerScreenState {
/// Initialize the service layer
Future<void> _initializeServices() async {
final currentPlayer = player;
if (!mounted || currentPlayer == null || _hasFatalPlaybackError) return;
if (!mounted || _shuttingDown || currentPlayer == null || _hasFatalPlaybackError) return;
// Live TV: send timeline heartbeats to keep transcode session alive
if (widget.isLive) {
@@ -3,7 +3,7 @@ part of '../../video_player_screen.dart';
extension _VideoPlayerPlaybackStartMethods on VideoPlayerScreenState {
Future<void> _startPlayback() async {
final currentPlayer = player;
if (!mounted || currentPlayer == null) return;
if (!mounted || _shuttingDown || currentPlayer == null) return;
final attempt = _beginPlaybackAttempt(currentPlayer);
final watchTogether = _activeWatchTogetherSession();
final watchTogetherLease = widget.watchTogetherLease;
@@ -59,7 +59,7 @@ extension _VideoPlayerPlaybackStartMethods on VideoPlayerScreenState {
);
if (elapsed > 60) {
final watchFromStart = await _showWatchFromStartDialog(effectiveStart, nowEpoch);
if (!mounted) return;
if (!mounted || !attempt.isCurrent) return;
if (watchFromStart == true) {
offsetSeconds = useProgramStart ? offsetProgramStart : captureBuffer.seekStartSeconds.round();
}
@@ -68,6 +68,7 @@ extension _VideoPlayerPlaybackStartMethods on VideoPlayerScreenState {
// Build the stream URL (with optional offset for time-shift)
final streamUrl = await session.streamUrlAt(offsetSeconds: offsetSeconds);
if (!attempt.isCurrent) return;
if (streamUrl == null || !mounted) {
throw PlaybackException(t.liveTv.failedToBuildStreamUrl, reason: PlaybackFailureReason.noPlayableSource);
}
@@ -97,7 +98,7 @@ extension _VideoPlayerPlaybackStartMethods on VideoPlayerScreenState {
_trackManager?.cacheExternalSubtitles(const []);
await _initVideoFilterAndPip();
if (!mounted || player != currentPlayer) return;
if (!mounted || !attempt.isCurrent) return;
if (mounted) {
// Live TV never commits a PlaybackSession, so the session-derived
@@ -113,7 +114,7 @@ extension _VideoPlayerPlaybackStartMethods on VideoPlayerScreenState {
} catch (e, st) {
appLogger.e('Failed to start live TV playback', error: e, stackTrace: st);
unawaited(_sendLiveTimeline('stopped'));
if (mounted) {
if (mounted && !_shuttingDown) {
showErrorSnackBar(context, e.toString());
unawaited(_handleBackButton());
}
+2 -2
View File
@@ -3,7 +3,7 @@ part of '../../video_player_screen.dart';
extension _VideoPlayerSeekingMethods on VideoPlayerScreenState {
Future<void> _seekPlayback(Duration position) async {
final currentPlayer = player;
if (!mounted || currentPlayer == null) return;
if (!mounted || _shuttingDown || currentPlayer == null) return;
final target = clampSeekPosition(currentPlayer, position);
// Declare intentional seeks before the delegate can unbind/reload at EOF.
_activeWatchTogetherSession()?.onLocalSeek(target);
@@ -12,7 +12,7 @@ extension _VideoPlayerSeekingMethods on VideoPlayerScreenState {
Future<void> _performSeekPlayback(Duration position, {bool Function()? isCurrent}) async {
final currentPlayer = player;
if (!mounted || currentPlayer == null) return;
if (!mounted || _shuttingDown || currentPlayer == null) return;
final generation = _transitionGate.generation;
final target = clampSeekPosition(currentPlayer, position);
@@ -13,6 +13,7 @@ extension _VideoPlayerWatchTogetherMethods on VideoPlayerScreenState {
/// Bind only a committed open and retain its session/output ownership for disposal.
void _attachToWatchTogetherSession({required WatchPlaybackLease lease, Future<void>? startupHold}) {
if (_shuttingDown) return;
final watchTogether = _activeWatchTogetherSession();
final currentPlayer = player;
final metadata = _playbackSession?.metadata ?? _currentMetadata;
@@ -84,10 +85,10 @@ extension _VideoPlayerWatchTogetherMethods on VideoPlayerScreenState {
/// Playback intent is guest-controllable only when the active room permits
/// it. Outside a room, the local screen remains authoritative.
bool _canControlPlayback() => _activeWatchTogetherSession()?.canControl() ?? true;
bool _canControlPlayback() => !_shuttingDown && (_activeWatchTogetherSession()?.canControl() ?? true);
/// Choosing another queue item or episode is host-only in every room mode.
bool _canNavigateMediaItems() => _activeWatchTogetherSession()?.isHost ?? true;
bool _canNavigateMediaItems() => !_shuttingDown && (_activeWatchTogetherSession()?.isHost ?? true);
void _commitWatchTogetherSelection(
WatchTogetherProvider? watchTogether,
+64 -3
View File
@@ -440,6 +440,8 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
String? _playerInitializationError;
Future<void>? _playerInitializationOperation;
int _playerInitializationGeneration = 0;
Future<void>? _shutdownOperation;
bool _shuttingDown = false;
late MediaItem _currentMetadata;
final EpisodeSessionState _episode = EpisodeSessionState();
@@ -646,7 +648,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
late final MediaControlsScreenController _mediaControls = MediaControlsScreenController(
manager: () => _mediaControlsManager,
player: () => player,
isMounted: () => mounted,
isMounted: () => mounted && !_shuttingDown,
isLive: widget.isLive,
shouldSkipForPip: () => _shouldSkipForPip,
isPlayerInitialized: () => _isPlayerInitialized,
@@ -786,10 +788,11 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
}
bool _isCurrentPlaybackGeneration(int generation, Player currentPlayer) {
return mounted && player == currentPlayer && _transitionGate.generation == generation;
return mounted && !_shuttingDown && player == currentPlayer && _transitionGate.generation == generation;
}
Future<void> _playWithPlaybackIntent(Player currentPlayer) {
if (_shuttingDown) return Future<void>.value();
if (!automotivePlaybackAllowedNow()) {
_playbackIntentShouldPlay = false;
appLogger.d('Playback blocked while Android Automotive app is not resumed');
@@ -814,6 +817,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
}
Future<void> _playOrPauseWithPlaybackIntent(Player currentPlayer) {
if (_shuttingDown) return Future<void>.value();
if (!automotivePlaybackAllowedNow()) {
appLogger.d('Play/pause requested while Android Automotive app is not resumed; keeping playback paused');
return _pauseWithPlaybackIntent(currentPlayer);
@@ -857,11 +861,16 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
@visibleForTesting
Future<void> debugSeekPlaybackForTesting(Duration position) => _seekPlayback(position);
@visibleForTesting
Future<void> debugWirePlayerStreamsForTesting() =>
_wirePlayerStreams(currentPlayer: player!, settingsService: SettingsService.instance, useExoPlayer: false);
late final PlayerNavigationCoordinator _playerNavigationCoordinator;
@override
void initState() {
super.initState();
PlaybackCoordinator.instance.registerVideoSession(shutdown: _shutdownVideo);
final launchLease = widget.watchTogetherLease;
if (launchLease != null) {
final watchTogether = context.read<WatchTogetherProvider?>();
@@ -1073,6 +1082,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
super.didChangeAppLifecycleState(state);
if (_shuttingDown) return;
switch (state) {
case AppLifecycleState.inactive:
@@ -1121,6 +1131,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
}
Future<void> _startPlayerInitialization({required bool replaceCurrent}) {
if (_shuttingDown) return Future<void>.value();
final activeOperation = _playerInitializationOperation;
if (activeOperation != null) return activeOperation;
@@ -1149,7 +1160,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
}
bool _isPlayerInitializationCurrent(int generation) {
return mounted && generation == _playerInitializationGeneration;
return mounted && !_shuttingDown && generation == _playerInitializationGeneration;
}
bool _ownsPlayerInitializationAttempt(int generation, Player currentPlayer) {
@@ -1820,6 +1831,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
@override
void dispose() {
PlaybackCoordinator.instance.unregisterVideoSession(_shutdownVideo);
unawaited(AndroidExitDiagnostics.markUiState(AndroidUiState.mainScreen));
_playerInitializationGeneration++;
_frameRate.dispose();
@@ -2275,6 +2287,55 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
return null;
}
Future<void> _shutdownVideo() {
final existing = _shutdownOperation;
if (existing != null) return existing;
final completer = Completer<void>();
_shutdownOperation = completer.future;
// No await until producers and all source-operation gates are closed.
// Do not use route exit (dialogs/navigation) or resumable TV suspension.
_shuttingDown = true;
_isExiting.value = true;
_playbackIntentShouldPlay = false;
_playerInitializationGeneration++;
_transitionGate.bumpGeneration();
_transitionGate.completeIdleWaiters();
_tvSuspend.cancelGrace();
_episode.autoPlayTimer?.cancel();
_stillWatchingTimer?.cancel();
_http503Watchdog.disarm();
_liveSeek.cancel();
_live.cancelClockOpens();
_live.resumeTimelineOnResume = false;
_stopLiveTimelineUpdates();
_progressTracker?.stopTracking();
_companionRemote.unbind();
_detachFromWatchTogetherSession(exiting: true);
_detachPipStateListener();
_clearAutoPipEnteringCallback();
final cancellations = _cancelPlayerStreamSubscriptions(includeMediaControls: true);
final remoteCancellation = _appleTvPlayPauseSubscription?.cancel();
if (remoteCancellation != null) cancellations.add(remoteCancellation);
final sleepCancellation = _sleepTimerSubscription?.cancel();
if (sleepCancellation != null) cancellations.add(sleepCancellation);
final currentPlayer = player;
// The tracker snapshots duration, tracks, identity and position before
// yielding. Native stop may reset them. This also retains offline writes
// and the tracker's terminal watched-state settlement.
final stoppedReport = _sendStoppedProgressOnce(positionOverride: currentPlayer?.state.position);
unawaited(() async {
try {
await Future.wait<void>([stoppedReport, if (currentPlayer != null) currentPlayer.stop(), ...cancellations]);
completer.complete();
} catch (error, stackTrace) {
completer.completeError(error, stackTrace);
}
}());
return completer.future;
}
Future<void> _sendStoppedProgressOnce({Duration? positionOverride}) {
if (widget.isLive) {
_stopLiveTimelineUpdates();
+24 -13
View File
@@ -10,6 +10,7 @@ typedef AppExitApplication = Future<ui.AppExitResponse> Function(ui.AppExitType
class AppExitService {
static const bool _tvosBuild = bool.fromEnvironment('TVOS_BUILD');
static const MethodChannel _channel = MethodChannel('com.plezy/app_exit');
static Future<bool>? _gracefulExitFuture;
/// Requests that the host platform closes or backgrounds the app.
///
@@ -42,19 +43,29 @@ class AppExitService {
return true;
}
/// Requests a *cancelable* exit so registered `onExitRequested` handlers run
/// before the process goes away — app-level teardown depends on it, including
/// the terminal playback report for trackers that own their own watched
/// semantics.
/// Awaits the app's exit observers before requesting native termination.
///
/// Desktop only; returns false elsewhere, and when the platform declined, so
/// the caller can fall back to a hard exit.
static Future<bool> requestGracefulExit({AppExitApplication? exitApplicationForTesting}) async {
if (!PlatformDetector.isDesktopOS()) return false;
final exitApplication =
exitApplicationForTesting ??
(exitType, exitCode) => ServicesBinding.instance.exitApplication(exitType, exitCode);
final response = await exitApplication(ui.AppExitType.cancelable, 0);
return response == ui.AppExitResponse.exit;
/// A cancelable native request is not a teardown barrier: Windows returns
/// `cancel` immediately and dispatches its observer request separately.
/// Dispatch directly so the required exit cannot overtake app cleanup.
///
/// Overlapping requests share one shutdown. Returns false on cancellation
/// or outside desktop platforms; cancellation must never trigger a hard exit.
static Future<bool> requestGracefulExit() {
if (!PlatformDetector.isDesktopOS()) return Future.value(false);
return _gracefulExitFuture ??= _requestGracefulExit().whenComplete(() {
_gracefulExitFuture = null;
});
}
static Future<bool> _requestGracefulExit() async {
final response = await ServicesBinding.instance.handleRequestAppExit();
if (response != ui.AppExitResponse.exit) return false;
// The root observer bounds teardown. This separate deadline applies only
// after acceptance, so a stalled platform exit can reach the window fallback.
final nativeResponse = await ServicesBinding.instance
.exitApplication(ui.AppExitType.required, 0)
.timeout(const Duration(seconds: 3));
return nativeResponse == ui.AppExitResponse.exit;
}
}
+26
View File
@@ -44,6 +44,32 @@ String buildJellyfinAuthHeader({
return 'MediaBrowser ${parts.join(', ')}';
}
/// The `Client` name for the same header, with the platform appended the way
/// the first-party apps do (`Jellyfin Android TV`, `Swiftfin tvOS`). Neither
/// Jellyfin nor Emby exposes a platform field on a session, so dashboards and
/// session trackers derive the platform from this string by keyword; a bare
/// `Plezy` on every platform makes every install look alike.
String jellyfinClientName(DeviceIdentity identity) {
final platform = _meaningful(identity.platform);
if (platform.isEmpty) return 'Plezy';
if (identity.isTv && platform.toLowerCase() == 'android') return 'Plezy Android TV';
return 'Plezy $platform';
}
/// The `Device` name for the same header: the user-facing device name, else
/// the hardware model, else the platform. An Apple TV whose name lookup failed
/// should appear in the server's device list as `Apple TV`, not as a second
/// `Plezy` next to the client name. Raw, not header-sanitized:
/// [buildJellyfinAuthHeader] percent-encodes it, so the server shows the name
/// verbatim.
String jellyfinDeviceName(DeviceIdentity identity) {
for (final candidate in [identity.deviceName, identity.deviceModel, identity.platform].nonNulls) {
final name = _meaningful(candidate);
if (name.isNotEmpty) return name;
}
return 'Plezy';
}
final RegExp _controlCharacters = RegExp(r'[\x00-\x1f\x7f-\x9f]');
/// Percent-encoding makes any byte transportable, so the only values worth
+6 -10
View File
@@ -150,6 +150,7 @@ mixin _JellyfinClientInternals on MediaServerCacheMixin {
bool? enableTranscoding,
bool? allowVideoStreamCopy,
bool? allowAudioStreamCopy,
bool isLiveTv,
bool audioProfile,
bool burnSubtitles,
});
@@ -282,18 +283,13 @@ class JellyfinClient
} catch (_) {
// Tests / non-platform contexts — keep the fallback version.
}
// Raw, not header-sanitized: [buildJellyfinAuthHeader] percent-encodes it.
String? deviceName;
try {
final resolved = (await DeviceIdentityService.resolve()).deviceName?.trim();
if (resolved != null && resolved.isNotEmpty) deviceName = resolved;
} catch (_) {
// Tests / non-platform contexts — keep the fallback name.
}
// Never throws: tests and non-platform contexts degrade to the bare OS
// name, which the helpers below turn into a usable client and device.
final identity = await DeviceIdentityService.resolve();
final authHeader = buildJellyfinAuthHeader(
clientName: 'Plezy',
clientName: jellyfinClientName(identity),
clientVersion: version,
deviceName: deviceName ?? 'Plezy',
deviceName: jellyfinDeviceName(identity),
deviceId: connection.deviceId,
accessToken: connection.accessToken,
);
@@ -205,6 +205,7 @@ class _JellyfinLiveTvSupport implements LiveTvSupport {
final wantsDirect = quality.isOriginal && !forceTranscode;
final info = await _client.getPlaybackInfo(
channelKey,
isLiveTv: true,
// Original sends no ceiling, mirroring the VOD path: a cap below the
// assumed 40 Mbps live bitrate silently forbids direct play.
maxStreamingBitrate: quality.isOriginal ? null : (quality.videoBitrateKbps ?? 100_000) * 1000,
@@ -765,6 +765,8 @@ mixin _JellyfinPlaybackMethods on _JellyfinClientInternals {
/// [audioStreamIndex] / [subtitleStreamIndex] tell the server which streams
/// to pick for the transcode profile (Jellyfin's negotiation factors them in
/// when picking codec compatibility).
/// [isLiveTv] selects the dialect's live HLS transport policy independently
/// of [autoOpenLiveStream], which controls server-side source lifecycle.
/// [audioProfile] extends the DeviceProfile with music direct-play and
/// audio→mp3 transcode entries for track playback; the video profiles (and
/// the request body when false) are untouched either way.
@@ -783,6 +785,7 @@ mixin _JellyfinPlaybackMethods on _JellyfinClientInternals {
bool? enableTranscoding,
bool? allowVideoStreamCopy,
bool? allowAudioStreamCopy,
bool isLiveTv = false,
bool audioProfile = false,
/// Drop `External` subtitle delivery from the profile, so the server burns
@@ -807,6 +810,9 @@ mixin _JellyfinPlaybackMethods on _JellyfinClientInternals {
final response = await _http.post(
'/Items/${_segment(itemId)}/PlaybackInfo',
queryParameters: query,
// Opening a cold tuner can delay response headers beyond the normal
// connect budget (#2274). Keep VOD and metadata-only requests unchanged.
timeout: isLiveTv && autoOpenLiveStream == true ? MediaServerTimeouts.tune : null,
body: {
'UserId': connection.userId,
'MaxStreamingBitrate': ?maxStreamingBitrate,
@@ -830,25 +836,27 @@ mixin _JellyfinPlaybackMethods on _JellyfinClientInternals {
// Every mpv backend already consumes fMP4 HLS — the Plex VOD
// target has shipped it since issue #1859.
'TranscodingProfiles': <Map<String, Object?>>[
{
'Type': 'Video',
'Container': 'mp4',
'Protocol': 'hls',
'VideoCodec': _jellyfinTranscodeVideoCodecs(dialect),
// Every audio codec Jellyfin can put in an fMP4 segment, so a
// transcode forced by the video stream can still copy the audio
// instead of re-encoding it; AAC leads because it is the only
// entry the server can reliably encode to. Two silent traps:
// the server validates this against `^[a-zA-Z0-9\-\._,|]{0,40}$`
// when it echoes the list into the transcode URL, so `alac` does
// not fit and `*` is not a wildcard; and omitting the key is not
// "accept everything" the way it is for a direct-play profile —
// the server substitutes the source codec, filters it against
// the same fMP4 set, and ships no audio at all for a source it
// cannot carry.
'AudioCodec': 'aac,mp3,ac3,eac3,flac,opus,dts,truehd',
},
// MPEG-TS fallback, listed second (#2198): Jellyfin drops every
if (!isLiveTv || !dialect.requiresMpegTsForLiveTv)
{
'Type': 'Video',
'Container': 'mp4',
'Protocol': 'hls',
'VideoCodec': _jellyfinTranscodeVideoCodecs(dialect),
// Every audio codec Jellyfin can put in an fMP4 segment, so a
// transcode forced by the video stream can still copy the audio
// instead of re-encoding it; AAC leads because it is the only
// entry the server can reliably encode to. Two silent traps:
// the server validates this against `^[a-zA-Z0-9\-\._,|]{0,40}$`
// when it echoes the list into the transcode URL, so `alac` does
// not fit and `*` is not a wildcard; and omitting the key is not
// "accept everything" the way it is for a direct-play profile —
// the server substitutes the source codec, filters it against
// the same fMP4 set, and ships no audio at all for a source it
// cannot carry.
'AudioCodec': 'aac,mp3,ac3,eac3,flac,opus,dts,truehd',
},
// MPEG-TS is the only Emby Live TV target (#2273); otherwise it
// stays second as Jellyfin's fallback (#2198). Jellyfin drops every
// non-ts transcoding profile for a live source with
// `UseMostCompatibleTranscodingProfile` — hardcoded true for
// HDHomeRun tuners, default true for M3U tuners — so with fMP4
+16
View File
@@ -16,6 +16,22 @@ class PlaybackCoordinator {
Future<void> Function()? _stopMusicSession;
Future<void> Function()? _shutdownVideoSession;
/// Register the screen that owns video, before its asynchronous startup.
void registerVideoSession({required Future<void> Function() shutdown}) {
_shutdownVideoSession = shutdown;
}
/// A replaced screen must not release its successor's registration.
void unregisterVideoSession(Future<void> Function() shutdown) {
if (_shutdownVideoSession == shutdown) _shutdownVideoSession = null;
}
/// Quiesce video and await its native stop and final backend report.
/// The owner coalesces repeated calls; the application owns the deadline.
Future<void> shutdownVideo() => _shutdownVideoSession?.call() ?? Future<void>.value();
/// Register the active music session's teardown. [stopAndDispose] must
/// stop playback, send final progress, and dispose the audio `Player`
/// before completing. Replaces any previous registration (there is one
+5 -1
View File
@@ -13,7 +13,11 @@ import 'dart:io';
/// those on its own.
Future<ConnectionTask<Socket>> happyEyeballsConnectionFactory(Uri url, String? proxyHost, int? proxyPort) {
if (proxyHost != null) return Socket.startConnect(proxyHost, proxyPort!);
return Future.value(startHappyEyeballsConnect(url.host, url.port, secure: url.isScheme('https')));
final secure = url.isScheme('https');
// WebSocket.connect supplies port 0 when a ws/wss URL omits its port.
// Match HttpClient's default-port substitution for direct connections.
final port = url.port == 0 ? (secure ? HttpClient.defaultHttpsPort : HttpClient.defaultHttpPort) : url.port;
return Future.value(startHappyEyeballsConnect(url.host, port, secure: secure));
}
const Duration defaultAttemptDelay = Duration(milliseconds: 250);
+3 -2
View File
@@ -56,8 +56,9 @@ class MediaServerTimeouts {
/// sum of phases.
static const perServerConnect = Duration(milliseconds: 6500);
/// HTTP timeout for the live-TV tune POST. Matches Plex web's value — the
/// default 10s connect budget is too tight on Fire-TV cold starts.
/// Per-phase HTTP timeout for Plex tune and MediaBrowser Live TV
/// PlaybackInfo that opens a source. Matches Plex web's value: a cold
/// tuner can take longer than the default 10s to return response headers.
static const tune = Duration(seconds: 30);
static const plexTvConnect = Duration(seconds: 15);
+1 -1
View File
@@ -895,7 +895,7 @@
repositoryURL = "https://github.com/edde746/mpv-build";
requirement = {
kind = revision;
revision = 3fd89c259b6ff6ef9a4c25e377d1287fb1407c9a;
revision = d38d607fd299e106a83f3557e310ac4b8202b39c;
};
};
/* End XCRemoteSwiftPackageReference section */
@@ -5,7 +5,7 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/edde746/mpv-build",
"state" : {
"revision" : "3fd89c259b6ff6ef9a4c25e377d1287fb1407c9a"
"revision" : "d38d607fd299e106a83f3557e310ac4b8202b39c"
}
},
{
@@ -5,7 +5,7 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/edde746/mpv-build",
"state" : {
"revision" : "3fd89c259b6ff6ef9a4c25e377d1287fb1407c9a"
"revision" : "d38d607fd299e106a83f3557e310ac4b8202b39c"
}
},
{
+20 -20
View File
@@ -4,54 +4,54 @@
"assetBase": "https://github.com/edde746/mpv-build/releases/download/binaries-android",
"assets": {
"arm64-v8a": {
"asset": "libmpv-android-d109720a9b8e-arm64-v8a.tar.gz",
"checksum": "0a7bd7cca69e94eef1396d78146b14b71818449ea633f5dd82792a849a172240"
"asset": "libmpv-android-125886efb728-arm64-v8a.tar.gz",
"checksum": "542b8fdabe4c1d75afb8fa159cbc28ec55d0f3523ada9839606512d54584e80c"
},
"armeabi-v7a": {
"asset": "libmpv-android-d109720a9b8e-armeabi-v7a.tar.gz",
"checksum": "3fc01ae61cf89fa82f9609d82c9ed048384edfe5f583eb7a4b0ffb7bc4a02692"
"asset": "libmpv-android-125886efb728-armeabi-v7a.tar.gz",
"checksum": "12d889c1198e5317442e5158244f3f104c6cbaf692705ae302282f725ef91c75"
},
"x86": {
"asset": "libmpv-android-d109720a9b8e-x86.tar.gz",
"checksum": "81d7a355874a2c5f62af01b505108d6d8aacbf513ce3aebc6b90d58c767a77e6"
"asset": "libmpv-android-125886efb728-x86.tar.gz",
"checksum": "0a99e0a7e6da45b599ee6fd57374f273d29e3bcccdd1fdb09284255c9096a257"
},
"x86_64": {
"asset": "libmpv-android-d109720a9b8e-x86_64.tar.gz",
"checksum": "6908a02d33dcd07c80c5b6c1f653e4058215ceba3d79dbc1fed9cfa99b7a7d9b"
"asset": "libmpv-android-125886efb728-x86_64.tar.gz",
"checksum": "10629366b5e58255bc559cdf2a88ffbfc0c358bb7a962b140b9b7891b07b718c"
}
},
"key": "d109720a9b8e"
"key": "125886efb728"
},
"linux": {
"assetBase": "https://github.com/edde746/mpv-build/releases/download/binaries-linux",
"assets": {
"aarch64": {
"asset": "libmpv-linux-0b78ba111724-aarch64.tar.zst",
"checksum": "bc593d99455f38d9691fefffa2028324c74de00cf387cbc6f2a76403404b97e3"
"asset": "libmpv-linux-59439f648815-aarch64.tar.zst",
"checksum": "21d86c267eeec53ab942a2d1b5749e2b58b258296901951a4d5b65b19cf75258"
},
"x86_64": {
"asset": "libmpv-linux-0b78ba111724-x86_64.tar.zst",
"checksum": "15ba8784dc919b72f519f5df584f6ab1a23f935a2f1ba42c033d35602bc731da"
"asset": "libmpv-linux-59439f648815-x86_64.tar.zst",
"checksum": "2868732f3359d99aa7e84806fa2c4c4ed67fcbf24a497e47af3a9cd2cd5cfd8a"
}
},
"key": "0b78ba111724"
"key": "59439f648815"
},
"windows": {
"assetBase": "https://github.com/edde746/mpv-build/releases/download/binaries-windows",
"assets": {
"aarch64": {
"asset": "libmpv-windows-2b33f3cb68c4-aarch64.zip",
"checksum": "f98162ab2af1b879a4b379aacec28113e96a863f7a756ac93be632a497a62790"
"asset": "libmpv-windows-ed133121277f-aarch64.zip",
"checksum": "fd039a7fe34fe08efe0215d682a16f3cc9597f3da79fafb2ab3a5e910c334865"
},
"x86_64": {
"asset": "libmpv-windows-2b33f3cb68c4-x86_64.zip",
"checksum": "eb969b4f5b6eef62eb41366302f862f1b7f4c9071157b7fe03b436b21afc7452"
"asset": "libmpv-windows-ed133121277f-x86_64.zip",
"checksum": "eb9587093709c38c87f89d62ce2d0274d8edacdf6be6771d03b41bec9ee34e52"
}
},
"key": "2b33f3cb68c4"
"key": "ed133121277f"
}
},
"commit": "3fd89c259b6ff6ef9a4c25e377d1287fb1407c9a",
"commit": "d38d607fd299e106a83f3557e310ac4b8202b39c",
"formatVersion": 1,
"repo": "edde746/mpv-build"
}
+1 -1
View File
@@ -1,7 +1,7 @@
name: plezy
description: "A beautiful Plex and Jellyfin client for Flutter"
publish_to: "none"
version: 2.19.0+148
version: 2.19.1+149
environment:
# Dart floor stays 3.12: freezed 3.x emits `final` constructor parameters,
@@ -7,6 +7,55 @@ import 'package:plezy/models/livetv_capture_buffer.dart';
import 'package:plezy/screens/video_player/live_timeline_report.dart';
void main() {
test('live stop drains an in-flight heartbeat and rejects later progress', () async {
final queue = LiveTimelineReportQueue();
final session = _FakeSession(_buffer(1000));
Future<void> report(String state, int position) => runLiveTimelineReport(
requestSession: session,
requestGeneration: 1,
state: state,
positionMs: position,
currentSession: () => session,
currentGeneration: () => 1,
isMounted: () => true,
commit: (_) {},
);
final playing = queue.send(stopped: false, report: () => report('playing', 100));
final queued = queue.send(stopped: false, report: () => report('paused', 200));
var stoppedDone = false;
final stopped = queue
.send(stopped: true, report: () => report('stopped', 321))
.whenComplete(() => stoppedDone = true);
final repeated = queue.send(stopped: true, report: () => report('stopped', 0));
final late = queue.send(stopped: false, report: () => report('playing', 400));
expect(session.states, ['playing']);
session.complete(0, null);
await playing;
await queued;
// Let the serialized terminal callback reach its HTTP await.
await Future<void>.delayed(Duration.zero);
expect(session.states, ['playing', 'stopped']);
expect(session.positions, [100, 321]);
expect(stoppedDone, isFalse);
session.complete(1, null);
await Future.wait([stopped, repeated, late]);
expect(stoppedDone, isTrue);
expect(session.states, ['playing', 'stopped']);
});
test('failed live heartbeat does not block the terminal attempt', () async {
final queue = LiveTimelineReportQueue();
final gate = Completer<void>();
final sent = <String>[];
final playing = queue.send(stopped: false, report: () => gate.future);
final failure = expectLater(playing, throwsStateError);
final stopped = queue.send(stopped: true, report: () async => sent.add('stopped'));
gate.completeError(StateError('connection lost'));
await failure;
await stopped;
expect(sent, ['stopped']);
});
group('runLiveTimelineReport', () {
test('late pre-channel heartbeat cannot replace adopted channel buffer', () async {
final bufferA = _buffer(1000);
@@ -180,6 +229,7 @@ class _FakeSession implements LiveTvPlaybackSession {
@override
final CaptureBuffer captureBuffer;
final List<String> states = [];
final List<int> positions = [];
final List<Completer<LiveTimelineUpdate?>> _reports = [];
void complete(int index, CaptureBuffer? buffer) =>
@@ -204,6 +254,7 @@ class _FakeSession implements LiveTvPlaybackSession {
required int durationMs,
}) {
states.add(state);
positions.add(positionMs);
final completer = Completer<LiveTimelineUpdate?>();
_reports.add(completer);
return completer.future;
@@ -36,6 +36,7 @@ import '../../test_helpers/mock_player_channels.dart';
import '../../test_helpers/multi_server_fixtures.dart';
import '../../test_helpers/prefs.dart';
import '../../test_helpers/playback_report_fakes.dart';
import '../../test_helpers/pump.dart';
import '../../test_helpers/watch_together_fakes.dart';
/// Exercises source reloads through the screen while the room remains live.
@@ -222,6 +223,48 @@ void main() {
expect(peer.latestState.phase, PlaybackPhase.paused);
}
// Exit after a committed reload must report the item actually
// loaded, not the route's original metadata or native stop's
// reset clock. Exercise both playing and paused exits.
// Startup is held before production stream wiring. Bind the real
// listeners now so the fake renderer event reaches reporting
// readiness rather than only the room's independent observer.
await key.currentState!.debugWirePlayerStreamsForTesting();
fakePlayer.emitPlaying(opens);
fakePlayer.emitPlaybackRestart();
await tester.pump();
// The room's initial alignment may seek on renderer readiness.
// Advance the playhead only after that alignment has settled.
fakePlayer.setPosition(const Duration(seconds: 137));
final terminalGate = Completer<void>();
client.stopGate = terminalGate;
var shutdownDone = false;
final shutdown = PlaybackCoordinator.instance.shutdownVideo().whenComplete(() => shutdownDone = true);
final repeatedShutdown = PlaybackCoordinator.instance.shutdownVideo();
await tester.pump();
final terminal = client.reports.last;
expect(terminal.kind, PlaybackReportKind.stopped);
expect(terminal.itemId, opens ? targetItem.id : priorItem.id);
expect(terminal.position, const Duration(seconds: 137));
expect(terminal.duration, const Duration(minutes: 40));
expect(fakePlayer.currentPosition, Duration.zero);
expect(fakePlayer.stopCalls, 1);
expect(shutdownDone, isFalse, reason: 'native stop alone must not release application teardown');
final reportCount = client.reports.length;
final openCount = fakePlayer.openCalls;
// Neither a lifecycle resume nor a pending startup released by
// music arbitration may reopen after the shutdown latch.
key.currentState!.didChangeAppLifecycleState(AppLifecycleState.resumed);
initializationHold.complete();
await tester.pump(const Duration(seconds: 30));
expect(fakePlayer.openCalls, openCount);
expect(client.reports.length, reportCount);
terminalGate.complete();
await pumpUntil(tester, () => shutdownDone);
await Future.wait([shutdown, repeatedShutdown]);
expect(shutdownDone, isTrue);
expect(fakePlayer.stopCalls, 1);
// Let the rollback's failure snackbar run its display timer down so
// nothing is pending when the tree unmounts.
await tester.pump(const Duration(seconds: 5));
@@ -241,6 +284,14 @@ class _ReloadPlayer extends FakeSyncPlayer {
: super(playing: true, position: const Duration(seconds: 121), duration: const Duration(minutes: 40), rate: 1.25);
bool opens;
int openCalls = 0;
int stopCalls = 0;
@override
Future<void> stop() async {
stopCalls++;
setPosition(Duration.zero);
emitPlaying(false);
}
@override
String get playerType => 'mpv';
@@ -254,6 +305,12 @@ class _ReloadPlayer extends FakeSyncPlayer {
@override
Future<void> setProperty(String name, String value) async {}
@override
Future<String?> getProperty(String name) async => null;
@override
Future<void> updateFrame() async {}
@override
Future<void> setDisplayCriteria(MediaDisplayCriteria? criteria, {int extraDelayMs = 0}) async {}
@@ -303,6 +360,8 @@ class _ScreenPeerService extends WatchTogetherPeerService {
}
class _ReloadClient with PlaybackReportRecorder implements MediaServerClient {
final reports = <PlaybackReportCall>[];
Completer<void>? stopGate;
@override
ServerId get serverId => ServerId('srv-1');
@override
@@ -326,7 +385,10 @@ class _ReloadClient with PlaybackReportRecorder implements MediaServerClient {
);
@override
Future<void> onPlaybackReport(PlaybackReportCall call) async {}
Future<void> onPlaybackReport(PlaybackReportCall call) async {
reports.add(call);
if (call.kind == PlaybackReportKind.stopped) await stopGate?.future;
}
@override
void close() {}
+203 -38
View File
@@ -1,52 +1,217 @@
import 'dart:async';
import 'dart:ui' as ui;
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:plezy/services/app_exit_service.dart';
import 'package:plezy/utils/platform_detector.dart';
// The standard test binding rejects required exits before they reach the binary
// messenger. Restore only that platform leg; lifecycle observer dispatch stays
// on the real WidgetsBinding implementation.
class _AppExitTestBinding extends AutomatedTestWidgetsFlutterBinding {
@override
Future<ui.AppExitResponse> exitApplication(ui.AppExitType exitType, [int exitCode = 0]) async {
final result = await SystemChannels.platform.invokeMethod<Map<String, Object?>>(
'System.exitApplication',
<String, Object?>{'type': exitType.name, 'exitCode': exitCode},
);
return result == null || result['response'] == 'cancel' ? ui.AppExitResponse.cancel : ui.AppExitResponse.exit;
}
}
void main() {
test('desktop exit uses the required application exit API', () async {
ui.AppExitType? requestedType;
int? requestedCode;
final binding = _AppExitTestBinding();
expect(
await AppExitService.requestExit(
exitApplicationForTesting: (exitType, exitCode) async {
requestedType = exitType;
requestedCode = exitCode;
return ui.AppExitResponse.exit;
},
),
isTrue,
);
expect(requestedType, ui.AppExitType.required);
expect(requestedCode, 0);
setUp(() {
PlatformDetector.debugSetIsDesktopOSOverride(true);
});
// The window's close button must run the registered onExitRequested handlers
// (app-level teardown, including the terminal playback report), which only a
// cancelable request does — `required` skips them.
test('graceful desktop exit uses a cancelable application exit', () async {
ui.AppExitType? requestedType;
int? requestedCode;
expect(
await AppExitService.requestGracefulExit(
exitApplicationForTesting: (exitType, exitCode) async {
requestedType = exitType;
requestedCode = exitCode;
return ui.AppExitResponse.exit;
},
),
isTrue,
);
expect(requestedType, ui.AppExitType.cancelable);
expect(requestedCode, 0);
tearDown(() {
binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null);
PlatformDetector.debugSetIsDesktopOSOverride(null);
});
test('a declined graceful exit reports failure so the caller can hard-exit', () async {
expect(
await AppExitService.requestGracefulExit(exitApplicationForTesting: (_, _) async => ui.AppExitResponse.cancel),
isFalse,
testWidgets('native termination waits for the exit listener to finish teardown', (tester) async {
final teardown = Completer<void>();
final events = <String>[];
final listener = AppLifecycleListener(
onExitRequested: () async {
events.add('teardown started');
await teardown.future;
events.add('stopped reported');
return ui.AppExitResponse.exit;
},
);
addTearDown(listener.dispose);
binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (call) async {
if (call.method != 'System.exitApplication') return null;
// Model Windows: a cancelable request immediately returns cancel, not
// the result of the app's asynchronously dispatched exit observers.
if ((call.arguments as Map)['type'] == 'cancelable') return {'response': 'cancel'};
events.add('native termination');
return {'response': 'exit'};
});
final close = AppExitService.requestGracefulExit();
await tester.pump();
expect(events, ['teardown started']);
await tester.pump(const Duration(seconds: 6));
expect(events, ['teardown started']);
teardown.complete();
await tester.pump();
expect(await close, isTrue);
expect(events, ['teardown started', 'stopped reported', 'native termination']);
});
testWidgets('a canceled close never terminates and a later accepted close can proceed', (tester) async {
var cancel = true;
var terminations = 0;
final listener = AppLifecycleListener(
onExitRequested: () async => cancel ? ui.AppExitResponse.cancel : ui.AppExitResponse.exit,
);
addTearDown(listener.dispose);
binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (call) async {
if (call.method != 'System.exitApplication') return null;
terminations++;
return {'response': 'exit'};
});
final canceledClose = AppExitService.requestGracefulExit();
await tester.pump();
expect(await canceledClose, isFalse);
expect(terminations, 0);
cancel = false;
final acceptedClose = AppExitService.requestGracefulExit();
await tester.pump();
expect(await acceptedClose, isTrue);
expect(terminations, 1);
});
testWidgets('concurrent closes share teardown and wait for native termination', (tester) async {
final teardown = Completer<void>();
final nativeExit = Completer<Map<String, String>>();
var teardownCalls = 0;
var terminations = 0;
var completedCloses = 0;
final listener = AppLifecycleListener(
onExitRequested: () async {
teardownCalls++;
await teardown.future;
return ui.AppExitResponse.exit;
},
);
addTearDown(listener.dispose);
binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (call) async {
if (call.method != 'System.exitApplication') return null;
terminations++;
return nativeExit.future;
});
Future<bool> close() => AppExitService.requestGracefulExit().then((accepted) {
completedCloses++;
return accepted;
});
final first = close();
final second = close();
await tester.pump();
expect(teardownCalls, 1);
expect(terminations, 0);
expect(completedCloses, 0);
teardown.complete();
await tester.pump();
final third = close();
await tester.pump();
expect(teardownCalls, 1);
expect(terminations, 1);
expect(completedCloses, 0);
nativeExit.complete({'response': 'exit'});
await tester.pump();
expect(await Future.wait([first, second, third]), [true, true, true]);
expect(terminations, 1);
});
testWidgets('native failure follows teardown and does not latch later close requests', (tester) async {
final teardown = Completer<void>();
final events = <String>[];
var failNativeExit = true;
final listener = AppLifecycleListener(
onExitRequested: () async {
await teardown.future;
events.add('teardown finished');
return ui.AppExitResponse.exit;
},
);
addTearDown(listener.dispose);
binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (call) async {
if (call.method != 'System.exitApplication') return null;
events.add('native termination');
if (failNativeExit) throw PlatformException(code: 'exit_failed');
return {'response': 'exit'};
});
final failedClose = expectLater(AppExitService.requestGracefulExit(), throwsA(isA<PlatformException>()));
await tester.pump();
expect(events, isEmpty);
teardown.complete();
await tester.pump();
await failedClose;
expect(events, ['teardown finished', 'native termination']);
failNativeExit = false;
final retry = AppExitService.requestGracefulExit();
await tester.pump();
expect(await retry, isTrue);
expect(events, ['teardown finished', 'native termination', 'teardown finished', 'native termination']);
});
testWidgets('native exit timeout starts after teardown and permits a later close', (tester) async {
final teardown = Completer<void>();
final stalledNativeExit = Completer<Map<String, String>>();
var stallNativeExit = true;
var terminations = 0;
var closeFailed = false;
final listener = AppLifecycleListener(
onExitRequested: () async {
await teardown.future;
return ui.AppExitResponse.exit;
},
);
addTearDown(listener.dispose);
binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (call) async {
if (call.method != 'System.exitApplication') return null;
terminations++;
return stallNativeExit ? stalledNativeExit.future : {'response': 'exit'};
});
final failedClose = expectLater(AppExitService.requestGracefulExit(), throwsA(isA<TimeoutException>())).then((_) {
closeFailed = true;
});
await tester.pump();
await tester.pump(const Duration(seconds: 6));
expect(terminations, 0);
expect(closeFailed, isFalse);
teardown.complete();
await tester.pump();
expect(terminations, 1);
await tester.pump(const Duration(milliseconds: 2999));
expect(closeFailed, isFalse);
await tester.pump(const Duration(milliseconds: 1));
await failedClose;
expect(closeFailed, isTrue);
stallNativeExit = false;
final retry = AppExitService.requestGracefulExit();
await tester.pump();
expect(await retry, isTrue);
expect(terminations, 2);
stalledNativeExit.complete({'response': 'exit'});
await tester.pump();
});
}
@@ -1,5 +1,6 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:plezy/services/jellyfin_auth_header.dart';
import 'package:plezy/utils/device_identity.dart';
/// Every field value Jellyfin reads back out of the header, mirroring the
/// server's own parse: split on the top-level commas, strip the quotes, then
@@ -111,4 +112,85 @@ void main() {
expect(requireJellyfinDeviceId('dev-1'), 'dev-1');
});
});
// Jellyfin and Emby sessions carry no platform field, so session trackers
// (Tracearr's `normalizeClient`, for one) keyword-match the Client string
// the way they do for `Jellyfin Android TV` and `Swiftfin tvOS`. Each
// expected value below was checked against that matcher.
group('jellyfinClientName', () {
test('appends the platform the way the first-party apps do', () {
for (final platform in ['iOS', 'Android', 'macOS', 'Windows', 'Linux']) {
expect(jellyfinClientName(DeviceIdentity(platform: platform)), 'Plezy $platform');
}
});
test('names the Android TV variant without repeating TV for tvOS', () {
expect(jellyfinClientName(const DeviceIdentity(platform: 'Android', isTv: true)), 'Plezy Android TV');
expect(jellyfinClientName(const DeviceIdentity(platform: 'tvOS', isTv: true)), 'Plezy tvOS');
});
test('keeps the TV suffix on the degraded lowercase OS name', () {
// DeviceIdentityService falls back to Platform.operatingSystem when the
// platform plugin fails, and that is lowercase.
expect(jellyfinClientName(const DeviceIdentity(platform: 'android', isTv: true)), 'Plezy Android TV');
});
test('only Android gets a TV suffix', () {
expect(jellyfinClientName(const DeviceIdentity(platform: 'Linux', isTv: true)), 'Plezy Linux');
});
test('falls back to the bare app name without a platform', () {
expect(jellyfinClientName(const DeviceIdentity(platform: '')), 'Plezy');
expect(jellyfinClientName(const DeviceIdentity(platform: ' \u0000 ')), 'Plezy');
});
test('survives the header round trip', () {
final header = buildJellyfinAuthHeader(
clientName: jellyfinClientName(const DeviceIdentity(platform: 'Android', isTv: true)),
clientVersion: '2.19.0',
deviceName: 'Living Room Shield',
deviceId: 'dev-1',
);
expect(parseAsJellyfinWould(header)['Client'], 'Plezy Android TV');
});
});
group('jellyfinDeviceName', () {
test('prefers the user-facing device name', () {
const identity = DeviceIdentity(platform: 'iOS', deviceModel: 'iPhone', deviceName: ' Bob\'s iPhone ');
expect(jellyfinDeviceName(identity), "Bob's iPhone");
});
test('falls back to the hardware model when the name lookup failed', () {
// An Apple TV without a resolvable name should be listed as `Apple TV`,
// not as a second `Plezy` next to the client name.
const identity = DeviceIdentity(platform: 'tvOS', deviceModel: 'Apple TV', isTv: true);
expect(jellyfinDeviceName(identity), 'Apple TV');
expect(
jellyfinDeviceName(const DeviceIdentity(platform: 'tvOS', deviceModel: 'Apple TV', deviceName: ' ')),
'Apple TV',
);
});
test('falls back to the platform when there is no model either', () {
expect(jellyfinDeviceName(const DeviceIdentity(platform: 'Linux')), 'Linux');
expect(jellyfinDeviceName(const DeviceIdentity(platform: 'Linux', deviceModel: '\u0000')), 'Linux');
});
test('falls back to the app name when nothing about the device is known', () {
expect(jellyfinDeviceName(const DeviceIdentity(platform: '')), 'Plezy');
});
});
group('jellyfinClientName and jellyfinDeviceName', () {
test('derive from the same resolved identity', () async {
// The production call sites resolve one identity and derive both names
// from it, so an override must steer both.
DeviceIdentityService.debugOverride(const DeviceIdentity(platform: 'Android', deviceModel: 'AFTKM', isTv: true));
addTearDown(() => DeviceIdentityService.debugOverride(null));
final identity = await DeviceIdentityService.resolve();
expect(jellyfinClientName(identity), 'Plezy Android TV');
expect(jellyfinDeviceName(identity), 'AFTKM');
});
});
}
+34 -5
View File
@@ -135,12 +135,14 @@ _initializeJellyfinAudioCarry({int? selectedAudioStreamId, AudioTrack? preferred
return (client: client, requests: requests);
}
const _testIdentity = DeviceIdentity(platform: 'Test');
/// URL-builder smoke tests. Without a live Jellyfin server, pin query keys and
/// authentication parameters directly.
void main() {
// Pin device identity so JellyfinClient.create's MediaBrowser header falls
// back to Device="Plezy" instead of resolving the host machine's name.
setUpAll(() => DeviceIdentityService.debugOverride(const DeviceIdentity(platform: 'Test')));
// Pin device identity so JellyfinClient.create's MediaBrowser header names
// the test platform instead of resolving the host machine's name.
setUpAll(() => DeviceIdentityService.debugOverride(_testIdentity));
tearDownAll(() => DeviceIdentityService.debugOverride(null));
group('JellyfinClient URL builders', () {
@@ -3054,8 +3056,8 @@ void main() {
final auth = headers['Authorization'];
expect(auth, isNotNull);
expect(auth, startsWith('MediaBrowser '));
expect(auth, contains('Client="Plezy"'));
expect(auth, contains('Device="Plezy"'));
expect(auth, contains('Client="Plezy%20Test"'));
expect(auth, contains('Device="Test"'));
expect(auth, contains('DeviceId="dev-xyz"'));
expect(auth, contains(RegExp(r'Version="[^"]+"')));
expect(auth, contains('Token="tok-abc"'));
@@ -3066,6 +3068,33 @@ void main() {
expect(headers['Accept'], 'application/json');
});
test('names the platform in Client and the device in Device', () async {
// Jellyfin sessions have no platform field: dashboards and session
// trackers keyword-match the Client string, the way they already do for
// `Jellyfin Android TV` and `Swiftfin tvOS`.
DeviceIdentityService.debugOverride(
const DeviceIdentity(platform: 'Android', deviceModel: 'SHIELD', deviceName: 'Living Room Shield', isTv: true),
);
addTearDown(() => DeviceIdentityService.debugOverride(_testIdentity));
final scoped = await JellyfinClient.create(_conn());
addTearDown(scoped.close);
final auth = scoped.defaultHeadersForTesting['Authorization'];
expect(auth, contains('Client="Plezy%20Android%20TV"'));
expect(auth, contains('Device="Living%20Room%20Shield"'));
});
test('falls back to the hardware model for Device when the name lookup failed', () async {
DeviceIdentityService.debugOverride(const DeviceIdentity(platform: 'tvOS', deviceModel: 'Apple TV', isTv: true));
addTearDown(() => DeviceIdentityService.debugOverride(_testIdentity));
final scoped = await JellyfinClient.create(_conn());
addTearDown(scoped.close);
final auth = scoped.defaultHeadersForTesting['Authorization'];
expect(auth, contains('Client="Plezy%20tvOS"'));
expect(auth, contains('Device="Apple%20TV"'));
});
test('fetchLibraryPagedContent sends a bounded paged Items request', () async {
Uri? captured;
final scoped = JellyfinClient.forTesting(
@@ -1,6 +1,8 @@
import 'dart:async';
import 'dart:convert';
import 'package:drift/native.dart';
import 'package:fake_async/fake_async.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
@@ -473,6 +475,192 @@ void main() {
});
});
for (final (connection, liveContainers) in [
(testJellyfinConnection(), ['mp4', 'ts']),
(testEmbyConnection(), ['ts']),
]) {
test('${connection.dialect.productName} allows cold live tune and recovery beyond ten seconds', () {
fakeAsync((async) {
var negotiations = 0;
final client = JellyfinClient.forTesting(
connection: connection,
httpClient: MockClient((request) async {
if (!request.url.path.endsWith('/PlaybackInfo')) return http.Response('', 204);
negotiations++;
await Future<void>.delayed(const Duration(seconds: 11));
return jsonResponse({
'PlaySessionId': 'play-$negotiations',
'MediaSources': [
{
'Id': 'source-1',
'Container': 'ts',
'LiveStreamId': 'live-$negotiations',
'SupportsDirectPlay': negotiations == 1,
'TranscodingUrl': '/Videos/channel-1/live.m3u8',
},
],
});
}),
);
try {
String? url;
Object? failure;
unawaited(
client.liveTv
.startPlayback('channel-1')
.then((session) async {
url = await session!.streamUrlAt();
final recovered = await session.recover(directStream: false, directStreamAudio: true);
url = await recovered!.streamUrlAt();
await recovered.reportTimeline(state: 'stopped', positionMs: 0, durationMs: 0);
})
.catchError((Object error) {
failure = error;
}),
);
async.elapse(const Duration(seconds: 11));
expect(failure, isNull);
expect(Uri.parse(url!).path, '/Videos/channel-1/stream.ts');
async.elapse(const Duration(seconds: 11));
expect(failure, isNull);
expect(Uri.parse(url!).path, '/Videos/channel-1/live.m3u8');
expect(negotiations, 2, reason: 'one tune and one recovery, without replay');
} finally {
client.close();
async.flushMicrotasks();
}
});
});
test('${connection.dialect.productName} aborts a stuck live tune at thirty seconds without replay', () {
fakeAsync((async) {
final transport = _HangingLiveTuneClient();
final client = JellyfinClient.forTesting(connection: connection, httpClient: transport);
try {
Object? failure;
unawaited(
client.liveTv
.startPlayback('channel-1')
.then<void>(
(_) => fail('A stuck tuner must not start playback'),
onError: (Object error) {
failure = error;
},
),
);
async.elapse(const Duration(seconds: 29));
expect(failure, isNull);
expect(transport.aborted, isFalse);
async.elapse(const Duration(seconds: 1));
expect(
failure,
isA<MediaServerHttpException>().having((e) => e.type, 'type', MediaServerHttpErrorType.connectionTimeout),
);
expect(transport.aborted, isTrue);
expect(transport.requests, 1);
} finally {
client.close();
async.flushMicrotasks();
}
});
});
for (final (name, isLiveTv, autoOpen) in [
('VOD', false, null),
('VOD opening a source', false, true),
('live metadata without opening a source', true, false),
]) {
test('${connection.dialect.productName} keeps the ten-second timeout for $name', () {
fakeAsync((async) {
final transport = _HangingLiveTuneClient();
final client = JellyfinClient.forTesting(connection: connection, httpClient: transport);
try {
Object? failure;
unawaited(
client
.getPlaybackInfo('item-1', isLiveTv: isLiveTv, autoOpenLiveStream: autoOpen)
.then<void>(
(_) => fail('A stuck request must not succeed'),
onError: (Object error) {
failure = error;
},
),
);
async.elapse(const Duration(seconds: 10));
expect(
failure,
isA<MediaServerHttpException>().having((e) => e.type, 'type', MediaServerHttpErrorType.connectionTimeout),
);
expect(transport.aborted, isTrue);
expect(transport.requests, 1);
} finally {
client.close();
async.flushMicrotasks();
}
});
});
}
test('${connection.dialect.productName} scopes HLS containers to live tune and recovery, not VOD', () async {
final negotiations = <Map<String, dynamic>>[];
final client = JellyfinClient.forTesting(
connection: connection,
httpClient: MockClient((request) async {
if (!request.url.path.endsWith('/PlaybackInfo')) return http.Response('', 204);
negotiations.add(jsonDecode(request.body) as Map<String, dynamic>);
return jsonResponse({
'PlaySessionId': 'play-${negotiations.length}',
'MediaSources': [
{
'Id': 'source-1',
'Container': 'ts',
'LiveStreamId': 'live-${negotiations.length}',
'SupportsDirectPlay': negotiations.length == 1,
'TranscodingUrl': '/Videos/channel-1/live.m3u8',
},
],
});
}),
);
addTearDown(client.close);
List<dynamic> containers(Map<String, dynamic> body) =>
((body['DeviceProfile'] as Map<String, dynamic>)['TranscodingProfiles'] as List)
.where((profile) => profile['Type'] == 'Video' && profile['Protocol'] == 'hls')
.map((profile) => profile['Container'])
.toList();
// Original must still allow direct play; selecting a live HLS container
// must not force the source through the transcoder (#2253).
final direct = (await client.liveTv.startPlayback('channel-1'))!;
expect(Uri.parse((await direct.streamUrlAt())!).path, '/Videos/channel-1/stream.ts');
expect(negotiations.single['EnableDirectPlay'], isTrue);
expect(containers(negotiations.single), liveContainers);
final recovered = (await direct.recover(directStream: false, directStreamAudio: true))!;
expect(Uri.parse((await recovered.streamUrlAt())!).path, '/Videos/channel-1/live.m3u8');
expect(containers(negotiations[1]), liveContainers);
expect(negotiations[1]['EnableDirectPlay'], isFalse);
expect(negotiations[1]['AllowVideoStreamCopy'], isTrue);
expect(negotiations[1]['AllowAudioStreamCopy'], isTrue);
await recovered.reportTimeline(state: 'stopped', positionMs: 0, durationMs: 0);
// A capped tune reaches HLS immediately rather than through recovery.
final capped = (await client.liveTv.startPlayback('channel-1', quality: TranscodeQualityPreset.p720_2mbps))!;
expect(containers(negotiations[2]), liveContainers);
expect(negotiations[2]['MaxStreamingBitrate'], 2_000_000);
expect(negotiations[2]['AllowVideoStreamCopy'], isTrue);
expect(negotiations[2]['AllowAudioStreamCopy'], isTrue);
await capped.reportTimeline(state: 'stopped', positionMs: 0, durationMs: 0);
// Returning to VOD on the same client must retain fMP4, even when a
// source asks the server to open a live stream during negotiation.
await client.getPlaybackInfo('movie-1', autoOpenLiveStream: true);
expect(containers(negotiations[3]), ['mp4', 'ts']);
await pumpEventQueue();
});
}
group('Jellyfin live playback session', () {
JellyfinConnection conn() => JellyfinConnection(
id: 'srv-1/user-1',
@@ -766,3 +954,22 @@ void main() {
});
});
}
/// Holds response headers until the transport receives the request's abort.
class _HangingLiveTuneClient extends http.BaseClient {
var requests = 0;
var aborted = false;
@override
Future<http.StreamedResponse> send(http.BaseRequest request) {
requests++;
final response = Completer<http.StreamedResponse>();
unawaited(
(request as http.Abortable).abortTrigger!.then((_) {
aborted = true;
response.completeError(http.RequestAbortedException(request.url));
}),
);
return response.future;
}
}
@@ -0,0 +1,40 @@
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:plezy/services/playback_coordinator.dart';
void main() {
test('stale video release preserves the active owner and waits for its stop', () async {
final coordinator = PlaybackCoordinator.instance;
final stopped = Completer<void>();
var oldStops = 0;
var musicStops = 0;
Future<void> oldOwner() async => oldStops++;
Future<void> activeOwner() => stopped.future;
Future<void> musicOwner() async => musicStops++;
coordinator.registerMusicSession(stopAndDispose: musicOwner);
coordinator.registerVideoSession(shutdown: oldOwner);
coordinator.registerVideoSession(shutdown: activeOwner);
addTearDown(() {
coordinator.unregisterVideoSession(oldOwner);
coordinator.unregisterVideoSession(activeOwner);
coordinator.unregisterMusicSession(musicOwner);
});
coordinator.unregisterVideoSession(oldOwner);
var done = false;
final shutdown = coordinator.shutdownVideo().whenComplete(() => done = true);
await Future<void>.delayed(Duration.zero);
expect(done, isFalse);
expect(oldStops, 0);
expect(musicStops, 0);
stopped.complete();
await shutdown;
expect(done, isTrue);
coordinator.unregisterVideoSession(activeOwner);
await coordinator.shutdownVideo();
expect(oldStops, 0);
expect(musicStops, 0);
});
}
+57
View File
@@ -268,6 +268,63 @@ void main() {
socket.add('after redirect and cancellation');
expect(await socket.first.timeout(const Duration(seconds: 5)), 'after redirect and cancellation');
});
test('a portless ws URL exchanges frames on port 80', () async {
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
addTearDown(() => server.close(force: true));
server.listen((request) async {
final socket = await WebSocketTransformer.upgrade(request);
addTearDown(socket.close);
socket.listen(socket.add, onDone: socket.close);
});
final parentZone = Zone.current;
await IOOverrides.runZoned(
() async {
final attempt = WebSocketConnectAttempt(
Uri.parse('ws://${server.address.address}/relay'),
connectTimeout: const Duration(seconds: 5),
);
addTearDown(attempt.cancel);
final socket = await attempt.socket;
addTearDown(socket.close);
socket.add('portless relay');
expect(await socket.first.timeout(const Duration(seconds: 5)), 'portless relay');
},
socketStartConnect: (host, port, {sourceAddress, sourcePort = 0}) {
// Route the default port to an isolated listener without binding port 80.
if (port != 80) return Future(() => throw SocketException('No listener on port $port'));
return parentZone.run(() => Socket.startConnect(host, server.port));
},
);
});
test('a portless wss URL negotiates TLS on port 443', () async {
final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
addTearDown(server.close);
final accepted = server.listen((socket) {
addTearDown(socket.destroy);
// A plaintext endpoint must fail TLS, not become an insecure WebSocket.
socket.add('HTTP/1.1 400 Bad Request\r\n\r\n'.codeUnits);
});
addTearDown(accepted.cancel);
final parentZone = Zone.current;
await IOOverrides.runZoned(
() async {
final attempt = WebSocketConnectAttempt(
Uri.parse('wss://${server.address.address}/relay'),
connectTimeout: const Duration(seconds: 5),
);
addTearDown(attempt.cancel);
await expectLater(attempt.socket, throwsA(isA<TlsException>()));
},
socketStartConnect: (host, port, {sourceAddress, sourcePort = 0}) {
// Only the HTTPS listener is reachable; port 0 fails before TLS.
if (port != 443) return Future(() => throw SocketException('No listener on port $port'));
return parentZone.run(() => Socket.startConnect(host, server.port));
},
);
});
});
group('connectWebSocketChannel', () {
+1 -1
View File
@@ -1175,7 +1175,7 @@
repositoryURL = "https://github.com/edde746/mpv-build";
requirement = {
kind = revision;
revision = 3fd89c259b6ff6ef9a4c25e377d1287fb1407c9a;
revision = d38d607fd299e106a83f3557e310ac4b8202b39c;
};
};
/* End XCRemoteSwiftPackageReference section */
@@ -6,7 +6,7 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/edde746/mpv-build",
"state" : {
"revision" : "3fd89c259b6ff6ef9a4c25e377d1287fb1407c9a"
"revision" : "d38d607fd299e106a83f3557e310ac4b8202b39c"
}
}
],
@@ -6,7 +6,7 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/edde746/mpv-build",
"state" : {
"revision" : "3fd89c259b6ff6ef9a4c25e377d1287fb1407c9a"
"revision" : "d38d607fd299e106a83f3557e310ac4b8202b39c"
}
}
],