From 9a3ff31278303039705cfbe9d6f7aeec3bff3e8d Mon Sep 17 00:00:00 2001 From: TongTongStudio Date: Wed, 2 Dec 2026 00:50:23 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=86=85=E7=BD=AE=E5=B1=80=E5=9F=9F?= =?UTF-8?q?=E7=BD=91=E7=9B=B4=E8=BF=9E=20Google=20Cast=EF=BC=88=E6=97=A0?= =?UTF-8?q?=E9=9C=80=20Google=20Play=20=E6=9C=8D=E5=8A=A1=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 无 GMS 设备上投屏页自动降级为局域网直连:自写 mDNS 查询 _googlecast._tcp(QU 单播应答),TLS 8009 + CastMessage 帧直连接收端 (CONNECT/LAUNCH/LOAD/PLAY/PAUSE/STOP/心跳/MEDIA_STATUS)。多 A 记录时 优先同网段地址;命令经发送队列在 IO 线程顺序写出,修复 UI 线程写 socket 导致的 NetworkOnMainThreadException。有 GMS 时保留 Media3 原流程。 --- docs/casting.md | 7 +- .../src/main/AndroidManifest.xml | 1 + .../com/ttstd/player/cast/google/CastWire.kt | 98 +++++++ .../player/cast/google/DirectCastClient.kt | 242 +++++++++++++++++ .../player/cast/google/GoogleCastActivity.kt | 254 ++++++++++++++++-- .../player/cast/google/LanCastDiscovery.kt | 200 ++++++++++++++ .../ttstd/player/cast/google/CastWireTest.kt | 38 +++ .../cast/google/LanCastDiscoveryTest.kt | 123 +++++++++ 8 files changed, 935 insertions(+), 28 deletions(-) create mode 100644 player-cast-google/src/main/kotlin/com/ttstd/player/cast/google/CastWire.kt create mode 100644 player-cast-google/src/main/kotlin/com/ttstd/player/cast/google/DirectCastClient.kt create mode 100644 player-cast-google/src/main/kotlin/com/ttstd/player/cast/google/LanCastDiscovery.kt create mode 100644 player-cast-google/src/test/kotlin/com/ttstd/player/cast/google/CastWireTest.kt create mode 100644 player-cast-google/src/test/kotlin/com/ttstd/player/cast/google/LanCastDiscoveryTest.kt diff --git a/docs/casting.md b/docs/casting.md index 2addd78..85c8899 100644 --- a/docs/casting.md +++ b/docs/casting.md @@ -10,7 +10,7 @@ | 发现/控制 | SSDP M-SEARCH、SOAP | Media3 MediaRouteButtonFactory/CastPlayer | | 控制入口 | 播放、暂停、前后跳转、结束并返回本机 | 投屏验证页 PlayerView、设备路由按钮、媒体通知 | | 生命周期 | 当前 Demo 页面拥有,销毁会停止和关闭 relay | MediaSessionService 拥有,可在后台继续 | -| 环境 | 同一可互访局域网,路由器未隔离客户端 | 同一可互访网络,Android 设备需可用的 Google Play 服务 | +| 环境 | 同一可互访局域网,路由器未隔离客户端 | 同一可互访网络;有 Google Play 服务走 Media3 CastPlayer,无 Google Play 服务走内置局域网直连 | DLNA 的名称不代表所有电视均具备相同编码/字幕能力。接收端不能解码时,需要媒体服务器转码;手机 relay 只转发字节,不做视频转换。 @@ -29,7 +29,10 @@ DLNA 的名称不代表所有电视均具备相同编码/字幕能力。接收 本机暂停后,投屏会话接管书签与 Jellyfin 观看进度。DLNA 通过 GetPositionInfo/GetTransportInfo 查询状态;Google Cast 由服务内 CastPlayer 获取位置。返回本机时恢复位置与播放意图,并重新解析来源,必要时重新创建 Jellyfin 转码会话。 -Google Cast 使用 Media3 1.11.1 的 CastPlayer、DefaultCastOptionsProvider 和 MediaSessionService;没有新建旧 RemoteMediaClient 包装层。服务持有独立本地 ExoPlayer,负责本机/远端之间转移。验证页在设备切换后重新绑定 PlayerView,结束时撤销路由、停止媒体服务并返回本机播放器。 +Google Cast 有两条路径: + +1. **Google Play 服务可用**:Media3 1.11.1 的 CastPlayer、DefaultCastOptionsProvider 和 MediaSessionService;服务持有独立本地 ExoPlayer,负责本机/远端之间转移。验证页在设备切换后重新绑定 PlayerView,结束时撤销路由、停止媒体服务并返回本机播放器。 +2. **无 Google Play 服务(如 AOSP 测试机)**:投屏页自动切换到「局域网直连」,自行查询 `_googlecast._tcp`(QU 位单播应答),凭 TXT 的 `fn`/`id` 列出设备,选中后通过 TLS 8009 + CastMessage 帧直连接收端(CC1AD845):CONNECT / LAUNCH / LOAD / PLAY / PAUSE / STOP / 心跳 / MEDIA_STATUS。多 A 记录时优先与本机同网段的地址。该路径不依赖 GMS,也不支持设备认证、镜像与后台服务保活(会话随投屏页结束)。 DLNA 目前是前台验证实现,没有用于长时间后台保活的独立前台服务;锁屏、进程被回收或页面销毁可能中断手机代理。Google Cast 服务后台播放也不能跨越系统强制停止/应用进程终止。不可将 Demo 的资源清理逻辑等同于完整产品的跨进程恢复。 diff --git a/player-cast-google/src/main/AndroidManifest.xml b/player-cast-google/src/main/AndroidManifest.xml index c055b57..4e96462 100644 --- a/player-cast-google/src/main/AndroidManifest.xml +++ b/player-cast-google/src/main/AndroidManifest.xml @@ -1,5 +1,6 @@ + diff --git a/player-cast-google/src/main/kotlin/com/ttstd/player/cast/google/CastWire.kt b/player-cast-google/src/main/kotlin/com/ttstd/player/cast/google/CastWire.kt new file mode 100644 index 0000000..4cf38c3 --- /dev/null +++ b/player-cast-google/src/main/kotlin/com/ttstd/player/cast/google/CastWire.kt @@ -0,0 +1,98 @@ +package com.ttstd.player.cast.google + +import java.io.ByteArrayOutputStream + +/** 一条 Cast v2 消息(protobuf 字段 1–6 的最小子集)。 */ +internal data class CastFrame( + val sourceId: String, + val destinationId: String, + val namespace: String, + val payload: String, +) + +/** Google Cast 帧格式:4 字节大端长度 + CastMessage protobuf。 */ +internal object CastWire { + fun encodeMessage(sourceId: String, destinationId: String, namespace: String, payload: String): ByteArray { + val body = ByteArrayOutputStream(128 + payload.length) + body.write(0x08); body.write(0x00) // 1: protocolVersion = 0 + writeString(body, 2, sourceId) + writeString(body, 3, destinationId) + writeString(body, 4, namespace) + body.write(0x28); body.write(0x00) // 5: payloadType = STRING(0) + writeString(body, 6, payload) + return body.toByteArray() + } + + fun frame(body: ByteArray): ByteArray { + val size = body.size + return ByteArray(4 + size).also { output -> + output[0] = (size ushr 24).toByte() + output[1] = (size ushr 16).toByte() + output[2] = (size ushr 8).toByte() + output[3] = size.toByte() + body.copyInto(output, 4) + } + } + + fun decode(body: ByteArray): CastFrame? { + var source = "" + var destination = "" + var namespace = "" + var payload = "" + var offset = 0 + while (offset < body.size) { + val tag = readVarint(body, offset) ?: return null + offset = tag.second + val field = (tag.first ushr 3).toInt() + when (tag.first and 7L) { + 0L -> { offset = readVarint(body, offset)?.second ?: return null } + 2L -> { + val length = readVarint(body, offset) ?: return null + val start = length.second + if (length.first < 0 || start + length.first > body.size) return null + val value = String(body, start, length.first.toInt(), Charsets.UTF_8) + offset = start + length.first.toInt() + when (field) { + 2 -> source = value + 3 -> destination = value + 4 -> namespace = value + 6 -> payload = value + } + } + 5L -> { if (offset + 4 > body.size) return null; offset += 4 } + else -> return null + } + } + return CastFrame(source, destination, namespace, payload) + } + + fun readVarint(data: ByteArray, start: Int): Pair? { + var value = 0L + var shift = 0 + var offset = start + while (offset < data.size && shift <= 63) { + val byte = data[offset].toInt() and 0xFF + value = value or ((byte and 0x7F).toLong() shl shift) + offset++ + if (byte and 0x80 == 0) return value to offset + shift += 7 + } + return null + } + + fun writeVarint(output: ByteArrayOutputStream, value: Int) { + var remaining = value + while (remaining and 0x7F.inv() != 0) { + output.write((remaining and 0x7F) or 0x80) + remaining = remaining ushr 7 + } + output.write(remaining) + } + + private fun writeString(output: ByteArrayOutputStream, field: Int, value: String) { + output.write((field shl 3) or 2) + val bytes = value.toByteArray(Charsets.UTF_8) + writeVarint(output, bytes.size) + output.write(bytes) + } +} diff --git a/player-cast-google/src/main/kotlin/com/ttstd/player/cast/google/DirectCastClient.kt b/player-cast-google/src/main/kotlin/com/ttstd/player/cast/google/DirectCastClient.kt new file mode 100644 index 0000000..cac0ce2 --- /dev/null +++ b/player-cast-google/src/main/kotlin/com/ttstd/player/cast/google/DirectCastClient.kt @@ -0,0 +1,242 @@ +package com.ttstd.player.cast.google + +import com.ttstd.player.cast.CastMedia +import com.ttstd.player.cast.RemotePlaybackState +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import kotlinx.coroutines.channels.Channel +import org.json.JSONObject +import java.io.DataInputStream +import java.net.InetSocketAddress +import java.net.Socket +import java.security.SecureRandom +import java.security.cert.X509Certificate +import java.util.concurrent.atomic.AtomicInteger +import javax.net.ssl.SSLContext +import javax.net.ssl.SSLSocket +import javax.net.ssl.X509TrustManager + +/** 自包含 Google Cast v2 客户端:TLS 8009 + CastMessage 帧,不依赖 Google Play 服务。 + * 只做默认媒体接收器(CC1AD845)的 LOAD/播放控制,不做镜像与设备认证。 */ +class DirectCastClient( + private val host: String, + private val port: Int, + private val scope: CoroutineScope, + private val onState: (RemotePlaybackState) -> Unit = {}, + private val onStatus: (String) -> Unit = {}, +) : AutoCloseable { + private val requests = AtomicInteger(1) + private val outgoing = Channel(Channel.UNLIMITED) + @Volatile private var socket: SSLSocket? = null + @Volatile private var closed = false + private var transportId: String? = null + private var mediaSessionId = 0L + private var loaded = false + private var media: CastMedia? = null + private var readJob: Job? = null + private var writeJob: Job? = null + private var heartbeatJob: Job? = null + private var pollJob: Job? = null + + suspend fun connectAndLoad(media: CastMedia, appId: String = DEFAULT_MEDIA_RECEIVER) = withContext(Dispatchers.IO) { + this@DirectCastClient.media = media + val raw = Socket() + raw.connect(InetSocketAddress(host, port), CONNECT_TIMEOUT_MS) + val ssl = (SSLContext.getInstance("TLS").apply { + init(null, arrayOf(TrustAll), SecureRandom()) + }.socketFactory.createSocket(raw, host, port, true) as SSLSocket).apply { startHandshake() } + socket = ssl + readJob = scope.launch(Dispatchers.IO) { readLoop(ssl) } + writeJob = scope.launch(Dispatchers.IO) { writeLoop(ssl) } + heartbeatJob = scope.launch(Dispatchers.IO) { heartbeatLoop() } + pollJob = scope.launch(Dispatchers.IO) { pollLoop() } + send(RECEIVER_ID, NS_CONNECTION, """{"type":"CONNECT"}""") + send(RECEIVER_ID, NS_RECEIVER, """{"type":"LAUNCH","appId":"$appId","requestId":${nextRequest()}}""") + } + + fun play() = mediaCommand("PLAY") + + fun pause() = mediaCommand("PAUSE") + + fun stop() = mediaCommand("STOP") + + fun seekTo(positionMs: Long) { + val transport = transportId ?: return + if (mediaSessionId == 0L) return + send(transport, NS_MEDIA, """{"type":"SEEK","mediaSessionId":$mediaSessionId,"currentTime":${positionMs / 1000.0},"requestId":${nextRequest()}}""") + } + + override fun close() { + if (closed) return + closed = true + outgoing.close() + readJob?.cancel() + writeJob?.cancel() + heartbeatJob?.cancel() + pollJob?.cancel() + runCatching { socket?.close() } + socket = null + } + + /** 所有命令经队列在 IO 线程顺序写出,UI 线程调用 send 不会触发 NetworkOnMainThread。 */ + private suspend fun writeLoop(ssl: SSLSocket) { + try { + val output = ssl.outputStream + for (frame in outgoing) { + output.write(frame) + output.flush() + } + } catch (error: Exception) { + if (!closed) { + onStatus("与接收端的连接已断开") + close() + } + } + } + + private fun readLoop(ssl: SSLSocket) { + try { + val input = DataInputStream(ssl.inputStream) + while (!closed && scope.isActive) { + val length = input.readInt() + require(length in 1..(1 shl 20)) { "非法 Cast 帧长度:$length" } + val body = ByteArray(length) + input.readFully(body) + CastWire.decode(body)?.let(::dispatch) + } + } catch (cancelled: CancellationException) { + throw cancelled + } catch (error: Exception) { + if (!closed) { + onStatus("与接收端的连接已断开") + close() + } + } + } + + private suspend fun heartbeatLoop() { + while (!closed) { + delay(HEARTBEAT_MS) + if (closed) return + runCatching { send(RECEIVER_ID, NS_HEARTBEAT, """{"type":"PING"}""") } + } + } + + private suspend fun pollLoop() { + while (!closed) { + delay(HEARTBEAT_MS) + val transport = transportId ?: continue + runCatching { send(transport, NS_MEDIA, """{"type":"GET_STATUS","requestId":${nextRequest()}}""") } + } + } + + private fun dispatch(frame: CastFrame) { + val json = runCatching { JSONObject(frame.payload) }.getOrNull() ?: return + when (frame.namespace) { + NS_HEARTBEAT -> if (json.optString("type") == "PING") { + runCatching { send(frame.sourceId, NS_HEARTBEAT, """{"type":"PONG"}""") } + } + NS_RECEIVER -> handleReceiver(json) + NS_MEDIA -> handleMedia(json) + } + } + + private fun handleReceiver(json: JSONObject) { + when (json.optString("type")) { + "RECEIVER_STATUS" -> { + val apps = json.optJSONObject("status")?.optJSONArray("applications") ?: return + if (apps.length() == 0) return + val transport = apps.optJSONObject(0)?.optString("transportId").orEmpty() + if (transport.isBlank()) return + if (transport != transportId) { + transportId = transport + send(transport, NS_CONNECTION, """{"type":"CONNECT"}""") + } + sendLoad() + } + "LAUNCH_ERROR", "LOAD_FAILED" -> onStatus("接收端拒绝启动:${json.optString("reason")}") + } + } + + private fun handleMedia(json: JSONObject) { + when (json.optString("type")) { + "MEDIA_STATUS" -> { + val status = json.optJSONArray("status") ?: return + val item = if (status.length() > 0) status.optJSONObject(0) ?: return else { + mediaSessionId = 0 + return + } + mediaSessionId = item.optLong("mediaSessionId", 0) + val duration = item.optJSONObject("media")?.optDouble("duration", Double.NaN) + onState( + RemotePlaybackState( + positionMs = (item.optDouble("currentTime", 0.0) * 1000).toLong().coerceAtLeast(0), + durationMs = duration?.takeIf { !it.isNaN() && it >= 0 }?.let { (it * 1000).toLong() }, + playing = item.optString("playerState") == "PLAYING", + ) + ) + } + "LOAD_FAILED" -> onStatus("接收端加载媒体失败") + "INVALID_PLAYER_STATE" -> Unit + } + } + + private fun sendLoad() { + val target = media ?: return + val transport = transportId ?: return + if (loaded) return + loaded = true + val payload = JSONObject() + .put("type", "LOAD") + .put("requestId", nextRequest()) + .put("autoplay", true) + .put("currentTime", target.startPositionMs / 1000.0) + .put( + "media", + JSONObject() + .put("contentId", target.uri) + .put("contentType", target.mimeType) + .put("streamType", "BUFFERED") + .put("metadata", JSONObject().put("metadataType", 0).put("title", target.title)), + ) + send(transport, NS_MEDIA, payload.toString()) + } + + private fun mediaCommand(type: String) { + val transport = transportId ?: return + if (mediaSessionId == 0L) return + send(transport, NS_MEDIA, """{"type":"$type","mediaSessionId":$mediaSessionId,"requestId":${nextRequest()}}""") + } + + private fun send(destinationId: String, namespace: String, payload: String) { + if (closed || socket == null) return + val frame = CastWire.frame(CastWire.encodeMessage(SOURCE_ID, destinationId, namespace, payload)) + outgoing.trySend(frame) + } + + private fun nextRequest(): Int = requests.getAndIncrement() + + private object TrustAll : X509TrustManager { + override fun checkClientTrusted(chain: Array?, authType: String?) = Unit + override fun checkServerTrusted(chain: Array?, authType: String?) = Unit + override fun getAcceptedIssuers(): Array = emptyArray() + } + + companion object { + const val DEFAULT_MEDIA_RECEIVER = "CC1AD845" + private const val NS_CONNECTION = "urn:x-cast:com.google.cast.tp.connection" + private const val NS_HEARTBEAT = "urn:x-cast:com.google.cast.tp.heartbeat" + private const val NS_RECEIVER = "urn:x-cast:com.google.cast.receiver" + private const val NS_MEDIA = "urn:x-cast:com.google.cast.media" + private const val RECEIVER_ID = "receiver-0" + private const val SOURCE_ID = "sender-0" + private const val CONNECT_TIMEOUT_MS = 5000 + private const val HEARTBEAT_MS = 5000L + } +} diff --git a/player-cast-google/src/main/kotlin/com/ttstd/player/cast/google/GoogleCastActivity.kt b/player-cast-google/src/main/kotlin/com/ttstd/player/cast/google/GoogleCastActivity.kt index dcda206..38a68c6 100644 --- a/player-cast-google/src/main/kotlin/com/ttstd/player/cast/google/GoogleCastActivity.kt +++ b/player-cast-google/src/main/kotlin/com/ttstd/player/cast/google/GoogleCastActivity.kt @@ -5,85 +5,273 @@ import android.content.ComponentName import android.content.Context import android.content.Intent import android.os.Bundle -import android.widget.* +import android.view.View +import android.widget.Button +import android.widget.LinearLayout +import android.widget.TextView +import androidx.activity.OnBackPressedCallback import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat +import androidx.lifecycle.lifecycleScope import androidx.media3.cast.MediaRouteButtonFactory -import androidx.media3.common.* +import androidx.media3.common.DeviceInfo +import androidx.media3.common.MediaItem +import androidx.media3.common.MediaMetadata +import androidx.media3.common.PlaybackException +import androidx.media3.common.Player import androidx.media3.session.MediaController import androidx.media3.session.SessionToken import androidx.media3.ui.PlayerView import androidx.mediarouter.app.MediaRouteButton import androidx.mediarouter.media.MediaRouter -import com.google.common.util.concurrent.* +import com.google.common.util.concurrent.FutureCallback +import com.google.common.util.concurrent.Futures +import com.google.common.util.concurrent.ListenableFuture import com.ttstd.player.cast.CastMedia +import com.ttstd.player.cast.RemotePlaybackState +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull -/** 投屏验证页。手机与接收端均使用服务的同一个 CastPlayer,支持媒体通知和回切。 - * 只接收宿主已解析为无需自定义 HTTP header 的链接(或手机 relay 链接)。 - */ +/** 投屏验证页。有 Google Play 服务时使用 Media3 CastPlayer;无 Google Play 服务时 + * 可用内置局域网直连(mDNS + Cast v2,直接连接接收端 TCP 8009)。 */ class GoogleCastActivity : AppCompatActivity() { private var controller: MediaController? = null private var future: ListenableFuture? = null private lateinit var playerView: PlayerView private lateinit var status: TextView + private lateinit var directStatus: TextView + private lateinit var directList: LinearLayout + private lateinit var directControls: LinearLayout + private lateinit var pauseButton: Button + private var direct: DirectCastClient? = null + private var directName: String? = null + private var directState = RemotePlaybackState() + private var directStarted = false private var returning = false + private val hasGoogleServices by lazy { + runCatching { packageManager.getPackageInfo("com.google.android.gms", 0) }.isSuccess + } private val listener = object : Player.Listener { override fun onDeviceInfoChanged(deviceInfo: DeviceInfo) { playerView.player = null playerView.player = controller status.text = if (deviceInfo.playbackType == DeviceInfo.PLAYBACK_TYPE_REMOTE) "正在 Google Cast 设备播放" else "本机播放,点击投屏图标选择设备" } - override fun onPlayerError(error: PlaybackException) { status.text = "投屏播放失败:${error.errorCodeName}" } + + override fun onPlayerError(error: PlaybackException) { + status.text = "投屏播放失败:${error.errorCodeName}" + } } + override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val root = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL } ViewCompat.setOnApplyWindowInsetsListener(root) { view, insets -> val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) - view.setPadding(16 + bars.left, bars.top, 16 + bars.right, bars.bottom); insets + view.setPadding(16 + bars.left, bars.top, 16 + bars.right, bars.bottom) + insets + } + status = TextView(this).apply { + text = if (hasGoogleServices) "正在连接 Google Cast 服务…" else "未安装 Google Play 服务:使用局域网直连 Cast" } - status = TextView(this).apply { text = "正在连接 Google Cast 服务…" } root.addView(status) - val route = MediaRouteButton(this) - root.addView(route) - val setup = runCatching { MediaRouteButtonFactory.setUpMediaRouteButton(this, route) }.getOrNull() - if (setup == null) status.text = "Google Cast 不可用,请检查 Google Play 服务与网络" - else Futures.addCallback(setup, object : FutureCallback { - override fun onSuccess(result: Void?) = Unit - override fun onFailure(t: Throwable) { status.text = "Google Cast 不可用,请检查 Google Play 服务与网络" } - }, ContextCompat.getMainExecutor(this)) + if (hasGoogleServices) { + val route = MediaRouteButton(this) + root.addView(route) + setupGoogleServices(route) + } playerView = PlayerView(this) root.addView(playerView, LinearLayout.LayoutParams(-1, 0, 1f)) - root.addView(Button(this).apply { text = "结束投屏并返回本机"; setOnClickListener { returnToLocal() } }) - setContentView(root) - onBackPressedDispatcher.addCallback(this, object : androidx.activity.OnBackPressedCallback(true) { - override fun handleOnBackPressed() { returnToLocal() } + if (!hasGoogleServices) playerView.visibility = View.GONE + + root.addView(TextView(this).apply { + text = "局域网直连(无需 Google 服务)" + setPadding(0, 16, 0, 4) }) + directStatus = TextView(this).apply { text = "正在搜索局域网 Cast 设备…" } + root.addView(directStatus) + directList = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL } + root.addView(directList) + root.addView(Button(this).apply { + text = "重新搜索局域网设备" + isAllCaps = false + setOnClickListener { searchDirect() } + }) + directControls = LinearLayout(this).apply { + orientation = LinearLayout.HORIZONTAL + visibility = View.GONE + } + pauseButton = Button(this).apply { + text = "暂停" + isAllCaps = false + setOnClickListener { toggleDirect() } + } + directControls.addView(pauseButton, LinearLayout.LayoutParams(0, -2, 1f)) + root.addView(directControls) + root.addView(Button(this).apply { + text = "结束投屏并返回本机" + isAllCaps = false + setOnClickListener { returnToLocal() } + }) + setContentView(root) + onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) { + override fun handleOnBackPressed() = returnToLocal() + }) + searchDirect() + } + + private fun setupGoogleServices(route: MediaRouteButton) { + val setup = runCatching { MediaRouteButtonFactory.setUpMediaRouteButton(this, route) }.getOrNull() + if (setup == null) { + status.text = "Google Cast 不可用,请检查 Google Play 服务与网络" + } else { + Futures.addCallback(setup, object : FutureCallback { + override fun onSuccess(result: Void?) = Unit + override fun onFailure(t: Throwable) { + status.text = "Google Cast 不可用,请检查 Google Play 服务与网络" + } + }, ContextCompat.getMainExecutor(this)) + } val token = SessionToken(this, ComponentName(this, GoogleCastService::class.java)) future = MediaController.Builder(this, token).buildAsync().also { connection -> Futures.addCallback(connection, object : FutureCallback { override fun onSuccess(result: MediaController?) { - if (isDestroyed || returning) { result?.release(); return } + if (isDestroyed || returning) { + result?.release() + return + } controller = result result ?: return result.addListener(listener) playerView.player = result val uri = intent.getStringExtra("uri") ?: return if (result.mediaItemCount == 0 || result.currentMediaItem?.localConfiguration?.uri.toString() != uri) { - result.setMediaItem(MediaItem.Builder().setUri(uri).setMimeType(intent.getStringExtra("mime")) - .setMediaMetadata(MediaMetadata.Builder().setTitle(intent.getStringExtra("title")).build()).build(), intent.getLongExtra("position", 0)) + result.setMediaItem( + MediaItem.Builder().setUri(uri).setMimeType(intent.getStringExtra("mime")) + .setMediaMetadata(MediaMetadata.Builder().setTitle(intent.getStringExtra("title")).build()).build(), + intent.getLongExtra("position", 0), + ) result.prepare(); result.play() } listener.onDeviceInfoChanged(result.deviceInfo) } - override fun onFailure(t: Throwable) { status.text = "Google Cast 服务连接失败;本地来源可返回继续播放" } + + override fun onFailure(t: Throwable) { + status.text = "Google Cast 服务连接失败;可使用局域网直连" + } }, ContextCompat.getMainExecutor(this)) } } + + private fun searchDirect() { + directList.removeAllViews() + directStatus.text = "正在搜索局域网 Cast 设备…" + lifecycleScope.launch { + val devices = runCatching { LanCastDiscovery(this@GoogleCastActivity).discover() }.getOrDefault(emptyList()) + if (isFinishing || isDestroyed) return@launch + directStatus.text = if (devices.isEmpty()) "未发现局域网 Cast 设备(请确认与接收端在同一 Wi-Fi)" else "选择要投屏的设备" + devices.forEach { device -> + directList.addView(Button(this@GoogleCastActivity).apply { + text = "${device.name} · ${device.host}" + isAllCaps = false + setOnClickListener { startDirect(device) } + }) + } + } + } + + private fun startDirect(device: LanCastDevice) { + val media = intentCastMedia() ?: return + direct?.close() + direct = null + directStarted = false + directState = RemotePlaybackState() + directControls.visibility = View.GONE + directName = device.name + directStatus.text = "正在连接 ${device.name}…" + val client = DirectCastClient( + device.host, + device.port, + lifecycleScope, + onState = { state -> + runOnUiThread { + directState = state + renderDirect() + } + }, + onStatus = { text -> runOnUiThread { directStatus.text = text } }, + ) + direct = client + lifecycleScope.launch { + try { + client.connectAndLoad(media) + directControls.visibility = View.VISIBLE + } catch (cancelled: CancellationException) { + throw cancelled + } catch (error: Exception) { + directStatus.text = "连接失败:${error.message ?: "网络错误"}" + client.close() + direct = null + } + } + } + + private fun renderDirect() { + val label = when { + directState.playing -> "播放中" + directState.positionMs > 0 -> "已暂停" + else -> "已连接" + } + directStatus.text = "${directName ?: "Cast 设备"} · $label · ${formatTime(directState.positionMs)}" + pauseButton.text = if (directState.playing) "暂停" else "继续" + val observer = GoogleCastResources.observer ?: return + lifecycleScope.launch { + if (!directStarted && directState.playing) { + directStarted = true + runCatching { observer.started(directState.positionMs) } + } + if (directStarted) runCatching { observer.progress(directState) } + } + } + + private fun toggleDirect() { + val client = direct ?: return + if (directState.playing) client.pause() else client.play() + } + + private fun intentCastMedia(): CastMedia? { + val uri = intent.getStringExtra("uri") ?: return null + return CastMedia( + uri, + intent.getStringExtra("title").orEmpty(), + intent.getStringExtra("mime") ?: "video/mp4", + intent.getLongExtra("position", 0), + ) + } + private fun returnToLocal() { if (returning) return + val client = direct + if (client != null) { + returning = true + val position = directState.positionMs + val playing = directState.playing + lifecycleScope.launch { + runCatching { client.stop() } + withTimeoutOrNull(1500) { runCatching { GoogleCastResources.observer?.stopped(position) } } + delay(200) // 留出时间让 STOP 帧写出后再断开 + client.close() + direct = null + GoogleCastResources.release() + setResult(RESULT_OK, Intent().putExtra("position", position).putExtra("playing", playing)) + finish() + } + return + } returning = true val position = controller?.currentPosition?.coerceAtLeast(0) ?: intent.getLongExtra("position", 0) val playing = controller?.playWhenReady ?: true @@ -94,14 +282,28 @@ class GoogleCastActivity : AppCompatActivity() { stopService(Intent(this, GoogleCastService::class.java)) finish() } + override fun onDestroy() { - controller?.removeListener(listener); if (::playerView.isInitialized) playerView.player = null + controller?.removeListener(listener) + if (::playerView.isInitialized) playerView.player = null future?.let(MediaController::releaseFuture) controller = null + val client = direct + if (client != null) { + client.close() + direct = null + if (!returning && !hasGoogleServices) GoogleCastResources.release() + } super.onDestroy() } + companion object { fun intent(context: Context, media: CastMedia) = Intent(context, GoogleCastActivity::class.java) .putExtra("uri", media.uri).putExtra("mime", media.mimeType).putExtra("title", media.title).putExtra("position", media.startPositionMs) + + private fun formatTime(positionMs: Long): String { + val seconds = positionMs.coerceAtLeast(0) / 1000 + return "%02d:%02d".format(seconds / 60, seconds % 60) + } } } diff --git a/player-cast-google/src/main/kotlin/com/ttstd/player/cast/google/LanCastDiscovery.kt b/player-cast-google/src/main/kotlin/com/ttstd/player/cast/google/LanCastDiscovery.kt new file mode 100644 index 0000000..ac710f2 --- /dev/null +++ b/player-cast-google/src/main/kotlin/com/ttstd/player/cast/google/LanCastDiscovery.kt @@ -0,0 +1,200 @@ +package com.ttstd.player.cast.google + +import android.content.Context +import android.net.wifi.WifiManager +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.io.ByteArrayOutputStream +import java.net.DatagramPacket +import java.net.DatagramSocket +import java.net.InetAddress +import java.net.SocketTimeoutException + +data class LanCastDevice(val id: String?, val name: String, val host: String, val port: Int) + +/** 自包含 mDNS 发现:查询 _googlecast._tcp,不依赖 Google Play 服务。 + * 查询设置 QU 位,接收端单播应答即可发现,不依赖手机接收组播。 */ +class LanCastDiscovery(context: Context) { + private val appContext = context.applicationContext + + suspend fun discover(timeoutMs: Long = 3500): List = withContext(Dispatchers.IO) { + val wifi = appContext.getSystemService(Context.WIFI_SERVICE) as? WifiManager + val lock = runCatching { + wifi?.createMulticastLock("TTVideoPlayer-cast")?.apply { setReferenceCounted(false); acquire() } + }.getOrNull() + try { + DatagramSocket().use { socket -> + socket.soTimeout = 300 + socket.broadcast = true + val group = InetAddress.getByName(MULTICAST) + val query = buildQuery() + val collector = MdnsCollector() + val until = System.nanoTime() + timeoutMs.coerceIn(500, 15000) * 1_000_000 + var nextSend = 0L + while (System.nanoTime() < until) { + val now = System.nanoTime() + if (now >= nextSend) { + socket.send(DatagramPacket(query, query.size, group, MDNS_PORT)) + nextSend = now + 1_000_000_000 + } + val packet = DatagramPacket(ByteArray(9000), 9000) + try { + socket.receive(packet) + collector.parse(packet.data, packet.length) + } catch (_: SocketTimeoutException) { + } + } + collector.devices(localAddresses()) + } + } finally { + if (lock?.isHeld == true) runCatching { lock.release() } + } + } + + /** 本机已连接的 IPv4(排除回环/链路本地),用于在多条 A 记录时优先同网段地址。 */ + private fun localAddresses(): List = runCatching { + java.util.Collections.list(java.net.NetworkInterface.getNetworkInterfaces()) + .flatMap { nic -> java.util.Collections.list(nic.inetAddresses) } + .filterIsInstance() + .filter { !it.isLoopbackAddress && !it.isLinkLocalAddress } + .mapNotNull { it.hostAddress } + }.getOrDefault(emptyList()) + + private fun buildQuery(): ByteArray { + val out = ByteArrayOutputStream() + out.write(byteArrayOf(0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0)) + for (label in QUERY_NAME.split('.')) { + val bytes = label.toByteArray(Charsets.UTF_8) + out.write(bytes.size) + out.write(bytes) + } + out.write(0) + out.write(byteArrayOf(0, 12)) // PTR + out.write(byteArrayOf(0x80.toByte(), 0x01)) // QU + IN + return out.toByteArray() + } + + companion object { + private const val QUERY_NAME = "_googlecast._tcp.local" + private const val MULTICAST = "224.0.0.251" + private const val MDNS_PORT = 5353 + } +} + +/** 跨多个报文累积 PTR/SRV/TXT/A,最后拼成设备列表;包内名字支持压缩指针。 */ +internal class MdnsCollector { + private val pointers = LinkedHashSet() + private val services = HashMap>() + private val texts = HashMap>() + private val addresses = HashMap>() + + fun parse(data: ByteArray, length: Int) { + if (length < 12) return + val questions = u16(data, 4) + val records = u16(data, 6) + u16(data, 8) + u16(data, 10) + var offset = 12 + repeat(questions) { + val name = readName(data, length, offset) ?: return + offset = name.second + 4 + if (offset > length) return + } + repeat(records) { + val name = readName(data, length, offset) ?: return + offset = name.second + if (offset + 10 > length) return + val type = u16(data, offset) + val dataLength = u16(data, offset + 8) + val start = offset + 10 + if (start + dataLength > length) return + val end = start + dataLength + when (type) { + 12 -> readName(data, length, start)?.let { target -> + if (name.first.equals(QUERY_NAME, true)) pointers.add(target.first) + } + 33 -> if (dataLength >= 7) { + val port = u16(data, start + 4) + val target = readName(data, length, start + 6) + if (target != null) services[name.first.lowercase()] = port to target.first + } + 16 -> texts[name.first.lowercase()] = parseTxt(data, start, end) + 1 -> if (dataLength == 4) { + addresses.getOrPut(name.first.lowercase()) { ArrayList() }.add( + "${data[start].toInt() and 0xFF}.${data[start + 1].toInt() and 0xFF}.${data[start + 2].toInt() and 0xFF}.${data[start + 3].toInt() and 0xFF}" + ) + } + } + offset = end + } + } + + fun devices(localAddresses: List = emptyList()): List = pointers.mapNotNull { instance -> + if (!instance.endsWith(QUERY_NAME, true)) return@mapNotNull null + val key = instance.lowercase() + val service = services[key] ?: return@mapNotNull null + val host = pickAddress(addresses[service.second.lowercase()], localAddresses) ?: return@mapNotNull null + val txt = texts[key].orEmpty() + val name = txt["fn"]?.takeIf { it.isNotBlank() } ?: instance.substringBefore("._googlecast", instance) + LanCastDevice(txt["id"], name, host, service.first) + }.distinctBy { it.host to it.port } + + /** 接收端可能把多块网卡的 A 记录都放进应答;优先选择与本机同 /24 的地址。 */ + private fun pickAddress(candidates: List?, localAddresses: List): String? { + if (candidates.isNullOrEmpty()) return null + if (candidates.size == 1) return candidates.first() + val localSubnets = localAddresses.mapNotNull { it.substringBeforeLast('.', "").takeIf(String::isNotEmpty) }.toSet() + return candidates.firstOrNull { it.substringBeforeLast('.', "") in localSubnets } ?: candidates.first() + } + + private fun parseTxt(data: ByteArray, start: Int, end: Int): Map { + val result = HashMap() + var offset = start + while (offset < end) { + val size = data[offset].toInt() and 0xFF + offset++ + if (offset + size > end) break + val entry = String(data, offset, size, Charsets.UTF_8) + offset += size + val separator = entry.indexOf('=') + if (separator > 0) result[entry.substring(0, separator)] = entry.substring(separator + 1) + } + return result + } + + /** 返回 (名字, 名字之后的下一个偏移);压缩指针跳转后仍返回原始位置之后的偏移。 */ + private fun readName(data: ByteArray, length: Int, start: Int): Pair? { + val labels = ArrayList(4) + var cursor = start + var next = start + var jumped = false + var jumps = 0 + while (true) { + if (cursor >= length) return null + val size = data[cursor].toInt() and 0xFF + if (size and 0xC0 == 0xC0) { + if (cursor + 1 >= length || ++jumps > 16) return null + if (!jumped) next = cursor + 2 + cursor = ((size and 0x3F) shl 8) or (data[cursor + 1].toInt() and 0xFF) + jumped = true + continue + } + if (size and 0xC0 != 0) return null + cursor++ + if (size == 0) { + if (!jumped) next = cursor + break + } + if (cursor + size > length) return null + labels.add(String(data, cursor, size, Charsets.UTF_8)) + cursor += size + if (!jumped) next = cursor + } + return labels.joinToString(".") to next + } + + private fun u16(data: ByteArray, offset: Int): Int = + ((data[offset].toInt() and 0xFF) shl 8) or (data[offset + 1].toInt() and 0xFF) + + private companion object { + const val QUERY_NAME = "_googlecast._tcp.local" + } +} diff --git a/player-cast-google/src/test/kotlin/com/ttstd/player/cast/google/CastWireTest.kt b/player-cast-google/src/test/kotlin/com/ttstd/player/cast/google/CastWireTest.kt new file mode 100644 index 0000000..5268533 --- /dev/null +++ b/player-cast-google/src/test/kotlin/com/ttstd/player/cast/google/CastWireTest.kt @@ -0,0 +1,38 @@ +package com.ttstd.player.cast.google + +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Test + +class CastWireTest { + @Test + fun messageRoundTrip() { + val payload = """{"type":"CONNECT"}""" + val body = CastWire.encodeMessage("sender-0", "receiver-0", "urn:x-cast:com.google.cast.tp.connection", payload) + val decoded = CastWire.decode(body) + assertNotNull(decoded) + assertEquals("sender-0", decoded!!.sourceId) + assertEquals("receiver-0", decoded.destinationId) + assertEquals("urn:x-cast:com.google.cast.tp.connection", decoded.namespace) + assertEquals(payload, decoded.payload) + } + + @Test + fun framePrefixesBigEndianLength() { + val body = CastWire.encodeMessage("a", "b", "ns", "{}") + val framed = CastWire.frame(body) + val length = ((framed[0].toInt() and 0xFF) shl 24) or + ((framed[1].toInt() and 0xFF) shl 16) or + ((framed[2].toInt() and 0xFF) shl 8) or + (framed[3].toInt() and 0xFF) + assertEquals(body.size, length) + assertEquals(4 + body.size, framed.size) + assertArrayEquals(body, framed.copyOfRange(4, framed.size)) + } + + @Test + fun rejectsTruncatedBody() { + assertEquals(null, CastWire.decode(byteArrayOf(0x12, 0x05, 0x41))) + } +} diff --git a/player-cast-google/src/test/kotlin/com/ttstd/player/cast/google/LanCastDiscoveryTest.kt b/player-cast-google/src/test/kotlin/com/ttstd/player/cast/google/LanCastDiscoveryTest.kt new file mode 100644 index 0000000..bcb5bdb --- /dev/null +++ b/player-cast-google/src/test/kotlin/com/ttstd/player/cast/google/LanCastDiscoveryTest.kt @@ -0,0 +1,123 @@ +package com.ttstd.player.cast.google + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.ByteArrayOutputStream + +class LanCastDiscoveryTest { + @Test + fun parsesPtrSrvTxtAndAddress() { + val packet = response() + val collector = MdnsCollector() + collector.parse(packet, packet.size) + val devices = collector.devices() + assertEquals(1, devices.size) + val device = devices.first() + assertEquals("同同投屏接收器", device.name) + assertEquals("192.168.100.222", device.host) + assertEquals(8009, device.port) + assertEquals("72e081aa12345678", device.id) + } + + @Test + fun requiresPtrSrvAndAddress() { + val collector = MdnsCollector() + val packet = response(includeSrv = false) + collector.parse(packet, packet.size) + assertTrue(collector.devices().isEmpty()) + } + + @Test + fun prefersAddressOnLocalSubnet() { + val packet = response( + addresses = listOf( + byteArrayOf(192.toByte(), 168.toByte(), 137.toByte(), 1), + byteArrayOf(192.toByte(), 168.toByte(), 100, 222.toByte()), + ), + ) + val collector = MdnsCollector() + collector.parse(packet, packet.size) + val device = collector.devices(localAddresses = listOf("192.168.100.141")).single() + assertEquals("192.168.100.222", device.host) + } + + /** 构造一条含 PTR/SRV/TXT/A 的 mDNS 响应,SRV/TXT 用压缩指针引用 PTR 的实例名。 */ + private fun response( + includeSrv: Boolean = true, + addresses: List = listOf(byteArrayOf(192.toByte(), 168.toByte(), 100, 222.toByte())), + ): ByteArray { + val instance = "TTS-72e081aa._googlecast._tcp.local" + val host = "tts-cast-72e081aa.local" + val out = ByteArrayOutputStream() + val answerCount = if (includeSrv) 3 + addresses.size - 1 else 2 + addresses.size - 1 + out.write(byteArrayOf(0, 0, 0x84.toByte(), 0, 0, 0, 0, 1, 0, 0, 0, answerCount.toByte())) + out.write(encodeName("_googlecast._tcp.local")) + writeU16(out, 12); writeU16(out, 1); writeU32(out, 120) + val instanceBytes = encodeName(instance) + writeU16(out, instanceBytes.size); out.write(instanceBytes) + val instanceOffset = out.size() - instanceBytes.size + + val records = mutableListOf() + if (includeSrv) { + val srv = ByteArrayOutputStream() + srv.write(byteArrayOf(0xC0.toByte(), instanceOffset.toByte())) + writeU16(srv, 33); writeU16(srv, 0x8001) + writeU32(srv, 120) + val srvData = ByteArrayOutputStream() + srvData.write(byteArrayOf(0, 0, 0, 0, 0x1F, 0x49.toByte())) + srvData.write(encodeName(host)) + val data = srvData.toByteArray() + writeU16(srv, data.size); srv.write(data) + records.add(srv.toByteArray()) + } + run { + val txt = ByteArrayOutputStream() + txt.write(byteArrayOf(0xC0.toByte(), instanceOffset.toByte())) + writeU16(txt, 16); writeU16(txt, 0x8001) + writeU32(txt, 120) + val entries = listOf("id=72e081aa12345678", "fn=同同投屏接收器") + val data = ByteArrayOutputStream() + entries.forEach { entry -> + val bytes = entry.toByteArray(Charsets.UTF_8) + data.write(bytes.size); data.write(bytes) + } + val bytes = data.toByteArray() + writeU16(txt, bytes.size); txt.write(bytes) + records.add(txt.toByteArray()) + } + addresses.forEach { ip -> + val address = ByteArrayOutputStream() + address.write(encodeName(host)) + writeU16(address, 1); writeU16(address, 0x8001) + writeU32(address, 120) + writeU16(address, 4) + address.write(ip) + records.add(address.toByteArray()) + } + records.forEach { out.write(it) } + return out.toByteArray() + } + + private fun encodeName(name: String): ByteArray { + val out = ByteArrayOutputStream() + name.split('.').forEach { label -> + val bytes = label.toByteArray(Charsets.UTF_8) + out.write(bytes.size); out.write(bytes) + } + out.write(0) + return out.toByteArray() + } + + private fun writeU16(out: ByteArrayOutputStream, value: Int) { + out.write((value ushr 8) and 0xFF) + out.write(value and 0xFF) + } + + private fun writeU32(out: ByteArrayOutputStream, value: Int) { + out.write((value ushr 24) and 0xFF) + out.write((value ushr 16) and 0xFF) + out.write((value ushr 8) and 0xFF) + out.write(value and 0xFF) + } +}