feat(video): 打通桌面端真实视频画面链路
- Rust: 新增 media::stream 访问单元队列与分片重组,FFI 增加 ttstd_video_next/pending/stats(ABI 2) - Windows: runner 内嵌 Media Foundation 解码纹理插件(NV12/RGB32→BGRA),开启 CODECAPI_AVLowLatencyMode 消除约 36 帧积压,按显示区域裁掉 16 对齐补齐行 - Android: 大帧按 1200 字节分片发送;csd(SPS/PPS) 随每个关键帧重发,修复先投屏后连接时只收到 P 帧导致的黑屏 - Flutter: 独立 ttstd/video 通道获取 textureId 与统计,VideoView 渲染 Texture 并显示分辨率/PTS/失败原因 - 诊断: stats 增加 format/auBytes/keyframes/submitHr;缺插件、缺 SPS/PPS 显式提示;TTSTD_DUMP_VIDEO 可抓码流配合 ffprobe 定位 - 发现与服务检查: mDNS 发现客户端、服务地址探测、设置页与连接状态卡片(启动本机监听/停止) - 工具与文档: video_feed 推流示例、一键打包脚本、DEMO 出画面排查表与实测截图
This commit is contained in:
1 parent
adaa23f895
commit
df2affa9e2
30 files changed
+2814
-134
No files matched your search
@@ -10,7 +10,8 @@
|
||||
<application
|
||||
android:allowBackup="false"
|
||||
android:label="@string/app_name"
|
||||
android:theme="@style/Theme.Lancast">
|
||||
android:theme="@style/Theme.Lancast"
|
||||
android:usesCleartextTraffic="true">
|
||||
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
|
||||
@@ -15,6 +15,8 @@ import java.net.NetworkInterface
|
||||
class MainActivity : Activity() {
|
||||
companion object {
|
||||
private const val REQUEST_CAPTURE = 1001
|
||||
private const val DEFAULT_HOST = "10.0.2.2"
|
||||
private const val DEFAULT_SIGNALING_URL = "http://10.0.2.2:8080"
|
||||
const val EXTRA_HOST = "com.ttstd.lancast.receiver.HOST"
|
||||
const val EXTRA_SIGNALING = "com.ttstd.lancast.receiver.SIGNALING"
|
||||
}
|
||||
@@ -29,15 +31,17 @@ class MainActivity : Activity() {
|
||||
status = TextView(this).apply {
|
||||
text = if (MediaProjectionService.isRunning) "状态:采集中" else "状态:未开始"
|
||||
}
|
||||
val initialHost = intent?.getStringExtra(EXTRA_HOST)?.takeIf { it.isNotBlank() } ?: ""
|
||||
val initialSignaling = intent?.getStringExtra(EXTRA_SIGNALING)?.takeIf { it.isNotBlank() } ?: ""
|
||||
val initialHost = DEFAULT_HOST
|
||||
val initialSignaling = DEFAULT_SIGNALING_URL
|
||||
hostInput = EditText(this).apply {
|
||||
hint = "主控端 IP"
|
||||
setText(initialHost)
|
||||
isEnabled = false
|
||||
}
|
||||
signalingInput = EditText(this).apply {
|
||||
hint = "信令服务器(可选)"
|
||||
hint = "信令服务器"
|
||||
setText(initialSignaling)
|
||||
isEnabled = false
|
||||
}
|
||||
val pairing = TextView(this).apply {
|
||||
text = "配对码:生成中..."
|
||||
@@ -83,8 +87,8 @@ class MainActivity : Activity() {
|
||||
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
||||
super.onActivityResult(requestCode, resultCode, data)
|
||||
if (requestCode != REQUEST_CAPTURE || resultCode != RESULT_OK || data == null) return
|
||||
val host = hostInput.text.toString().trim()
|
||||
val signalingUrl = signalingInput.text.toString().trim()
|
||||
val host = DEFAULT_HOST
|
||||
val signalingUrl = DEFAULT_SIGNALING_URL
|
||||
MediaProjectionService.start(this, resultCode, data, host, signalingUrl)
|
||||
status.text = "状态:连接中..."
|
||||
}
|
||||
|
||||
@@ -46,7 +46,9 @@ class ReceiverSession(
|
||||
clipboard,
|
||||
fileService,
|
||||
)
|
||||
private val encoder = VideoEncoder { buffer, info -> transport.sendVideo(buffer, info) }
|
||||
private val encoder = VideoEncoder { buffer, info ->
|
||||
transport.sendVideo(buffer, info, preferH265)
|
||||
}
|
||||
|
||||
private var capturer: ScreenCapturer? = null
|
||||
private var audio: AudioCapturer? = null
|
||||
@@ -107,7 +109,7 @@ class ReceiverSession(
|
||||
announcer?.stop()
|
||||
nsdAdvertiser?.stop()
|
||||
opusEncoder.stop()
|
||||
transport.close()
|
||||
transport.stop()
|
||||
encoder.stop()
|
||||
executor.shutdownNow()
|
||||
}
|
||||
|
||||
+35
-16
@@ -1,5 +1,6 @@
|
||||
package com.ttstd.lancast.receiver.discovery
|
||||
|
||||
import android.util.Log
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.net.HttpURLConnection
|
||||
@@ -25,9 +26,13 @@ class ReceiverAnnouncer(
|
||||
future = exec.scheduleWithFixedDelay({
|
||||
try {
|
||||
val path = if (registered) "/heartbeat" else "/register"
|
||||
post(path, body())
|
||||
registered = true
|
||||
} catch (_: Exception) {
|
||||
registered = post(path, body())
|
||||
if (!registered) {
|
||||
Log.w(TAG, "信令注册失败,将在下一轮重试")
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
registered = false
|
||||
Log.w(TAG, "信令请求异常:$error")
|
||||
}
|
||||
}, 0, 15, TimeUnit.SECONDS)
|
||||
}
|
||||
@@ -53,19 +58,33 @@ class ReceiverAnnouncer(
|
||||
put("ttl", 30)
|
||||
}.toString()
|
||||
|
||||
private fun post(path: String, body: String) {
|
||||
try {
|
||||
val connection = URL(signalingUrl.trimEnd('/') + path).openConnection() as HttpURLConnection
|
||||
connection.requestMethod = "POST"
|
||||
connection.doOutput = true
|
||||
connection.setRequestProperty("Content-Type", "application/json")
|
||||
connection.connectTimeout = 3000
|
||||
connection.readTimeout = 3000
|
||||
connection.outputStream.use { it.write(body.toByteArray(Charsets.UTF_8)) }
|
||||
connection.responseCode
|
||||
connection.disconnect()
|
||||
} catch (_: Exception) {
|
||||
// 信令临时不可达不影响 mDNS 同网段直连。
|
||||
private fun post(path: String, body: String): Boolean {
|
||||
var connection: HttpURLConnection? = null
|
||||
return try {
|
||||
val http = URL(signalingUrl.trimEnd('/') + path).openConnection() as HttpURLConnection
|
||||
connection = http
|
||||
http.requestMethod = "POST"
|
||||
http.doOutput = true
|
||||
http.setRequestProperty("Content-Type", "application/json")
|
||||
http.connectTimeout = 3000
|
||||
http.readTimeout = 3000
|
||||
http.outputStream.use { it.write(body.toByteArray(Charsets.UTF_8)) }
|
||||
val code = http.responseCode
|
||||
if (code !in 200..299) {
|
||||
Log.w(TAG, "信令 $path 返回 HTTP $code")
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
Log.w(TAG, "信令 $path 请求失败:$error")
|
||||
false
|
||||
} finally {
|
||||
connection?.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val TAG = "ReceiverAnnouncer"
|
||||
}
|
||||
}
|
||||
+60
-2
@@ -12,6 +12,13 @@ class VideoEncoder(private val onPacket: (ByteBuffer, MediaCodec.BufferInfo) ->
|
||||
var inputSurface: Surface? = null
|
||||
private set
|
||||
|
||||
/**
|
||||
* 编解码配置(SPS/PPS)。摄像头/Surface 输入的编码器不会把 SPS/PPS 放在码流里,
|
||||
* 而是通过 csd-0/csd-1 或 CODEC_CONFIG 帧单独给出。缺了它的裸流解不出任何画面,
|
||||
* 所以这里记录下来并随每个关键帧一起发送。
|
||||
*/
|
||||
private var codecConfig: ByteArray? = null
|
||||
|
||||
fun start(width: Int, height: Int, fps: Int, bitrateBps: Int, preferH265: Boolean) {
|
||||
val mime = if (preferH265) MediaFormat.MIMETYPE_VIDEO_HEVC else MediaFormat.MIMETYPE_VIDEO_AVC
|
||||
val format = MediaFormat.createVideoFormat(mime, width, height).apply {
|
||||
@@ -31,16 +38,66 @@ class VideoEncoder(private val onPacket: (ByteBuffer, MediaCodec.BufferInfo) ->
|
||||
val encoder = codec ?: return
|
||||
val info = MediaCodec.BufferInfo()
|
||||
var index = encoder.dequeueOutputBuffer(info, 0)
|
||||
while (index >= 0) {
|
||||
while (index >= 0 || index == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
|
||||
if (index == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
|
||||
// 输出格式一旦确定就带回 csd-0/csd-1(SPS/PPS)。
|
||||
captureCodecConfig(encoder)
|
||||
index = encoder.dequeueOutputBuffer(info, 0)
|
||||
continue
|
||||
}
|
||||
val buffer = encoder.getOutputBuffer(index)
|
||||
if (buffer != null && info.size > 0) {
|
||||
onPacket(buffer, info)
|
||||
if (info.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG != 0) {
|
||||
// 部分设备把 SPS/PPS 作为独立的配置帧输出。
|
||||
codecConfig = ByteArray(info.size).also { target ->
|
||||
val view = buffer.duplicate()
|
||||
view.position(info.offset)
|
||||
view.limit(info.offset + info.size)
|
||||
view.get(target)
|
||||
}
|
||||
} else {
|
||||
emitWithConfig(buffer, info)
|
||||
}
|
||||
}
|
||||
encoder.releaseOutputBuffer(index, false)
|
||||
index = encoder.dequeueOutputBuffer(info, 0)
|
||||
}
|
||||
}
|
||||
|
||||
/** 把 SPS/PPS 前置到关键帧,保证对端随时能从任意关键帧开始解码。 */
|
||||
private fun emitWithConfig(buffer: ByteBuffer, info: MediaCodec.BufferInfo) {
|
||||
val config = codecConfig
|
||||
val isKeyFrame = info.flags and MediaCodec.BUFFER_FLAG_KEY_FRAME != 0
|
||||
if (config == null || config.isEmpty() || !isKeyFrame) {
|
||||
onPacket(buffer, info)
|
||||
return
|
||||
}
|
||||
val payload = ByteArray(config.size + info.size)
|
||||
System.arraycopy(config, 0, payload, 0, config.size)
|
||||
val view = buffer.duplicate()
|
||||
view.position(info.offset)
|
||||
view.limit(info.offset + info.size)
|
||||
view.get(payload, config.size, info.size)
|
||||
val merged = MediaCodec.BufferInfo().apply {
|
||||
set(0, payload.size, info.presentationTimeUs, info.flags)
|
||||
}
|
||||
onPacket(ByteBuffer.wrap(payload), merged)
|
||||
}
|
||||
|
||||
private fun captureCodecConfig(encoder: MediaCodec) {
|
||||
val format = encoder.outputFormat
|
||||
val chunks = ArrayList<ByteArray>(2)
|
||||
for (name in listOf("csd-0", "csd-1")) {
|
||||
val csd = format.getByteBuffer(name) ?: continue
|
||||
val bytes = ByteArray(csd.remaining())
|
||||
csd.duplicate().get(bytes)
|
||||
chunks += bytes
|
||||
}
|
||||
if (chunks.isNotEmpty()) {
|
||||
codecConfig = chunks.reduce { acc, item -> acc + item }
|
||||
}
|
||||
}
|
||||
|
||||
fun requestKeyFrame() {
|
||||
codec?.setParameters(Bundle().apply {
|
||||
putInt(MediaCodec.PARAMETER_KEY_REQUEST_SYNC_FRAME, 0)
|
||||
@@ -51,6 +108,7 @@ class VideoEncoder(private val onPacket: (ByteBuffer, MediaCodec.BufferInfo) ->
|
||||
codec?.stop()
|
||||
codec?.release()
|
||||
codec = null
|
||||
codecConfig = null
|
||||
inputSurface?.release()
|
||||
inputSurface = null
|
||||
}
|
||||
|
||||
@@ -8,6 +8,13 @@ import javax.crypto.spec.SecretKeySpec
|
||||
object MediaPackets {
|
||||
const val FLAG_KEYFRAME = 1
|
||||
const val FLAG_AUDIO = 2
|
||||
// 与 Rust Core 的 media::stream 保持一致的扩展标志位。
|
||||
const val FLAG_HEVC = 0x08
|
||||
const val FLAG_FRAGMENT_START = 0x10
|
||||
const val FLAG_FRAGMENT_CONTINUE = 0x20
|
||||
const val FLAG_FRAGMENT_END = 0x40
|
||||
// 单个 UDP 分片的负载上限:13 字节头 + 4 字节 MAC + 1200 负载仍远小于 MTU。
|
||||
const val FRAGMENT_PAYLOAD_SIZE = 1200
|
||||
private const val HEADER_SIZE = 13
|
||||
private const val MAC_SIZE = 4
|
||||
|
||||
|
||||
+96
-38
@@ -44,6 +44,8 @@ class ReceiverTransport(
|
||||
private var udp: DatagramSocket? = null
|
||||
private var keys: SessionCrypto.SessionKeys? = null
|
||||
@Volatile
|
||||
private var active = false
|
||||
@Volatile
|
||||
private var running = false
|
||||
@Volatile
|
||||
private var sequence = 0
|
||||
@@ -51,34 +53,63 @@ class ReceiverTransport(
|
||||
val keyEstablished: Boolean get() = keys != null
|
||||
|
||||
fun start() {
|
||||
if (active) return
|
||||
active = true
|
||||
executor.execute {
|
||||
try {
|
||||
val raw = Socket().apply {
|
||||
tcpNoDelay = true
|
||||
soTimeout = 5000
|
||||
connect(InetSocketAddress(host, controlPort), 5000)
|
||||
while (active) {
|
||||
try {
|
||||
connectAndRun()
|
||||
} catch (error: Exception) {
|
||||
Log.e("ReceiverTransport", "Failed to connect or handshake", error)
|
||||
} finally {
|
||||
resetConnection()
|
||||
}
|
||||
if (!active) break
|
||||
try {
|
||||
Thread.sleep(2000)
|
||||
} catch (_: InterruptedException) {
|
||||
break
|
||||
}
|
||||
socket = raw
|
||||
output = DataOutputStream(raw.outputStream)
|
||||
val input = DataInputStream(raw.inputStream)
|
||||
|
||||
// ECDH 握手:先发本地公钥,再读取对端 65 字节公钥。
|
||||
output?.write(crypto.publicBytes)
|
||||
output?.flush()
|
||||
val peerPublic = ByteArray(65)
|
||||
input.readFully(peerPublic)
|
||||
keys = crypto.deriveKeys(peerPublic)
|
||||
|
||||
udp = DatagramSocket()
|
||||
running = true
|
||||
readLoop(input)
|
||||
} catch (e: Exception) {
|
||||
Log.e("ReceiverTransport", "Failed to connect or handshake", e)
|
||||
close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun connectAndRun() {
|
||||
val raw = Socket().apply {
|
||||
tcpNoDelay = true
|
||||
soTimeout = 5000
|
||||
connect(InetSocketAddress(host, controlPort), 5000)
|
||||
}
|
||||
socket = raw
|
||||
output = DataOutputStream(raw.outputStream)
|
||||
val input = DataInputStream(raw.inputStream)
|
||||
|
||||
// ECDH 握手:先发本地公钥,再读取对端 65 字节公钥。
|
||||
output?.write(crypto.publicBytes)
|
||||
output?.flush()
|
||||
val peerPublic = ByteArray(65)
|
||||
input.readFully(peerPublic)
|
||||
keys = crypto.deriveKeys(peerPublic)
|
||||
|
||||
udp = DatagramSocket()
|
||||
running = true
|
||||
Log.i("ReceiverTransport", "Connected to $host:$controlPort")
|
||||
readLoop(input)
|
||||
}
|
||||
|
||||
private fun resetConnection() {
|
||||
running = false
|
||||
try {
|
||||
socket?.close()
|
||||
udp?.close()
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
socket = null
|
||||
output = null
|
||||
udp = null
|
||||
keys = null
|
||||
}
|
||||
|
||||
fun sendControl(event: ControlEvent) {
|
||||
executor.execute {
|
||||
val key = keys?.control ?: return@execute
|
||||
@@ -88,7 +119,7 @@ class ReceiverTransport(
|
||||
}
|
||||
}
|
||||
|
||||
fun sendVideo(buffer: ByteBuffer, info: MediaCodec.BufferInfo) {
|
||||
fun sendVideo(buffer: ByteBuffer, info: MediaCodec.BufferInfo, hevc: Boolean = false) {
|
||||
val key = keys?.video ?: return
|
||||
if (!running) return
|
||||
val duplicate = buffer.duplicate().apply {
|
||||
@@ -97,32 +128,59 @@ class ReceiverTransport(
|
||||
}
|
||||
val payload = ByteArray(info.size)
|
||||
duplicate.get(payload)
|
||||
val flags = if (info.flags and MediaCodec.BUFFER_FLAG_KEY_FRAME != 0) {
|
||||
var flags = if (info.flags and MediaCodec.BUFFER_FLAG_KEY_FRAME != 0) {
|
||||
MediaPackets.FLAG_KEYFRAME
|
||||
} else {
|
||||
0
|
||||
}
|
||||
val packet = MediaPackets.encode(payload, info.presentationTimeUs, flags, key)
|
||||
udp?.send(DatagramPacket(packet, packet.size, InetSocketAddress(host, mediaPort)))
|
||||
if (hevc) flags = flags or MediaPackets.FLAG_HEVC
|
||||
val target = InetSocketAddress(host, mediaPort)
|
||||
val chunk = MediaPackets.FRAGMENT_PAYLOAD_SIZE
|
||||
try {
|
||||
if (payload.size <= chunk) {
|
||||
val packet = MediaPackets.encode(payload, info.presentationTimeUs, flags, key)
|
||||
udp?.send(DatagramPacket(packet, packet.size, target))
|
||||
return
|
||||
}
|
||||
// 大帧(尤其 I 帧)必须分片,否则超过 UDP 上限会被整帧丢弃。
|
||||
var offset = 0
|
||||
while (offset < payload.size) {
|
||||
val end = minOf(offset + chunk, payload.size)
|
||||
var fragmentFlags = flags
|
||||
fragmentFlags = fragmentFlags or if (offset == 0) {
|
||||
MediaPackets.FLAG_FRAGMENT_START
|
||||
} else {
|
||||
MediaPackets.FLAG_FRAGMENT_CONTINUE
|
||||
}
|
||||
if (end >= payload.size) {
|
||||
fragmentFlags = fragmentFlags or MediaPackets.FLAG_FRAGMENT_END
|
||||
}
|
||||
val part = payload.copyOfRange(offset, end)
|
||||
val packet = MediaPackets.encode(part, info.presentationTimeUs, fragmentFlags, key)
|
||||
udp?.send(DatagramPacket(packet, packet.size, target))
|
||||
offset = end
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
}
|
||||
|
||||
fun sendAudio(opusPacket: ByteArray, pts: Long) {
|
||||
val key = keys?.audio ?: return
|
||||
if (!running) return
|
||||
val packet = MediaPackets.encode(opusPacket, pts, MediaPackets.FLAG_AUDIO, key)
|
||||
udp?.send(DatagramPacket(packet, packet.size, InetSocketAddress(host, audioPort)))
|
||||
try {
|
||||
udp?.send(DatagramPacket(packet, packet.size, InetSocketAddress(host, audioPort)))
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
}
|
||||
|
||||
fun close() {
|
||||
running = false
|
||||
try {
|
||||
socket?.close()
|
||||
udp?.close()
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
socket = null
|
||||
udp = null
|
||||
keys = null
|
||||
active = false
|
||||
resetConnection()
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
close()
|
||||
executor.shutdownNow()
|
||||
}
|
||||
|
||||
@@ -150,8 +208,8 @@ class ReceiverTransport(
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
// 对端断开时结束读取循环。
|
||||
} catch (error: Exception) {
|
||||
Log.w("ReceiverTransport", "Control channel ended: $error")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user