From ee9798fe3b88face2fa34f14874770f509c788a5 Mon Sep 17 00:00:00 2001 From: Christophe Besson Date: Mon, 5 Oct 2026 02:29:27 +0200 Subject: feat(cast): music on the TV, the music bar as its remote MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A cast button in Music's toolbar and in the music bar. With a television chosen, each decrypted track goes to the relay with its cover — found as the album card finds it — and plays there as music with its title, artist and album; the bar's play, pause, seek, previous and next drive the receiver, its clock is the receiver's, and the end of a track there moves the queue on. A film or a photo taking the television pauses the bar; stopping the cast carries the track on locally. Photos and tracks now share one path: a whole file sent to the relay in pieces (binary frames on Android, written to disk there), served at /file with byte ranges and its cover at /cover, and loaded as what the relay says it is. cast:image is gone; cast:chromecast:seek is new. Co-Authored-By: Claude Opus 5.5 --- .../app/src/main/assets/bridge/meshbay-bridge.js | 19 +- .../kotlin/org/meshbay/client/bridge/Channels.kt | 3 +- .../kotlin/org/meshbay/client/cast/CastChannels.kt | 50 ++- .../kotlin/org/meshbay/client/cast/CastControl.kt | 38 ++- .../kotlin/org/meshbay/client/cast/CastRelay.kt | 169 ++++++++-- .../kotlin/org/meshbay/client/save/SaveNames.kt | 1 + .../kotlin/org/meshbay/client/CastRelayTest.kt | 68 +++- packages/meshbay-client/src/cast-chromecast.js | 48 ++- packages/meshbay-client/src/cast-relay.js | 154 +++++++-- packages/meshbay-client/src/main.js | 32 +- packages/meshbay-client/src/preload.js | 14 +- .../src/meshbay_hub/static/cast-session.js | 59 +++- .../src/meshbay_hub/static/music-app.js | 3 + .../src/meshbay_hub/static/music-player.js | 212 +++++++++++- .../meshbay-hub/src/meshbay_hub/static/platform.js | 25 +- .../meshbay-hub/src/meshbay_hub/static/style.css | 2 + .../src/meshbay_hub/static/video-player.js | 1 + .../tests/harness/cast_session_probe.py | 166 +++++++-- packages/meshbay-hub/tests/test_android_cast.py | 8 +- packages/meshbay-hub/tests/test_cast_files.py | 372 +++++++++++++++++++++ packages/meshbay-hub/tests/test_cast_photos.py | 240 ------------- 21 files changed, 1275 insertions(+), 409 deletions(-) create mode 100644 packages/meshbay-hub/tests/test_cast_files.py delete mode 100644 packages/meshbay-hub/tests/test_cast_photos.py (limited to 'packages') diff --git a/packages/meshbay-android/app/src/main/assets/bridge/meshbay-bridge.js b/packages/meshbay-android/app/src/main/assets/bridge/meshbay-bridge.js index 21d27df..b71b5e8 100644 --- a/packages/meshbay-android/app/src/main/assets/bridge/meshbay-bridge.js +++ b/packages/meshbay-android/app/src/main/assets/bridge/meshbay-bridge.js @@ -50,6 +50,10 @@ // per 48 KB chunk). Without ArrayBuffer messages, base64 over JSON. const SAVE_WRITE = 1; const CAST_PUSH = 2; + const CAST_FILE = 3; + // A file crosses in pieces this size: big enough to be few, small enough + // that no one message is a burden to the WebView or the bridge. + const FILE_PIECE = 1024 * 1024; const bytesOf = (chunk) => (chunk instanceof Uint8Array ? chunk : ArrayBuffer.isView(chunk) ? new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength) : new Uint8Array(chunk)); @@ -151,7 +155,19 @@ push: (data) => pushSegment(data), stop: () => call('cast:stop'), subtitle: (sub) => call('cast:subtitle', sub), - image: (img) => call('cast:image', { bytes: base64Of(bytesOf(img.bytes)), type: img.type }), + // A whole file — a photo, a track — in pieces: one message the size of a + // lossless track would be the WebView's to refuse. + file: async (f) => { + const bytes = bytesOf(f.bytes); + const cover = f.cover ? { bytes: base64Of(bytesOf(f.cover.bytes)), type: f.cover.type } : null; + await call('cast:file:begin', { type: f.type, size: bytes.length, cover, + title: f.title, artist: f.artist, album: f.album }); + for (let at = 0; at < bytes.length; at += FILE_PIECE) { + const piece = bytes.subarray(at, at + FILE_PIECE); + await (BINARY ? sendBinary(CAST_FILE, 0, piece) : call('cast:file:write', base64Of(piece))); + } + return call('cast:file:end'); + }, finish: () => call('cast:finish'), status: () => call('cast:status'), scan: () => call('cast:scan'), @@ -161,6 +177,7 @@ chromecastDisconnect: () => call('cast:chromecast:disconnect'), chromecastPause: () => call('cast:chromecast:pause'), chromecastPlay: () => call('cast:chromecast:play'), + chromecastSeek: (seconds) => call('cast:chromecast:seek', seconds), } } : {}), // Music is playing: keep the process, the Wi-Fi and the page awake with diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/bridge/Channels.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/bridge/Channels.kt index 7542fa1..f7094a0 100644 --- a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/bridge/Channels.kt +++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/bridge/Channels.kt @@ -63,6 +63,7 @@ class Channels( fun binary(frame: BinaryFrame): Any? = when (frame.channel) { BinaryFrame.SAVE_WRITE -> saves().write(frame.handle, frame.bytes, frame.offset, frame.length) BinaryFrame.CAST_PUSH -> (cast ?: throw Refused("Refused: no such channel")).push(frame.bytes, frame.offset, frame.length) + BinaryFrame.CAST_FILE -> (cast ?: throw Refused("Refused: no such channel")).writeFile(frame.bytes, frame.offset, frame.length) else -> throw Refused("Refused: no such channel") } @@ -72,7 +73,7 @@ class Channels( * they could overtake one another; these run on one thread, in arrival order. */ fun ordered(channel: String) = cast?.ordered(channel) == true - fun ordered(frame: BinaryFrame) = frame.channel == BinaryFrame.CAST_PUSH + fun ordered(frame: BinaryFrame) = frame.channel == BinaryFrame.CAST_PUSH || frame.channel == BinaryFrame.CAST_FILE private fun setLocale(code: String): String { // A code, never text, and only one the package has a catalogue for. diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/CastChannels.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/CastChannels.kt index 6be5d72..edaec67 100644 --- a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/CastChannels.kt +++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/CastChannels.kt @@ -26,8 +26,9 @@ class CastChannels( fun handles(channel: String) = channel.startsWith("cast:") - /** What must reach the relay in the order the page sent it: start, pushes, subtitle, photo, finish, stop. */ - fun ordered(channel: String) = channel in setOf("cast:start", "cast:push", "cast:subtitle", "cast:image", "cast:finish", "cast:stop") + /** What must reach the relay in the order the page sent it: start, pushes, subtitle, a file's pieces, finish, stop. */ + fun ordered(channel: String) = channel in setOf("cast:start", "cast:push", "cast:subtitle", + "cast:file:begin", "cast:file:write", "cast:file:end", "cast:finish", "cast:stop") fun call(channel: String, a: JSONArray): Any? = when (channel) { "cast:start" -> { @@ -38,11 +39,20 @@ class CastChannels( started } "cast:subtitle" -> relay.setSubtitle(a.optJSONObject(0)) - // No foreground service for a photo: the receiver has it once loaded. - "cast:image" -> { + // A whole file — a photo, a track — in pieces. No foreground service + // for one: a photo needs nothing once loaded, and music keeps the page + // alive through its own playback hold. + "cast:file:begin" -> { val o = a.optJSONObject(0) ?: JSONObject() - relay.showImage(Base64.getDecoder().decode(o.optString("bytes", "")), o.optString("type", "")) + val cover = o.optJSONObject("cover") + relay.beginFile(o.optString("type", ""), o.optLong("size", -1), + cover?.optString("bytes", "")?.takeIf { it.isNotEmpty() }?.let { Base64.getDecoder().decode(it) }, + cover?.optString("type", ""), o) } + "cast:file:write" -> { // the base64 path, for a WebView without ArrayBuffer messages + relay.writeFile(Base64.getDecoder().decode(a.optString(0, ""))) + } + "cast:file:end" -> relay.endFile() "cast:push" -> { // the base64 path, for a WebView without ArrayBuffer messages relay.push(Base64.getDecoder().decode(a.optString(0, ""))); true } @@ -56,15 +66,16 @@ class CastChannels( "cast:chromecast:connect" -> { val o = a.optJSONObject(0) ?: JSONObject() val url = relayUrl(o) - reported { control.connect(o.optString("deviceId", ""), url, subtitleFor(url, o), typeOf(url)) } + reported { control.connect(o.optString("deviceId", ""), url, subtitleFor(url, o), fileOf(url), startOf(url, o)) } } "cast:chromecast:reload" -> { val o = a.optJSONObject(0) ?: JSONObject() val url = relayUrl(o) - reported { control.reload(url, subtitleFor(url, o), typeOf(url)) } + reported { control.reload(url, subtitleFor(url, o), fileOf(url), startOf(url, o)) } } "cast:chromecast:pause" -> control.pause() "cast:chromecast:play" -> control.play() + "cast:chromecast:seek" -> control.seek(a.optDouble(0, 0.0)) "cast:chromecast:disconnect" -> control.disconnect() else -> throw Refused("Refused: no such channel") } @@ -84,26 +95,37 @@ class CastChannels( fun push(bytes: ByteArray, offset: Int, length: Int): Boolean { relay.push(bytes, offset, length); return true } + fun writeFile(bytes: ByteArray, offset: Int, length: Int): Boolean = relay.writeFile(bytes, offset, length) + /** * The receiver is only ever pointed at this relay. A URL the page names is - * accepted when it is the relay's own stream or photo, and refused + * accepted when it is the relay's own stream or file, and refused * otherwise — a page cannot use this application to make a television * fetch anything else. */ private fun relayUrl(o: JSONObject): String { val asked = o.optString("mediaUrl", "") val ours = relay.url ?: throw Refused("The cast relay is not running") - if (asked != ours && asked != relay.imageUrl) throw Refused("Refused: not this relay's stream") + if (asked != ours && asked != relay.fileUrl) throw Refused("Refused: not this relay's stream") return asked } - /** The relay's photo is loaded as a picture, anything else as the stream; the page does not say which. */ - private fun typeOf(url: String): String = - if (url == relay.imageUrl) relay.imageType ?: "image/jpeg" else "video/mp4" + /** + * The relay's file is loaded as what the relay says it is — its type, and + * the title, artist, album and cover it was given — and anything else as + * the stream (null here); the page does not say which. + */ + private fun fileOf(url: String): JSONObject? = + if (url != relay.fileUrl) null + else JSONObject().put("contentType", relay.fileType).put("meta", relay.fileMeta() ?: JSONObject()) + + /** Where in a track to begin; a film starts where its relay does. */ + private fun startOf(url: String, o: JSONObject): Double = + if (url == relay.fileUrl) maxOf(0.0, o.optDouble("startAt", 0.0)) else 0.0 - /** As main.js: no subtitle named means the relay's current one; a photo has none. */ + /** As main.js: no subtitle named means the relay's current one; a file has none. */ private fun subtitleFor(url: String, o: JSONObject): JSONObject? = when { - url == relay.imageUrl -> null + url == relay.fileUrl -> null o.has("subtitle") && o.get("subtitle") != JSONObject.NULL -> o.optJSONObject("subtitle") else -> relay.subtitleInfo() } diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/CastControl.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/CastControl.kt index 56a1f5e..0d18a90 100644 --- a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/CastControl.kt +++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/CastControl.kt @@ -2,6 +2,7 @@ package org.meshbay.client.cast import android.content.Context import android.graphics.Color +import android.net.Uri import android.os.Handler import android.os.Looper import android.util.Log @@ -11,6 +12,8 @@ import com.google.android.gms.cast.CastMediaControlIntent import com.google.android.gms.cast.MediaInfo import com.google.android.gms.cast.MediaLoadRequestData import com.google.android.gms.cast.MediaMetadata +import com.google.android.gms.cast.MediaSeekOptions +import com.google.android.gms.common.images.WebImage import com.google.android.gms.cast.MediaStatus import com.google.android.gms.cast.MediaTrack import com.google.android.gms.cast.TextTrackStyle @@ -112,7 +115,7 @@ class CastControl(private val context: Context) { } /** Connect, launch the default receiver, load; answers once the receiver has. */ - fun connect(deviceId: String, mediaUrl: String, subtitle: JSONObject?, contentType: String = "video/mp4"): JSONObject { + fun connect(deviceId: String, mediaUrl: String, subtitle: JSONObject?, file: JSONObject? = null, startAt: Double = 0.0): JSONObject { need() val session = onMain { val cast = CastContext.getSharedInstance(context) @@ -168,7 +171,7 @@ class CastControl(private val context: Context) { // device's name included: read it there, never from this worker. val name = deviceName ?: onMain { session.castDevice?.friendlyName } Log.i(TAG, "session up on '$name', loading the relay stream") - val state = load(session, mediaUrl, subtitle, contentType) + val state = load(session, mediaUrl, subtitle, file, startAt) watch(session) return JSONObject().put("deviceName", name ?: JSONObject.NULL).put("playerState", state) } @@ -201,23 +204,41 @@ class CastControl(private val context: Context) { watched = c } - fun reload(mediaUrl: String, subtitle: JSONObject?, contentType: String = "video/mp4"): JSONObject { + fun reload(mediaUrl: String, subtitle: JSONObject?, file: JSONObject? = null, startAt: Double = 0.0): JSONObject { need() val session = onMain { CastContext.getSharedInstance(context).sessionManager.currentCastSession } ?: throw Refused("Not connected") - val state = load(session, mediaUrl, subtitle, contentType) + val state = load(session, mediaUrl, subtitle, file, startAt) watch(session) return JSONObject().put("playerState", state) } - private fun load(session: CastSession, mediaUrl: String, subtitle: JSONObject?, contentType: String): String { - val photo = contentType.startsWith("image/") + /** + * `file` is the relay's description of its file (type and what to show + * with it), or null for the stream. A photo is not a stream at all; a + * music track is an ordinary buffered file the receiver seeks in itself. + */ + private fun load(session: CastSession, mediaUrl: String, subtitle: JSONObject?, + file: JSONObject?, startAt: Double): String { + val contentType = file?.optString("contentType", "") ?: "video/mp4" + val photo = file != null && contentType.startsWith("image/") val subUrl = subtitle?.optString("url", "")?.takeIf { it.isNotEmpty() } val info = if (photo) { // A picture, not a stream: nothing to seek, nothing to buffer. MediaInfo.Builder(mediaUrl).setContentType(contentType) .setStreamType(MediaInfo.STREAM_TYPE_NONE) .setMetadata(MediaMetadata(MediaMetadata.MEDIA_TYPE_PHOTO)).build() + } else if (file != null) { + val meta = file.optJSONObject("meta") ?: JSONObject() + MediaInfo.Builder(mediaUrl).setContentType(contentType) + .setStreamType(MediaInfo.STREAM_TYPE_BUFFERED) + .setMetadata(MediaMetadata(MediaMetadata.MEDIA_TYPE_MUSIC_TRACK).apply { + putString(MediaMetadata.KEY_TITLE, meta.optString("title", "")) + putString(MediaMetadata.KEY_ARTIST, meta.optString("artist", "")) + putString(MediaMetadata.KEY_ALBUM_TITLE, meta.optString("album", "")) + meta.optString("cover", "").takeIf { it.isNotEmpty() && it != "null" } + ?.let { addImage(WebImage(Uri.parse(it))) } + }).build() } else MediaInfo.Builder(mediaUrl) .setContentType("video/mp4") // LIVE: the relay has no beginning to seek back to — the film's own @@ -243,6 +264,7 @@ class CastControl(private val context: Context) { } }.build() val request = MediaLoadRequestData.Builder().setMediaInfo(info).setAutoplay(true) + .apply { if (startAt > 0) setCurrentTime((startAt * 1000).toLong()) } .apply { if (subUrl != null) setActiveTrackIds(longArrayOf(TEXT_TRACK_ID)) }.build() val loaded = CountDownLatch(1) var ok = false @@ -295,6 +317,10 @@ class CastControl(private val context: Context) { /** The player as a remote: pause and play the receiver, answered once it has. */ fun pause(): JSONObject = command { it.pause() } fun play(): JSONObject = command { it.play() } + /** Where in a track the receiver should be; a film seeks by restarting the relay instead. */ + fun seek(seconds: Double): JSONObject = command { + it.seek(MediaSeekOptions.Builder().setPosition((maxOf(0.0, seconds) * 1000).toLong()).build()) + } private fun command(send: (com.google.android.gms.cast.framework.media.RemoteMediaClient) -> com.google.android.gms.common.api.PendingResult): JSONObject { diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/CastRelay.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/CastRelay.kt index 41bf4bd..5b76f60 100644 --- a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/CastRelay.kt +++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/cast/CastRelay.kt @@ -82,7 +82,13 @@ class CastRelay(private val lanAddress: () -> InetAddress?, private val spoolDir private val spoolSeq = AtomicLong() private class Subtitle(val vtt: ByteArray, val language: String, val label: String) - private class Image(val bytes: ByteArray, val type: String) + private class Cover(val bytes: ByteArray, val type: String) + /** A whole file on disk, served at `/file`: a photo, or a track with its cover. */ + private class FileSlot(val path: File, val size: Long, val type: String, val cover: Cover?, val meta: JSONObject) + private class Incoming(val slot: FileSlot) { + val out = java.io.FileOutputStream(slot.path) + var received = 0L + } @Volatile private var server: ServerSocket? = null @Volatile private var port = 0 @@ -93,8 +99,10 @@ class CastRelay(private val lanAddress: () -> InetAddress?, private val spoolDir @Volatile private var headerReady = false @Volatile private var subtitle: Subtitle? = null @Volatile private var subtitleVersion = 0 - @Volatile private var image: Image? = null - @Volatile private var imageVersion = 0 + @Volatile private var file: FileSlot? = null + @Volatile private var fileVersion = 0 + private var incoming: Incoming? = null // guarded by this + private val fileSeq = AtomicLong() /** How many times a receiver asked for the stream since the relay started. */ @Volatile var streamRequests = 0 private set @@ -117,24 +125,74 @@ class CastRelay(private val lanAddress: () -> InetAddress?, private val spoolDir else "http://${hostPart()}:$port/subs.vtt?t=$token&v=$subtitleVersion" /** Versioned like the subtitle: a receiver handed the same address twice shows what it has. */ - val imageUrl get() = - if (server == null || image == null) null - else "http://${hostPart()}:$port/image?t=$token&v=$imageVersion" + val fileUrl get() = + if (server == null || file == null) null + else "http://${hostPart()}:$port/file?t=$token&v=$fileVersion" + + val fileType get() = file?.type - val imageType get() = image?.type + /** What the receiver is told the file is: title, artist, album, and the cover's address. */ + fun fileMeta(): JSONObject? = file?.let { f -> + JSONObject(f.meta.toString()).put("cover", + if (f.cover == null) JSONObject.NULL else "http://${hostPart()}:$port/cover?t=$token&v=$fileVersion") + } /** - * One photo, scaled and re-encoded by the page, served at `/image` until - * the next one. The relay starts for it when nothing else has. + * A file arrives in three steps, so that a large one never crosses the + * bridge as one message: `beginFile` names it, `writeFile` appends, and + * `endFile` puts it up and answers its address. It is written to the spool + * directory rather than held: a long lossless track is a few hundred + * megabytes. The relay starts for it when nothing else has. */ @Synchronized - fun showImage(bytes: ByteArray, type: String): JSONObject { - if (type !in IMAGE_TYPES) throw IllegalArgumentException("Not a picture a receiver shows: $type") + fun beginFile(type: String, size: Long, cover: ByteArray?, coverType: String?, meta: JSONObject): Boolean { + if (type !in FILE_TYPES) throw IllegalArgumentException("Not something a receiver shows: $type") + if (size <= 0 || size > FILE_MAX_BYTES) throw IllegalArgumentException("Bad file size: $size") + if (cover != null && (coverType == null || !coverType.startsWith("image/") || coverType !in FILE_TYPES)) { + throw IllegalArgumentException("Bad cover type: $coverType") + } if (server == null) start(null, null) - image = Image(bytes, type) - imageVersion++ - log("image set: ${bytes.size} bytes, $type, v$imageVersion") - return JSONObject().put("url", imageUrl) + dropIncoming() + // At most the file being shown and the one arriving: anything older + // has been replaced on the television already. + spoolDir.listFiles()?.filter { it.name.startsWith("file-") && it != file?.path }?.forEach { it.delete() } + val text = { k: String -> meta.optString(k, "").take(500) } + val slot = FileSlot(File(spoolDir, "file-${fileSeq.incrementAndGet()}.bin"), size, type, + cover?.let { Cover(it, coverType!!) }, + JSONObject().put("title", text("title")).put("artist", text("artist")).put("album", text("album"))) + incoming = Incoming(slot) + return true + } + + @Synchronized + fun writeFile(data: ByteArray, offset: Int = 0, length: Int = data.size - offset): Boolean { + val f = incoming ?: throw IllegalStateException("No file is being sent") + if (f.received + length > f.slot.size) { dropIncoming(); throw IllegalStateException("More bytes than announced") } + f.out.write(data, offset, length) + f.received += length + return true + } + + @Synchronized + fun endFile(): JSONObject { + val f = incoming ?: throw IllegalStateException("No file is being sent") + incoming = null + f.out.close() + if (f.received != f.slot.size) { + f.slot.path.delete() + throw IllegalStateException("File cut short: ${f.received} of ${f.slot.size} bytes") + } + // The previous file stays on disk until the next one begins: a receiver + // may still be reading it. + file = f.slot + fileVersion++ + log("file set: ${f.slot.size} bytes, ${f.slot.type}, v$fileVersion") + return JSONObject().put("url", fileUrl) + } + + private fun dropIncoming() { + incoming?.let { try { it.out.close() } catch (e: Exception) {}; it.slot.path.delete() } + incoming = null } fun subtitleInfo(): JSONObject? = subtitle?.let { @@ -169,7 +227,8 @@ class CastRelay(private val lanAddress: () -> InetAddress?, private val spoolDir spoolDir.mkdirs() spoolDir.listFiles()?.forEach { it.delete() } subtitle = null - image = null + dropIncoming() + file = null setSubtitle(sub) var bound: ServerSocket? = null @@ -276,7 +335,10 @@ class CastRelay(private val lanAddress: () -> InetAddress?, private val spoolDir clients.clear() server?.let { try { it.close() } catch (e: Exception) {} } server = null - port = 0; token = null; initSegment = null; subtitle = null; image = null + port = 0; token = null; initSegment = null; subtitle = null + dropIncoming() + file = null + spoolDir.listFiles()?.filter { it.name.startsWith("file-") }?.forEach { it.delete() } synchronized(ring) { ring.clear(); ringBytes = 0 } accum.reset() } @@ -295,7 +357,12 @@ class CastRelay(private val lanAddress: () -> InetAddress?, private val spoolDir socket.soTimeout = 15000 val reader = BufferedReader(InputStreamReader(socket.getInputStream(), Charsets.ISO_8859_1)) val requestLine = reader.readLine() ?: return socket.close() - while (true) { val line = reader.readLine() ?: break; if (line.isEmpty()) break } + var range: String? = null + while (true) { + val line = reader.readLine() ?: break + if (line.isEmpty()) break + if (line.startsWith("range:", ignoreCase = true)) range = line.substringAfter(':').trim() + } socket.soTimeout = 0 val parts = requestLine.split(' ') val method = parts.getOrElse(0) { "" } @@ -316,7 +383,8 @@ class CastRelay(private val lanAddress: () -> InetAddress?, private val spoolDir if (token == null || query["t"] != token) return respond(out, socket, 403, emptyMap()) when (path) { "/subs.vtt" -> serveSubtitle(out, socket) - "/image" -> serveImage(out, socket) + "/file" -> serveFile(out, socket, range) + "/cover" -> serveCover(out, socket) "/stream.mp4" -> { streamRequests++; serveStream(out, socket) } else -> respond(out, socket, 404, emptyMap()) } @@ -334,13 +402,52 @@ class CastRelay(private val lanAddress: () -> InetAddress?, private val spoolDir ), sub.vtt) } - private fun serveImage(out: OutputStream, socket: Socket) { - val img = image ?: return respond(out, socket, 404, CORS_HEADERS) + /** The whole file, or the one range asked for: a receiver seeks in a track that way. */ + private fun serveFile(out: OutputStream, socket: Socket, range: String?) { + val f = file ?: return respond(out, socket, 404, CORS_HEADERS) + val total = f.size + val base = CORS_HEADERS + mapOf("Content-Type" to f.type, "Cache-Control" to "no-store", + "Accept-Ranges" to "bytes", "Connection" to "close") + var from = 0L + var to = total - 1 + var status = 200 + val m = range?.let { Regex("^bytes=(\\d*)-(\\d*)$").matchEntire(it) } + if (m != null && (m.groupValues[1].isNotEmpty() || m.groupValues[2].isNotEmpty())) { + val a = m.groupValues[1]; val b = m.groupValues[2] + from = if (a.isEmpty()) total - b.toLong() else a.toLong() + to = if (a.isEmpty() || b.isEmpty()) total - 1 else minOf(b.toLong(), total - 1) + from = maxOf(0L, from) + if (from > to || from >= total) { + head(out, 416, base + ("Content-Range" to "bytes */$total") + ("Content-Length" to "0")) + out.flush(); socket.close(); return + } + status = 206 + } + val length = to - from + 1 + head(out, status, base + ("Content-Length" to length.toString()) + + (if (status == 206) mapOf("Content-Range" to "bytes $from-$to/$total") else emptyMap())) + RandomAccessFile(f.path, "r").use { raf -> + raf.seek(from) + val block = ByteArray(BLOCK) + var left = length + while (left > 0) { + val n = raf.read(block, 0, minOf(BLOCK.toLong(), left).toInt()) + if (n <= 0) break + out.write(block, 0, n) + left -= n + } + } + out.flush() + socket.close() + } + + private fun serveCover(out: OutputStream, socket: Socket) { + val c = file?.cover ?: return respond(out, socket, 404, CORS_HEADERS) respond(out, socket, 200, CORS_HEADERS + mapOf( - "Content-Type" to img.type, - "Content-Length" to img.bytes.size.toString(), + "Content-Type" to c.type, + "Content-Length" to c.bytes.size.toString(), "Cache-Control" to "no-store", - ), img.bytes) + ), c.bytes) } private fun serveStream(out: OutputStream, socket: Socket) { @@ -428,8 +535,13 @@ class CastRelay(private val lanAddress: () -> InetAddress?, private val spoolDir } const val RING_CAP = 64 - // The page re-encodes every photo to JPEG: a guard, not a menu. - val IMAGE_TYPES = setOf("image/jpeg", "image/png", "image/webp") + // What a receiver is ever handed as a file: the page re-encodes every + // photo to JPEG, and plays a track in the format it is stored in. + val FILE_TYPES = setOf("image/jpeg", "image/png", "image/webp", + "audio/mpeg", "audio/mp4", "audio/aac", "audio/flac", "audio/ogg", "audio/opus", + "audio/wav", "audio/webm") + // Only stops a page from filling the phone: a long lossless track is a few hundred MB. + const val FILE_MAX_BYTES = 1024L * 1024 * 1024 const val RING_MAX_BYTES = 32L * 1024 * 1024 const val SPOOL_MAX_BYTES = 2L * 1024 * 1024 * 1024 private const val HEADER_WAIT_MS = 10_000L @@ -450,8 +562,9 @@ class CastRelay(private val lanAddress: () -> InetAddress?, private val spoolDir "Access-Control-Expose-Headers" to "Content-Length, Content-Range", ) - private val REASONS = mapOf(200 to "OK", 204 to "No Content", 403 to "Forbidden", - 404 to "Not Found", 405 to "Method Not Allowed") + private val REASONS = mapOf(200 to "OK", 204 to "No Content", 206 to "Partial Content", + 403 to "Forbidden", 404 to "Not Found", 405 to "Method Not Allowed", + 416 to "Range Not Satisfiable") private fun randomToken(): String { val b = ByteArray(16).also { SecureRandom().nextBytes(it) } diff --git a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/save/SaveNames.kt b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/save/SaveNames.kt index 2414730..40250c7 100644 --- a/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/save/SaveNames.kt +++ b/packages/meshbay-android/app/src/main/kotlin/org/meshbay/client/save/SaveNames.kt @@ -59,6 +59,7 @@ class BinaryFrame(val id: Long, val channel: Int, val handle: Long, val bytes: B const val HEADER = 16 const val SAVE_WRITE = 1 const val CAST_PUSH = 2 + const val CAST_FILE = 3 private val MAGIC = byteArrayOf('M'.code.toByte(), 'B'.code.toByte(), 'B'.code.toByte(), '1'.code.toByte()) private fun u32(b: ByteArray, at: Int) = diff --git a/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/CastRelayTest.kt b/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/CastRelayTest.kt index 8013e29..14f49cf 100644 --- a/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/CastRelayTest.kt +++ b/packages/meshbay-android/app/src/test/kotlin/org/meshbay/client/CastRelayTest.kt @@ -158,9 +158,38 @@ class CastRelayTest { assertEquals(200, get(r.getString("url"), readBytes = 0).status) } - @Test fun `a photo starts the relay and is served behind the token, re-addressed when it changes`() { + private fun send(bytes: ByteArray, type: String, meta: JSONObject = JSONObject(), + cover: ByteArray? = null): String { + relay.beginFile(type, bytes.size.toLong(), cover, cover?.let { "image/jpeg" }, meta) + var at = 0 + while (at < bytes.size) { val n = minOf(3, bytes.size - at); relay.writeFile(bytes, at, n); at += n } + return relay.endFile().getString("url") + } + + private fun getRange(url: String, range: String): Reply { + val u = java.net.URI(url) + Socket(u.host, u.port).use { s -> + s.soTimeout = 5000 + s.getOutputStream().write("GET ${u.rawPath}?${u.rawQuery} HTTP/1.1\r\nHost: x\r\nRange: $range\r\n\r\n".toByteArray()) + val input = DataInputStream(s.getInputStream()) + val lines = ArrayList() + val line = StringBuilder() + while (true) { + val c = input.read() + if (c == -1) break + if (c == '\n'.code) { val l = line.toString().trimEnd('\r'); if (l.isEmpty()) break; lines.add(l); line.clear() } + else line.append(c.toChar()) + } + val headers = lines.drop(1).associate { it.substringBefore(':').lowercase() to it.substringAfter(':').trim() } + val body = ByteArray(headers["content-length"]?.toInt() ?: 0) + input.readFully(body) + return Reply(lines[0].split(' ')[1].toInt(), headers, body) + } + } + + @Test fun `a file starts the relay and is served behind the token, re-addressed when it changes`() { val jpeg = byteArrayOf(0xFF.toByte(), 0xD8.toByte(), 1, 2, 3, 0xFF.toByte(), 0xD9.toByte()) - val first = relay.showImage(jpeg, "image/jpeg").getString("url") + val first = send(jpeg, "image/jpeg") assertTrue(relay.active) val reply = get(first) assertEquals(200, reply.status) @@ -169,21 +198,42 @@ class CastRelayTest { assertArrayEquals(jpeg, reply.body) assertEquals(403, get(first.replace(Regex("t=[0-9a-f]+"), "t=x")).status) // A receiver handed the same address twice shows what it already has. - val second = relay.showImage(byteArrayOf(9), "image/jpeg").getString("url") + val second = send(byteArrayOf(9), "image/jpeg") assertNotEquals(first, second) assertArrayEquals(byteArrayOf(9), get(second).body) } - @Test fun `only a picture is served as one`() { - val refused = try { relay.showImage(byteArrayOf(1), "text/html"); false } catch (e: IllegalArgumentException) { true } + @Test fun `a track is served with its cover, and by range`() { + val track = ByteArray(20) { it.toByte() } + val cover = byteArrayOf(0xFF.toByte(), 0xD8.toByte(), 7) + val url = send(track, "audio/flac", JSONObject().put("title", "A Song").put("artist", "Some Band"), cover) + assertEquals("audio/flac", relay.fileType) + val meta = relay.fileMeta()!! + assertEquals("A Song", meta.getString("title")) + assertArrayEquals(cover, get(meta.getString("cover")).body) + val part = getRange(url, "bytes=5-9") + assertEquals(206, part.status) + assertEquals("bytes 5-9/20", part.headers["content-range"]) + assertArrayEquals(track.copyOfRange(5, 10), part.body) + assertArrayEquals(track.copyOfRange(15, 20), getRange(url, "bytes=15-").body) + assertEquals(416, getRange(url, "bytes=50-60").status) + } + + @Test fun `only a whole picture or sound is served as one`() { + val refused = try { relay.beginFile("text/html", 1, null, null, JSONObject()); false } catch (e: IllegalArgumentException) { true } assertTrue(refused) - assertNull(relay.imageUrl) + assertNull(relay.fileUrl) + relay.beginFile("audio/mpeg", 10, null, null, JSONObject()) + relay.writeFile(byteArrayOf(1, 2, 3)) + val short = try { relay.endFile(); false } catch (e: IllegalStateException) { true } + assertTrue(short) + assertNull(relay.fileUrl) } - @Test fun `a film started over a photo takes the photo down`() { - relay.showImage(byteArrayOf(1), "image/jpeg") + @Test fun `a film started over a file takes the file down`() { + send(byteArrayOf(1), "image/jpeg") relay.start(null, null) - assertNull(relay.imageUrl) + assertNull(relay.fileUrl) } @Test fun `the preflight is answered before the token is checked`() { diff --git a/packages/meshbay-client/src/cast-chromecast.js b/packages/meshbay-client/src/cast-chromecast.js index 4c8ddf0..8c6c9c6 100644 --- a/packages/meshbay-client/src/cast-chromecast.js +++ b/packages/meshbay-client/src/cast-chromecast.js @@ -42,17 +42,30 @@ const TEXT_TRACK_STYLE = Object.freeze({ /** * What to hand `player.load()` for a stream, with or without subtitles, or - * for a photo. + * for a whole file the relay serves. * * `streamType: 'LIVE'` because the relay has no beginning to seek back to — * the film's own timeline lives on this side, and a seek restarts the relay. - * A photo is not a stream at all. + * A file is the relay's to describe (`file`: its type and what to show with + * it), never the page's: a photo is not a stream at all, and a music track is + * an ordinary buffered file the receiver seeks in itself. */ -function mediaFor(mediaUrl, subtitle, contentType) { - if (contentType && contentType.startsWith('image/')) { - return { contentId: mediaUrl, contentType, streamType: 'NONE', +function mediaFor(mediaUrl, subtitle, file) { + if (file && file.contentType.startsWith('image/')) { + return { contentId: mediaUrl, contentType: file.contentType, streamType: 'NONE', metadata: { metadataType: 4 } }; // PhotoMediaMetadata } + if (file) { + const meta = file.meta || {}; + return { + contentId: mediaUrl, contentType: file.contentType, streamType: 'BUFFERED', + metadata: { + metadataType: 3, // MusicTrackMediaMetadata + title: meta.title || '', artist: meta.artist || '', albumName: meta.album || '', + images: meta.cover ? [{ url: meta.cover }] : [], + }, + }; + } const media = { contentId: mediaUrl, contentType: 'video/mp4', @@ -73,11 +86,14 @@ function mediaFor(mediaUrl, subtitle, contentType) { return media; } -function loadOptionsFor(subtitle) { - return { +function loadOptionsFor(subtitle, startAt) { + const options = { autoplay: true, activeTrackIds: subtitle && subtitle.url ? [TEXT_TRACK_ID] : [], }; + // Where in a track to begin: a cast started mid-song carries on from there. + if (startAt > 0) options.currentTime = startAt; + return options; } class CastChromecast { @@ -145,7 +161,7 @@ class CastChromecast { } } - async connect(deviceId, mediaUrl, subtitle, contentType) { + async connect(deviceId, mediaUrl, subtitle, file, startAt) { const device = this._devices.get(deviceId); if (!device) throw new Error(`Unknown device: ${deviceId}`); @@ -185,7 +201,7 @@ class CastChromecast { debug(`[cast-chromecast] loading with ${subtitle?.url ? 'subtitles' : 'no subtitles'}`); const status = await new Promise((resolve, reject) => { - player.load(mediaFor(mediaUrl, subtitle, contentType), loadOptionsFor(subtitle), + player.load(mediaFor(mediaUrl, subtitle, file), loadOptionsFor(subtitle, startAt), (err, s) => { if (err) return reject(err); resolve(s); @@ -197,12 +213,12 @@ class CastChromecast { return { deviceName: device.name, playerState: status.playerState }; } - async reload(mediaUrl, subtitle, contentType) { + async reload(mediaUrl, subtitle, file, startAt) { if (!this._player) throw new Error('Not connected'); debug(`[cast-chromecast] reloading stream on "${this._connectedDevice?.name}"` + ` with ${subtitle?.url ? 'subtitles' : 'no subtitles'}`); const status = await new Promise((resolve, reject) => { - this._player.load(mediaFor(mediaUrl, subtitle, contentType), loadOptionsFor(subtitle), + this._player.load(mediaFor(mediaUrl, subtitle, file), loadOptionsFor(subtitle, startAt), (err, s) => { if (err) return reject(err); resolve(s); @@ -256,6 +272,16 @@ class CastChromecast { return { playerState: status && status.playerState }; } + /** Where in a track the receiver should be; a film seeks by restarting the relay instead. */ + async seek(seconds) { + if (!this._player) throw new Error('Not connected'); + const status = await new Promise((resolve, reject) => { + this._player.seek(Math.max(0, Number(seconds) || 0), (err, s) => (err ? reject(err) : resolve(s))); + }); + this._noteStatus(status); + return { playerState: status && status.playerState }; + } + async play() { if (!this._player) throw new Error('Not connected'); const status = await new Promise((resolve, reject) => { diff --git a/packages/meshbay-client/src/cast-relay.js b/packages/meshbay-client/src/cast-relay.js index c5eadc7..ed20b33 100644 --- a/packages/meshbay-client/src/cast-relay.js +++ b/packages/meshbay-client/src/cast-relay.js @@ -15,9 +15,11 @@ * a media element, so unlike the stream it needs CORS headers to be readable * at all. * - * A photo is served at `/image`, one at a time: the page decrypts it, scales - * it to the television and hands it here, and the receiver loads it as a - * picture. The relay starts for it when it is not already running. + * A whole file — a photo, or a music track with its cover at `/cover` — is + * served at `/file`, one at a time: the page decrypts it and hands it over in + * pieces (begin, writes, end), and the receiver loads it as a picture or as + * music. Ranges are honoured there, which is what a receiver seeks with. The + * relay starts for a file when it is not already running. * * Mitigations: * · Bind to the LAN interface, never 0.0.0.0 @@ -56,7 +58,14 @@ const debug = util.debuglog('cast-relay'); const RING_CAP = 64; // What the receiver is ever told a photo is. The page re-encodes every photo // to JPEG, so this list is a guard, not a menu. -const IMAGE_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp']); +const FILE_TYPES = new Set([ + 'image/jpeg', 'image/png', 'image/webp', + 'audio/mpeg', 'audio/mp4', 'audio/aac', 'audio/flac', 'audio/ogg', 'audio/opus', + 'audio/wav', 'audio/webm', +]); +// A track is a few megabytes, a long lossless one a few hundred; this only +// stops a page from filling the machine's memory. +const FILE_MAX_BYTES = 1024 * 1024 * 1024; const BACKPRESSURE_HIGH = 8 * 1024 * 1024; const MOOF = 0x6d6f6f66; const PORT_BASE = 19550; @@ -170,8 +179,9 @@ class CastRelay { this._bytesSent = 0; this._subtitle = null; this._subtitleVersion = 0; - this._image = null; - this._imageVersion = 0; + this._file = null; + this._fileVersion = 0; + this._incoming = null; } get active() { return this._server !== null; } @@ -195,26 +205,67 @@ class CastRelay { } /** - * Where the current photo can be fetched, or null when there is none. + * Where the current file can be fetched, or null when there is none. * Versioned for the same reason as the subtitle: a receiver handed the same * address twice shows what it already has. */ - get imageUrl() { - if (!this._server || !this._image) return null; - return `http://${this._lanIP}:${this._port}/image` - + `?t=${this._token}&v=${this._imageVersion}`; + get fileUrl() { + if (!this._server || !this._file) return null; + return `http://${this._lanIP}:${this._port}/file` + + `?t=${this._token}&v=${this._fileVersion}`; } - get imageType() { return this._image ? this._image.type : null; } + get fileType() { return this._file ? this._file.type : null; } - /** Serve one photo, starting the relay if nothing else has. */ - async showImage({ bytes, type }) { - if (!IMAGE_TYPES.has(type)) throw new Error(`Not a picture a receiver shows: ${type}`); + /** What the receiver is told the file is: title, artist, album, cover. */ + get fileMeta() { + if (!this._file) return null; + const { title, artist, album } = this._file.meta; + const cover = this._file.cover + ? `http://${this._lanIP}:${this._port}/cover?t=${this._token}&v=${this._fileVersion}` + : null; + return { title, artist, album, cover }; + } + + /** + * A file arrives in three steps, so that a large one never has to cross in + * a single message: `beginFile` names it, `writeFile` appends, `endFile` + * puts it up and answers its address. The relay starts if nothing has. + */ + async beginFile({ type, size, cover, title, artist, album }) { + if (!FILE_TYPES.has(type)) throw new Error(`Not something a receiver shows: ${type}`); + if (!(size > 0 && size <= FILE_MAX_BYTES)) throw new Error(`Bad file size: ${size}`); + if (cover && !FILE_TYPES.has(cover.type)) throw new Error(`Bad cover type: ${cover.type}`); if (!this._server) await this.start({}); - this._image = { bytes: Buffer.from(bytes), type }; - this._imageVersion++; - debug(`[cast-relay] image set: ${this._image.bytes.length} bytes, ${type}, v${this._imageVersion}`); - return { url: this.imageUrl }; + const text = (v) => (typeof v === 'string' ? v.slice(0, 500) : ''); + this._incoming = { + type, size, parts: [], received: 0, + cover: cover && cover.type.startsWith('image/') + ? { bytes: Buffer.from(cover.bytes), type: cover.type } : null, + meta: { title: text(title), artist: text(artist), album: text(album) }, + }; + return true; + } + + writeFile(bytes) { + const f = this._incoming; + if (!f) throw new Error('No file is being sent'); + const buf = Buffer.from(bytes); + if (f.received + buf.length > f.size) throw new Error('More bytes than announced'); + f.parts.push(buf); + f.received += buf.length; + return true; + } + + endFile() { + const f = this._incoming; + this._incoming = null; + if (!f) throw new Error('No file is being sent'); + if (f.received !== f.size) throw new Error(`File cut short: ${f.received} of ${f.size} bytes`); + this._file = { bytes: Buffer.concat(f.parts), type: f.type, cover: f.cover, meta: f.meta }; + this._fileVersion++; + debug(`[cast-relay] file set: ${f.size} bytes, ${f.type}, v${this._fileVersion}`); + return { url: this.fileUrl }; } get subtitle() { @@ -264,7 +315,8 @@ class CastRelay { this._chunkCount = 0; this._bytesSent = 0; this._subtitle = null; - this._image = null; + this._file = null; + this._incoming = null; this.setSubtitle(subtitle); const server = http.createServer((req, res) => this._handle(req, res)); @@ -356,7 +408,8 @@ class CastRelay { this._token = null; this._initSegment = null; this._subtitle = null; - this._image = null; + this._file = null; + this._incoming = null; this._ring = []; this._accum.reset(); this._fragCount = 0; @@ -400,8 +453,13 @@ class CastRelay { return; } - if (url.pathname === '/image') { - this._handleImage(res); + if (url.pathname === '/file') { + this._handleFile(req, res); + return; + } + + if (url.pathname === '/cover') { + this._handleCover(res); return; } @@ -459,20 +517,58 @@ class CastRelay { debug(`[cast-relay] subtitle served: ${this._subtitle.vtt.length} bytes`); } - _handleImage(res) { - if (!this._image) { + /** + * The whole file, or the one range asked for: a receiver seeks in a track + * by asking for the bytes from there on. + */ + _handleFile(req, res) { + const f = this._file; + if (!f) { + res.writeHead(404, CORS_HEADERS); + res.end(); + return; + } + const total = f.bytes.length; + const base = { + ...CORS_HEADERS, + 'Content-Type': f.type, + 'Cache-Control': 'no-store', + 'Accept-Ranges': 'bytes', + }; + const m = /^bytes=(\d*)-(\d*)$/.exec(req.headers.range || ''); + if (m && (m[1] !== '' || m[2] !== '')) { + let from = m[1] === '' ? total - Number(m[2]) : Number(m[1]); + let to = m[1] === '' || m[2] === '' ? total - 1 : Math.min(Number(m[2]), total - 1); + from = Math.max(0, from); + if (from > to || from >= total) { + res.writeHead(416, { ...base, 'Content-Range': `bytes */${total}` }); + res.end(); + return; + } + res.writeHead(206, { ...base, 'Content-Range': `bytes ${from}-${to}/${total}`, + 'Content-Length': to - from + 1 }); + res.end(f.bytes.subarray(from, to + 1)); + return; + } + res.writeHead(200, { ...base, 'Content-Length': total }); + res.end(f.bytes); + debug(`[cast-relay] file served: ${total} bytes`); + } + + _handleCover(res) { + const c = this._file && this._file.cover; + if (!c) { res.writeHead(404, CORS_HEADERS); res.end(); return; } res.writeHead(200, { ...CORS_HEADERS, - 'Content-Type': this._image.type, - 'Content-Length': this._image.bytes.length, + 'Content-Type': c.type, + 'Content-Length': c.bytes.length, 'Cache-Control': 'no-store', }); - res.end(this._image.bytes); - debug(`[cast-relay] image served: ${this._image.bytes.length} bytes`); + res.end(c.bytes); } } diff --git a/packages/meshbay-client/src/main.js b/packages/meshbay-client/src/main.js index 1c371f5..a2a7a86 100644 --- a/packages/meshbay-client/src/main.js +++ b/packages/meshbay-client/src/main.js @@ -2333,29 +2333,31 @@ function registerBridge() { handle('cast:devices', async () => castChromecast.devices()); - // One photo at a time, scaled and re-encoded by the page. - handle('cast:image', async (_e, img) => { - return castRelay.showImage({ bytes: Buffer.from(img.bytes), type: img.type }); - }); - - // The relay's photo is loaded as a picture, anything else as the stream; - // the page does not get to say which. + // A whole file for the receiver — a photo, a music track — in three steps, + // so that a large one never crosses in a single message. + handle('cast:file:begin', async (_e, f) => castRelay.beginFile(f || {})); + handle('cast:file:write', async (_e, data) => castRelay.writeFile(Buffer.from(data))); + handle('cast:file:end', async () => castRelay.endFile()); + + // The relay's file is loaded as what the relay says it is, anything else as + // the stream; the page does not get to say which. const loadOf = (mediaUrl, subtitle) => ( - mediaUrl && mediaUrl === castRelay.imageUrl - ? { subtitle: null, contentType: castRelay.imageType } - : { subtitle: subtitle === undefined ? castRelay.subtitle : subtitle, - contentType: 'video/mp4' }); + mediaUrl && mediaUrl === castRelay.fileUrl + ? { subtitle: null, file: { contentType: castRelay.fileType, meta: castRelay.fileMeta } } + : { subtitle: subtitle === undefined ? castRelay.subtitle : subtitle, file: null }); - handle('cast:chromecast:connect', async (_e, { deviceId, mediaUrl, subtitle }) => { + handle('cast:chromecast:connect', async (_e, { deviceId, mediaUrl, subtitle, startAt }) => { const l = loadOf(mediaUrl, subtitle); - return castChromecast.connect(deviceId, mediaUrl, l.subtitle, l.contentType); + return castChromecast.connect(deviceId, mediaUrl, l.subtitle, l.file, l.file ? startAt : 0); }); - handle('cast:chromecast:reload', async (_e, { mediaUrl, subtitle }) => { + handle('cast:chromecast:reload', async (_e, { mediaUrl, subtitle, startAt }) => { const l = loadOf(mediaUrl, subtitle); - return castChromecast.reload(mediaUrl, l.subtitle, l.contentType); + return castChromecast.reload(mediaUrl, l.subtitle, l.file, l.file ? startAt : 0); }); + handle('cast:chromecast:seek', async (_e, seconds) => castChromecast.seek(seconds)); + // The player becomes a remote while casting: these drive the receiver. handle('cast:chromecast:pause', async () => castChromecast.pause()); handle('cast:chromecast:play', async () => castChromecast.play()); diff --git a/packages/meshbay-client/src/preload.js b/packages/meshbay-client/src/preload.js index f12d68e..0de76db 100644 --- a/packages/meshbay-client/src/preload.js +++ b/packages/meshbay-client/src/preload.js @@ -178,7 +178,18 @@ contextBridge.exposeInMainWorld('meshbay', { push: (data) => ipcRenderer.invoke('cast:push', data), stop: () => ipcRenderer.invoke('cast:stop'), subtitle: (sub) => ipcRenderer.invoke('cast:subtitle', sub), - image: (img) => ipcRenderer.invoke('cast:image', img), + // A file in pieces of a few megabytes, as the Android bridge sends it. + file: async (f) => { + const bytes = f.bytes; + await ipcRenderer.invoke('cast:file:begin', { + type: f.type, size: bytes.length, cover: f.cover || null, + title: f.title, artist: f.artist, album: f.album, + }); + for (let at = 0; at < bytes.length; at += 4 * 1024 * 1024) { + await ipcRenderer.invoke('cast:file:write', bytes.subarray(at, at + 4 * 1024 * 1024)); + } + return ipcRenderer.invoke('cast:file:end'); + }, finish: () => ipcRenderer.invoke('cast:finish'), status: () => ipcRenderer.invoke('cast:status'), scan: () => ipcRenderer.invoke('cast:scan'), @@ -188,6 +199,7 @@ contextBridge.exposeInMainWorld('meshbay', { chromecastDisconnect: () => ipcRenderer.invoke('cast:chromecast:disconnect'), chromecastPause: () => ipcRenderer.invoke('cast:chromecast:pause'), chromecastPlay: () => ipcRenderer.invoke('cast:chromecast:play'), + chromecastSeek: (seconds) => ipcRenderer.invoke('cast:chromecast:seek', seconds), }, // A sink that writes to disk as chunks arrive, never a buffer handed over at diff --git a/packages/meshbay-hub/src/meshbay_hub/static/cast-session.js b/packages/meshbay-hub/src/meshbay_hub/static/cast-session.js index 007722c..9f93919 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/cast-session.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/cast-session.js @@ -11,10 +11,14 @@ import * as platform from './platform.js'; // in the lightbox is shown there. In memory only: a television chosen // yesterday may be off today, and choosing it again is one tap. // -// The receiver is the default media receiver, which shows a film or a -// picture and nothing else; the interface itself stays on this device. +// The receiver is the default media receiver, which shows one film, one +// picture or one track at a time and nothing else; the interface itself stays +// on this device. `owner` says which of the three the television is showing +// now ('video', 'photo', 'music'), so that the music bar stops treating the +// receiver as its own once a film or a photo has taken it. let current = null; +let owner = null; const listeners = new Set(); function notify() { @@ -23,7 +27,15 @@ function notify() { export const castSession = { get device() { return current; }, + get owner() { return owner; }, get supported() { return Boolean(platform.capabilities.lanCast && platform.cast.available); }, + /** Whether a whole file (a photo, a track) can be sent: an older shell cannot. */ + get canSendFiles() { return this.supported && platform.cast.canSendFiles; }, + /** The television now shows what `who` sends it. */ + claim(who) { + owner = who; + notify(); + }, choose(device) { current = device ? { id: device.id, name: device.name } : null; notify(); @@ -32,6 +44,7 @@ export const castSession = { forget() { this.choose(null); }, /** Stop casting: the television goes back to its idle screen. */ async end() { + owner = null; this.choose(null); photoGen++; await platform.cast.chromecastDisconnect().catch(() => {}); @@ -49,6 +62,27 @@ export function useCastDevice() { return device; } +// ── A file on the television ───────────────────────────────────────────────── +// +// A photo or a music track, whole, handed to the relay and loaded on the +// session's television — connected if it is not yet, reloaded if it is. The +// relay, not the page, tells the receiver what the file is; the page only +// names it (title, artist, album, cover) and says where in it to begin. + +export async function loadFile({ owner: who, startAt = 0, ...file }) { + const device = current; + if (!device || !castSession.canSendFiles) throw new Error('No television to cast to'); + castSession.claim(who); + const sent = await platform.cast.file(file); + if (!sent) throw new Error('The cast relay did not take the file'); + const status = await platform.cast.status(); + if (status && status.chromecast && status.chromecast.connected) { + await platform.cast.chromecastReload({ mediaUrl: sent.url, startAt }); + } else { + await platform.cast.chromecastConnect({ deviceId: device.id, mediaUrl: sent.url, startAt }); + } +} + // ── A photo on the television ──────────────────────────────────────────────── // // Scaled to fit 1920×1080 and re-encoded as JPEG before it leaves: a camera's @@ -87,18 +121,10 @@ let photoChain = Promise.resolve(); export function showPhoto(blob) { const gen = ++photoGen; photoChain = photoChain.then(async () => { - const device = current; - if (gen !== photoGen || !device || !platform.cast.canShowImages) return; + if (gen !== photoGen || !current || !castSession.canSendFiles) return; const bytes = await scaledForTv(blob); if (gen !== photoGen) return; - const shown = await platform.cast.image({ bytes, type: 'image/jpeg' }); - if (!shown || gen !== photoGen) return; - const status = await platform.cast.status(); - if (status && status.chromecast && status.chromecast.connected) { - await platform.cast.chromecastReload({ mediaUrl: shown.url }); - } else { - await platform.cast.chromecastConnect({ deviceId: device.id, mediaUrl: shown.url }); - } + await loadFile({ owner: 'photo', bytes, type: 'image/jpeg' }); }).catch((err) => console.warn('[cast] photo not shown:', err)); return photoChain; } @@ -111,9 +137,12 @@ export function showPhoto(blob) { // toolbar. `cls` and `iconCls` are the button's and its icon's own classes, // so it matches its neighbours. // `onChosen` runs after a television is picked, for the view that has -// something to show on it straight away. +// something to show on it straight away. `up` opens the menu above the +// button, for one at the bottom of the window. -export function CastButton({ variant = 'page', cls = 'tb-btn tb-btn-icon', iconCls = '', onChosen }) { +export function CastButton({ + variant = 'page', cls = 'tb-btn tb-btn-icon', iconCls = '', onChosen, up = false, +}) { const device = useCastDevice(); const [open, setOpen] = useState(false); const [devices, setDevices] = useState([]); @@ -143,7 +172,7 @@ export function CastButton({ variant = 'page', cls = 'tb-btn tb-btn-icon', iconC if (!castSession.supported) return null; const overlay = variant === 'overlay'; - const menuCls = overlay ? 'cast-picker' : 'ctx-menu cast-menu'; + const menuCls = `${overlay ? 'cast-picker' : 'ctx-menu cast-menu'}${up ? ' cast-menu-up' : ''}`; const itemCls = overlay ? 'cast-picker-item' : 'ctx-menu-item'; const title = device ? `${t('cast.casting_to')} ${device.name}` : t('cast.start'); diff --git a/packages/meshbay-hub/src/meshbay_hub/static/music-app.js b/packages/meshbay-hub/src/meshbay_hub/static/music-app.js index 67be344..f2c4374 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/music-app.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/music-app.js @@ -10,6 +10,7 @@ import { usePager, Pager, pageSizeFrom } from './pager.js'; import { Menu, MenuDots, useMenu } from './menu.js'; import { PlaylistMenuButton, NameModal, usePlaylists } from './playlist-menu.js'; import * as P from './playlists.js'; +import { CastButton } from './cast-session.js'; // -- Music -------------------------------------------------------------------- // @@ -747,6 +748,8 @@ function MusicApp({ lists=${playlists} reload=${reloadPlaylists} onPlayQueue=${onPlayQueue} onSync=${syncNow} />`} <${Pager} pager=${pager} /> + ${/* The television the music bar plays to (cast-session.js). */''} + <${CastButton} /> ${!hideFilter && html`
${formatTime(currentTime)} - - ${formatTime(duration)} + + ${formatTime(shownDuration)}
<${Icon} name="volume" /> setVolume(parseFloat(e.target.value))} />
+ <${CastButton} cls="music-player-btn" up /> diff --git a/packages/meshbay-hub/src/meshbay_hub/static/platform.js b/packages/meshbay-hub/src/meshbay_hub/static/platform.js index 3a0c628..28817c7 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/platform.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/platform.js @@ -460,14 +460,16 @@ export const cast = { if (!bridge || !bridge.cast || !bridge.cast.subtitle) return null; return bridge.cast.subtitle(sub); }, - // A photo for the receiver: `{ bytes, type }`, already scaled to the - // television. Absent from an older shell, so callers check `canShowImages`. - get canShowImages() { - return Boolean(bridge && bridge.cast && bridge.cast.image); + // A whole file for the receiver — a photo already scaled to the television, + // a music track — as `{ bytes, type, cover?: { bytes, type }, title?, + // artist?, album? }`; answers `{ url }` to load. Absent from an older + // shell, so callers check `canSendFiles`. + get canSendFiles() { + return Boolean(bridge && bridge.cast && bridge.cast.file); }, - async image(img) { - if (!this.canShowImages) return null; - return bridge.cast.image(img); + async file(f) { + if (!this.canSendFiles) return null; + return bridge.cast.file(f); }, async finish() { if (!bridge || !bridge.cast) return false; @@ -529,6 +531,15 @@ export const cast = { if (!this.canControl) return null; return bridge.cast.chromecastPlay(); }, + // Seeking inside a file the receiver plays (a track); a film seeks by + // restarting the relay instead. + get canSeek() { + return Boolean(bridge && bridge.cast && bridge.cast.chromecastSeek); + }, + async chromecastSeek(seconds) { + if (!this.canSeek) return null; + return bridge.cast.chromecastSeek(seconds); + }, }; /** diff --git a/packages/meshbay-hub/src/meshbay_hub/static/style.css b/packages/meshbay-hub/src/meshbay_hub/static/style.css index 9be414f..9383043 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/style.css +++ b/packages/meshbay-hub/src/meshbay_hub/static/style.css @@ -2054,6 +2054,8 @@ button:disabled { opacity: 0.5; cursor: not-allowed; } any other menu there, hung under the button rather than at a point. */ .cast-btn.casting { color: var(--accent); border-color: var(--accent); } .ctx-menu.cast-menu { position: absolute; top: calc(100% + 4px); right: 0; z-index: 150; } +/* From the music bar, at the bottom of the window: the menu opens upward. */ +.cast-menu-up { top: auto !important; bottom: calc(100% + 4px); } .ctx-menu-item.cast-menu-current { color: var(--text-dim); cursor: default; } .ctx-menu-item.cast-menu-current:hover { background: none; } .ctx-menu-item svg { width: 16px; height: 16px; flex-shrink: 0; } diff --git a/packages/meshbay-hub/src/meshbay_hub/static/video-player.js b/packages/meshbay-hub/src/meshbay_hub/static/video-player.js index ed1f18c..37ea727 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/video-player.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/video-player.js @@ -1316,6 +1316,7 @@ function VideoPlayer({ entry, transportRef, gekRef, onClose, onDownload }) { }).then(async (result) => { if (castRestartGenRef.current !== gen) return; if (!result) return; + if (device || castSession.device) castSession.claim('video'); setCastUrl(result.url); const status = await platform.cast.status(); if (status && status.chromecast && status.chromecast.connected) { diff --git a/packages/meshbay-hub/tests/harness/cast_session_probe.py b/packages/meshbay-hub/tests/harness/cast_session_probe.py index 2904860..573dd95 100644 --- a/packages/meshbay-hub/tests/harness/cast_session_probe.py +++ b/packages/meshbay-hub/tests/harness/cast_session_probe.py @@ -40,9 +40,13 @@ FRAME = r"""