Multiroom auto-scan, and the channel matching comes across (0.108.53)

Paul, after the first real join:
- A set-up Orbit can be found on the Wi-Fi whenever it's open (NSD), and a new TV that
  picks it knocks: the chosen TV shows its code over whatever's on, then Allow (with the
  Adult PIN). One knock every 20 seconds; Not now, Back or five minutes end it.
- Each lit channel's pool ("here's where everything goes") travels compressed with the
  channels, and seedLoop uses a fresh cached pool, so the new room plans without reading
  the library again.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-11-06 12:18:18 +00:00
co-authored by Claude Opus 5.5
parent b6fb7c2d5b
commit 5b85a24998
9 changed files with 193 additions and 19 deletions
@@ -243,6 +243,9 @@ internal class ChannelScheduler(private val store: ScheduleStore,
/** Starts a channel that has no loop yet: reads its pool, then gives it a small fallback made from that pool. */
fun seedLoop(session: EmbySampleSession, userId: String, programming: ChannelProgramming, checkActive: () -> Unit = {}): SampleChannel {
val choices = store.loadChoices(userId, programming.number)
// A fresh pool already on the box (from another room, or turned on before) needs no reading of the library.
store.loadPool(userId, programming.number)?.takeIf { clock() - it.fetchedAtMs < POOL_REFRESH_MS && it.signature == "${programming.signature}#${choices.tag}" }
?.let { cached -> loopFromPool(cached.series, programming)?.let { return it } }
val read = session.readChannelPool(programming, null, choices, checkActive)
val loop = loopFromPool(read.series, programming) ?: throw EmbyCheckException("None of ${programming.name}'s shows were found with episodes to schedule.")
store.savePool(userId, programming.number, ScheduleStore.SavedPool(read.series, clock(), "${programming.signature}#${choices.tag}"))
@@ -62,9 +62,9 @@ internal class HttpsEmbyTransport(internal val deviceId: String = UUID.randomUUI
}
/** The sign-in headers for this kind of server. */
internal fun authHeaders(token: String?): Map<String, String> = when (kind) {
ServerKind.Emby -> mapOf("X-Emby-Authorization" to "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.52\"") +
ServerKind.Emby -> mapOf("X-Emby-Authorization" to "Emby Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.53\"") +
(token?.let { mapOf("X-Emby-Token" to it) } ?: emptyMap())
ServerKind.Jellyfin -> mapOf("Authorization" to "MediaBrowser Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.52\"" +
ServerKind.Jellyfin -> mapOf("Authorization" to "MediaBrowser Client=\"Orbit TV\", Device=\"Orbit TV\", DeviceId=\"$deviceId\", Version=\"0.108.53\"" +
(token?.let { ", Token=\"$it\"" } ?: ""))
}
/** One picture from the provider, or nothing. Same fixed origin and no redirects, and failures are never shown or logged. */
@@ -44,8 +44,12 @@ internal val Barlow = FontFamily(Font(R.font.barlow_regular), Font(R.font.barlow
internal fun clock(time: Long) = SimpleDateFormat("HH:mm", Locale.UK).format(Date(time))
class MainActivity : ComponentActivity() {
override fun onStart() { super.onStart(); if (PhoneLink.phones.isNotEmpty()) PhoneLink.start() }
override fun onStop() { PhoneLink.stop(); super.onStop() }
override fun onStart() {
super.onStart(); if (PhoneLink.phones.isNotEmpty()) PhoneLink.start()
// Multiroom auto-scan: a set-up Orbit can be found by a new TV while it's open.
if (Onboarding.done(this)) RoomBeacon.on(this)
}
override fun onStop() { RoomBeacon.off(this); PhoneLink.offerRoom(null); PhoneLink.stop(); super.onStop() }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
@@ -211,6 +215,8 @@ private fun OrbitApp() {
// Full screen draws its own, over the programme.
if (SleepTimer.warning && !FullScreen.active) SleepWarning(Modifier.align(Alignment.TopCenter).padding(top = 64.dp))
if (SleepTimer.goodnight && !FullScreen.active) LunaGoodnight()
// A new TV joining (Multiroom auto-scan), over everything else.
RoomKnockOverlay()
}
}
}
@@ -63,7 +63,17 @@ internal object PhoneLink {
@Volatile var handler: PhoneHandler? = null
/** Multiroom: the room being added, answered at /room/ while Settings shows its code. */
@Volatile var roomOffer: RoomOffer? = null
fun offerRoom(offer: RoomOffer?) { roomOffer = offer; if (offer != null) start() else if (phones.isEmpty() && pairing == null) stop() }
/** The same offer, for the screen to follow. */
var offerShown by mutableStateOf<RoomOffer?>(null)
private set
fun offerRoom(offer: RoomOffer?) { roomOffer = offer; offerShown = offer; if (offer != null) start() else if (!needed()) stop() }
/** Multiroom auto-scan: while Orbit is open and signed in, a new TV may knock, and this one shows a code. */
@Volatile var knock: ((String) -> RoomOffer?)? = null
@Volatile private var lastKnockMs = 0L
/** Kept running while Orbit is open and can be found by a new room. */
@Volatile var listening = false
set(value) { field = value; if (value) start() else if (!needed()) stop() }
private fun needed() = phones.isNotEmpty() || pairing != null || roomOffer != null || listening
/** Put in front of [handler] for a while: the Welcome Tour's, which saves nothing. */
@Volatile var standIn: PhoneHandler? = null
var pairing by mutableStateOf<Pairing?>(null)
@@ -114,7 +124,7 @@ internal object PhoneLink {
}
fun pairingUrl(p: Pairing): String? = homeAddress()?.let { "http://$it:$PORT/join?k=${p.secret}" }
fun forget(id: String) { prefs().remove(id); loadPhones(); if (phones.isEmpty() && pairing == null) stop() }
fun forget(id: String) { prefs().remove(id); loadPhones(); if (!needed()) stop() }
@Synchronized fun start() {
if (server != null || store == null) return
@@ -180,6 +190,18 @@ internal object PhoneLink {
val input = BufferedInputStream(socket.getInputStream()); val out = socket.getOutputStream()
val r = readRequest(input) ?: return
if (!hostIsAnAddress(r.headers["host"])) return respond(out, 400, "text/plain", "Use the TV's address.".toByteArray())
if (r.path == "/room/knock" && r.method == "POST") {
// A new TV asks to join: this one shows a code, or the one it's already showing. One knock every 20 seconds.
roomOffer?.takeIf { it.state == RoomOffer.State.Waiting && System.currentTimeMillis() < it.untilMs }?.let { return json(out, 200, JSONObject().put("room", Rooms.name)) }
val now = System.currentTimeMillis()
val make = knock ?: return json(out, 404, JSONObject().put("error", "That TV isn't ready to add a room."))
if (now - lastKnockMs < 20_000) return json(out, 429, JSONObject().put("error", "Wait a moment, then try again."))
lastKnockMs = now
val name = runCatching { JSONObject(r.body).optString("name") }.getOrDefault("").trim().take(30).ifBlank { "A new TV" }
val offer = make(name) ?: return json(out, 404, JSONObject().put("error", "That TV isn't ready to add a room."))
offerRoom(offer)
return json(out, 200, JSONObject().put("room", Rooms.name))
}
if (r.path.startsWith("/room/")) {
val offer = roomOffer ?: return json(out, 404, JSONObject().put("error", "That TV isn't adding a room right now."))
val (status, reply) = runCatching { offer.handle(r.method, r.path, r.body) }.getOrElse { 400 to JSONObject() }
@@ -73,7 +73,7 @@ private val LookKeys = listOf("look", "subtitles_on", "channel_logo", "idents",
"cast_on", "drive_in_intro", "reduce_motion")
private val ArcadeKeys = listOf("snake_best", "block_drop_best", "brick_break_best", "pairs_best", "patience_wins", "orb_man_best", "blast_best", "skydoku_solved", "snake_music")
private val DirectorFiles = listOf("director-decisions-0.json", "director-learning-0.json", "event-ideas-history-0.json")
private const val BUNDLE_LIMIT = 4 * 1024 * 1024
private const val BUNDLE_LIMIT = 12 * 1024 * 1024
/** What one box sends another: plain settings and small files, read from the open workspace. Never a password or token. */
internal object RoomBundle {
@@ -94,7 +94,14 @@ internal object RoomBundle {
}
edit.apply()
}
private fun files(dir: File, names: List<String>) = JSONObject().also { o -> names.forEach { n -> File(dir, n).takeIf { it.isFile && it.length() < 1_000_000 }?.let { o.put(n, it.readText()) } } }
private fun files(dir: File, names: List<String>) = JSONObject().also { o -> names.forEach { n -> File(dir, n).takeIf { it.isFile && it.length() < 3_000_000 }?.let { o.put(n, it.readText()) } } }
internal fun gzip(text: String): String = java.io.ByteArrayOutputStream().also { b -> java.util.zip.GZIPOutputStream(b).use { it.write(text.toByteArray()) } }
.toByteArray().let { java.util.Base64.getEncoder().encodeToString(it) }
private fun gunzip(text: String): String = java.util.zip.GZIPInputStream(java.util.Base64.getDecoder().decode(text).inputStream()).use { input ->
val out = java.io.ByteArrayOutputStream(); val buffer = ByteArray(16_384); var total = 0
while (true) { val n = input.read(buffer); if (n < 0) break; total += n; require(total <= 32 * 1024 * 1024); out.write(buffer, 0, n) }
out.toString(Charsets.UTF_8.name())
}
/** This box's set-up, as the existing room sends it. */
fun collect(context: Context, workspace: ServerWorkspace, room: String): JSONObject {
@@ -102,8 +109,11 @@ internal object RoomBundle {
// The channels that are on here; the new room plans its own schedules for them.
val lineup = SmartChannels.map { it.number }.filter { n -> runCatching { JSONObject(File(dir, "progress-$n.json").readText()).optBoolean("enabled") }.getOrDefault(false) }
val choices = dir.listFiles { f -> Regex("choices-\\d+\\.json").matches(f.name) }?.map { it.name }.orEmpty()
// "Here's where everything goes": each channel's matched shows, so the new room plans straight away instead of
// reading the library again. Compressed; the same account's own, checked by the store as it reads them.
val pools = files(dir, lineup.map { "episodes-$it.json" })
return JSONObject().put("version", 1).put("room", room).put("server", workspace.origin)
.put(RoomPart.Channels.name, JSONObject().put("lineup", JSONArray(lineup)).put("files", files(dir, choices + "yours.json")))
.put(RoomPart.Channels.name, JSONObject().put("lineup", JSONArray(lineup)).put("files", files(dir, choices + "yours.json")).put("pools", gzip(pools.toString())))
.put(RoomPart.Family.name, JSONObject().put("profiles", prefsJson(context, "orbit_profiles", null)).put("lock", prefsJson(context, "orbit_lock", listOf("after_dark_salt", "after_dark_pin"))))
.put(RoomPart.Look.name, prefsJson(context, "orbit_settings", LookKeys))
.put(RoomPart.Director.name, files(dir, DirectorFiles))
@@ -125,12 +135,13 @@ internal object RoomBundle {
fun applyToWorkspace(dir: File, bundle: JSONObject, parts: Set<RoomPart>): List<Int> {
dir.mkdirs()
fun write(files: JSONObject?) = files?.keys()?.forEach { n ->
if (Regex("(choices-\\d+|yours|director-decisions-0|director-learning-0|event-ideas-history-0)\\.json").matches(n) && !File(dir, n).exists())
if (Regex("(choices-\\d+|episodes-\\d+|yours|director-decisions-0|director-learning-0|event-ideas-history-0)\\.json").matches(n) && !File(dir, n).exists())
File(dir, n).writeText(files.getString(n))
}
var lineup = emptyList<Int>()
if (RoomPart.Channels in parts) bundle.optJSONObject(RoomPart.Channels.name)?.let { c ->
write(c.optJSONObject("files")); CustomChannels.load(dir)
c.optString("pools").takeIf { it.isNotBlank() }?.let { packed -> runCatching { write(JSONObject(gunzip(packed))) } }
lineup = c.optJSONArray("lineup")?.let { a -> (0 until minOf(a.length(), 200)).map { a.getInt(it) } }.orEmpty()
}
if (RoomPart.Director in parts) write(bundle.optJSONObject(RoomPart.Director.name))
@@ -162,7 +173,7 @@ internal object Rooms {
* The existing room's side: one offer at a time, while Settings › Rooms and phones › Add a room is showing its code. Answers
* the phone link's /room/ requests: hello (keys), proof (the code), and the copy once this TV has allowed it.
*/
internal class RoomOffer(val code: String, val untilMs: Long, private val room: String, private val bundle: () -> JSONObject) {
internal class RoomOffer(val code: String, val untilMs: Long, private val room: String, val knocked: Boolean = false, private val bundle: () -> JSONObject) {
enum class State { Waiting, Asking, Allowed, Refused, Sent, Ended }
var state by mutableStateOf(State.Waiting)
var joining by mutableStateOf<String?>(null)
@@ -223,6 +234,14 @@ internal class RoomJoin(private val call: (method: String, path: String, body: S
var otherRoom: String? = null
private set
/** Asks the other TV to show a code (auto-scan): the room it's in, or why not. */
fun knock(name: String): Result<String> = runCatching {
val (status, text) = call("POST", "/room/knock", JSONObject().put("name", name).toString())
val reply = JSONObject(text)
check(status == 200) { reply.optString("error").ifBlank { "That TV couldn't show a code." } }
reply.optString("room").take(30).also { otherRoom = it }
}
/** Says hello and proves the code; true when the other TV must now allow it. */
fun prove(code: String, name: String): Result<Unit> = runCatching {
val mine = RoomCrypto.publicOf(pair)
@@ -75,6 +75,84 @@ internal class RoomFinder(context: Context) {
fun stop() { listener?.let { runCatching { nsd?.stopServiceDiscovery(it) } }; listener = null }
}
/** This room, findable on the Wi-Fi by its name while Orbit is open (auto-scan), and ready to show a code when a new TV knocks. */
internal object RoomBeacon {
private var registration: NsdManager.RegistrationListener? = null
fun on(context: Context) {
if (registration != null) return
val app = context.applicationContext
PhoneLink.knock = { joining -> RoomOffer(RoomCrypto.code(), System.currentTimeMillis() + OFFER_MS, Rooms.name, knocked = true) { RoomBundle.collect(app, Workspaces.current(app), Rooms.name) }.also { it.joining = joining } }
PhoneLink.listening = true
val nsd = app.getSystemService(Context.NSD_SERVICE) as? NsdManager ?: return
registration = object : NsdManager.RegistrationListener {
override fun onServiceRegistered(info: NsdServiceInfo) {}
override fun onRegistrationFailed(info: NsdServiceInfo, error: Int) {}
override fun onServiceUnregistered(info: NsdServiceInfo) {}
override fun onUnregistrationFailed(info: NsdServiceInfo, error: Int) {}
}.also { runCatching { nsd.registerService(NsdServiceInfo().apply { serviceName = Rooms.name; serviceType = ROOM_SERVICE; port = PhoneLink.PORT }, NsdManager.PROTOCOL_DNS_SD, it) } }
}
fun off(context: Context) {
PhoneLink.knock = null; PhoneLink.listening = false
val nsd = context.applicationContext.getSystemService(Context.NSD_SERVICE) as? NsdManager
registration?.let { r -> runCatching { nsd?.unregisterService(r) } }; registration = null
}
}
/**
* A new TV knocked (auto-scan): wherever this TV is, a card shows the code to enter there, then Allow, with the Adult PIN
* if one is set. Not now, Back or five minutes passing ends it, and nothing is copied.
*/
@Composable
internal fun RoomKnockOverlay() {
val offer = PhoneLink.offerShown?.takeIf { it.knocked } ?: return
val context = LocalContext.current
var asking by remember(offer) { mutableStateOf(false) }
var problem by remember(offer) { mutableStateOf<String?>(null) }
var now by remember { mutableLongStateOf(System.currentTimeMillis()) }
LaunchedEffect(offer) { while (true) { delay(1_000); now = System.currentTimeMillis()
if (offer.state == RoomOffer.State.Waiting && now > offer.untilMs) { PhoneLink.offerRoom(null); return@LaunchedEffect } } }
LaunchedEffect(offer.state) {
when (offer.state) {
RoomOffer.State.Sent -> { offer.joining?.let { Rooms.recordJoined(context, it, System.currentTimeMillis()) }; delay(6_000); PhoneLink.offerRoom(null) }
RoomOffer.State.Refused, RoomOffer.State.Ended -> { delay(3_000); PhoneLink.offerRoom(null) }
else -> {}
}
}
BackHandler { if (asking) asking = false else { offer.refuse(); PhoneLink.offerRoom(null) } }
Box(Modifier.fillMaxSize().background(Navy.copy(alpha = .55f)), contentAlignment = Alignment.Center) {
if (asking) { PinEntry("Enter the Adult PIN to allow it", problem, onDone = { pin ->
if (AfterDarkLock.check(context, pin)) { asking = false; offer.allow() } else problem = "That PIN didn't match."
}, onCancel = { asking = false }); return@Box }
val first = remember { FocusRequester() }
Column(Modifier.width(560.dp).background(Panel, RoundedCornerShape(14.dp)).padding(22.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text("${offer.joining ?: "A new TV"} wants to join", color = Ink, fontFamily = Anton, fontSize = 26.sp)
when (offer.state) {
RoomOffer.State.Waiting -> {
Text("To copy this Orbit's set-up, enter this code on the new TV:", color = Muted, fontSize = 14.sp)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
offer.code.forEach { digit -> Box(Modifier.size(50.dp, 62.dp).background(Navy, RoundedCornerShape(8.dp)), contentAlignment = Alignment.Center) {
Text("$digit", color = Yellow, fontFamily = Anton, fontSize = 32.sp) } }
}
val left = ((offer.untilMs - now) / 1000).coerceAtLeast(0)
Text("Works once, for %d:%02d more. Not expecting this? Choose Not now.".format(left / 60, left % 60), color = Muted, fontSize = 12.sp)
OrbitButton("Not now", Modifier.width(180.dp).focusRequester(first), centred = true) { offer.refuse(); PhoneLink.offerRoom(null) }
}
RoomOffer.State.Asking -> {
Text("It entered the right code. Allow it to copy this Orbit's set-up? Your password never travels.", color = Muted, fontSize = 14.sp, textAlign = TextAlign.Center)
Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
OrbitButton("Allow", Modifier.width(160.dp).focusRequester(first), centred = true) { if (AfterDarkLock.pinSet) { problem = null; asking = true } else offer.allow() }
OrbitButton("Not now", Modifier.width(160.dp), centred = true) { offer.refuse() }
}
}
RoomOffer.State.Allowed -> Text("Sending the set-up…", color = Muted, fontSize = 14.sp)
RoomOffer.State.Sent -> Text("Done: it has this Orbit's set-up. Nothing stays connected.", color = Mint, fontSize = 15.sp, fontWeight = FontWeight.SemiBold)
RoomOffer.State.Refused, RoomOffer.State.Ended -> Text("Nothing was copied.", color = Muted, fontSize = 14.sp)
}
}
LaunchedEffect(offer.state, asking) { runCatching { first.requestFocus() } }
}
}
/** What arrived from the other room, kept until this box has signed in and can put the rest in place. */
internal object RoomArrival {
var bundle by mutableStateOf<JSONObject?>(null)
@@ -182,6 +260,16 @@ internal fun JoinRoomFlow(onJoined: () -> Unit, onBack: () -> Unit) {
var working by remember { mutableStateOf(false) }
val first = remember { FocusRequester() }
LaunchedEffect(phase) { runCatching { first.requestFocus() } }
// Auto-scan: asks the chosen TV to show its code, wherever it is in Orbit.
fun knock() {
val transport = roomTransport(address) ?: return
working = true; note = null
scope.launch {
val answer = withContext(Dispatchers.IO) { RoomJoin(transport).knock("A new TV") }
working = false
answer.onSuccess { room -> roomName = room.ifBlank { roomName }; code = ""; phase = JoinPhase.Code }.onFailure { note = it.message }
}
}
BackHandler { if (phase == JoinPhase.Find) onBack() else { phase = JoinPhase.Find; note = null; code = "" } }
LaunchedEffect(phase, join) {
val j = join ?: return@LaunchedEffect
@@ -200,22 +288,22 @@ internal fun JoinRoomFlow(onJoined: () -> Unit, onBack: () -> Unit) {
note?.let { Text(it, color = Yellow, fontSize = 14.sp) }
when (phase) {
JoinPhase.Find -> {
Text("On the TV that already has Orbit, go to Settings › Rooms and phones › Add a room. It shows up here.", color = Muted, fontSize = 15.sp, textAlign = TextAlign.Center)
Text("Choose the TV to copy. It shows a code to enter here, then asks to allow it.", color = Muted, fontSize = 15.sp, textAlign = TextAlign.Center)
Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
finder.found.forEachIndexed { i, (room, ip) ->
ChoiceCard(room, listOf("Found on your Wi-Fi", ip), Modifier.width(240.dp).then(if (i == 0) Modifier.focusRequester(first) else Modifier)) {
address = ip; roomName = room; note = null; phase = JoinPhase.Code }
address = ip; roomName = room; knock() }
}
}
if (finder.found.isEmpty()) Text("Looking on your Wi-Fi…", color = Muted, fontSize = 13.sp)
if (finder.found.isEmpty()) Text("Looking for Orbit on your Wi-Fi… Make sure Orbit is open on the other TV.", color = Muted, fontSize = 13.sp)
Text("Not listed? Type the address that TV shows, like 192.168.0.20:", color = Muted, fontSize = 13.sp)
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) {
OrbitField(address, { if (it.length <= 15) address = it.filter { c -> c.isDigit() || c == '.' } }, "192.168.0.20", Modifier.width(260.dp).then(if (finder.found.isEmpty()) Modifier.focusRequester(first) else Modifier))
OrbitButton("Next", Modifier.width(140.dp), centred = true, enabled = roomTransport(address) != null) { roomName = null; note = null; phase = JoinPhase.Code }
OrbitButton(if (working) "Asking…" else "Next", Modifier.width(140.dp), centred = true, enabled = roomTransport(address) != null && !working) { roomName = null; knock() }
}
}
JoinPhase.Code -> {
Text("Enter the six digits ${roomName ?: "the other TV"} is showing.", color = Muted, fontSize = 15.sp)
Text("${roomName ?: "The other TV"} is showing a code now. Enter its six digits.", color = Muted, fontSize = 15.sp)
OrbitField(code, { if (it.length <= 6) code = it.filter(Char::isDigit) }, "6 digits", Modifier.width(220.dp).focusRequester(first))
OrbitButton(if (working) "Checking…" else "Join", Modifier.width(200.dp), centred = true, enabled = code.length == 6 && !working) {
val transport = roomTransport(address) ?: return@OrbitButton
@@ -39,7 +39,7 @@ internal class SecureMediaDataSource(private val session: EmbySampleSession) : B
next.instanceFollowRedirects = false
next.connectTimeout = 10_000
next.readTimeout = 20_000
next.setRequestProperty("User-Agent", "OrbitTV/0.108.52")
next.setRequestProperty("User-Agent", "OrbitTV/0.108.53")
next.setRequestProperty("Accept-Encoding", "identity")
session.mediaHeaders(address).forEach { (key, value) -> next.setRequestProperty(key, value) }
if (dataSpec.position != 0L || dataSpec.length != C.LENGTH_UNSET.toLong()) {