- 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 出画面排查表与实测截图
557 lines
18 KiB
Dart
557 lines
18 KiB
Dart
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';
|
|
import 'features/discovery/device_list.dart';
|
|
import 'features/media/video_view.dart';
|
|
import 'features/session/connect_bar.dart';
|
|
import 'features/settings/settings_page.dart';
|
|
|
|
void main() => runApp(const TTSTDConnectApp());
|
|
|
|
class TTSTDConnectApp extends StatelessWidget {
|
|
const TTSTDConnectApp({super.key});
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return MaterialApp(
|
|
title: 'TTSTD Connect',
|
|
debugShowCheckedModeBanner: false,
|
|
theme: ThemeData(
|
|
useMaterial3: true,
|
|
colorSchemeSeed: const Color(0xFF5468FF),
|
|
brightness: Brightness.dark,
|
|
),
|
|
home: const HomePage(),
|
|
);
|
|
}
|
|
}
|
|
|
|
class HomePage extends StatefulWidget {
|
|
const HomePage({super.key});
|
|
|
|
@override
|
|
State<HomePage> createState() => _HomePageState();
|
|
}
|
|
|
|
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;
|
|
ConnectionPhase _phase = ConnectionPhase.idle;
|
|
AppSettings _settings = AppSettings.defaults;
|
|
String _effectiveSignalingUrl = AppSettings.defaults.signalingUrl;
|
|
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
|
|
void initState() {
|
|
super.initState();
|
|
try {
|
|
_nativeCore = NativeCore();
|
|
} on Object catch (error) {
|
|
_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();
|
|
_refreshDevices();
|
|
_demoStatusTimer = Timer.periodic(
|
|
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();
|
|
super.dispose();
|
|
}
|
|
|
|
void _refreshDemoStatus() {
|
|
if (_nativeCore == null || !mounted) return;
|
|
try {
|
|
final status = _bridge.demoStatus();
|
|
setState(() {
|
|
_demoStatus = status;
|
|
final running = status['running'] == true;
|
|
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 &&
|
|
_phase != ConnectionPhase.failed) {
|
|
_phase = ConnectionPhase.probing;
|
|
}
|
|
});
|
|
} 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);
|
|
if (!mounted) return;
|
|
setState(() => _localSignalingRunning = started);
|
|
} else {
|
|
await _bridge.stopLocalSignaling();
|
|
if (!mounted) return;
|
|
setState(() => _localSignalingRunning = false);
|
|
}
|
|
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(signalingUrl: _effectiveSignalingUrl);
|
|
if (!mounted) return;
|
|
setState(() {
|
|
_devices = devices;
|
|
if (_selected == null || !devices.any((device) => device.id == _selected!.id)) {
|
|
_selected = devices.isEmpty ? null : devices.first;
|
|
}
|
|
_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);
|
|
_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);
|
|
}
|
|
|
|
Future<void> _openSettings() async {
|
|
final updated = await Navigator.of(context).push<AppSettings>(
|
|
MaterialPageRoute(
|
|
builder: (_) => SettingsPage(settings: _settings, bridge: _bridge),
|
|
),
|
|
);
|
|
if (updated == null) return;
|
|
setState(() => _settings = updated);
|
|
await _bridge.saveSettings(updated);
|
|
await _applySignalingSettings();
|
|
}
|
|
|
|
Future<void> _showPairing() async {
|
|
final uri = await _bridge.pairingUri();
|
|
if (!mounted) return;
|
|
if (uri == null) {
|
|
ScaffoldMessenger.of(context).showSnackBar(
|
|
const SnackBar(content: Text('当前平台不支持扫码配对')),
|
|
);
|
|
return;
|
|
}
|
|
showDialog<void>(
|
|
context: context,
|
|
builder: (context) => AlertDialog(
|
|
title: const Text('扫码配对'),
|
|
content: SingleChildScrollView(
|
|
child: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
Container(
|
|
width: 180,
|
|
height: 180,
|
|
decoration: BoxDecoration(
|
|
color: Colors.white,
|
|
borderRadius: BorderRadius.circular(12),
|
|
),
|
|
child: const Icon(Icons.qr_code_2, size: 140, color: Colors.black87),
|
|
),
|
|
const SizedBox(height: 16),
|
|
SelectableText(uri, textAlign: TextAlign.center),
|
|
const SizedBox(height: 12),
|
|
Text(
|
|
'首次连接需在被控端确认指纹;配对时可选择“仅查看 / 查看+控制 / 全权限”。',
|
|
style: Theme.of(context).textTheme.bodySmall,
|
|
textAlign: TextAlign.center,
|
|
),
|
|
],
|
|
),
|
|
),
|
|
actions: [
|
|
TextButton(
|
|
onPressed: () => Navigator.of(context).pop(),
|
|
child: const Text('关闭'),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
|
|
void _sendControl(String type, Map<String, dynamic> payload) {
|
|
_bridge.sendControl(type, payload);
|
|
ScaffoldMessenger.of(context).showSnackBar(
|
|
SnackBar(content: Text('已发送 $type 控制事件'), duration: const Duration(milliseconds: 900)),
|
|
);
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return Scaffold(
|
|
appBar: AppBar(
|
|
title: const Text('TTSTD Connect'),
|
|
actions: [
|
|
IconButton(
|
|
tooltip: '扫码配对',
|
|
onPressed: _showPairing,
|
|
icon: const Icon(Icons.qr_code_scanner),
|
|
),
|
|
IconButton(
|
|
tooltip: '设置',
|
|
onPressed: _openSettings,
|
|
icon: const Icon(Icons.settings),
|
|
),
|
|
],
|
|
),
|
|
floatingActionButton: FloatingActionButton(
|
|
onPressed: _showPairing,
|
|
tooltip: '扫码配对',
|
|
child: const Icon(Icons.add_link),
|
|
),
|
|
body: LayoutBuilder(
|
|
builder: (context, constraints) {
|
|
if (constraints.maxWidth >= 1000) {
|
|
return Row(
|
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
children: [
|
|
SizedBox(
|
|
width: 360,
|
|
child: Card(
|
|
margin: const EdgeInsets.all(12),
|
|
clipBehavior: Clip.antiAlias,
|
|
child: DeviceList(
|
|
devices: _devices,
|
|
selectedId: _selected?.id,
|
|
onSelected: (device) => setState(() => _selected = device),
|
|
onRefresh: _refreshDevices,
|
|
refreshing: _refreshing,
|
|
),
|
|
),
|
|
),
|
|
const VerticalDivider(width: 1),
|
|
Expanded(child: SingleChildScrollView(child: _buildStage())),
|
|
],
|
|
);
|
|
}
|
|
return SingleChildScrollView(
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
children: [
|
|
SizedBox(
|
|
height: 360,
|
|
child: Card(
|
|
margin: const EdgeInsets.fromLTRB(12, 12, 12, 0),
|
|
clipBehavior: Clip.antiAlias,
|
|
child: DeviceList(
|
|
devices: _devices,
|
|
selectedId: _selected?.id,
|
|
onSelected: (device) => setState(() => _selected = device),
|
|
onRefresh: _refreshDevices,
|
|
refreshing: _refreshing,
|
|
),
|
|
),
|
|
),
|
|
_buildStage(),
|
|
],
|
|
),
|
|
);
|
|
},
|
|
),
|
|
);
|
|
}
|
|
|
|
Widget _buildConnectionStatusCard() {
|
|
final status = _demoStatus;
|
|
final connected = status['peerConnected'] == true;
|
|
final keyEstablished = status['keyEstablished'] == true;
|
|
final peerIp = (status['peerIp'] as String? ?? '').trim();
|
|
|
|
return Card(
|
|
child: Padding(
|
|
padding: const EdgeInsets.all(12),
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
children: [
|
|
Row(
|
|
children: [
|
|
const Icon(Icons.link, size: 18),
|
|
const SizedBox(width: 8),
|
|
const Text('连接状态', style: TextStyle(fontWeight: FontWeight.bold)),
|
|
],
|
|
),
|
|
const SizedBox(height: 8),
|
|
if (_nativeError != null)
|
|
Text(
|
|
_nativeError!,
|
|
style: TextStyle(color: Theme.of(context).colorScheme.error, fontSize: 12),
|
|
)
|
|
else
|
|
Text(
|
|
'被控端 ${connected ? '已连接' : '未连接'} · '
|
|
'${keyEstablished ? '会话密钥已建立' : '等待 ECDH 协商'}' +
|
|
(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),
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
children: [
|
|
VideoView(
|
|
textureId: _textureId,
|
|
connected: _phase.isConnected,
|
|
resolution: _videoResolution,
|
|
pts: _videoPts,
|
|
error: _videoError,
|
|
),
|
|
const SizedBox(height: 16),
|
|
ConnectBar(
|
|
phase: _phase,
|
|
device: _selected,
|
|
onConnect: _connect,
|
|
onDisconnect: _disconnect,
|
|
),
|
|
const SizedBox(height: 16),
|
|
ControlToolbar(
|
|
enabled: _phase.isConnected,
|
|
onEvent: _sendControl,
|
|
),
|
|
const SizedBox(height: 12),
|
|
_buildConnectionStatusCard(),
|
|
const SizedBox(height: 12),
|
|
Card(
|
|
child: Padding(
|
|
padding: const EdgeInsets.all(12),
|
|
child: Text(
|
|
_settings.useLocalSignaling
|
|
? 'mDNS 同网段优先;本机信令${_localSignalingRunning ? '运行中' : '未运行'} · $_effectiveSignalingUrl,探测失败自动降级到信令中转。'
|
|
: 'mDNS 同网段优先;外部信令 · $_effectiveSignalingUrl,探测失败自动降级到信令中转。',
|
|
style: Theme.of(context).textTheme.bodySmall,
|
|
),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
}
|