diff --git a/android/app/src/main/java/tv/orbit/classic/ChannelSchedule.kt b/android/app/src/main/java/tv/orbit/classic/ChannelSchedule.kt index ab3575d0..39602e27 100644 --- a/android/app/src/main/java/tv/orbit/classic/ChannelSchedule.kt +++ b/android/app/src/main/java/tv/orbit/classic/ChannelSchedule.kt @@ -318,7 +318,11 @@ internal data class ScheduleEntry(val seriesId: String, val mark: EpisodeMark, v /** The block's or event's presentation key, saved when the programme is booked (see [DayPart.key]). Empty for ordinary programmes and older bookings. */ val presentation: String = "", /** The shorts slot this programme was booked in ([shortsTag]), or empty. Presentation only: the programme is still its own entry. */ - val group: String = "") { + val group: String = "", + /** Where it was first booked, before any re-timing for real lengths (ProgrammeLengths.kt), so a channel's drift can be held. */ + val bookedStartMs: Long = startMs, + /** The file's real length when its slot differs from it (a squeezed ending, or a short file the ident fills out); null when they're the same. */ + val fileMs: Long? = null) { val endMs get() = startMs + media.durationMs } @@ -1117,7 +1121,7 @@ internal fun rotationSet(titles: List, cap: Int, week: Long, weekMs: Lon internal class ScheduledChannel(val loop: SampleChannel, plan: ChannelPlan) : SampleChannel(loop.lineup, loop.name, loop.number) { @Volatile var plan: ChannelPlan = plan private val parts by lazy { SmartChannels.firstOrNull { it.number == number }?.dayParts.orEmpty() } - private fun presented(entry: ScheduleEntry) = SampleBroadcast(entry.media, entry.startMs, presentationOf(entry, parts), entry.group) + private fun presented(entry: ScheduleEntry) = SampleBroadcast(entry.media, entry.startMs, presentationOf(entry, parts), entry.group, entry.fileMs) /** The shorts slot [show] belongs to, from the booked programmes around it, or null. */ fun slotOf(show: SampleBroadcast): ShortsBlock? { if (show.group.isEmpty()) return null diff --git a/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt b/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt index 4d7b6465..7d55fb29 100644 --- a/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt +++ b/android/app/src/main/java/tv/orbit/classic/ChannelScheduler.kt @@ -362,7 +362,6 @@ internal class ChannelScheduler(private val store: ScheduleStore, } } val started = android.os.SystemClock.elapsedRealtime() - val existing = store.loadPlan(userId, number) val progress = store.loadProgress(userId, number) val base = progress?.aired ?: ScheduleCursor() // Other channels' plans are only read if this one is actually about to grow, and a plan read before is reused until its file changes. @@ -372,11 +371,16 @@ internal class ChannelScheduler(private val store: ScheduleStore, clashesWithAirings((SmartChannels.map { it.number }.filter { it != number } + DRIVE_IN_NUMBER).flatMap { airingsOn(userId, it) }) .also { othersMs = android.os.SystemClock.elapsedRealtime() - began } } - val plan = topUpPlan(existing, base, pool?.series?.let { withoutFailed(it, store.loadFailed(userId)) }?.let { if (programming.mixedTurns) mixedTurnOrder(it, number) else it }, now, programming.filmRestMs, programming.finishTogether, programming.dayParts, - avoid = { show, startMs, endMs -> others(show, startMs, endMs) }, shuffle = programming.shuffleEpisodes, mixed = programming::mixes, - weightOf = programming.tierWeights?.let { programming::weightOf }, adaptiveRest = programming.adaptiveFilmRest, fileRestMs = programming.fileRestMs, stories = programming.storyGrouping, shorts = programming.shorts, marathon = programming.marathon, - seasonEndMs = seasonEndMs(number, now)) ?: throw EmbyCheckException("${programming.name} has no episodes to schedule.") - if (plan !== existing) store.savePlan(userId, number, plan) + // Under the plan lock, so a programme being re-timed for its real length (PlanEdits) is never written over. + val (existing, plan) = synchronized(PlanEdits.lock) { + val existing = store.loadPlan(userId, number) + val plan = topUpPlan(existing, base, pool?.series?.let { withoutFailed(it, store.loadFailed(userId)) }?.let { if (programming.mixedTurns) mixedTurnOrder(it, number) else it }, now, programming.filmRestMs, programming.finishTogether, programming.dayParts, + avoid = { show, startMs, endMs -> others(show, startMs, endMs) }, shuffle = programming.shuffleEpisodes, mixed = programming::mixes, + weightOf = programming.tierWeights?.let { programming::weightOf }, adaptiveRest = programming.adaptiveFilmRest, fileRestMs = programming.fileRestMs, stories = programming.storyGrouping, shorts = programming.shorts, marathon = programming.marathon, + seasonEndMs = seasonEndMs(number, now)) ?: throw EmbyCheckException("${programming.name} has no episodes to schedule.") + if (plan !== existing) store.savePlan(userId, number, plan) + existing to plan + } // Stage C, report only: every work any plan books, so "not yet shown on Orbit" has evidence. if (plan !== existing) runCatching { val known = store.loadBooked(userId) diff --git a/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt b/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt index ff7c51ff..26c30d9e 100644 --- a/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt +++ b/android/app/src/main/java/tv/orbit/classic/EmbyConnectionScreen.kt @@ -447,10 +447,9 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea if (scheduler.enabled(active.accountId, programming.number)) { // Paced and within the hour's background budget (0.129): see BackgroundPacing. BackgroundPacing.run { scheduler.topUp(active, active.accountId, programming, loop) } - val fresh = scheduleStore.loadPlan(active.accountId, programming.number) val onAirNow = scheduledChannels[programming.number]?.takeIf { it.loop === loop } - if (fresh != null && onAirNow != null) onAirNow.plan = fresh - else scheduler.load(active.accountId, loop)?.let { scheduledChannels = scheduledChannels + (programming.number to it) } + val fresh = synchronized(PlanEdits.lock) { scheduleStore.loadPlan(active.accountId, programming.number)?.also { if (onAirNow != null) onAirNow.plan = it } } + if (fresh == null || onAirNow == null) scheduler.load(active.accountId, loop)?.let { scheduledChannels = scheduledChannels + (programming.number to it) } } } } catch (cancelled: CancellationException) { throw cancelled } diff --git a/android/app/src/main/java/tv/orbit/classic/GuidePicture.kt b/android/app/src/main/java/tv/orbit/classic/GuidePicture.kt index cb9d3893..c98aafac 100644 --- a/android/app/src/main/java/tv/orbit/classic/GuidePicture.kt +++ b/android/app/src/main/java/tv/orbit/classic/GuidePicture.kt @@ -116,7 +116,7 @@ internal fun GuidePicture(session: EmbySampleSession, channel: SampleChannel, li var cantPlay by remember(channel.number, current.startMs) { mutableStateOf(false) } Box(Modifier.fillMaxSize().background(Panel)) { if (live && foreground && !cantPlay && !resting) key(channel.number, current.startMs) { - GuideLiveProgramme(session, channel.number, current, handoff, onReady = { ready = true }, onCantPlay = { id -> cantPlay = true; ready = false; id?.let(onUnplayable) }) + GuideLiveProgramme(session, channel, current, handoff, onReady = { ready = true }, onCantPlay = { id -> cantPlay = true; ready = false; id?.let(onUnplayable) }) } val branding = ChannelBrands.forNumber(channel.number) if (!ready) Box(Modifier.matchParentSize().background(Panel)) { @@ -127,7 +127,9 @@ internal fun GuidePicture(session: EmbySampleSession, channel: SampleChannel, li } @Composable -private fun GuideLiveProgramme(session: EmbySampleSession, channelNumber: Int, programme: SampleBroadcast, handoff: LiveHandoff, onReady: () -> Unit, onCantPlay: (String?) -> Unit) { +private fun GuideLiveProgramme(session: EmbySampleSession, channel: SampleChannel, programme: SampleBroadcast, handoff: LiveHandoff, onReady: () -> Unit, onCantPlay: (String?) -> Unit) { + val channelNumber = channel.number + val context = LocalContext.current val returned = remember { val stream = handoff.returned handoff.returned = null @@ -142,7 +144,12 @@ private fun GuideLiveProgramme(session: EmbySampleSession, channelNumber: Int, p if (returned != null) return@LaunchedEffect try { val opened = withContext(Dispatchers.IO) { session.prepareForTuning(programme.media.item, programme.media.sourceId) { Thread.sleep(2_000) } } - if (scheduledRuntimeMatches(opened.durationMs, programme.media.durationMs)) plan = opened + val fit = runtimeFit(opened, programme) + // A longer file makes room for itself here too, so the picture and full screen agree (ProgrammeLengths.kt). + if (fit == RuntimeFit.Adjust) opened.durationMs?.let { actual -> + withContext(Dispatchers.IO) { PlanEdits.retime(channel, Workspaces.current(context).schedules, session.accountId, programme.startMs, actual) } + } + if (fit != RuntimeFit.Refuse) plan = opened } catch (cancelled: CancellationException) { throw cancelled } catch (_: Exception) { /* The artwork stays. Tuning full screen still explains any problem. */ } } diff --git a/android/app/src/main/java/tv/orbit/classic/ProgrammeLengths.kt b/android/app/src/main/java/tv/orbit/classic/ProgrammeLengths.kt new file mode 100644 index 00000000..a6708592 --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/ProgrammeLengths.kt @@ -0,0 +1,121 @@ +package tv.orbit.classic + +/** + * A file whose length differs from its slot (Paul, 12 November 2026: Scream 2 wouldn't play on the new server because the + * first scan had changed its length by seconds; "whats 14 secs really"). Orbit behaves like a real network: + * + * - The same length, within a couple of seconds: plays as booked. + * - A small difference: plays, and the channel adjusts around it ([retimedPlan]). + * - A large difference: plays only when it is the booked file, the same Emby item and the same version of it, and its new + * length is believable (half to twice the booked one). Then it's treated as a small one. + * - Anything else, or a file with no length at all, is skipped as before. + */ +internal enum class RuntimeFit { Same, Adjust, Refuse } + +/** Within this, a file is taken as the length it was booked at. */ +internal const val RUNTIME_SAME_MS = 2_000L +/** Up to this much longer or shorter plays without further checks: another cut, longer credits, a scan filling in exact lengths. */ +internal const val RUNTIME_SMALL_MS = 10 * 60_000L + +internal fun runtimeFit(openedMs: Long?, bookedMs: Long, sameFile: Boolean): RuntimeFit { + if (openedMs == null || openedMs <= 0 || bookedMs <= 0) return RuntimeFit.Refuse + val difference = kotlin.math.abs(openedMs - bookedMs) + return when { + difference <= RUNTIME_SAME_MS -> RuntimeFit.Same + !sameFile -> RuntimeFit.Refuse + difference <= RUNTIME_SMALL_MS -> RuntimeFit.Adjust + openedMs * 2 >= bookedMs && openedMs <= bookedMs * 2 -> RuntimeFit.Adjust + else -> RuntimeFit.Refuse + } +} + +/** The booked file is the one opened: the same Emby item, and the same version of it. Compared with the file's known length. */ +internal fun runtimeFit(opened: EmbyPlaybackPlan, booked: SampleBroadcast): RuntimeFit = + runtimeFit(opened.durationMs, booked.fileMs ?: booked.media.durationMs, opened.item.id == booked.media.item.id && opened.sourceId == booked.media.sourceId) + +/** How far behind its booked times a channel may run before endings start being squeezed to hold it there. */ +internal const val MAX_DRIFT_MS = 2 * 60_000L +/** The most a film's slot is ever shortened to hold a channel's drift: closing credits, which the squeeze-back shows anyway. */ +internal const val FILM_SQUEEZE_MAX_MS = 2 * 60_000L +/** The same for an episode, whose credits are short. */ +internal const val EPISODE_SQUEEZE_MAX_MS = 20_000L + +private fun ScheduleEntry.file() = fileMs ?: media.durationMs +private fun ScheduleEntry.withSlot(slotMs: Long, file: Long) = copy( + media = media.copy(durationMs = slotMs, item = media.item.copy(minutes = slotMs / 60_000, durationMs = slotMs)), + fileMs = file.takeIf { it != slotMs }) + +/** + * The plan with the programme starting at [startMs] re-timed for its file's real length [actualMs], as a real network would. + * + * - Longer than its slot: it finishes rather than being cut off, and what follows moves later. A gap in the plan (the run-in + * before an on-time programme) takes up the difference first, so fixed times hold wherever there's room. + * - Small corrections never add up for long. Once a channel would run more than [MAX_DRIFT_MS] behind its booked times, the + * ending of the programme before is squeezed (its closing credits, within [FILM_SQUEEZE_MAX_MS] or [EPISODE_SQUEEZE_MAX_MS]; + * never the programme that ran long) to hold it there. + * - Shorter: when the channel is running late, it wins the time back, the programmes after it moving earlier but never + * before their booked times. Any time left over is filled by the channel's ident, so a fixed time never comes early. + * + * Null when there's nothing to change: the programme isn't in the plan, or its length is already known. + */ +internal fun retimedPlan(plan: ChannelPlan, startMs: Long, actualMs: Long): ChannelPlan? { + val at = plan.entries.indexOfFirst { it.startMs == startMs }.takeIf { it >= 0 } ?: return null + val booked = plan.entries[at] + if (kotlin.math.abs(actualMs - booked.file()) <= RUNTIME_SAME_MS || actualMs <= 0 || actualMs > SampleChannel.MAX_DURATION_MS) return null + val entries = plan.entries.toMutableList() + val slot = booked.media.durationMs + // An ending already squeezed to hold the channel's drift stays squeezed by as much, whatever the file's real length. + val squeezed = (booked.file() - slot).coerceAtLeast(0) + if (actualMs - squeezed > slot) { + entries[at] = booked.withSlot(actualMs - squeezed, actualMs) + var previousEnd = entries[at].endMs + for (i in at + 1 until entries.size) { + val entry = plan.entries[i] + if (entry.startMs >= previousEnd) break + var start = previousEnd + val over = start - entry.bookedStartMs - MAX_DRIFT_MS + if (over > 0 && i - 1 != at) { + val before = entries[i - 1] + val squeezed = (before.file() - before.media.durationMs).coerceAtLeast(0) + val limit = (if (before.media.item.type == "Movie") FILM_SQUEEZE_MAX_MS else EPISODE_SQUEEZE_MAX_MS) - squeezed + val squeeze = minOf(over, limit, before.media.durationMs / 2).coerceAtLeast(0) + if (squeeze > 0) { entries[i - 1] = before.withSlot(before.media.durationMs - squeeze, before.file()); start -= squeeze } + } + entries[i] = entry.copy(startMs = start) + previousEnd = entries[i].endMs + } + } else { + // The back-to-back run after it, up to the first gap; how late the least-late of them is, is how much can be won back. + var last = at + while (last + 1 < plan.entries.size && plan.entries[last + 1].startMs == plan.entries[last].endMs) last++ + val late = if (last == at) 0L else (at + 1..last).minOf { plan.entries[it].startMs - plan.entries[it].bookedStartMs }.coerceAtLeast(0) + val back = minOf((slot - actualMs).coerceAtLeast(0), late) + entries[at] = booked.withSlot(slot - back, actualMs) + if (back > 0) for (i in at + 1..last) entries[i] = plan.entries[i].copy(startMs = plan.entries[i].startMs - back) + } + return plan.copy(entries = entries) +} + +/** Every change to a saved plan goes through this, so a top-up and a re-timing never write over each other. */ +internal object PlanEdits { + val lock = Any() + + /** + * Re-times a booked programme on a live channel for its real length ([retimedPlan]) and saves the result (called off the + * main thread). The saved plan is re-timed rather than the one in memory, in case a top-up has just added to it. Every + * screen (guide, What's On, the Companion, the player) reads the same plan, so they all move together. Returns how many + * programmes moved. + */ + fun retime(channel: SampleChannel, store: ScheduleStore, userId: String, startMs: Long, actualMs: Long): Int { + if (channel !is ScheduledChannel || channel.number == DRIVE_IN_NUMBER) return 0 + synchronized(lock) { + val saved = store.loadPlan(userId, channel.number) ?: return 0 + val updated = retimedPlan(saved, startMs, actualMs) ?: return 0 + store.savePlan(userId, channel.number, updated) + channel.plan = updated + val moved = updated.entries.zip(saved.entries).count { (a, b) -> a.startMs != b.startMs } + android.util.Log.i("OrbitSchedule", "channel=${channel.number} runtimeAdjusted start=$startMs extraMs=${actualMs - saved.entries.first { it.startMs == startMs }.media.durationMs} moved=$moved squeezed=${updated.entries.count { (it.fileMs ?: 0) > it.media.durationMs } - saved.entries.count { (it.fileMs ?: 0) > it.media.durationMs }}") + return moved + } + } +} diff --git a/android/app/src/main/java/tv/orbit/classic/SampleChannel.kt b/android/app/src/main/java/tv/orbit/classic/SampleChannel.kt index 560fa8ef..eda02fce 100644 --- a/android/app/src/main/java/tv/orbit/classic/SampleChannel.kt +++ b/android/app/src/main/java/tv/orbit/classic/SampleChannel.kt @@ -5,7 +5,9 @@ internal data class SampleBroadcast(val media: ScheduledMedia, val startMs: Long /** The booked programme's block or event presentation key (see [presentationOf]), empty for ordinary programmes. */ val presentation: String = "", /** The shorts slot the programme was booked in ([ScheduleEntry.group]), or empty. */ - val group: String = "") { + val group: String = "", + /** The file's real length when its slot differs from it ([ScheduleEntry.fileMs]); null when they're the same. */ + val fileMs: Long? = null) { val endMs: Long get() = startMs + media.durationMs fun offsetAt(timeMs: Long) = (timeMs - startMs).coerceIn(0, media.durationMs - 1) } diff --git a/android/app/src/main/java/tv/orbit/classic/SampleChannelScreens.kt b/android/app/src/main/java/tv/orbit/classic/SampleChannelScreens.kt index bafea978..82f6745c 100644 --- a/android/app/src/main/java/tv/orbit/classic/SampleChannelScreens.kt +++ b/android/app/src/main/java/tv/orbit/classic/SampleChannelScreens.kt @@ -31,9 +31,6 @@ import kotlinx.coroutines.withContext import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock -/** A schedule is only true if the file still runs as long as the slot it was given. */ -internal fun scheduledRuntimeMatches(openedMs: Long?, scheduledMs: Long) = openedMs != null && kotlin.math.abs(openedMs - scheduledMs) <= 2_000 - @Composable internal fun ScheduledChannelPlayer(session: EmbySampleSession, channel: SampleChannel, clockOffsetMs: Long, onClose: () -> Unit, onStep: (Int) -> Unit = {}, onLast: () -> Unit = {}, onNumber: (Int) -> Boolean = { false }, handoff: LiveHandoff? = null, onUnplayable: ((String) -> Unit)? = null, @@ -80,6 +77,7 @@ internal fun ScheduledChannelPlayer(session: EmbySampleSession, channel: SampleC val phase = if (identsHere) identPhase(current.startMs, current.endMs, now, identMs, if (squeezeOn) SQUEEZE_MS + IDENT_LOAD_AHEAD_MS else IDENT_LOAD_AHEAD_MS) else IdentPhase.None // Each changeover in the playback notes, so a missing ident can be explained afterwards. val notes = remember { Workspaces.current(settingsContext).scheduleDir } + val schedules = remember { Workspaces.current(settingsContext).schedules } DisposableEffect(Unit) { FullScreen.active = true; onDispose { FullScreen.active = false } } val introPlayback = rememberIntro(intro) { PlaybackNotes.add(notes, "channel=${channel.number} $it") } LaunchedEffect(channel, current.startMs) { @@ -103,7 +101,10 @@ internal fun ScheduledChannelPlayer(session: EmbySampleSession, channel: SampleC 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 + if (runtimeFit(opened, next) == RuntimeFit.Refuse || phase != IdentPhase.Showing) return@LaunchedEffect + if (runtimeFit(opened, next) == RuntimeFit.Adjust && clockOffsetMs == 0L) opened.durationMs?.let { actual -> + withContext(Dispatchers.IO) { PlanEdits.retime(channel, schedules, session.accountId, next.startMs, actual) } + } 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)) @@ -143,8 +144,13 @@ internal fun ScheduledChannelPlayer(session: EmbySampleSession, channel: SampleC } } android.util.Log.i("OrbitSchedule", "channel=${channel.number} tunePrepareMs=${android.os.SystemClock.elapsedRealtime() - tuneStarted} ahead=${ahead != null}") - if (!scheduledRuntimeMatches(plan.durationMs, current.media.durationMs)) - throw EmbyCheckException("This programme's runtime changed. Return and rebuild the sample channel.") + // A different length plays like a real network's would (ProgrammeLengths.kt); only a file that isn't the one booked is skipped. + val fit = runtimeFit(plan, current) + if (fit == RuntimeFit.Refuse) throw EmbyCheckException("This programme's runtime changed. Return and rebuild the sample channel.") + // Live only: Catch Up replays the past, which mustn't move what's on now. + if (fit == RuntimeFit.Adjust && clockOffsetMs == 0L) plan.durationMs?.let { actual -> + withContext(Dispatchers.IO) { PlanEdits.retime(channel, schedules, session.accountId, current.startMs, actual) } + } preparedSlot = current.startMs; prepared = plan } catch (cancelled: CancellationException) { throw cancelled } catch (failure: EmbyCheckException) { problem = if (channel is ScheduledChannel) "This programme isn't available right now. Orbit moves on at ${clock(current.endMs)}." else failure.message } diff --git a/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt b/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt index a7eb7ec6..73bc34dd 100644 --- a/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt +++ b/android/app/src/main/java/tv/orbit/classic/ScheduleStore.kt @@ -128,7 +128,7 @@ internal class ScheduleStore(private val directory: File) { fun savePlan(userId: String, number: Int, plan: ChannelPlan) { val entries = JSONArray() plan.entries.forEach { e -> entries.put(JSONObject().put("s", e.seriesId).put("n", JSONArray().put(e.mark.season).put(e.mark.episode)) - .put("i", e.media.item.id).put("c", e.media.sourceId).put("t", e.media.item.title).put("d", e.media.durationMs).put("a", e.startMs).also { row -> if (e.media.item.type == "Movie") row.put("k", "Movie"); if (e.why.isNotEmpty()) row.put("w", e.why); if (e.presentation.isNotEmpty()) row.put("p", e.presentation); if (e.group.isNotEmpty()) row.put("g", e.group) }) } + .put("i", e.media.item.id).put("c", e.media.sourceId).put("t", e.media.item.title).put("d", e.media.durationMs).put("a", e.startMs).also { row -> if (e.media.item.type == "Movie") row.put("k", "Movie"); if (e.why.isNotEmpty()) row.put("w", e.why); if (e.presentation.isNotEmpty()) row.put("p", e.presentation); if (e.group.isNotEmpty()) row.put("g", e.group); if (e.bookedStartMs != e.startMs) row.put("b", e.bookedStartMs); e.fileMs?.let { row.put("f", it) } }) } write(file("schedule", number), root(userId, number).put("tail", encodeCursor(plan.tail)).put("entries", entries)) } /** Changes whenever the plan file is written, so a plan already read can be reused until then. */ @@ -144,7 +144,10 @@ internal class ScheduleStore(private val directory: File) { // Absent in plans booked before presentations were kept; anything unexpected is ignored rather than refused. o.optString("p").takeIf { PRESENTATION_KEY.matches(it) }.orEmpty(), // A shorts slot's tag: absent before slots existed, and anything unexpected is ignored. - o.optString("g").takeIf { SHORTS_TAG.matches(it) }.orEmpty()) + o.optString("g").takeIf { SHORTS_TAG.matches(it) }.orEmpty(), + // Re-timing for real lengths (ProgrammeLengths.kt): absent unless a programme was moved or its slot differs from its file. + if (o.has("b")) o.getLong("b") else o.getLong("a"), + if (o.has("f")) validDuration(o.getLong("f")) else null) } require(entries.zipWithNext().all { (first, second) -> first.endMs <= second.startMs }) ChannelPlan(entries, decodeCursor(root.getJSONObject("tail"))) diff --git a/android/app/src/test/java/tv/orbit/classic/GuideGridTest.kt b/android/app/src/test/java/tv/orbit/classic/GuideGridTest.kt index 696efcb6..09cd7580 100644 --- a/android/app/src/test/java/tv/orbit/classic/GuideGridTest.kt +++ b/android/app/src/test/java/tv/orbit/classic/GuideGridTest.kt @@ -45,10 +45,11 @@ class GuideGridTest { } @Test - fun aProgrammeOnlyOpensIfItStillFitsItsSlot() { - assertTrue(scheduledRuntimeMatches(1_000_000, 1_001_500)) - assertFalse(scheduledRuntimeMatches(1_000_000, 1_002_001)) - assertFalse(scheduledRuntimeMatches(null, 1_000_000)) + fun aProgrammeOpensWhenItsTheBookedFile() { + assertEquals(RuntimeFit.Same, runtimeFit(1_000_000, 1_001_500, sameFile = true)) + assertEquals(RuntimeFit.Adjust, runtimeFit(1_000_000, 1_002_001, sameFile = true)) + assertEquals(RuntimeFit.Refuse, runtimeFit(1_000_000, 1_002_001, sameFile = false)) + assertEquals(RuntimeFit.Refuse, runtimeFit(null, 1_000_000, sameFile = true)) } @Test diff --git a/android/app/src/test/java/tv/orbit/classic/ProgrammeLengthsTest.kt b/android/app/src/test/java/tv/orbit/classic/ProgrammeLengthsTest.kt new file mode 100644 index 00000000..b26ad2c8 --- /dev/null +++ b/android/app/src/test/java/tv/orbit/classic/ProgrammeLengthsTest.kt @@ -0,0 +1,140 @@ +package tv.orbit.classic + +import org.junit.Assert.* +import org.junit.Test + +/** Paul, 12 November 2026: a file that runs a little differently plays, and the channel adjusts like a real network. */ +class ProgrammeLengthsTest { + private val min = 60_000L + private fun entry(id: String, startMs: Long, lengthMs: Long, presentation: String = "") = + ScheduleEntry(id, EpisodeMark(1, 1), ScheduledMedia(SampleItem(id, "Movie", lengthMs / min, "", id, lengthMs), "v$id", lengthMs), startMs, presentation = presentation) + private fun plan(vararg entries: ScheduleEntry) = ChannelPlan(entries.toList(), ScheduleCursor()) + + @Test + fun scream2sFourteenSecondsPlays() { + // The two copies on the new server differ by about 14 seconds; the scan can swap one length for the other. + assertEquals(RuntimeFit.Adjust, runtimeFit(7_232_267L, 7_218_612L, sameFile = true)) + assertEquals(RuntimeFit.Adjust, runtimeFit(7_218_612L, 7_232_267L, sameFile = true)) + } + + @Test + fun smallDifferencesPlayAndLargeOnesOnlyWhenItsTheBookedFile() { + val booked = 100 * min + assertEquals(RuntimeFit.Same, runtimeFit(booked + 1_500, booked, sameFile = true)) + assertEquals(RuntimeFit.Adjust, runtimeFit(booked + 10 * min, booked, sameFile = true)) + assertEquals(RuntimeFit.Adjust, runtimeFit(booked - 10 * min, booked, sameFile = true)) + // A director's cut half an hour longer: the same item and version, so it's what was booked. + assertEquals(RuntimeFit.Adjust, runtimeFit(booked + 30 * min, booked, sameFile = true)) + // Not the booked version, or nothing like the booked length (a trailer or sample in its place): skipped. + assertEquals(RuntimeFit.Refuse, runtimeFit(booked + 5 * min, booked, sameFile = false)) + assertEquals(RuntimeFit.Refuse, runtimeFit(3 * min, booked, sameFile = true)) + assertEquals(RuntimeFit.Refuse, runtimeFit(booked * 3, booked, sameFile = true)) + assertEquals(RuntimeFit.Refuse, runtimeFit(null, booked, sameFile = true)) + } + + @Test + fun aLongerFilmFinishesAndWhatFollowsMovesLater() { + val p = plan(entry("a", 0, 100 * min), entry("b", 100 * min, 30 * min), entry("c", 130 * min, 30 * min)) + val r = retimedPlan(p, 0, 100 * min + 14_000)!! + assertEquals(100 * min + 14_000, r.entries[0].endMs) + assertEquals(listOf(100 * min + 14_000, 130 * min + 14_000), r.entries.drop(1).map { it.startMs }) + assertTrue(r.entries.zipWithNext().all { (x, y) -> x.endMs <= y.startMs }) + } + + @Test + fun aGapBeforeAFixedTimeTakesUpTheDifference() { + // A five-minute run-in before an 8 pm event: a three-minute overrun leaves the event on time. + val p = plan(entry("a", 0, 100 * min), entry("b", 100 * min, 15 * min), entry("event", 120 * min, 90 * min, "vortex.movienight")) + val r = retimedPlan(p, 0, 103 * min)!! + assertEquals(103 * min, r.entries[1].startMs) + assertEquals(120 * min, r.entries[2].startMs) + // Seven minutes over: the gap takes five, and the event starts two minutes late, as a real network's would. + val late = retimedPlan(p, 0, 107 * min)!! + assertEquals(122 * min, late.entries[2].startMs) + assertTrue(late.entries.zipWithNext().all { (x, y) -> x.endMs <= y.startMs }) + } + + @Test + fun aShorterFileOnTimeKeepsItsSlotAndTheIdentFillsTheRest() { + val p = plan(entry("a", 0, 100 * min), entry("b", 100 * min, 30 * min)) + val r = retimedPlan(p, 0, 99 * min)!! + assertEquals(100 * min, r.entries[0].endMs) + assertEquals(99 * min, r.entries[0].fileMs) + assertEquals(100 * min, r.entries[1].startMs) + assertNull(retimedPlan(p, 0, 100 * min + 1_000)) + assertNull(retimedPlan(p, 55 * min, 120 * min)) + } + + @Test + fun aShorterFileWinsBackLostTimeButNeverRunsEarly() { + // An evening of back-to-back films, the first a minute and a half long; then the second turns out four minutes short. + val p = plan(entry("a", 0, 100 * min), entry("b", 100 * min, 100 * min), entry("c", 200 * min, 100 * min), entry("d", 300 * min, 100 * min)) + val late = retimedPlan(p, 0, 101 * min + 30_000)!! + assertEquals(listOf(101 * min + 30_000, 201 * min + 30_000, 301 * min + 30_000), late.entries.drop(1).map { it.startMs }) + val back = retimedPlan(late, 101 * min + 30_000, 96 * min)!! + // A minute and a half won back, so c and d are on their booked times again; the rest is the ident. + assertEquals(listOf(200 * min, 300 * min), back.entries.drop(2).map { it.startMs }) + assertEquals(98 * min + 30_000, back.entries[1].media.durationMs) + assertEquals(96 * min, back.entries[1].fileMs) + assertTrue(back.entries.zipWithNext().all { (x, y) -> x.endMs <= y.startMs }) + } + + @Test + fun tinyOverrunsNeverDriftAChannelMoreThanTwoMinutes() { + // Thirty back-to-back episodes, each found 20 seconds longer than booked as the evening goes on. + var p = plan(*(0 until 30).map { entry("e$it", it * 30 * min, 30 * min).let { e -> e.copy(media = e.media.copy(item = e.media.item.copy(type = "Episode"))) } }.toTypedArray()) + for (i in 0 until 30) p = retimedPlan(p, p.entries[i].startMs, 30 * min + 20_000) ?: p + // At most two minutes, plus the one overrun that's on screen when it's reached (that programme is never squeezed). + val drift = p.entries.maxOf { it.startMs - it.bookedStartMs } + assertTrue("drift $drift", drift <= MAX_DRIFT_MS + 20_000) + assertTrue("end drift", p.entries.last().startMs - p.entries.last().bookedStartMs <= MAX_DRIFT_MS + 20_000) + // Held by squeezing endings, never by more than an episode's allowance, and never overlapping. + assertTrue(p.entries.all { (it.fileMs ?: it.media.durationMs) - it.media.durationMs <= EPISODE_SQUEEZE_MAX_MS }) + assertTrue(p.entries.zipWithNext().all { (x, y) -> x.endMs <= y.startMs }) + } + + @Test + fun joiningHalfWayFindsTheRightPlace() { + // A 21:00 film that really runs 14 seconds longer; someone tunes in at 21:45, and later at the next programme's start. + val nine = 21 * 60 * min + val p = retimedPlan(plan(entry("film", nine, 100 * min), entry("next", nine + 100 * min, 30 * min)), nine, 100 * min + 14_000)!! + val channel = ScheduledChannel(SampleChannel(listOf(entry("loop1", 0, 30 * min).media, entry("loop2", 0, 30 * min).media), "Test", 305), p) + val at945 = channel.at(nine + 45 * min) + assertEquals("film", at945.media.item.id) + assertEquals(45 * min, at945.offsetAt(nine + 45 * min)) + // At 22:40:05 the film is still on (it used to end at 22:40:00); the next programme starts at 22:40:14, from its start. + assertEquals("film", channel.at(nine + 100 * min + 5_000).media.item.id) + val next = channel.at(nine + 100 * min + 14_000) + assertEquals("next", next.media.item.id) + assertEquals(0L, next.offsetAt(nine + 100 * min + 14_000)) + } + + @Test + fun theFitIsJudgedAgainstTheFilesKnownLength() { + val p = retimedPlan(plan(entry("a", 0, 100 * min), entry("b", 100 * min, 30 * min)), 0, 99 * min)!! + val shown = ScheduledChannel(SampleChannel(listOf(entry("loop1", 0, 30 * min).media, entry("loop2", 0, 30 * min).media), "Test", 305), p).at(10 * min) + assertEquals(99 * min, shown.fileMs) + assertEquals(RuntimeFit.Same, runtimeFit(99 * min, shown.fileMs ?: shown.media.durationMs, sameFile = true)) + } + + @Test + fun reTimingTwiceMovesNothingMore() { + val p = plan(entry("a", 0, 100 * min), entry("b", 100 * min, 30 * min)) + val once = retimedPlan(p, 0, 101 * min)!! + assertNull(retimedPlan(once, 0, 101 * min)) + } + + @Test + fun aReTimedPlanSavesAndLoads() { + val dir = kotlin.io.path.createTempDirectory("lengths").toFile() + try { + val store = ScheduleStore(dir) + val p = plan(entry("a1", 0, 100 * min), entry("b1", 100 * min, 30 * min)) + val r = retimedPlan(retimedPlan(p, 0, 101 * min)!!, 101 * min, 29 * min)!! + store.savePlan("u1", 305, r) + val loaded = store.loadPlan("u1", 305)!! + assertEquals(r.entries.map { it.startMs to it.endMs }, loaded.entries.map { it.startMs to it.endMs }) + assertEquals(r.entries.map { it.bookedStartMs to it.fileMs }, loaded.entries.map { it.bookedStartMs to it.fileMs }) + } finally { dir.deleteRecursively() } + } +}