One stream per TV: the next show's stream opens only after the ident has stopped the old one

Paul's Emby provider allows 3 streams across the house. Ahead of the ident only
the next show's details are asked for (IsPlayback=false, no stream); its player
is created once the ident covers the screen and the show under it has faded and
stopped (0.8 s). Neighbour channel look-ups are information-only too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-09 17:05:46 +00:00
co-authored by Claude Opus 5.5
parent c989ae95d9
commit 1ccdfc9a1f
5 changed files with 34 additions and 12 deletions
@@ -94,12 +94,13 @@ internal class EmbySampleSession(private val transport: EmbyTransport, private v
return if (kind == ServerKind.Jellyfin) mapOf("Authorization" to "MediaBrowser Token=\"$auth\"") else mapOf("X-Emby-Token" to auth)
}
/** Tuning shouldn't fail on one slow answer, so a timeout or dropped connection gets one more try. */
fun prepareForTuning(item: SampleItem, sourceId: String, pause: () -> Unit = {}): EmbyPlaybackPlan = try {
prepare(item, preferredSourceId = sourceId)
/** [ahead]: asked before it's needed (9 November 2026), so the server is told it's information only, not playback. */
fun prepareForTuning(item: SampleItem, sourceId: String, ahead: Boolean = false, pause: () -> Unit = {}): EmbyPlaybackPlan = try {
prepare(item, isPlayback = !ahead, preferredSourceId = sourceId)
} catch (failure: EmbyCheckException) {
if (!failure.retryable) throw failure
pause()
prepare(item, preferredSourceId = sourceId)
prepare(item, isPlayback = !ahead, preferredSourceId = sourceId)
}
fun prepare(item: SampleItem, isPlayback: Boolean = true, preferredSourceId: String? = null): EmbyPlaybackPlan {
if (preferredSourceId != null && !EmbyClient.validId(preferredSourceId)) throw EmbyCheckException("The channel source is no longer usable.")
@@ -28,6 +28,8 @@ internal const val IDENT_VIDEO_MS = 7_000L
internal const val IDENT_STING_MS = 5_000L
/** Long enough to open the next show and fill its buffer before the ident starts. */
internal const val IDENT_LOAD_AHEAD_MS = 12_000L
/** How long the show under an ident takes to fade (0.5 s) and stop, freeing its stream, before the next one opens. */
internal const val ONE_STREAM_HANDOVER_MS = 800L
/** How long past the changeover an ident may hold its last frame while the next programme's picture arrives. */
internal const val IDENT_HOLD_MS = 6_000L
private const val IDENT_SHORTEST_PROGRAMME_MS = 3 * 60_000L
@@ -91,16 +91,21 @@ internal fun ScheduledChannelPlayer(session: EmbySampleSession, channel: SampleC
LaunchedEffect(channel, current.startMs, phase == IdentPhase.Showing) {
if (phase == IdentPhase.Showing) PlaybackNotes.add(notes, "channel=${channel.number} ident shown next=${next.startMs} loaded=${loaded?.startMs == next.startMs}" + if (block != null) " block=${next.presentation}" else "")
}
// A problem here only means the next show tunes in the ordinary way.
LaunchedEffect(channel, current.startMs, phase == IdentPhase.None) {
// One stream per TV (Paul, 9 November 2026: his Emby provider allows 3 at once across the house). Ahead of the ident only
// the next show's details are asked for, which opens no stream. Its stream is opened once the ident covers the screen and
// the show underneath has stopped and let go of its own. A problem here only means the next show tunes in the ordinary way.
var nextDetails by remember(channel) { mutableStateOf<Pair<Long, EmbyPlaybackPlan>?>(null) }
LaunchedEffect(channel, current.startMs, phase == IdentPhase.None, phase == IdentPhase.Showing) {
if (phase == IdentPhase.None || loaded?.startMs == next.startMs) return@LaunchedEffect
try {
val opened = withContext(Dispatchers.IO) { session.prepareForTuning(next.media.item, next.media.sourceId) { Thread.sleep(2_000) } }
if (scheduledRuntimeMatches(opened.durationMs, next.media.durationMs)) {
if (loaded?.startMs == current.startMs) playing = loaded else loaded?.discard(session)
loaded = LoadedNext(next.startMs, opened, loadNextPlayer(playerContext, session, opened, audioPreference.value))
android.util.Log.i("OrbitSchedule", "channel=${channel.number} nextLoadedAheadMs=${next.startMs - System.currentTimeMillis()}")
}
val opened = nextDetails?.takeIf { it.first == next.startMs }?.second
?: withContext(Dispatchers.IO) { session.prepareForTuning(next.media.item, next.media.sourceId, ahead = true) { Thread.sleep(2_000) } }
.also { nextDetails = next.startMs to it }
if (!scheduledRuntimeMatches(opened.durationMs, next.media.durationMs) || phase != IdentPhase.Showing) return@LaunchedEffect
delay(ONE_STREAM_HANDOVER_MS)
if (loaded?.startMs == current.startMs) playing = loaded else loaded?.discard(session)
loaded = LoadedNext(next.startMs, opened, loadNextPlayer(playerContext, session, opened, audioPreference.value))
android.util.Log.i("OrbitSchedule", "channel=${channel.number} nextLoadedAheadMs=${next.startMs - System.currentTimeMillis()} oneStream=true")
} catch (cancelled: CancellationException) { throw cancelled } catch (_: Exception) { }
}
val loadedNow = listOfNotNull(loaded, playing).firstOrNull { it.startMs == current.startMs }
@@ -32,7 +32,7 @@ internal object TuneAhead {
}
try {
val started = android.os.SystemClock.elapsedRealtime()
val plan = withContext(Dispatchers.IO) { session.prepare(programme.media.item, preferredSourceId = programme.media.sourceId) }
val plan = withContext(Dispatchers.IO) { session.prepare(programme.media.item, isPlayback = false, preferredSourceId = programme.media.sourceId) }
synchronized(this) { ready[k] = Ready(session, plan, System.currentTimeMillis()); ready.entries.removeAll { System.currentTimeMillis() - it.value.at >= KEEP_MS } }
android.util.Log.i("OrbitSchedule", "channel=${channel.number} readyAheadMs=${android.os.SystemClock.elapsedRealtime() - started}")
} catch (cancelled: CancellationException) { throw cancelled }
@@ -21,6 +21,20 @@ class EmbyPlaybackTest {
private fun fails(block: () -> Unit) {
try { block(); fail("Expected rejection") } catch (_: EmbyCheckException) { }
}
/** One stream per TV (9 November 2026): asking ahead tells the server it's information only; tuning still says playback. */
@Test fun askingAheadIsInformationOnly() {
val fake = Fake(); fake.response = EmbyReply(200, info(source()))
val session = session(fake)
session.prepareForTuning(item, "source-123", ahead = true)
assertFalse(JSONObject(fake.requests.last().body!!).getBoolean("IsPlayback"))
session.prepareForTuning(item, "source-123")
assertTrue(JSONObject(fake.requests.last().body!!).getBoolean("IsPlayback"))
assertTrue(fake.requests.all { it.path.endsWith("/PlaybackInfo") }) // asking never opens the stream itself
}
@Test fun theNextShowOpensOnlyAfterTheOldOneLetsGo() {
// The show under an ident fades for 0.5 s, then stops; the next stream waits longer than that, and well inside the shortest ident.
assertTrue(ONE_STREAM_HANDOVER_MS > 500); assertTrue(ONE_STREAM_HANDOVER_MS + 3_000 < IDENT_STING_MS)
}
@Test fun preparesOnlySelectedSampleWithoutTranscodingOrTokenInUrl() {
val fake = Fake(); fake.response = EmbyReply(200, info(source()))
val session = session(fake); val plan = session.prepare(item)