feat(core): 新增上行事件队列与 msgType=9 会话配置帧

- demo_server 增加 inbound 队列,mirror 应答与上行剪贴板入队供界面轮询(上限 64,丢最旧)
- 新增 peek_inbound_event / pop_inbound_event,FFI 暴露 ttstd_event_next(缓冲不足时不出队)
- 协议新增 MSG_CONFIG=9:payload 为 UTF-8 JSON,binary 编解码与 ffi 下发均已支持
- 补充 Config 事件编解码单测
This commit is contained in:
tongtong committed 2026-11-27 17:42:22 +08:00
1 parent cbbc2a642d
commit e43e51d9c3
4 files changed
+154 -5

No files matched your search

+14 -3
View File
@@ -1,8 +1,9 @@
use super::codec::{CodecError, ControlFrameCodec, ControlFrameHeader};
use super::events::{
ClipboardEvent, ControlEvent, ControlEventKind, KeyAction, KeyboardEvent, MirrorEvent,
MouseAction, MouseEvent, TouchAction, TouchEvent, WheelEvent, MSG_CLIPBOARD, MSG_KEY,
MSG_MIRROR, MSG_MOUSE, MSG_PING, MSG_PONG, MSG_TOUCH, MSG_WHEEL, PROTOCOL_VERSION,
ClipboardEvent, ConfigEvent, ControlEvent, ControlEventKind, KeyAction, KeyboardEvent,
MirrorEvent, MouseAction, MouseEvent, TouchAction, TouchEvent, WheelEvent, MSG_CLIPBOARD,
MSG_CONFIG, MSG_KEY, MSG_MIRROR, MSG_MOUSE, MSG_PING, MSG_PONG, MSG_TOUCH, MSG_WHEEL,
PROTOCOL_VERSION,
};
#[derive(Debug, Default, Clone, Copy)]
@@ -55,6 +56,9 @@ impl ControlFrameCodec for BinaryCodec {
buffer.push(payload.action);
buffer.extend_from_slice(payload.message.as_bytes());
}
ControlEventKind::Config(payload) => {
buffer.extend_from_slice(payload.json.as_bytes());
}
}
let payload_len = (buffer.len() - ControlFrameHeader::LEN) as u32;
@@ -162,6 +166,10 @@ fn decode_payload(msg_type: u8, payload: &[u8]) -> Result<ControlEventKind, Code
.map_err(|_| CodecError::InvalidUtf8)?;
Ok(ControlEventKind::Mirror(MirrorEvent { action, message }))
}
MSG_CONFIG => {
let json = String::from_utf8(payload.to_vec()).map_err(|_| CodecError::InvalidUtf8)?;
Ok(ControlEventKind::Config(ConfigEvent { json }))
}
other => Err(CodecError::UnknownMsgType(other)),
}
}
@@ -219,6 +227,9 @@ mod tests {
action: 5,
message: "无屏幕录制权限".to_string(),
}));
assert_roundtrip(ControlEventKind::Config(ConfigEvent {
json: r#"{"preferH265":true,"bitrateMbps":12}"#.to_string(),
}));
}
#[test]
+12
View File
@@ -11,6 +11,10 @@ pub const MSG_PONG: u8 = 6;
/// 投屏请求/应答。payload = `[action:u8]` + 可选 UTF-8 文本。
pub const MSG_MIRROR: u8 = 8;
/// 会话配置。payload = UTF-8 JSON:`preferH265` / `bitrateMbps` /
/// `audioEnabled` / `clipboardSync`,字段全部可选。
pub const MSG_CONFIG: u8 = 9;
/// 投屏控制动作,两端必须保持一致。
pub mod mirror_action {
pub const REQUEST: u8 = 0;
@@ -158,6 +162,12 @@ pub struct MirrorEvent {
pub message: String,
}
/// 会话配置负载。`json` 是主控端下发的原始 UTF-8 JSON 串。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfigEvent {
pub json: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ControlEventKind {
Touch(TouchEvent),
@@ -168,6 +178,7 @@ pub enum ControlEventKind {
Ping(u64),
Pong(u64),
Mirror(MirrorEvent),
Config(ConfigEvent),
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -195,6 +206,7 @@ impl ControlEvent {
ControlEventKind::Ping(_) => MSG_PING,
ControlEventKind::Pong(_) => MSG_PONG,
ControlEventKind::Mirror(_) => MSG_MIRROR,
ControlEventKind::Config(_) => MSG_CONFIG,
}
}
}
+101 -2
View File
@@ -6,6 +6,7 @@
//! 3. 后续控制帧使用 `SecureControlChannel`(8 字节明头 + 12 字节 nonce + 密文 + 16 字节 tag)。
//! 4. 视频/音频通过 UDP 41000/41002 发送,使用 `MediaPackets` 的 13 字节头 + 4 字节 HMAC。
use std::collections::VecDeque;
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream, UdpSocket};
use std::sync::atomic::{AtomicBool, Ordering};
@@ -14,8 +15,8 @@ use std::thread::{self, JoinHandle};
use std::time::Duration;
use crate::control::events::{
ClipboardEvent, KeyAction, KeyboardEvent, MirrorEvent, MouseAction, MouseEvent, TouchAction,
TouchEvent, WheelEvent,
ClipboardEvent, ConfigEvent, KeyAction, KeyboardEvent, MirrorEvent, MouseAction, MouseEvent,
TouchAction, TouchEvent, WheelEvent, MSG_CLIPBOARD, MSG_MIRROR,
};
use crate::control::{ControlEvent, ControlEventKind};
@@ -72,6 +73,44 @@ struct ControlSender {
channel: SecureControlChannel,
}
/// 被控端上行的控制事件(mirror 应答 / 剪贴板),供 UI 侧轮询消费。
///
/// 与 `events`(诊断用的字符串环形缓冲)分开:这里只放界面真正要处理的事件,
/// 取走即出队,不会因为诊断日志刷太快把有用事件挤掉。
#[derive(Debug, Clone)]
struct InboundEvent {
msg_type: u8,
action: i32,
text: String,
}
impl InboundEvent {
fn to_json(&self) -> String {
format!(
"{{\"type\":{},\"action\":{},\"text\":\"{}\"}}",
self.msg_type,
self.action,
escape_json(&self.text)
)
}
}
fn escape_json(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for ch in text.chars() {
match ch {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
control if (control as u32) < 0x20 => out.push(' '),
other => out.push(other),
}
}
out
}
struct Shared {
running: AtomicBool,
peer_connected: AtomicBool,
@@ -82,6 +121,7 @@ struct Shared {
audio_key: Mutex<Option<[u8; 32]>>,
sender: Mutex<Option<ControlSender>>,
events: Mutex<Vec<String>>,
inbound: Mutex<VecDeque<InboundEvent>>,
}
impl Shared {
@@ -96,6 +136,7 @@ impl Shared {
audio_key: Mutex::new(None),
sender: Mutex::new(None),
events: Mutex::new(Vec::new()),
inbound: Mutex::new(VecDeque::new()),
}
}
@@ -108,6 +149,22 @@ impl Shared {
}
}
fn push_inbound(&self, event: InboundEvent) {
if let Ok(mut queue) = self.inbound.lock() {
// 界面没及时消费时丢最旧的,避免无限增长。
if queue.len() >= 64 {
queue.pop_front();
}
queue.push_back(event);
}
}
fn clear_inbound(&self) {
if let Ok(mut queue) = self.inbound.lock() {
queue.clear();
}
}
fn status(&self) -> DemoStatus {
let key_prefix = |key: &Mutex<Option<[u8; 32]>>| -> String {
key.lock()
@@ -190,6 +247,7 @@ fn reset_session_state(shared: &Shared) {
*guard = None;
}
}
shared.clear_inbound();
shared.peer_connected.store(false, Ordering::SeqCst);
shared.key_established.store(false, Ordering::SeqCst);
if let Ok(mut ip) = shared.peer_ip.lock() {
@@ -286,6 +344,24 @@ pub fn status() -> DemoStatus {
server_handle().shared.status()
}
/// 查看队首的上行事件(mirror 应答 / 剪贴板)JSON,队列空时返回 None。
///
/// 与 [`pop_inbound_event`] 配对使用:调用方先把 JSON 拷进自己的缓冲,再出队,
/// 避免缓冲不够时把事件丢掉。
pub fn peek_inbound_event() -> Option<String> {
let shared = &server_handle().shared;
let queue = shared.inbound.lock().ok()?;
queue.front().map(|event| event.to_json())
}
/// 丢弃队首的上行事件(通常紧跟在 [`peek_inbound_event`] 之后)。
pub fn pop_inbound_event() {
let shared = &server_handle().shared;
if let Ok(mut queue) = shared.inbound.lock() {
queue.pop_front();
}
}
/// 把控制事件编码为 AES-GCM 帧并下发给当前被控端。
/// 返回 Ok(()) 表示已写入 TCP,Err 表示未连接或写入失败。
pub fn send_control(event: ControlEvent) -> Result<(), String> {
@@ -366,6 +442,11 @@ pub fn mirror_event(sequence: u16, action: u8, message: String) -> ControlEvent
ControlEvent::new(sequence, ControlEventKind::Mirror(MirrorEvent { action, message }))
}
/// msgType=9 会话配置帧:payload 是主控端拼好的 UTF-8 JSON。
pub fn config_event(sequence: u16, json: String) -> ControlEvent {
ControlEvent::new(sequence, ControlEventKind::Config(ConfigEvent { json }))
}
fn run_tcp(listener: TcpListener, shared: Arc<Shared>) {
while shared.running.load(Ordering::Relaxed) {
match listener.accept() {
@@ -505,6 +586,24 @@ fn handle_peer(stream: &mut std::net::TcpStream, shared: &Arc<Shared>) {
event.sequence(),
event.msg_type()
));
// 界面要处理的事件单独入队:诊断日志刷得快,不能只靠 events 环。
match &event.kind {
ControlEventKind::Mirror(mirror) => {
shared.push_inbound(InboundEvent {
msg_type: MSG_MIRROR,
action: i32::from(mirror.action),
text: mirror.message.clone(),
});
}
ControlEventKind::Clipboard(clipboard) => {
shared.push_inbound(InboundEvent {
msg_type: MSG_CLIPBOARD,
action: 0,
text: clipboard.text.clone(),
});
}
_ => {}
}
buffer.drain(..consumed);
if let crate::control::ControlEventKind::Ping(timestamp) = event.kind {
let pong = crate::control::ControlEvent::new(
+27
View File
@@ -301,6 +301,7 @@ pub unsafe extern "C" fn ttstd_control_decode(
ControlEventKind::Wheel(_) => "wheel",
ControlEventKind::Clipboard(_) => "clipboard",
ControlEventKind::Mirror(_) => "mirror",
ControlEventKind::Config(_) => "config",
};
let json = format!(
"{{\"sequence\":{},\"msgType\":{},\"kind\":\"{}\"}}",
@@ -313,6 +314,7 @@ pub unsafe extern "C" fn ttstd_control_decode(
/// 向当前被控端下发控制帧。payload 为各事件类型的二进制负载。
/// msg_type: 0=touch 1=mouse 2=key 3=wheel 4=clipboard(UTF-8) 5=ping(u64 LE)
/// 8=mirror([action:u8]+文本) 9=sessionConfig(UTF-8 JSON)
#[no_mangle]
pub unsafe extern "C" fn ttstd_demo_send_control(
sequence: u16,
@@ -365,6 +367,11 @@ pub unsafe extern "C" fn ttstd_demo_send_control(
bytes[0],
String::from_utf8_lossy(&bytes[1..]).to_string(),
)),
// 9 = 会话配置:payload 就是 UTF-8 JSON
9 => Some(crate::demo_server::config_event(
sequence,
String::from_utf8_lossy(bytes).to_string(),
)),
_ => None,
};
match event {
@@ -398,6 +405,26 @@ pub unsafe extern "C" fn ttstd_demo_status(out_json: *mut u8, capacity: usize) -
copy_out(json.as_bytes(), out_json, capacity)
}
/// 取出一个待处理的上行控制事件 JSON:`{"type":8,"action":2,"text":"..."}`。
///
/// - 返回正数:写入 `out_json` 的字节数,事件已出队。
/// - 返回 `0`:队列为空。
/// - 返回 [`ERR_BUFFER_TOO_SMALL`]:容量不足,事件**保留**在队列中。
///
/// # Safety
/// out_json 可写且容量为 capacity。
#[no_mangle]
pub unsafe extern "C" fn ttstd_event_next(out_json: *mut u8, capacity: usize) -> i32 {
let Some(json) = crate::demo_server::peek_inbound_event() else {
return 0;
};
let written = copy_out(json.as_bytes(), out_json, capacity);
if written >= 0 {
crate::demo_server::pop_inbound_event();
}
written
}
/// 视频访问单元元信息。字段布局需与 Windows 原生解码侧保持一致。
#[repr(C)]
#[derive(Debug, Clone, Copy, Default)]