From 51db35d0c9eeb5fd7f6bd6f91297612617e7bd77 Mon Sep 17 00:00:00 2001 From: Pauljd Date: Tue, 10 Nov 2026 16:17:13 +0000 Subject: [PATCH] Stage 0 (0.129): local, optional timings for screens, keys and tuning OrbitTiming: off unless switched on by adb on a household TV (--es orbit_timing on|off|clear); kept on the TV only, as OrbitTiming log lines and timing/timing.jsonl. Screen names, key codes, channel numbers and milliseconds only. Play never has the switch (check_editions refuses orbit_timing in Play). Co-Authored-By: Claude Opus 5.5 --- .../java/tv/orbit/classic/Edition.kt | 2 + .../java/tv/orbit/classic/DirectorChair.kt | 2 +- .../tv/orbit/classic/EmbyPlaybackDialog.kt | 10 +- .../java/tv/orbit/classic/MainActivity.kt | 8 ++ .../main/java/tv/orbit/classic/OrbitTiming.kt | 118 ++++++++++++++++++ .../main/java/tv/orbit/classic/Settings.kt | 2 + tools/check_editions.py | 2 +- 7 files changed, 141 insertions(+), 3 deletions(-) create mode 100644 android/app/src/main/java/tv/orbit/classic/OrbitTiming.kt diff --git a/android/app/src/household/java/tv/orbit/classic/Edition.kt b/android/app/src/household/java/tv/orbit/classic/Edition.kt index da66a5de..e676be65 100644 --- a/android/app/src/household/java/tv/orbit/classic/Edition.kt +++ b/android/app/src/household/java/tv/orbit/classic/Edition.kt @@ -28,6 +28,8 @@ internal object Edition { intent?.getStringExtra("orbit_even_volume")?.let { PlayerSwitches.setEvenVolume(activity, it) } when (intent?.getStringExtra("orbit_avi")) { "on" -> PlayerSwitches.setAvi(activity, true); "off" -> PlayerSwitches.setAvi(activity, false) } if (intent?.getBooleanExtra("orbit_shadow_catalogue_stop", false) == true) CatalogueShadow.cancel = true + // Timings (0.129 stage 0): on, off or clear; local only. + intent?.getStringExtra("orbit_timing")?.let { OrbitTiming.set(activity, it) } if (intent?.hasExtra("orbit_shadow_from") == true) CatalogueShadow.from = intent.getLongExtra("orbit_shadow_from", 0L).coerceAtLeast(0L) if (intent?.getBooleanExtra("orbit_shadow_resume", false) == true) CatalogueShadow.resume = true if (intent?.hasExtra("orbit_shadow_catalogue") == true) CatalogueShadow.pending = intent.getIntExtra("orbit_shadow_catalogue", 5) diff --git a/android/app/src/main/java/tv/orbit/classic/DirectorChair.kt b/android/app/src/main/java/tv/orbit/classic/DirectorChair.kt index 18c695e3..bde1cb7b 100644 --- a/android/app/src/main/java/tv/orbit/classic/DirectorChair.kt +++ b/android/app/src/main/java/tv/orbit/classic/DirectorChair.kt @@ -410,7 +410,7 @@ internal fun DirectorChair(load: (DirectorMode) -> DeskReport?, first: FocusRequ var lesson by remember { mutableStateOf(null) } var eventOpen by remember { mutableStateOf(null) } val scope = rememberCoroutineScope() - LaunchedEffect(mode, version) { withContext(Dispatchers.Default) { runCatching { load(mode) }.getOrNull() }?.let { report = it } } + LaunchedEffect(mode, version) { withContext(Dispatchers.Default) { runCatching { load(mode) }.getOrNull() }?.let { report = it; OrbitTiming.ready("Director's Chair") } } Column(modifier, verticalArrangement = Arrangement.spacedBy(8.dp)) { Row(verticalAlignment = androidx.compose.ui.Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { Text("DIRECTOR'S CHAIR", color = ChairGold, fontFamily = Anton, fontSize = 20.sp) 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 8354d7e2..45120717 100644 --- a/android/app/src/main/java/tv/orbit/classic/EmbyPlaybackDialog.kt +++ b/android/app/src/main/java/tv/orbit/classic/EmbyPlaybackDialog.kt @@ -121,6 +121,11 @@ internal fun EmbyPlaybackDialog(session: EmbySampleSession, plan: EmbyPlaybackPl setMediaItem(channelMediaItem(plan)) if (scheduled != null) seekTo(scheduled.programme.offsetAt(scheduled.nowMs())) trackSelectionParameters = trackSelectionParameters.buildUpon().setPreferredAudioLanguage(audioPreference?.value ?: "en").build() + OrbitTiming.tune(scheduled?.channel?.number) + if (OrbitTiming.on) addAnalyticsListener(object : androidx.media3.exoplayer.analytics.AnalyticsListener { + @androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) + override fun onAudioPositionAdvancing(eventTime: androidx.media3.exoplayer.analytics.AnalyticsListener.EventTime, playoutStartSystemTimeMs: Long) = OrbitTiming.firstSound() + }) prepare(); playWhenReady = !holdStart } } @@ -248,7 +253,7 @@ internal fun EmbyPlaybackDialog(session: EmbySampleSession, plan: EmbyPlaybackPl ready = false } override fun onIsPlayingChanged(isPlaying: Boolean) { playing = isPlaying } - override fun onRenderedFirstFrame() { onFirstFrame?.invoke() } + override fun onRenderedFirstFrame() { OrbitTiming.firstFrame(); onFirstFrame?.invoke() } override fun onTracksChanged(tracks: Tracks) { tracks.groups.filter { it.isSelected && (it.type == C.TRACK_TYPE_AUDIO || it.type == C.TRACK_TYPE_VIDEO) }.forEach { group -> val format = (0 until group.length).firstOrNull(group::isTrackSelected)?.let(group::getTrackFormat) ?: return@forEach @@ -285,6 +290,7 @@ internal fun EmbyPlaybackDialog(session: EmbySampleSession, plan: EmbyPlaybackPl 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_READY && !ready) OrbitTiming.prepared() // 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) { val sinceSeek = SystemClock.elapsedRealtime() - PlaybackHealth.seekedAt @@ -345,6 +351,7 @@ internal fun EmbyPlaybackDialog(session: EmbySampleSession, plan: EmbyPlaybackPl // back to the TV's own choice when the programme closes. Full screen is a dialog window over the activity, so the // preference is set on both: Android takes it from the window on top. val dialogWindow = (androidx.compose.ui.platform.LocalView.current.parent as? androidx.compose.ui.window.DialogWindowProvider)?.window + LaunchedEffect(dialogWindow) { OrbitTiming.watch(dialogWindow) } DisposableEffect(player) { val windows = listOfNotNull(dialogWindow, generateSequence(context) { (it as? android.content.ContextWrapper)?.baseContext }.filterIsInstance().firstOrNull()?.window) fun match(fps: Float) = windows.forEach { FrameRateMatch.apply(it, fps) } @@ -422,6 +429,7 @@ internal fun EmbyPlaybackDialog(session: EmbySampleSession, plan: EmbyPlaybackPl PlayerView(nativeContext).apply { useController = false setOnKeyListener { _, code, event -> + if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) OrbitTiming.key(code) val isOk = code == KeyEvent.KEYCODE_DPAD_CENTER || code == KeyEvent.KEYCODE_ENTER val typedDigit = if (code in KeyEvent.KEYCODE_0..KeyEvent.KEYCODE_9) code - KeyEvent.KEYCODE_0 else null // The sleep timer's last minute: any button keeps you watching, and does nothing else. diff --git a/android/app/src/main/java/tv/orbit/classic/MainActivity.kt b/android/app/src/main/java/tv/orbit/classic/MainActivity.kt index 31e9c772..b31f8aaa 100644 --- a/android/app/src/main/java/tv/orbit/classic/MainActivity.kt +++ b/android/app/src/main/java/tv/orbit/classic/MainActivity.kt @@ -66,15 +66,22 @@ class MainActivity : ComponentActivity() { * opens as one copy (singleTask, 8 November 2026), also when adb sends them to an Orbit already open. */ private fun readAdbRequests(intent: android.content.Intent?) = Edition.readAdbRequests(this, intent) + override fun dispatchKeyEvent(event: android.view.KeyEvent): Boolean { + if (event.action == android.view.KeyEvent.ACTION_DOWN && event.repeatCount == 0) OrbitTiming.key(event.keyCode) + return super.dispatchKeyEvent(event) + } override fun onNewIntent(intent: android.content.Intent) { super.onNewIntent(intent); setIntent(intent); readAdbRequests(intent) } override fun onCreate(savedInstanceState: Bundle?) { // A restore confirmed on the phone's backup is put in place first, before anything here reads the data. PhoneBackups.finishAtStart(this) + // Timings (0.129 stage 0): off unless switched on by adb on a household TV; kept on this TV only. + OrbitTiming.load(this) OrbitScreen.open = true OrbitCompanion.activity = java.lang.ref.WeakReference(this) super.onCreate(savedInstanceState) tv.orbit.classic.ArcadeProgress.init(this) window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + OrbitTiming.watch(window) Motion.load(OrbitSettings(this)) // The guide's logos, decoded ahead on a background thread so the guide opens with them ready. Thread({ Pictures.warmLogos(resources) }, "orbit-logos").apply { priority = Thread.MIN_PRIORITY }.start() @@ -133,6 +140,7 @@ private fun NavItem(label: String, selected: Boolean, focus: FocusRequester?, be private fun OrbitApp() { var realChannelAvailable by remember { mutableStateOf(false) } var section by remember { mutableStateOf("Home") } + LaunchedEffect(section) { OrbitTiming.screen(section) } var restoreChecked by remember { mutableStateOf(false) } var playingGame by remember { mutableStateOf(false) } // With nothing to watch yet, the only place to be is signing in or choosing channels. diff --git a/android/app/src/main/java/tv/orbit/classic/OrbitTiming.kt b/android/app/src/main/java/tv/orbit/classic/OrbitTiming.kt new file mode 100644 index 00000000..9abe22bb --- /dev/null +++ b/android/app/src/main/java/tv/orbit/classic/OrbitTiming.kt @@ -0,0 +1,118 @@ +package tv.orbit.classic + +import android.app.Activity +import android.content.Context +import android.os.Handler +import android.os.HandlerThread +import android.view.FrameMetrics +import android.view.Window +import org.json.JSONObject +import java.io.File +import java.util.concurrent.Executors + +/** + * Orbit's own timings (0.129 stage 0, Paul, 10 November 2026): how long screens, key presses and tuning take, measured on the + * TV and kept on the TV. Off unless switched on, and only the household edition can switch it on (by adb: + * `--es orbit_timing on|off|clear`). Nothing is sent anywhere: lines go to the log as `OrbitTiming` and to a file in Orbit's + * own folder on the TV (timing/timing.jsonl), for adb to pull. Only names of screens, key codes, channel numbers and + * milliseconds are kept: never titles, names, addresses or anything typed. + * + * What it measures, all on the TV's own clock (System.nanoTime): + * - `key`: a remote key pressed, to the end of the next frame drawn after it (the screen's answer to the press). + * - `screen`: a screen opened (from the key press that opened it, when there was one), to the end of its first frame. + * - `ready`: a screen that loads first (Director's Chair), from opening to its content shown. + * - `tune`, `firstFrame`, `firstSound`: a programme asked for, its player ready, its first picture, its sound starting. + * - `frames`: once a minute, frames drawn, frames over 16.7 ms and over 33 ms, the slowest, and the memory in use. + */ +internal object OrbitTiming { + private const val KEY = "timing_log" + @Volatile var on = false + private set + private var file: File? = null + private val writer = Executors.newSingleThreadExecutor { Thread(it, "orbit-timing").apply { isDaemon = true } } + private var frameThread: HandlerThread? = null + private val watched = java.util.Collections.newSetFromMap(java.util.WeakHashMap()) + + // What's waiting for its frame. + @Volatile private var keyAt = 0L + @Volatile private var keyCode = 0 + @Volatile private var screen: Pair? = null + private val opened = java.util.concurrent.ConcurrentHashMap() + @Volatile private var tuneAt = 0L + @Volatile private var tuneChannel: Int? = null + // The minute's frames. + private var frames = 0; private var over16 = 0; private var over33 = 0; private var slowest = 0.0; private var minuteAt = 0L + + /** Whatever a key press set going is measured from the press, if it was in the last second. */ + private fun startFrom(now: Long) = keyAt.takeIf { it > 0 && now - it < 1_000_000_000L } ?: now + + fun load(context: Context) { + on = context.getSharedPreferences("orbit_settings", Context.MODE_PRIVATE).getBoolean(KEY, false) + file = File(context.getExternalFilesDir(null), "timing/timing.jsonl") + } + + /** The household edition's adb switch: on, off, or clear (removes what's been kept). */ + fun set(activity: Activity, value: String) { + when (value) { + "on" -> { on = true; activity.getSharedPreferences("orbit_settings", Context.MODE_PRIVATE).edit().putBoolean(KEY, true).apply(); watch(activity.window) } + "off" -> { on = false; activity.getSharedPreferences("orbit_settings", Context.MODE_PRIVATE).edit().putBoolean(KEY, false).apply() } + "clear" -> writer.execute { file?.delete() } + } + android.util.Log.i("OrbitTiming", "switch $value") + } + + /** Counts [window]'s frames while timing is on (the main window, and the full-screen programme's own window). */ + fun watch(window: Window?) { + if (!on || window == null || !watched.add(window)) return + val thread = frameThread ?: HandlerThread("orbit-frames").also { it.start(); frameThread = it } + runCatching { window.addOnFrameMetricsAvailableListener({ _, metrics, _ -> frame(metrics) }, Handler(thread.looper)) } + } + + private fun frame(metrics: FrameMetrics) { + if (!on) return + val start = metrics.getMetric(FrameMetrics.INTENDED_VSYNC_TIMESTAMP) + val total = metrics.getMetric(FrameMetrics.TOTAL_DURATION) + val end = start + total + val ms = total / 1_000_000.0 + frames++; if (ms > 16.7) over16++; if (ms > 33.4) over33++; if (ms > slowest) slowest = ms + val k = keyAt + if (k in 1 until start) { keyAt = 0; if (end - k < 2_000_000_000L) record("key", (end - k) / 1e6, JSONObject().put("code", keyCode)) } + screen?.let { (name, from) -> if (from < end) { screen = null; record("screen", (end - from) / 1e6, JSONObject().put("screen", name)) } } + val now = System.nanoTime() + if (minuteAt == 0L) minuteAt = now + if (now - minuteAt >= 60_000_000_000L) { + val rt = Runtime.getRuntime() + record("frames", slowest, JSONObject().put("frames", frames).put("over16ms", over16).put("over33ms", over33) + .put("heapMb", (rt.totalMemory() - rt.freeMemory()) / 1_048_576)) + frames = 0; over16 = 0; over33 = 0; slowest = 0.0; minuteAt = now + } + } + + fun key(code: Int) { if (on) { keyAt = System.nanoTime(); keyCode = code } } + /** A screen opened: [name] is a section's own name, never anything from the library. */ + fun screen(name: String) { if (on) { val now = System.nanoTime(); screen = name to startFrom(now); opened[name] = startFrom(now) } } + /** A screen that loads first has its content showing. */ + fun ready(name: String) { if (!on) return; opened.remove(name)?.let { record("ready", (System.nanoTime() - it) / 1e6, JSONObject().put("screen", name)) } } + + fun tune(channel: Int?) { if (on) { tuneAt = startFrom(System.nanoTime()); tuneChannel = channel } } + fun prepared() { since("ready") } + fun firstFrame() { since("firstFrame") } + fun firstSound() { since("firstSound") } + private fun since(kind: String) { + if (!on || tuneAt == 0L) return + record(kind, (System.nanoTime() - tuneAt) / 1e6, JSONObject().put("channel", tuneChannel ?: JSONObject.NULL)) + if (kind == "firstSound") tuneAt = 0L + } + + private fun record(kind: String, ms: Double, detail: JSONObject) { + val line = detail.put("at", System.currentTimeMillis()).put("kind", kind).put("ms", Math.round(ms * 10) / 10.0).toString() + android.util.Log.i("OrbitTiming", line) + val target = file ?: return + writer.execute { runCatching { + target.parentFile?.mkdirs() + // Kept small: a long evening is a few thousand lines; past 5 MB the oldest half goes. + if (target.length() > 5_000_000) target.writeText(target.readLines().let { it.drop(it.size / 2) }.joinToString("\n", postfix = "\n")) + target.appendText(line + "\n") + } } + } +} diff --git a/android/app/src/main/java/tv/orbit/classic/Settings.kt b/android/app/src/main/java/tv/orbit/classic/Settings.kt index eafee8a9..f76e9b49 100644 --- a/android/app/src/main/java/tv/orbit/classic/Settings.kt +++ b/android/app/src/main/java/tv/orbit/classic/Settings.kt @@ -533,6 +533,8 @@ internal fun SettingsScreen(section: SettingsSection, onSection: (SettingsSectio var made by remember { mutableStateOf(null) } var opened by remember { mutableStateOf(null) } LaunchedEffect(section) { opened = null } + // Stage 0 timings (0.129): each Settings page, and the Chair and New arrivals opening in place of the list. + LaunchedEffect(section, opened) { OrbitTiming.screen("Settings/" + (opened?.name ?: section.name)) } val listFirst = remember { FocusRequester() } val firstFocus = remember { FocusRequester() } val firstSwitch = remember { FocusRequester() } diff --git a/tools/check_editions.py b/tools/check_editions.py index 3f555da4..ce6242a2 100644 --- a/tools/check_editions.py +++ b/tools/check_editions.py @@ -74,7 +74,7 @@ if "android.permission.REQUEST_INSTALL_PACKAGES" not in editions["household APK" forbidden = [b"android/content/pm/PackageInstaller", b"RoomUpdates", b"ROOM_UPDATE", b"/room/orbit.apk", b"InstallSnapshotReceiver", b"INSTALL_SNAPSHOT", b"PlaybackTestActivity", b"orbit_play_test", b"orbit_shadow_catalogue", b"orbit_provider_catalogue", - b"orbit_frame_rate", b"orbit_avi", b"PlaytestFileActivity", b"playtest-approved", b"appboxmanager"] + b"orbit_frame_rate", b"orbit_avi", b"orbit_timing", b"PlaytestFileActivity", b"playtest-approved", b"appboxmanager"] for label, path in (("Play APK", play_apk), ("Play bundle", play_aab)): found = [f.decode() for f in forbidden if f in dex(path)] if found: problems.append(f"{label} contains: {', '.join(found)}")