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 createState() => _HomePageState(); } class _HomePageState extends State { NativeCore? _nativeCore; late final SenderBridge _bridge; final DiagnosticLog _diagnosticLog = DiagnosticLog(); Timer? _demoStatusTimer; Timer? _diagnosticTimer; Timer? _connectWatchdog; Timer? _discoveryTimer; Timer? _videoStatsTimer; List _devices = const []; DeviceInfo? _selected; ConnectionPhase _phase = ConnectionPhase.idle; AppSettings _settings = AppSettings.defaults; String _effectiveSignalingUrl = AppSettings.defaults.signalingUrl; bool _localSignalingRunning = false; bool _refreshing = false; Map _demoStatus = const {'running': false}; Map _videoStats = const {}; int? _textureId; /// 串流画面是否已弹出到独立原生窗口。 bool _videoWindowOpen = false; 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 _refreshVideoTextureId() async { final id = await _bridge.videoTextureId(); if (!mounted || id == null || id == _textureId) return; setState(() => _textureId = id); } /// 轮询原生解码统计:纹理 ID、分辨率、PTS 与失败原因。 Future _refreshVideoStats() async { if (!mounted) return; final stats = await _bridge.videoStats(); if (!mounted || stats.isEmpty) return; final id = stats['textureId']; final windowOpen = stats['windowOpen']; setState(() { _videoStats = stats; if (_textureId == null && id is int && id > 0) { _textureId = id; } if (windowOpen is bool) { _videoWindowOpen = windowOpen; } }); } /// 把串流画面弹出/收回独立原生窗口(Windows)。 Future _toggleVideoWindow() async { if (_videoWindowOpen) { await _bridge.closeVideoWindow(); if (!mounted) return; setState(() => _videoWindowOpen = false); return; } final opened = await _bridge.openVideoWindow(); if (!mounted) return; if (!opened) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('当前平台不支持独立串流窗口')), ); return; } setState(() => _videoWindowOpen = true); } void _writeDiagnosticLog() { Map status; if (_nativeCore == null) { status = {'available': false, 'error': _nativeError ?? ''}; } else { try { status = _bridge.demoStatus(); } on Object catch (error) { status = {'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 _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 _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 _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 _disconnect() async { _diagnosticLog.write('disconnect requested'); _connectWatchdog?.cancel(); await _bridge.disconnect(); if (!mounted) return; setState(() => _phase = ConnectionPhase.idle); } Future _openSettings() async { final updated = await Navigator.of(context).push( MaterialPageRoute( builder: (_) => SettingsPage(settings: _settings, bridge: _bridge), ), ); if (updated == null) return; setState(() => _settings = updated); await _bridge.saveSettings(updated); await _applySignalingSettings(); } Future _showPairing() async { final uri = await _bridge.pairingUri(); if (!mounted) return; if (uri == null) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('当前平台不支持扫码配对')), ); return; } showDialog( 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 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: _videoWindowOpen ? '收回串流窗口' : '串流独立窗口', onPressed: _toggleVideoWindow, icon: Icon(_videoWindowOpen ? Icons.close_fullscreen : Icons.open_in_new), ), 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(); /// 按实际码流宽高算显示比例;竖屏被控端(如 1080x2400)不再被压成 16:9。 double get _videoAspectRatio { final width = _videoStats['width']; final height = _videoStats['height']; if (width is int && height is int && width > 0 && height > 0) { return width / height; } return 16 / 9; } Widget _buildStage() { return Padding( padding: const EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ VideoView( // 独立窗口在播时不再占用主窗口纹理。 textureId: _videoWindowOpen ? null : _textureId, connected: _phase.isConnected, resolution: _videoResolution, pts: _videoPts, error: _videoError, standalone: _videoWindowOpen, aspectRatio: _videoAspectRatio, ), 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, ), ), ), ], ), ); } }