feat(connection): 增加远程视频录制、分辨率/帧率切换及高刷适配
- 新增 VideoRecorder 基于 flutter_webrtc MediaRecorder 录制远程视频为 MP4 - 新增 ControlMessageDecoder 解析被控端上报的 REPORT_* protobuf 消息 - 连接控制器支持分辨率/帧率切换、录制状态管理与远程上报处理 - 远程控制页新增更多菜单(静音/分辨率/帧率/录制),并统一退出时断开连接 - WebRTC 编排器在 DataChannel 打开及媒体就绪后主动请求默认分辨率,解决黑屏问题 - 新增 DisplayModeUtil 在 Android 上启用最高刷新率 - 登出时失效设备相关 Provider,避免切换账号后读到旧缓存
This commit is contained in:
1 parent
41a514e9cc
commit
bfb106f1fb
13 files changed
+1267
-514
No files matched your search
@@ -137,3 +137,102 @@ class ControlMessageEncoder {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 被控端上报的远程视频信息(REPORT_RESOLUTION / REPORT_STREAM_MODE)。
|
||||
class ReportInfo {
|
||||
final int action;
|
||||
final int width;
|
||||
final int height;
|
||||
final int fps;
|
||||
final int streamMode;
|
||||
final List<int> supportedFps;
|
||||
|
||||
const ReportInfo({
|
||||
this.action = 0,
|
||||
this.width = 0,
|
||||
this.height = 0,
|
||||
this.fps = 0,
|
||||
this.streamMode = 0,
|
||||
this.supportedFps = const [],
|
||||
});
|
||||
}
|
||||
|
||||
/// protobuf wire format 解码器。
|
||||
///
|
||||
/// 与控制端 `com.ttstd.control.ControlMessage`(protobuf 3)字段号完全对齐,
|
||||
/// 仅解析被控端会回传的字段(action/width/height/fps/stream_mode/supported_fps)。
|
||||
class ControlMessageDecoder {
|
||||
/// 解析被控端上报的 REPORT_* 消息;无法解析返回 null。
|
||||
static ReportInfo? decode(Uint8List data) {
|
||||
int action = 0;
|
||||
int width = 0;
|
||||
int height = 0;
|
||||
int fps = 0;
|
||||
int streamMode = 0;
|
||||
final supportedFps = <int>[];
|
||||
|
||||
final reader = ByteData.sublistView(data);
|
||||
var pos = 0;
|
||||
try {
|
||||
while (pos < data.length) {
|
||||
final tag = _readVarint(reader, pos);
|
||||
pos = tag.$2;
|
||||
final field = tag.$1 >> 3;
|
||||
final wireType = tag.$1 & 0x07;
|
||||
switch (wireType) {
|
||||
case 0: // varint
|
||||
final v = _readVarint(reader, pos);
|
||||
pos = v.$2;
|
||||
final val = v.$1;
|
||||
switch (field) {
|
||||
case 1:
|
||||
action = val;
|
||||
break;
|
||||
case 12:
|
||||
width = val;
|
||||
break;
|
||||
case 13:
|
||||
height = val;
|
||||
break;
|
||||
case 14:
|
||||
fps = val;
|
||||
break;
|
||||
case 15:
|
||||
streamMode = val;
|
||||
break;
|
||||
case 16:
|
||||
supportedFps.add(val);
|
||||
break;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
// 未知 wire type:跳过(解析到 known fields 前不应出现)
|
||||
return null;
|
||||
}
|
||||
}
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
return ReportInfo(
|
||||
action: action,
|
||||
width: width,
|
||||
height: height,
|
||||
fps: fps,
|
||||
streamMode: streamMode,
|
||||
supportedFps: supportedFps,
|
||||
);
|
||||
}
|
||||
|
||||
/// 读取一个 varint,返回 (值, 新的位置)。越界抛异常。
|
||||
static (int, int) _readVarint(ByteData data, int pos) {
|
||||
var result = 0;
|
||||
var shift = 0;
|
||||
while (true) {
|
||||
final byte = data.getUint8(pos++);
|
||||
result |= (byte & 0x7F) << shift;
|
||||
if ((byte & 0x80) == 0) break;
|
||||
shift += 7;
|
||||
}
|
||||
return (result, pos);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter_webrtc/flutter_webrtc.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
/// 远程视频录制器:基于 flutter_webrtc 的 [MediaRecorder],
|
||||
/// 把远端视频轨道(MediaStreamTrack)直接封装为 MP4 保存到本地。
|
||||
///
|
||||
/// 跨平台(Android / iOS)由 flutter_webrtc 内部完成 H.264 编码与封装,
|
||||
/// 无需自行触碰原生 VideoSink。
|
||||
///
|
||||
/// 录制文件保存位置:
|
||||
/// - Android:/Android/data/<包名>/files/WebRTCRecordings/(app 专属外部存储,无需存储权限)
|
||||
/// - iOS:<App>/Documents/WebRTCRecordings/
|
||||
class VideoRecorder {
|
||||
MediaRecorder? _recorder;
|
||||
bool _recording = false;
|
||||
String? _currentPath;
|
||||
|
||||
/// 是否正在录制。
|
||||
bool get isRecording => _recording;
|
||||
|
||||
/// 是否为空(从未真正开始)。
|
||||
String? get currentPath => _currentPath;
|
||||
|
||||
/// 开始录制指定媒体流中的视频轨道。
|
||||
///
|
||||
/// 返回 true 表示成功开始;空流 / 无视频轨道会抛异常。
|
||||
Future<bool> start(MediaStream stream) async {
|
||||
if (_recording) return false;
|
||||
final videoTracks = stream.getVideoTracks();
|
||||
if (videoTracks.isEmpty) {
|
||||
throw Exception('当前没有可用的远端视频轨道,无法录制');
|
||||
}
|
||||
final path = await _buildOutputPath();
|
||||
// ignore: avoid_print
|
||||
print('[VideoRecorder] 录制开始,保存地址:$path');
|
||||
_recorder = MediaRecorder(albumName: 'WebRTCRecordings');
|
||||
await _recorder!.start(path, videoTrack: videoTracks.first);
|
||||
_currentPath = path;
|
||||
_recording = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// 停止录制,返回最终保存的文件路径;未开始录制返回 null。
|
||||
Future<String?> stop() async {
|
||||
if (!_recording || _recorder == null) return null;
|
||||
try {
|
||||
await _recorder!.stop();
|
||||
} catch (e) {
|
||||
// 停止失败时仍清理状态,避免界面卡在"录制中"
|
||||
// ignore: avoid_print
|
||||
print('[VideoRecorder] stop error: $e');
|
||||
} finally {
|
||||
_recorder = null;
|
||||
_recording = false;
|
||||
}
|
||||
final p = _currentPath;
|
||||
_currentPath = null;
|
||||
// ignore: avoid_print
|
||||
print('[VideoRecorder] 录制结束,已保存至:$p');
|
||||
return p;
|
||||
}
|
||||
|
||||
/// 释放资源(断开连接 / 页面销毁时调用)。
|
||||
Future<void> dispose() async {
|
||||
if (_recording && _recorder != null) {
|
||||
try {
|
||||
await _recorder!.stop();
|
||||
} catch (_) {
|
||||
// 忽略
|
||||
}
|
||||
}
|
||||
_recorder = null;
|
||||
_recording = false;
|
||||
_currentPath = null;
|
||||
}
|
||||
|
||||
static String _pad(int n) => n.toString().padLeft(2, '0');
|
||||
|
||||
static Future<Directory> _getRecordingDir() async {
|
||||
final base = Platform.isAndroid
|
||||
? (await getExternalStorageDirectory())!
|
||||
: await getApplicationDocumentsDirectory();
|
||||
final dir = Directory('${base.path}/WebRTCRecordings');
|
||||
if (!await dir.exists()) {
|
||||
await dir.create(recursive: true);
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
|
||||
static Future<String> _buildOutputPath() async {
|
||||
final dir = await _getRecordingDir();
|
||||
final now = DateTime.now();
|
||||
final name = 'rec_${now.year}${_pad(now.month)}${_pad(now.day)}_'
|
||||
'${_pad(now.hour)}${_pad(now.minute)}${_pad(now.second)}.mp4';
|
||||
return '${dir.path}/$name';
|
||||
}
|
||||
}
|
||||
@@ -54,8 +54,8 @@ class WebRtcOrchestrator {
|
||||
/// 远程屏幕渲染器(供页面 RTCVideoView 使用)。
|
||||
final RTCVideoRenderer remoteRenderer = RTCVideoRenderer();
|
||||
|
||||
/// 接收到的被控端报告消息(如 REPORT_RESOLUTION)。
|
||||
void Function(Uint8List data)? onControlMessage;
|
||||
/// 被控端上报的 REPORT_* 消息(REPORT_RESOLUTION / REPORT_STREAM_MODE)。
|
||||
void Function(ReportInfo report)? onReport;
|
||||
|
||||
/// 连接状态变化(用于 UI 显示 "已连接")。
|
||||
void Function(bool connected)? onConnectionState;
|
||||
@@ -74,6 +74,7 @@ class WebRtcOrchestrator {
|
||||
|
||||
/// 发起连接:创建 PeerConnection + DataChannel + 发送 OFFER。
|
||||
Future<void> start() async {
|
||||
await remoteRenderer.initialize();
|
||||
await _initPeerConnection();
|
||||
|
||||
// 创建 control_channel(有序、可靠,保证指令不丢)
|
||||
@@ -83,11 +84,18 @@ class WebRtcOrchestrator {
|
||||
_controlChannel = await _pc!.createDataChannel(_dataChannelLabel, dataChannelInit);
|
||||
_controlChannel!.onMessage = (RTCDataChannelMessage message) {
|
||||
if (message.isBinary) {
|
||||
onControlMessage?.call(message.binary);
|
||||
final report = ControlMessageDecoder.decode(message.binary);
|
||||
if (report != null) {
|
||||
onReport?.call(report);
|
||||
}
|
||||
}
|
||||
};
|
||||
_controlChannel!.onDataChannelState = (RTCDataChannelState state) {
|
||||
debugPrint('[webrtc] control_channel state: $state');
|
||||
if (state == RTCDataChannelState.RTCDataChannelOpen) {
|
||||
// DataChannel 开启后发送一次默认分辨率指令,确保被控端开始推流(解决黑屏需操作才显示的 bug)
|
||||
sendSetResolution();
|
||||
}
|
||||
};
|
||||
|
||||
// 创建 Offer
|
||||
@@ -127,22 +135,16 @@ class WebRtcOrchestrator {
|
||||
debugPrint('[webrtc] 收到远程屏幕轨道');
|
||||
final stream = event.streams.isNotEmpty ? event.streams.first : null;
|
||||
if (stream != null) {
|
||||
// RTCVideoRenderer 必须先 initialize() 再设置 srcObject,否则抛
|
||||
// "Call initialize before setting the stream" 异常,导致画面不渲染。
|
||||
remoteRenderer.initialize().then((_) {
|
||||
remoteRenderer.srcObject = stream;
|
||||
}).catchError((e) {
|
||||
debugPrint('[webrtc] renderer initialize error: $e');
|
||||
});
|
||||
remoteRenderer.srcObject = stream;
|
||||
onConnectionState?.call(true);
|
||||
// 媒体就绪后唤醒被控端持续推流,解决静止画面黑屏/需操作才显示。
|
||||
_wakeUpStreaming();
|
||||
}
|
||||
};
|
||||
|
||||
_pc!.onConnectionState = (RTCPeerConnectionState state) {
|
||||
debugPrint('[webrtc] connection state: ${state.name}');
|
||||
if (state == RTCPeerConnectionState.RTCPeerConnectionStateConnected) {
|
||||
onConnectionState?.call(true);
|
||||
} else if (state == RTCPeerConnectionState.RTCPeerConnectionStateDisconnected ||
|
||||
if (state == RTCPeerConnectionState.RTCPeerConnectionStateDisconnected ||
|
||||
state == RTCPeerConnectionState.RTCPeerConnectionStateFailed ||
|
||||
state == RTCPeerConnectionState.RTCPeerConnectionStateClosed) {
|
||||
onConnectionState?.call(false);
|
||||
@@ -264,6 +266,31 @@ class WebRtcOrchestrator {
|
||||
sendCommand(bytes);
|
||||
}
|
||||
|
||||
/// 发送串流模式指令(mode:0=WebRTC 内置媒体流,1=自编码 H.264)。
|
||||
///
|
||||
/// 注意:被控端 `stream_mode` 语义是「编码方式」而非「按需/持续推流」。
|
||||
/// 本控制端未移植自编码解码链路(方案 §7.1 裁剪),因此**不要**发送
|
||||
/// `mode=1`,否则被控端会切到无人消费的 `video_channel` 自编码裸流导致黑屏。
|
||||
void sendSetStreamMode(int mode) {
|
||||
final bytes = ControlMessageEncoder(
|
||||
action: ActionType.setStreamMode,
|
||||
streamMode: mode,
|
||||
).encode();
|
||||
sendCommand(bytes);
|
||||
}
|
||||
|
||||
/// 媒体连接建立后唤醒被控端推帧:延迟发送一次轻量指令,确保被控端已就绪。
|
||||
///
|
||||
/// 静止画面持续推流由被控端自身保障(`ScreenCaptureService` 的 heartbeat
|
||||
/// 每秒刷新通知扰动 MediaProjection 强制产帧),控制端无需也不应发送
|
||||
/// `SET_STREAM_MODE`。这里仅请求一次默认分辨率(width=0=原生)触发关键帧刷新。
|
||||
void _wakeUpStreaming() {
|
||||
Future.delayed(const Duration(milliseconds: 300), () {
|
||||
// 请求一次默认分辨率(原生长边),触发被控端关键帧刷新远端画面。
|
||||
sendSetResolution();
|
||||
});
|
||||
}
|
||||
|
||||
/// 关闭连接。
|
||||
Future<void> dispose() async {
|
||||
try {
|
||||
|
||||
Reference in new issue
Block a user