diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index a7bc7edb..55e714a7 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -9,8 +9,8 @@ android { applicationId = "tv.orbit.classic" minSdk = 26 targetSdk = 36 - versionCode = 315 - versionName = "0.123.0-player" + versionCode = 316 + versionName = "0.123.1-player" } buildFeatures { compose = true } // The finished build for the TVs (Paul, 6 November 2026: the test build stuttered on the box). Not debuggable, so diff --git a/android/app/src/main/java/tv/orbit/classic/BoxDecoders.kt b/android/app/src/main/java/tv/orbit/classic/BoxDecoders.kt index 90ab3e5c..d7e1727f 100644 --- a/android/app/src/main/java/tv/orbit/classic/BoxDecoders.kt +++ b/android/app/src/main/java/tv/orbit/classic/BoxDecoders.kt @@ -10,7 +10,9 @@ internal fun videoMimeFor(codec: String): String? = when (codec.trim().lowercase "vp9" -> "video/x-vnd.on2.vp9" "av1" -> "video/av01" "mpeg2video", "mpeg2" -> "video/mpeg2" - "mpeg4", "msmpeg4v3", "divx", "xvid" -> "video/mp4v-es" + "mpeg4", "divx", "xvid" -> "video/mp4v-es" + // Microsoft's MPEG-4 (DivX 3 and older) isn't MPEG-4 Part 2: no Android TV decodes it (9 November 2026, tested). + "msmpeg4v1", "msmpeg4v2", "msmpeg4v3", "msmpeg4", "div3" -> "video/x-ms-mpeg4" "h263" -> "video/3gpp" "vc1", "wmv3" -> "video/wvc1" else -> null diff --git a/android/app/src/main/java/tv/orbit/classic/CatalogueShadow.kt b/android/app/src/main/java/tv/orbit/classic/CatalogueShadow.kt index 95f36672..9ff5f568 100644 --- a/android/app/src/main/java/tv/orbit/classic/CatalogueShadow.kt +++ b/android/app/src/main/java/tv/orbit/classic/CatalogueShadow.kt @@ -187,8 +187,11 @@ internal object CatalogueShadow { /** What the full-screen player is doing, for background work that must give way to it (9 November 2026). */ internal object PlaybackHealth { @Volatile var playing = false - /** Times playback has stalled to rebuffer after it started, since Orbit opened. */ + /** Times playback has stalled to rebuffer after it started, since Orbit opened; refilling just after a seek isn't counted. */ @Volatile var stalls = 0 + /** When the player last seeked (elapsedRealtime). */ + @Volatile var seekedAt = 0L + const val SEEK_SETTLE_MS = 5_000L } /** diff --git a/android/app/src/main/java/tv/orbit/classic/EmbyPlaybackDialog.kt b/android/app/src/main/java/tv/orbit/classic/EmbyPlaybackDialog.kt index 6af96ccd..a8b36abe 100644 --- a/android/app/src/main/java/tv/orbit/classic/EmbyPlaybackDialog.kt +++ b/android/app/src/main/java/tv/orbit/classic/EmbyPlaybackDialog.kt @@ -250,6 +250,16 @@ internal fun EmbyPlaybackDialog(session: EmbySampleSession, plan: EmbyPlaybackPl format.sampleMimeType, format.channelCount, format.sampleRate, format.language, format.width, format.height)) } val video = tracks.groups.filter { it.type == C.TRACK_TYPE_VIDEO } + // An AVI whose picture Media3 can't even read (DivX 3, found 9 November 2026) comes through as sound alone. + val aviWithoutPicture = video.isEmpty() && tracks.groups.any { it.type == C.TRACK_TYPE_AUDIO } && plan.url.substringBefore('?').endsWith(".avi") + if (scheduled != null && aviWithoutPicture) { + android.util.Log.w("OrbitSchedule", "channel=${scheduled.channel.number} noVideoTrack=avi") + player.stop(); ready = false + Unplayable.note(plan.item.id, plan.item.title, scheduled.channel.number, "This TV can't read the picture in this AVI file.") + onUnplayable?.invoke(plan.item.id) + failure = "This programme won't play on this box. Orbit moves on at ${clock(scheduled.programme.endMs)}." + return + } // Sound with no picture: the box can't decode this file's video. if (scheduled != null && video.isNotEmpty() && video.none { it.isSupported }) { android.util.Log.w("OrbitSchedule", "channel=${scheduled.channel.number} noVideoDecoder=${video.first().getTrackFormat(0).sampleMimeType}") @@ -264,8 +274,12 @@ internal fun EmbyPlaybackDialog(session: EmbySampleSession, plan: EmbyPlaybackPl subtitleChoice(subtitlePreference?.value, audioLanguages(), available.map { it.getTrackFormat(0).language.orEmpty() })?.let { chooseSubtitle(it, available) } } } + override fun onPositionDiscontinuity(oldPosition: Player.PositionInfo, newPosition: Player.PositionInfo, reason: Int) { + if (reason == Player.DISCONTINUITY_REASON_SEEK || reason == Player.DISCONTINUITY_REASON_SEEK_ADJUSTMENT) PlaybackHealth.seekedAt = SystemClock.elapsedRealtime() + } override fun onPlaybackStateChanged(state: Int) { - if (state == Player.STATE_BUFFERING && ready) PlaybackHealth.stalls++ + // A stall is buffering that nobody asked for: refilling after a seek (tuning in, Catch Up, skipping) isn't one. + if (state == Player.STATE_BUFFERING && ready && SystemClock.elapsedRealtime() - PlaybackHealth.seekedAt > PlaybackHealth.SEEK_SETTLE_MS) PlaybackHealth.stalls++ PlaybackHealth.playing = state == Player.STATE_READY || state == Player.STATE_BUFFERING buffering = state == Player.STATE_BUFFERING if (state == Player.STATE_ENDED && scheduled != null) onEndedEarly?.invoke() @@ -311,11 +325,15 @@ internal fun EmbyPlaybackDialog(session: EmbySampleSession, plan: EmbyPlaybackPl override fun onTracksChanged(tracks: Tracks) { if (!PlayerSwitches.frameRate || window == null) return val fps = tracks.groups.firstOrNull { it.type == C.TRACK_TYPE_VIDEO && it.isSelected }?.getTrackFormat(0)?.frameRate ?: return - FrameRateMatch.apply(window, fps) + if (fps > 0) FrameRateMatch.apply(window, fps) } } + // Most files don't state their frame rate (9 November 2026: none of the test MKVs or AVIs did), so it's measured + // from the first frames' timestamps instead, and applied on the main thread. + val probe = FrameRateProbe { fps -> if (PlayerSwitches.frameRate && window != null) android.os.Handler(android.os.Looper.getMainLooper()).post { FrameRateMatch.apply(window, fps) } } player.addListener(matcher) - onDispose { player.removeListener(matcher); window?.let(FrameRateMatch::reset) } + if (PlayerSwitches.frameRate) player.setVideoFrameMetadataListener(probe) + onDispose { player.removeListener(matcher); runCatching { player.clearVideoFrameMetadataListener(probe) }; window?.let(FrameRateMatch::reset) } } val covered = ident != null // Luna's goodnight: the programme fades out beneath her, and back up if a button keeps Orbit on. diff --git a/android/app/src/main/java/tv/orbit/classic/PlayerSwitches.kt b/android/app/src/main/java/tv/orbit/classic/PlayerSwitches.kt index 2470504e..f8603eda 100644 --- a/android/app/src/main/java/tv/orbit/classic/PlayerSwitches.kt +++ b/android/app/src/main/java/tv/orbit/classic/PlayerSwitches.kt @@ -56,3 +56,43 @@ internal object FrameRateMatch { window.attributes = window.attributes.also { it.preferredDisplayModeId = 0 } } } + +/** + * Measures a video's frame rate from the presentation times of its first frames (9 November 2026), for files that don't + * state it. Calls [onRate] once with the rate; called on the playback thread. Timestamps in MKV are often whole + * milliseconds and AVI's can arrive out of order, so it takes about five seconds of frames and works from the span. + */ +@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) +internal class FrameRateProbe(private val onRate: (Float) -> Unit) : androidx.media3.exoplayer.video.VideoFrameMetadataListener { + private val times = ArrayList(FRAMES) + @Volatile private var done = false + override fun onVideoFrameAboutToBeRendered(presentationTimeUs: Long, releaseTimeNs: Long, format: androidx.media3.common.Format, mediaFormat: android.media.MediaFormat?) { + if (done) return + if (times.isNotEmpty() && kotlin.math.abs(presentationTimeUs - times.last()) > 1_000_000L) times.clear() // a seek: start again + times += presentationTimeUs + if (times.size < FRAMES) return + done = true + frameRateFrom(times)?.let(onRate) + } + companion object { + const val FRAMES = 120 + /** The usual video rates; a measurement within 0.03 of one is taken as that rate exactly. */ + private val STANDARD = floatArrayOf(23.976f, 24f, 25f, 29.97f, 30f, 47.952f, 48f, 50f, 59.94f, 60f) + /** + * The rate from frame times in microseconds. The times are sorted; the typical gap (the mean of those near the + * median, so a dropped frame doesn't count) says how many frame intervals the span holds, and the span gives the rate. + */ + fun frameRateFrom(timesUs: List): Float? { + val t = timesUs.distinct().sorted() + val gaps = t.zipWithNext { a, b -> b - a }.filter { it in 4_000L..200_000L }.sorted() + if (gaps.size < 5) return null + val median = gaps[gaps.size / 2] + val typical = gaps.filter { it < median * 1.5 && it > median * 0.5 }.average() + val span = t.last() - t.first() + val intervals = Math.round(span / typical) + if (intervals < 4) return null + val fps = (intervals * 1_000_000.0 / span).toFloat() + return STANDARD.minByOrNull { kotlin.math.abs(it - fps) }?.takeIf { kotlin.math.abs(it - fps) < 0.03f } ?: fps + } + } +} diff --git a/android/app/src/playtest/java/tv/orbit/classic/PlaytestFileActivity.kt b/android/app/src/playtest/java/tv/orbit/classic/PlaytestFileActivity.kt index 6ecc79cd..cc8894e3 100644 --- a/android/app/src/playtest/java/tv/orbit/classic/PlaytestFileActivity.kt +++ b/android/app/src/playtest/java/tv/orbit/classic/PlaytestFileActivity.kt @@ -46,6 +46,7 @@ class PlaytestFileActivity : Activity() { private var retried = false private var reopenedAt = 0L private var finished = false + private var seekedAt = 0L override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -66,7 +67,7 @@ class PlaytestFileActivity : Activity() { if (refusal != null) { result.put("outcome", "refused").put("reason", refusal); end(); return } val view = PlayerView(this).apply { useController = false } setContentView(view) - result.put("modeBefore", modeNow()) + view.post { result.put("modeBefore", modeNow()) } val p = ExoPlayer.Builder(this, programmeRenderers(this)).setLoadControl(programmeLoadControl()) .setMediaSourceFactory(DefaultMediaSourceFactory(DefaultDataSource.Factory(this), OrbitExtractorsFactory())).build() player = p; view.player = p @@ -78,15 +79,19 @@ class PlaytestFileActivity : Activity() { .put("height", f.height).put("fps", f.frameRate.toDouble()).put("decoder", video.isSupported)) } audio?.getTrackFormat(0)?.let { f -> result.put("audio", JSONObject().put("mime", f.sampleMimeType).put("decoder", audio.isSupported)) } if (video != null && !video.isSupported) { result.put("outcome", "no video decoder (as Orbit: unplayable, moves on)"); end(); return } - if (PlayerSwitches.frameRate) video?.getTrackFormat(0)?.frameRate?.let { FrameRateMatch.apply(window, it) } + if (PlayerSwitches.frameRate) video?.getTrackFormat(0)?.frameRate?.takeIf { it > 0 }?.let { FrameRateMatch.apply(window, it) } + if (video == null && audio != null && name.endsWith(".avi")) { result.put("outcome", "no picture track (as Orbit: unplayable, moves on)"); end(); return } main.postDelayed({ result.put("modeDuring", modeNow()) }, 4_000) } override fun onRenderedFirstFrame() { if (!result.has("firstFrameMs")) result.put("firstFrameMs", SystemClock.elapsedRealtime() - startedAt) if (reopenedAt > 0 && !result.has("recoveredMs")) result.put("recoveredMs", SystemClock.elapsedRealtime() - reopenedAt) } + override fun onPositionDiscontinuity(oldPosition: Player.PositionInfo, newPosition: Player.PositionInfo, reason: Int) { + if (reason == Player.DISCONTINUITY_REASON_SEEK || reason == Player.DISCONTINUITY_REASON_SEEK_ADJUSTMENT) seekedAt = SystemClock.elapsedRealtime() + } override fun onPlaybackStateChanged(state: Int) { - if (state == Player.STATE_BUFFERING && ready) stalls++ + if (state == Player.STATE_BUFFERING && ready && SystemClock.elapsedRealtime() - seekedAt > PlaybackHealth.SEEK_SETTLE_MS) stalls++ if (state == Player.STATE_READY) ready = true } override fun onPlayerError(error: PlaybackException) { @@ -95,10 +100,12 @@ class PlaytestFileActivity : Activity() { else { result.put("outcome", "failed after one retry"); end() } } }) + // As Orbit does: the frame rate measured from the first frames when the file doesn't state it. + p.setVideoFrameMetadataListener(FrameRateProbe { fps -> main.post { result.put("measuredFps", fps.toDouble()); if (PlayerSwitches.frameRate) FrameRateMatch.apply(window, fps) } }) startedAt = SystemClock.elapsedRealtime() p.setMediaItem(MediaItem.fromUri(Uri.fromFile(file))); p.prepare(); p.play() main.postDelayed({ p.seekTo(40_000) }, 8_000) - main.postDelayed({ val at = p.currentPosition; ready = false; p.stop(); reopenedAt = SystemClock.elapsedRealtime(); p.seekTo(at); p.prepare(); p.play() }, 16_000) + main.postDelayed({ val at = p.currentPosition; ready = false; seekedAt = SystemClock.elapsedRealtime(); p.stop(); reopenedAt = SystemClock.elapsedRealtime(); p.seekTo(at); p.prepare(); p.play() }, 16_000) main.postDelayed({ if (!result.has("outcome")) result.put("outcome", if (result.has("recoveredMs")) "played" else "played, but didn't recover after reopening"); end() }, 26_000) } diff --git a/android/app/src/test/java/tv/orbit/classic/PlayerSwitchesTest.kt b/android/app/src/test/java/tv/orbit/classic/PlayerSwitchesTest.kt index a5dfd591..a1d13e74 100644 --- a/android/app/src/test/java/tv/orbit/classic/PlayerSwitchesTest.kt +++ b/android/app/src/test/java/tv/orbit/classic/PlayerSwitchesTest.kt @@ -46,4 +46,25 @@ class PlayerSwitchesTest { assertEquals("avi", supportedDirectContainer(" AVI ")); assertEquals(true, DirectVideoContainers.endsWith(",avi")) assertEquals("mkv", supportedDirectContainer("mkv")) } + + @Test fun measuresTheFrameRateFromFrameTimes() { + // Whole milliseconds, as MKV stores them (the test clips measured 23.81 with the first, median-only version). + fun times(fps: Double, n: Int = 120) = (0 until n).map { Math.round(it * 1_000.0 / fps) * 1_000L } + assertEquals(23.976f, FrameRateProbe.frameRateFrom(times(24_000.0 / 1001))!!, 0.002f) + assertEquals(24f, FrameRateProbe.frameRateFrom(times(24.0))!!, 0.002f) + assertEquals(25f, FrameRateProbe.frameRateFrom(times(25.0))!!, 0.002f) + assertEquals(59.94f, FrameRateProbe.frameRateFrom(times(60_000.0 / 1001))!!, 0.01f) + // A dropped frame doesn't move it, and the measured 23.976 still picks the TV's 23.976 mode, not 24. + val dropped = times(24_000.0 / 1001).filterIndexed { i, _ -> i != 10 } + assertEquals(855, FrameRateMatch.pick(tv, at60, FrameRateProbe.frameRateFrom(dropped)!!)) + assertNull(FrameRateProbe.frameRateFrom(listOf(0L, 40_000L))) + // AVI's H.264 arrives out of order: the same rate once sorted. + assertEquals(25f, FrameRateProbe.frameRateFrom(times(25.0).chunked(3).flatMap { it.reversed() })!!, 0.002f) + assertEquals(29.97f, FrameRateProbe.frameRateFrom(times(30_000.0 / 1001))!!, 0.002f) + } + + @Test fun divx3IsNeverTakenForMpeg4() { + assertEquals("video/x-ms-mpeg4", videoMimeFor("msmpeg4v3")) + assertEquals("video/mp4v-es", videoMimeFor("xvid")) + } } diff --git a/docs/INSTALL-0.123.0-PROCEDURE.md b/docs/INSTALL-0.123.0-PROCEDURE.md index f029bd46..c95e4242 100644 --- a/docs/INSTALL-0.123.0-PROCEDURE.md +++ b/docs/INSTALL-0.123.0-PROCEDURE.md @@ -150,3 +150,27 @@ Watching the same title on another airing or another day is a separate viewing, - **Tests:** release gate passed, with 1,126 tests (6 new ones for these rules). - **Caution for installing:** while the two TVs run different versions, Rooms sync on the older TV drops the new caught-end events and fields it doesn't recognise. So Stage 2 should go onto both TVs close together. + +## 8. Results (9 November afternoon) +- **Recovery rehearsal** (test app, downstairs). Going back to an older version was refused with + `INSTALL_FAILED_VERSION_DOWNGRADE`, and nothing changed. The fix-forward (version 390) then installed over it: + the install date and the data file were identical afterwards. The Orbit fix-forward is + `apks/orbit-tv-0.122.1-fixforward.apk`: 0.122.1's exact code at version 390. +- **0.123.0 installed downstairs at 15:28** (tools/install-tv.sh). The comparison came back UNCHANGED: + 2,370 bookings kept and 17 added, and 12,083 planned programmes unchanged. + - Smoke test passed: Home, guide, tuning a channel, Catch Up, Arcade and Companion. + - All switches off. One copy of Orbit running, and no crashes. +- **First AVI and frame-rate test run:** it found three problems, all in code that's switched off or in the test app. + - None of the clips states its frame rate, so matching never switched. + - Refilling after a seek counted as a stall. This affects tonight: the comparison would have stopped after three channel tunes. + - DivX 3 played as sound with no picture. +- **0.123.1** (versionCode 316) fixes all three: + - The frame rate is measured from about five seconds of frames, and snapped to the standard rates. + - Buffering within 5 s of a seek isn't a stall. + - An AVI with no picture track, or Microsoft MPEG-4 / DivX 3, is unplayable and skipped. +- **Third test run, all as intended** (`audits/playtest-20261109-1617/`): + - 23.976 switched the TV to 23.976 Hz, 24 to 24 Hz, and 25 and 50 to 50 Hz. 29.97 and 59.94 stayed at 59.94, which + already fits. With the switch off, nothing changed. The TV always went back to 59.94 afterwards. + - Each AVI was refused with the switch off. With it on, XviD+MP3, DivX 5+AC3 and H.264+MP3 played and recovered + after reopening, and DivX 3 was reported unplayable. + - No stalls. No errors. Reopening recovered within 0.2 to 1.2 s. diff --git a/tools/playtest-run.sh b/tools/playtest-run.sh index 9a8a560a..049ff53e 100755 --- a/tools/playtest-run.sh +++ b/tools/playtest-run.sh @@ -17,7 +17,7 @@ for f in "$MEDIA"/fps-*.mkv "$MEDIA"/avi-*.avi; do $A -s $D shell am start -W -n tv.orbit.classic.playtest/tv.orbit.classic.PlaytestFileActivity --es file "$n" --es $sw $state >/dev/null sleep 33 $A -s $D pull "$DIR/results/$n.json" "$OUT/${n%.*}-$sw-$state.json" >/dev/null 2>&1 - python3 -c "import json,sys; r=json.load(open(sys.argv[1])); v=r.get('video',{}); print(f\"{sys.argv[2]:<28} {r.get('outcome')}; fps {v.get('fps')}; decoder {v.get('decoder')}; mode {r.get('modeBefore')} > {r.get('modeDuring')} > {r.get('modeAfter')}; first frame {r.get('firstFrameMs')} ms; recovered {r.get('recoveredMs')} ms; stalls {r.get('stalls')}; errors {r.get('errors')}\")" "$OUT/${n%.*}-$sw-$state.json" "$n $sw=$state" 2>/dev/null | tee -a "$OUT/summary.txt" || echo "$n $sw=$state: no result" | tee -a "$OUT/summary.txt" + python3 -c "import json,sys; r=json.load(open(sys.argv[1])); v=r.get('video',{}); print(f\"{sys.argv[2]:<28} {r.get('outcome')}; fps {v.get('fps')} measured {r.get('measuredFps')}; decoder {v.get('decoder')}; mode {r.get('modeBefore')} > {r.get('modeDuring')} > {r.get('modeAfter')}; first frame {r.get('firstFrameMs')} ms; recovered {r.get('recoveredMs')} ms; stalls {r.get('stalls')}; errors {r.get('errors')}\")" "$OUT/${n%.*}-$sw-$state.json" "$n $sw=$state" 2>/dev/null | tee -a "$OUT/summary.txt" || echo "$n $sw=$state: no result" | tee -a "$OUT/summary.txt" done done $A -s $D shell rm -r "$DIR" >/dev/null