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
@@ -3,6 +3,7 @@ import 'dart:io';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import 'discovery_client.dart';
|
||||
import 'local_signaling.dart';
|
||||
import 'models.dart';
|
||||
import 'native_core.dart';
|
||||
@@ -21,6 +22,9 @@ class SenderBridge {
|
||||
final NativeCore? _native;
|
||||
final LocalSignalingProcess _localSignaling = LocalSignalingProcess();
|
||||
|
||||
/// 原生视频解码纹理通道(Windows runner 内嵌插件)。
|
||||
static const MethodChannel _video = MethodChannel('ttstd/video');
|
||||
|
||||
NativeCore? get nativeCore => _native;
|
||||
|
||||
bool get isLocalSignalingRunning => _localSignaling.isRunning;
|
||||
@@ -33,23 +37,13 @@ class SenderBridge {
|
||||
.distinct();
|
||||
}
|
||||
|
||||
Future<List<DeviceInfo>> discover() async {
|
||||
Future<List<DeviceInfo>> discover({String? signalingUrl}) async {
|
||||
if (signalingUrl != null && signalingUrl.trim().isNotEmpty) {
|
||||
final discovered = await DiscoveryClient.listDevices(signalingUrl);
|
||||
if (discovered.isNotEmpty) return discovered;
|
||||
}
|
||||
if (_native != null) {
|
||||
final localIp = await _localIp();
|
||||
if (localIp == null) return const <DeviceInfo>[];
|
||||
return [
|
||||
DeviceInfo(
|
||||
id: 'local-listener',
|
||||
name: '本机监听端点',
|
||||
ip: localIp,
|
||||
mediaPort: 41000,
|
||||
controlPort: 41001,
|
||||
fingerprint: '',
|
||||
capabilities: const <String>[],
|
||||
model: '',
|
||||
resolution: '',
|
||||
),
|
||||
];
|
||||
return const <DeviceInfo>[];
|
||||
}
|
||||
try {
|
||||
final raw = await _method.invokeListMethod<dynamic>('discover');
|
||||
@@ -62,6 +56,22 @@ class SenderBridge {
|
||||
}
|
||||
}
|
||||
|
||||
Future<DeviceInfo?> localListener() async {
|
||||
final localIp = await _localIp();
|
||||
if (localIp == null) return null;
|
||||
return DeviceInfo(
|
||||
id: 'local-listener',
|
||||
name: '本机监听端点',
|
||||
ip: localIp,
|
||||
mediaPort: 41000,
|
||||
controlPort: 41001,
|
||||
fingerprint: '',
|
||||
capabilities: const <String>[],
|
||||
model: '',
|
||||
resolution: '',
|
||||
);
|
||||
}
|
||||
|
||||
static Future<String?> _localIp() async {
|
||||
try {
|
||||
final interfaces = await NetworkInterface.list(
|
||||
@@ -202,6 +212,35 @@ class SenderBridge {
|
||||
Map<String, dynamic> demoStatus() =>
|
||||
_native?.demoStatus() ?? <String, dynamic>{'running': false};
|
||||
|
||||
/// 原生视频纹理 ID;无原生实现或纹理尚未注册时返回 null。
|
||||
Future<int?> videoTextureId() async {
|
||||
try {
|
||||
final id = await _video.invokeMethod<int>('textureId');
|
||||
if (id == null || id <= 0) return null;
|
||||
return id;
|
||||
} on MissingPluginException {
|
||||
return null;
|
||||
} on PlatformException {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// 原生视频解码统计:textureId/decoded/pending/received/width/height/pts/error。
|
||||
Future<Map<String, dynamic>> videoStats() async {
|
||||
try {
|
||||
final stats = await _video.invokeMapMethod<String, dynamic>('stats');
|
||||
return stats ?? const <String, dynamic>{};
|
||||
} on MissingPluginException {
|
||||
// 老构建产物(runner 里没有视频纹理插件)会走到这里,必须显式提示,
|
||||
// 否则界面只会停在「视频通道已建立」,看不出是二进制过期。
|
||||
return const <String, dynamic>{
|
||||
'error': '当前程序缺少原生视频插件(旧版构建),请重新构建/重新解压发布包',
|
||||
};
|
||||
} on PlatformException {
|
||||
return const <String, dynamic>{};
|
||||
}
|
||||
}
|
||||
|
||||
Future<String?> pairingUri() async {
|
||||
try {
|
||||
final value = await _method.invokeMethod<String>('pairingUri');
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import 'dart:io';
|
||||
|
||||
class DiagnosticLog {
|
||||
DiagnosticLog([this.fileName = 'ttstd_connect.log']);
|
||||
|
||||
final String fileName;
|
||||
File? _file;
|
||||
|
||||
String get path => _file?.path ?? '';
|
||||
|
||||
void start() {
|
||||
final directories = <Directory>[
|
||||
File(Platform.resolvedExecutable).parent,
|
||||
Directory.current,
|
||||
Directory.systemTemp,
|
||||
];
|
||||
for (final directory in directories) {
|
||||
try {
|
||||
final candidate = File(
|
||||
'${directory.path}${Platform.pathSeparator}$fileName',
|
||||
);
|
||||
candidate.writeAsStringSync(
|
||||
'=== TTSTD Connect diagnostic log ===\n'
|
||||
'started: ${DateTime.now().toIso8601String()}\n',
|
||||
mode: FileMode.write,
|
||||
flush: true,
|
||||
);
|
||||
_file = candidate;
|
||||
return;
|
||||
} on Object catch (_) {}
|
||||
}
|
||||
}
|
||||
|
||||
void write(String message) {
|
||||
final file = _file;
|
||||
if (file == null) return;
|
||||
try {
|
||||
if (file.lengthSync() > 2 * 1024 * 1024) {
|
||||
file.writeAsStringSync(
|
||||
'=== log rotated: ${DateTime.now().toIso8601String()} ===\n',
|
||||
mode: FileMode.write,
|
||||
flush: true,
|
||||
);
|
||||
}
|
||||
file.writeAsStringSync(
|
||||
'${DateTime.now().toIso8601String()} $message\n',
|
||||
mode: FileMode.append,
|
||||
flush: true,
|
||||
);
|
||||
} on Object catch (_) {}
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
write('=== stopped ===');
|
||||
_file = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'models.dart';
|
||||
|
||||
class DiscoveryClient {
|
||||
static Future<List<DeviceInfo>> listDevices(
|
||||
String signalingUrl, {
|
||||
Duration timeout = const Duration(seconds: 2),
|
||||
}) async {
|
||||
final trimmed = signalingUrl.trim();
|
||||
if (trimmed.isEmpty) return const <DeviceInfo>[];
|
||||
final client = HttpClient()..connectionTimeout = timeout;
|
||||
try {
|
||||
final base = Uri.parse(trimmed);
|
||||
final path = base.path.endsWith('/')
|
||||
? '${base.path}list'
|
||||
: '${base.path}/list';
|
||||
final request = await client.getUrl(base.replace(path: path)).timeout(timeout);
|
||||
final response = await request.close().timeout(timeout);
|
||||
final body = await utf8.decoder.bind(response).join().timeout(timeout);
|
||||
if (response.statusCode != HttpStatus.ok) return const <DeviceInfo>[];
|
||||
final value = jsonDecode(body);
|
||||
if (value is! Map) return const <DeviceInfo>[];
|
||||
return DeviceInfo.listFromJson(value['devices']);
|
||||
} on Object {
|
||||
return const <DeviceInfo>[];
|
||||
} finally {
|
||||
client.close(force: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -168,7 +168,7 @@ class NativeCore {
|
||||
try {
|
||||
final written = _mediaDecode(packetPtr, packet.length, keyPtr, out, 256);
|
||||
_check(written, 'ttstd_media_decode');
|
||||
return jsonDecode(_copy(out, written).toString()) as Map<String, dynamic>;
|
||||
return jsonDecode(utf8.decode(_copy(out, written))) as Map<String, dynamic>;
|
||||
} finally {
|
||||
calloc.free(out);
|
||||
}
|
||||
@@ -199,11 +199,11 @@ class NativeCore {
|
||||
void stopDemoServer() => _demoStop();
|
||||
|
||||
Map<String, dynamic> demoStatus() {
|
||||
final out = calloc<Uint8>(8192);
|
||||
final out = calloc<Uint8>(65536);
|
||||
try {
|
||||
final written = _demoStatus(out, 8192);
|
||||
final written = _demoStatus(out, 65536);
|
||||
_check(written, 'ttstd_demo_status');
|
||||
return jsonDecode(_copy(out, written).toString()) as Map<String, dynamic>;
|
||||
return jsonDecode(utf8.decode(_copy(out, written))) as Map<String, dynamic>;
|
||||
} finally {
|
||||
calloc.free(out);
|
||||
}
|
||||
@@ -321,7 +321,7 @@ class SecureChannel {
|
||||
try {
|
||||
final written = _core._controlDecode(_handle, framePtr, frame.length, out, 256);
|
||||
if (written < 0) throw NativeCoreException('ttstd_control_decode', written);
|
||||
return jsonDecode(NativeCore._copy(out, written).toString()) as Map<String, dynamic>;
|
||||
return jsonDecode(utf8.decode(NativeCore._copy(out, written))) as Map<String, dynamic>;
|
||||
} finally {
|
||||
calloc.free(out);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
class ServiceCheckResult {
|
||||
const ServiceCheckResult({
|
||||
required this.nativeCoreLoaded,
|
||||
required this.localSignalingRunning,
|
||||
required this.signalingReachable,
|
||||
required this.listenerRunning,
|
||||
required this.listenerReachable,
|
||||
required this.signalingUrl,
|
||||
required this.listenerHost,
|
||||
required this.listenerPort,
|
||||
});
|
||||
|
||||
final bool nativeCoreLoaded;
|
||||
final bool localSignalingRunning;
|
||||
final bool signalingReachable;
|
||||
final bool listenerRunning;
|
||||
final bool listenerReachable;
|
||||
final String signalingUrl;
|
||||
final String listenerHost;
|
||||
final int listenerPort;
|
||||
}
|
||||
|
||||
class ServiceChecker {
|
||||
static Future<bool> checkSignaling(
|
||||
String url, {
|
||||
Duration timeout = const Duration(seconds: 2),
|
||||
}) async {
|
||||
final trimmed = url.trim();
|
||||
if (trimmed.isEmpty) return false;
|
||||
final client = HttpClient()..connectionTimeout = timeout;
|
||||
try {
|
||||
final base = Uri.parse(trimmed);
|
||||
final path = base.path.endsWith('/')
|
||||
? '${base.path}healthz'
|
||||
: '${base.path}/healthz';
|
||||
final request = await client.getUrl(base.replace(path: path)).timeout(timeout);
|
||||
final response = await request.close().timeout(timeout);
|
||||
await response.drain<void>().timeout(timeout);
|
||||
return response.statusCode == HttpStatus.ok;
|
||||
} on Object {
|
||||
return false;
|
||||
} finally {
|
||||
client.close(force: true);
|
||||
}
|
||||
}
|
||||
|
||||
static Future<bool> checkTcp(
|
||||
String host,
|
||||
int port, {
|
||||
Duration timeout = const Duration(seconds: 2),
|
||||
}) async {
|
||||
try {
|
||||
final socket = await Socket.connect(host, port, timeout: timeout);
|
||||
socket.destroy();
|
||||
return true;
|
||||
} on Object {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -158,7 +158,11 @@ class _EmptyState extends StatelessWidget {
|
||||
const SizedBox(height: 12),
|
||||
const Text('未发现设备'),
|
||||
const SizedBox(height: 4),
|
||||
Text('确认手机与主控端处于同一网段', style: Theme.of(context).textTheme.bodySmall),
|
||||
Text(
|
||||
'本机监听端点已移至设置;请确认被控端与主控端处于同一网段',
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
OutlinedButton.icon(
|
||||
onPressed: onRefresh,
|
||||
|
||||
@@ -7,6 +7,7 @@ class VideoView extends StatelessWidget {
|
||||
this.connected = false,
|
||||
this.resolution = '',
|
||||
this.pts,
|
||||
this.error = '',
|
||||
});
|
||||
|
||||
final int? textureId;
|
||||
@@ -14,6 +15,9 @@ class VideoView extends StatelessWidget {
|
||||
final String resolution;
|
||||
final int? pts;
|
||||
|
||||
/// 原生解码链路的失败原因,为空表示没有错误。
|
||||
final String error;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
@@ -46,8 +50,15 @@ class VideoView extends StatelessWidget {
|
||||
Text(connected ? '视频通道已建立' : '等待投屏画面',
|
||||
style: theme.textTheme.titleMedium),
|
||||
const SizedBox(height: 4),
|
||||
Text('H.264/H.265 → External Texture',
|
||||
style: theme.textTheme.bodySmall),
|
||||
Text(
|
||||
error.isNotEmpty ? error : 'H.264/H.265 → External Texture',
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: error.isNotEmpty
|
||||
? theme.colorScheme.error
|
||||
: theme.textTheme.bodySmall?.color,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
),
|
||||
if (resolution.isNotEmpty)
|
||||
|
||||
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
|
||||
|
||||
import '../../core/bridge.dart';
|
||||
import '../../core/models.dart';
|
||||
import '../../core/service_check.dart';
|
||||
|
||||
class SettingsPage extends StatefulWidget {
|
||||
const SettingsPage({
|
||||
@@ -28,6 +29,10 @@ class _SettingsPageState extends State<SettingsPage> {
|
||||
late bool _clipboardSync;
|
||||
late bool _fileTransfer;
|
||||
late int _bitrateMbps;
|
||||
DeviceInfo? _localListener;
|
||||
ServiceCheckResult? _serviceResult;
|
||||
bool _checkingServices = false;
|
||||
bool _listenerRunning = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -42,6 +47,8 @@ class _SettingsPageState extends State<SettingsPage> {
|
||||
_clipboardSync = widget.settings.clipboardSync;
|
||||
_fileTransfer = widget.settings.fileTransfer;
|
||||
_bitrateMbps = widget.settings.bitrateMbps;
|
||||
_loadLocalListener();
|
||||
_refreshListenerState();
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -62,6 +69,102 @@ class _SettingsPageState extends State<SettingsPage> {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _loadLocalListener() async {
|
||||
final listener = await widget.bridge.localListener();
|
||||
if (!mounted) return;
|
||||
setState(() => _localListener = listener);
|
||||
}
|
||||
|
||||
void _refreshListenerState() {
|
||||
try {
|
||||
final status = widget.bridge.demoStatus();
|
||||
_listenerRunning = status['running'] == true;
|
||||
} on Object catch (_) {
|
||||
_listenerRunning = false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _runServiceCheck() async {
|
||||
setState(() => _checkingServices = true);
|
||||
final url = _useLocalSignaling
|
||||
? widget.bridge.localSignalingUrl(_port)
|
||||
: _signalingUrl.text.trim();
|
||||
final listener = _localListener ?? await widget.bridge.localListener();
|
||||
final host = listener?.ip ?? '127.0.0.1';
|
||||
final results = await Future.wait<bool>([
|
||||
ServiceChecker.checkSignaling(url),
|
||||
ServiceChecker.checkTcp(host, 41001),
|
||||
]);
|
||||
Map<String, dynamic> status = const <String, dynamic>{'running': false};
|
||||
try {
|
||||
status = widget.bridge.demoStatus();
|
||||
} on Object catch (_) {}
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_localListener = listener;
|
||||
_listenerRunning = status['running'] == true;
|
||||
_serviceResult = ServiceCheckResult(
|
||||
nativeCoreLoaded: widget.bridge.nativeCore != null,
|
||||
localSignalingRunning: widget.bridge.isLocalSignalingRunning,
|
||||
signalingReachable: results[0],
|
||||
listenerRunning: _listenerRunning,
|
||||
listenerReachable: results[1],
|
||||
signalingUrl: url,
|
||||
listenerHost: host,
|
||||
listenerPort: 41001,
|
||||
);
|
||||
_checkingServices = false;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _toggleListener() async {
|
||||
if (_listenerRunning) {
|
||||
widget.bridge.stopDemoServer();
|
||||
if (!mounted) return;
|
||||
setState(() => _listenerRunning = false);
|
||||
} else {
|
||||
final started = widget.bridge.startDemoServer();
|
||||
var running = started;
|
||||
if (!running) {
|
||||
try {
|
||||
running = widget.bridge.demoStatus()['running'] == true;
|
||||
} on Object catch (_) {}
|
||||
}
|
||||
if (!mounted) return;
|
||||
setState(() => _listenerRunning = running);
|
||||
if (!running) _snack('本机监听启动失败');
|
||||
}
|
||||
await _runServiceCheck();
|
||||
}
|
||||
|
||||
Widget _serviceRow(String label, bool? ok) {
|
||||
final theme = Theme.of(context);
|
||||
final icon = ok == null
|
||||
? Icons.help_outline
|
||||
: ok
|
||||
? Icons.check_circle
|
||||
: Icons.cancel;
|
||||
final color = ok == null
|
||||
? theme.colorScheme.outline
|
||||
: ok
|
||||
? theme.colorScheme.primary
|
||||
: theme.colorScheme.error;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 3),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(icon, size: 18, color: color),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(child: Text(label, style: theme.textTheme.bodySmall)),
|
||||
Text(
|
||||
ok == null ? '未检测' : ok ? '正常' : '异常',
|
||||
style: theme.textTheme.bodySmall?.copyWith(color: color),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _setLocalServer(bool enabled) {
|
||||
setState(() => _localSignalingEnabled = enabled);
|
||||
}
|
||||
@@ -203,6 +306,77 @@ class _SettingsPageState extends State<SettingsPage> {
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Icon(Icons.health_and_safety, color: theme.colorScheme.primary),
|
||||
const SizedBox(width: 8),
|
||||
Text('服务检测', style: theme.textTheme.titleMedium),
|
||||
const Spacer(),
|
||||
TextButton.icon(
|
||||
onPressed: _checkingServices ? null : _runServiceCheck,
|
||||
icon: _checkingServices
|
||||
? const SizedBox(
|
||||
width: 16,
|
||||
height: 16,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Icon(Icons.refresh),
|
||||
label: Text(_checkingServices ? '检测中' : '检测'),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
_serviceRow('Rust Core 动态库', _serviceResult?.nativeCoreLoaded),
|
||||
_serviceRow('本机信令进程', _serviceResult?.localSignalingRunning),
|
||||
_serviceRow('信令 /healthz', _serviceResult?.signalingReachable),
|
||||
_serviceRow('本机监听服务', _serviceResult?.listenerRunning),
|
||||
_serviceRow('主控监听端口 41001', _serviceResult?.listenerReachable),
|
||||
const Divider(height: 24),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text('本机监听端点', style: theme.textTheme.titleSmall),
|
||||
),
|
||||
TextButton.icon(
|
||||
onPressed: _toggleListener,
|
||||
icon: Icon(
|
||||
_listenerRunning ? Icons.stop : Icons.play_arrow,
|
||||
size: 18,
|
||||
),
|
||||
label: Text(_listenerRunning ? '停止' : '启动'),
|
||||
),
|
||||
],
|
||||
),
|
||||
Text(
|
||||
_localListener == null
|
||||
? '未获取到本机 IPv4 地址'
|
||||
: '${_localListener!.ip}:${_localListener!.controlPort} · 媒体 ${_localListener!.mediaPort}',
|
||||
style: theme.textTheme.bodySmall,
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'该端点仅用于被控端接入,不再显示在主页设备列表。',
|
||||
style: theme.textTheme.bodySmall,
|
||||
),
|
||||
if (_serviceResult != null && _serviceResult!.signalingUrl.isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 4),
|
||||
child: Text(
|
||||
'检测地址:${_serviceResult!.signalingUrl}',
|
||||
style: theme.textTheme.labelSmall,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const Divider(height: 32),
|
||||
SwitchListTile(
|
||||
title: const Text('优先使用 H.265'),
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'core/bridge.dart';
|
||||
import 'core/diagnostic_log.dart';
|
||||
import 'core/native_core.dart';
|
||||
import 'core/models.dart';
|
||||
import 'features/control/control_toolbar.dart';
|
||||
@@ -41,7 +43,12 @@ class HomePage extends StatefulWidget {
|
||||
class _HomePageState extends State<HomePage> {
|
||||
NativeCore? _nativeCore;
|
||||
late final SenderBridge _bridge;
|
||||
final DiagnosticLog _diagnosticLog = DiagnosticLog();
|
||||
Timer? _demoStatusTimer;
|
||||
Timer? _diagnosticTimer;
|
||||
Timer? _connectWatchdog;
|
||||
Timer? _discoveryTimer;
|
||||
Timer? _videoStatsTimer;
|
||||
|
||||
List<DeviceInfo> _devices = const <DeviceInfo>[];
|
||||
DeviceInfo? _selected;
|
||||
@@ -51,6 +58,8 @@ class _HomePageState extends State<HomePage> {
|
||||
bool _localSignalingRunning = false;
|
||||
bool _refreshing = false;
|
||||
Map<String, dynamic> _demoStatus = const <String, dynamic>{'running': false};
|
||||
Map<String, dynamic> _videoStats = const <String, dynamic>{};
|
||||
int? _textureId;
|
||||
String? _nativeError;
|
||||
|
||||
@override
|
||||
@@ -62,7 +71,10 @@ class _HomePageState extends State<HomePage> {
|
||||
_nativeError = error.toString();
|
||||
}
|
||||
_bridge = SenderBridge(nativeCore: _nativeCore);
|
||||
_diagnosticLog.start();
|
||||
_diagnosticLog.write('app initialized; nativeError=${_nativeError ?? '-'}');
|
||||
_bridge.watchPhase().listen((phase) {
|
||||
_diagnosticLog.write('phase event -> ${phase.wireName} (${phase.label})');
|
||||
if (mounted) setState(() => _phase = phase);
|
||||
});
|
||||
_applySignalingSettings();
|
||||
@@ -71,11 +83,34 @@ class _HomePageState extends State<HomePage> {
|
||||
const Duration(seconds: 1),
|
||||
(_) => _refreshDemoStatus(),
|
||||
);
|
||||
_diagnosticTimer = Timer.periodic(
|
||||
const Duration(seconds: 1),
|
||||
(_) => _writeDiagnosticLog(),
|
||||
);
|
||||
_discoveryTimer = Timer.periodic(
|
||||
const Duration(seconds: 5),
|
||||
(_) => _refreshDevices(),
|
||||
);
|
||||
_videoStatsTimer = Timer.periodic(
|
||||
const Duration(milliseconds: 500),
|
||||
(_) => _refreshVideoStats(),
|
||||
);
|
||||
_refreshVideoTextureId();
|
||||
// 自测/演示用开关:TTSTD_DEMO_AUTOSTART=1 时启动即开启本机监听。
|
||||
if (Platform.environment['TTSTD_DEMO_AUTOSTART'] == '1') {
|
||||
_startDemoListener();
|
||||
}
|
||||
_writeDiagnosticLog();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_demoStatusTimer?.cancel();
|
||||
_diagnosticTimer?.cancel();
|
||||
_connectWatchdog?.cancel();
|
||||
_discoveryTimer?.cancel();
|
||||
_videoStatsTimer?.cancel();
|
||||
_diagnosticLog.dispose();
|
||||
_bridge.stopDemoServer();
|
||||
_bridge.stopLocalSignaling();
|
||||
_nativeCore?.dispose();
|
||||
@@ -92,16 +127,65 @@ class _HomePageState extends State<HomePage> {
|
||||
final connected = status['peerConnected'] == true;
|
||||
final keyEstablished = status['keyEstablished'] == true;
|
||||
if (running && connected && keyEstablished) {
|
||||
_connectWatchdog?.cancel();
|
||||
_phase = ConnectionPhase.direct;
|
||||
} else if (running && _phase != ConnectionPhase.idle) {
|
||||
} else if (running &&
|
||||
_phase != ConnectionPhase.idle &&
|
||||
_phase != ConnectionPhase.failed) {
|
||||
_phase = ConnectionPhase.probing;
|
||||
}
|
||||
});
|
||||
} on Object catch (_) {
|
||||
// 动态库不可用时忽略轮询错误。
|
||||
} on Object catch (error) {
|
||||
_diagnosticLog.write('demoStatus refresh failed: $error');
|
||||
}
|
||||
}
|
||||
|
||||
/// 首帧前先取一次纹理 ID,避免等待轮询。
|
||||
Future<void> _refreshVideoTextureId() async {
|
||||
final id = await _bridge.videoTextureId();
|
||||
if (!mounted || id == null || id == _textureId) return;
|
||||
setState(() => _textureId = id);
|
||||
}
|
||||
|
||||
/// 轮询原生解码统计:纹理 ID、分辨率、PTS 与失败原因。
|
||||
Future<void> _refreshVideoStats() async {
|
||||
if (!mounted) return;
|
||||
final stats = await _bridge.videoStats();
|
||||
if (!mounted || stats.isEmpty) return;
|
||||
final id = stats['textureId'];
|
||||
setState(() {
|
||||
_videoStats = stats;
|
||||
if (_textureId == null && id is int && id > 0) {
|
||||
_textureId = id;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void _writeDiagnosticLog() {
|
||||
Map<String, dynamic> status;
|
||||
if (_nativeCore == null) {
|
||||
status = <String, dynamic>{'available': false, 'error': _nativeError ?? ''};
|
||||
} else {
|
||||
try {
|
||||
status = _bridge.demoStatus();
|
||||
} on Object catch (error) {
|
||||
status = <String, dynamic>{'available': true, 'error': error.toString()};
|
||||
}
|
||||
}
|
||||
final selected = _selected;
|
||||
final target = selected == null
|
||||
? '-'
|
||||
: '${selected.id} ${selected.ip}:${selected.mediaPort}/${selected.controlPort}';
|
||||
_diagnosticLog.write(
|
||||
'phase=${_phase.wireName} label=${_phase.label}; '
|
||||
'devices=${_devices.length} target=$target refreshing=$_refreshing; '
|
||||
'signaling local=${_settings.useLocalSignaling} '
|
||||
'running=$_localSignalingRunning url=$_effectiveSignalingUrl; '
|
||||
'nativeError=${_nativeError ?? '-'}; textureId=${_textureId ?? '-'}; '
|
||||
'video=$_videoStats; demoStatus=$status',
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _applySignalingSettings() async {
|
||||
if (_settings.localSignalingEnabled) {
|
||||
final started = await _bridge.startLocalSignaling(_settings.localSignalingPort);
|
||||
@@ -115,12 +199,13 @@ class _HomePageState extends State<HomePage> {
|
||||
final url = await _bridge.resolveSignalingUrl(_settings);
|
||||
if (!mounted) return;
|
||||
setState(() => _effectiveSignalingUrl = url);
|
||||
unawaited(_refreshDevices());
|
||||
}
|
||||
|
||||
Future<void> _refreshDevices() async {
|
||||
if (_refreshing) return;
|
||||
setState(() => _refreshing = true);
|
||||
final devices = await _bridge.discover();
|
||||
final devices = await _bridge.discover(signalingUrl: _effectiveSignalingUrl);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_devices = devices;
|
||||
@@ -129,16 +214,42 @@ class _HomePageState extends State<HomePage> {
|
||||
}
|
||||
_refreshing = false;
|
||||
});
|
||||
_diagnosticLog.write('discover result: ${devices.length} devices');
|
||||
}
|
||||
|
||||
Future<void> _connect() async {
|
||||
final device = _selected;
|
||||
if (device == null) return;
|
||||
_diagnosticLog.write(
|
||||
'connect requested: ${device.id} ${device.ip}:${device.mediaPort}/${device.controlPort}',
|
||||
);
|
||||
_connectWatchdog?.cancel();
|
||||
setState(() => _phase = ConnectionPhase.probing);
|
||||
await _bridge.connect(device);
|
||||
_connectWatchdog = Timer(const Duration(seconds: 10), () {
|
||||
if (!mounted || _phase != ConnectionPhase.probing) return;
|
||||
_diagnosticLog.write('connect timeout after 10s');
|
||||
_writeDiagnosticLog();
|
||||
setState(() => _phase = ConnectionPhase.failed);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('连接超时:被控端未接入,请检查 IP、端口和网络')),
|
||||
);
|
||||
});
|
||||
try {
|
||||
await _bridge.connect(device);
|
||||
} on Object catch (error) {
|
||||
_connectWatchdog?.cancel();
|
||||
_diagnosticLog.write('connect failed: $error');
|
||||
if (!mounted) return;
|
||||
setState(() => _phase = ConnectionPhase.failed);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('连接失败:$error')),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _disconnect() async {
|
||||
_diagnosticLog.write('disconnect requested');
|
||||
_connectWatchdog?.cancel();
|
||||
await _bridge.disconnect();
|
||||
if (!mounted) return;
|
||||
setState(() => _phase = ConnectionPhase.idle);
|
||||
@@ -317,12 +428,88 @@ class _HomePageState extends State<HomePage> {
|
||||
(peerIp.isEmpty ? '' : ' · 对端 $peerIp'),
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
"诊断日志:${_diagnosticLog.path.isEmpty ? '不可写' : _diagnosticLog.path}",
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Row(
|
||||
children: [
|
||||
FilledButton.tonalIcon(
|
||||
onPressed: _nativeError != null || _demoRunning
|
||||
? null
|
||||
: _startDemoListener,
|
||||
icon: const Icon(Icons.dns_outlined, size: 18),
|
||||
label: const Text('启动本机监听'),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
OutlinedButton.icon(
|
||||
onPressed: _demoRunning ? _stopDemoListener : null,
|
||||
icon: const Icon(Icons.stop_circle_outlined, size: 18),
|
||||
label: const Text('停止'),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
_demoRunning
|
||||
? 'TCP 41001 / UDP 41000 已监听,等待被控端接入'
|
||||
: '监听未开启:被控端无法反连本机',
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
bool get _demoRunning => _demoStatus['running'] == true;
|
||||
|
||||
void _startDemoListener() {
|
||||
final started = _bridge.startDemoServer();
|
||||
_diagnosticLog.write('demo listener start -> $started');
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
if (started) {
|
||||
_phase = ConnectionPhase.probing;
|
||||
}
|
||||
});
|
||||
if (!started) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('启动本机监听失败:端口可能被占用')),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void _stopDemoListener() {
|
||||
_bridge.stopDemoServer();
|
||||
_diagnosticLog.write('demo listener stopped');
|
||||
if (!mounted) return;
|
||||
setState(() => _phase = ConnectionPhase.idle);
|
||||
}
|
||||
|
||||
String get _videoResolution {
|
||||
final width = _videoStats['width'];
|
||||
final height = _videoStats['height'];
|
||||
if (width is int && height is int && width > 0 && height > 0) {
|
||||
return '${width}x$height';
|
||||
}
|
||||
return _selected?.resolution ?? '';
|
||||
}
|
||||
|
||||
int? get _videoPts {
|
||||
final decoded = _videoStats['decoded'];
|
||||
final pts = _videoStats['pts'];
|
||||
if (decoded is int && decoded > 0 && pts is int) return pts;
|
||||
return null;
|
||||
}
|
||||
|
||||
String get _videoError => (_videoStats['error'] as String? ?? '').trim();
|
||||
|
||||
Widget _buildStage() {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
@@ -330,9 +517,11 @@ class _HomePageState extends State<HomePage> {
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
VideoView(
|
||||
textureId: null,
|
||||
textureId: _textureId,
|
||||
connected: _phase.isConnected,
|
||||
resolution: _selected?.resolution ?? '',
|
||||
resolution: _videoResolution,
|
||||
pts: _videoPts,
|
||||
error: _videoError,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
ConnectBar(
|
||||
|
||||
Reference in new issue
Block a user