feat: 接入端到端 demo 与签名变体
- Flutter 桌面端通过 dart:ffi 调用 Rust Core cdylib - 实现 ECDH P-256 密钥协商、HKDF 子密钥派生、AES-256-GCM 控制帧 - Android 被控端用派生密钥做控制帧加密与媒体包 MAC - 新增 libopus JNI 骨架,默认回退 MediaCodec - 新增 aosp/zhanxun/neutral 签名变体与系统 sharedUserId - 本机独立信令服务与设置页开关 - 新增 .gitignore 排除所有编译产物与打包目录
This commit is contained in:
commit
31b9a52eb4
154 files changed
+13287
No files matched your search
@@ -0,0 +1,174 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import 'local_signaling.dart';
|
||||
import 'models.dart';
|
||||
import 'native_core.dart';
|
||||
|
||||
class SenderBridge {
|
||||
SenderBridge({
|
||||
MethodChannel? method,
|
||||
EventChannel? events,
|
||||
NativeCore? nativeCore,
|
||||
}) : _method = method ?? const MethodChannel('ttstd/sender'),
|
||||
_events = events ?? const EventChannel('ttstd/sender/events'),
|
||||
_native = nativeCore;
|
||||
|
||||
final MethodChannel _method;
|
||||
final EventChannel _events;
|
||||
final NativeCore? _native;
|
||||
final LocalSignalingProcess _localSignaling = LocalSignalingProcess();
|
||||
|
||||
NativeCore? get nativeCore => _native;
|
||||
|
||||
bool get isLocalSignalingRunning => _localSignaling.isRunning;
|
||||
|
||||
static const mockDevices = [
|
||||
DeviceInfo(
|
||||
id: 'demo-pixel',
|
||||
name: '客厅 Pixel',
|
||||
ip: '192.168.1.10',
|
||||
mediaPort: 41000,
|
||||
controlPort: 41001,
|
||||
fingerprint: 'sha256:ab12cd34ef567890',
|
||||
capabilities: ['h264', 'opus', 'uibc', 'clipboard', 'file'],
|
||||
model: 'Pixel8',
|
||||
resolution: '1920x1080',
|
||||
),
|
||||
DeviceInfo(
|
||||
id: 'demo-tablet',
|
||||
name: '书房平板',
|
||||
ip: '192.168.1.23',
|
||||
mediaPort: 42000,
|
||||
controlPort: 42001,
|
||||
fingerprint: 'sha256:9988776655443322',
|
||||
capabilities: ['h265', 'opus', 'uibc'],
|
||||
model: 'PadPro',
|
||||
resolution: '2560x1600',
|
||||
),
|
||||
];
|
||||
|
||||
Stream<ConnectionPhase> watchPhase() {
|
||||
return _events
|
||||
.receiveBroadcastStream()
|
||||
.handleError((Object _) => null)
|
||||
.map<ConnectionPhase>(ConnectionPhaseX.fromWire)
|
||||
.distinct();
|
||||
}
|
||||
|
||||
Future<List<DeviceInfo>> discover() async {
|
||||
try {
|
||||
final raw = await _method.invokeListMethod<dynamic>('discover');
|
||||
if (raw == null || raw.isEmpty) return mockDevices;
|
||||
return DeviceInfo.listFromJson(raw);
|
||||
} on MissingPluginException {
|
||||
return mockDevices;
|
||||
} on PlatformException {
|
||||
return mockDevices;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> connect(DeviceInfo device) async {
|
||||
await _invokeIgnoringMissing('connect', device.toJson());
|
||||
}
|
||||
|
||||
Future<void> disconnect() async {
|
||||
await _invokeIgnoringMissing('disconnect');
|
||||
}
|
||||
|
||||
Future<void> sendControl(String type, Map<String, dynamic> payload) async {
|
||||
await _invokeIgnoringMissing('control', {'type': type, ...payload});
|
||||
}
|
||||
|
||||
Future<void> saveSettings(AppSettings settings) async {
|
||||
await _invokeIgnoringMissing('settings', settings.toJson());
|
||||
}
|
||||
|
||||
Future<bool> startLocalSignaling(int port) => _localSignaling.start(port: port);
|
||||
|
||||
Future<void> stopLocalSignaling() => _localSignaling.stop();
|
||||
|
||||
String localSignalingUrl(int port) => _localSignaling.url(port: port);
|
||||
|
||||
Future<String> resolveSignalingUrl(AppSettings settings) async {
|
||||
if (settings.useLocalSignaling) {
|
||||
return _localSignaling.url(port: settings.localSignalingPort);
|
||||
}
|
||||
return settings.signalingUrl;
|
||||
}
|
||||
|
||||
/// 通过 Rust Core 跑一次真实 ECDH + HKDF + AES-GCM + 媒体 MAC 自检。
|
||||
Map<String, dynamic> runCryptoSelfTest() {
|
||||
final native = _native;
|
||||
if (native == null) {
|
||||
return <String, dynamic>{'available': false, 'reason': 'Rust Core 未加载'};
|
||||
}
|
||||
final alice = native.generateKeyPair();
|
||||
final bob = native.generateKeyPair();
|
||||
try {
|
||||
final aliceSecret = alice.agree(bob.publicBytes);
|
||||
final bobSecret = bob.agree(alice.publicBytes);
|
||||
final controlKey = native.deriveSubkey(aliceSecret, 'lancast/control/v1');
|
||||
final videoKey = native.deriveSubkey(aliceSecret, 'lancast/video/v1');
|
||||
final channel = native.createSecureChannel(controlKey);
|
||||
final frame = channel.encodePing(1, DateTime.now().millisecondsSinceEpoch);
|
||||
final decoded = channel.decode(frame);
|
||||
channel.dispose();
|
||||
final media = native.mediaEncode(
|
||||
1234,
|
||||
1,
|
||||
videoKey,
|
||||
const <int>[1, 2, 3, 4, 5],
|
||||
);
|
||||
final mediaDecoded = native.mediaDecode(media, videoKey);
|
||||
return <String, dynamic>{
|
||||
'available': true,
|
||||
'ecdhMatch': aliceSecret.join() == bobSecret.join(),
|
||||
'controlFrameBytes': frame.length,
|
||||
'controlKind': decoded['kind'],
|
||||
'mediaPacketBytes': media.length,
|
||||
'mediaPts': mediaDecoded['pts'],
|
||||
'controlKey': _hexPrefix(controlKey),
|
||||
'videoKey': _hexPrefix(videoKey),
|
||||
};
|
||||
} finally {
|
||||
alice.free();
|
||||
bob.free();
|
||||
}
|
||||
}
|
||||
|
||||
/// 启动 Rust Core 的本机 demo 服务。
|
||||
bool startDemoServer() =>
|
||||
_native?.startDemoServer() ?? false;
|
||||
|
||||
void stopDemoServer() => _native?.stopDemoServer();
|
||||
|
||||
Map<String, dynamic> demoStatus() =>
|
||||
_native?.demoStatus() ?? <String, dynamic>{'running': false};
|
||||
|
||||
static String _hexPrefix(List<int> bytes) => bytes
|
||||
.take(4)
|
||||
.map((byte) => byte.toRadixString(16).padLeft(2, '0'))
|
||||
.join();
|
||||
|
||||
Future<String> pairingUri() async {
|
||||
try {
|
||||
final value = await _method.invokeMethod<String>('pairingUri');
|
||||
if (value != null && value.isNotEmpty) return value;
|
||||
} on MissingPluginException {
|
||||
// 桌面/测试环境没有原生桥时给出可扫描的示例 URI。
|
||||
} on PlatformException {
|
||||
// 同上。
|
||||
}
|
||||
return 'lancast://pair?ip=192.168.1.10&port=41001&fp=sha256:ab12cd34ef567890';
|
||||
}
|
||||
|
||||
Future<void> _invokeIgnoringMissing(String method, [Object? argument]) async {
|
||||
try {
|
||||
await _method.invokeMethod<void>(method, argument);
|
||||
} on MissingPluginException {
|
||||
// 测试或尚未接入 Rust Core 时使用 UI 演示数据。
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import 'dart:io';
|
||||
|
||||
class LocalSignalingProcess {
|
||||
LocalSignalingProcess() {
|
||||
_refreshLocalIp();
|
||||
}
|
||||
|
||||
Process? _process;
|
||||
bool _running = false;
|
||||
String _localIp = '127.0.0.1';
|
||||
|
||||
bool get isRunning => _running;
|
||||
|
||||
Future<bool> start({int port = 8080}) async {
|
||||
if (_running) return true;
|
||||
await _refreshLocalIp();
|
||||
final binary = _resolveBinary();
|
||||
if (binary == null) return false;
|
||||
|
||||
try {
|
||||
final process = await Process.start(
|
||||
binary.path,
|
||||
const <String>[],
|
||||
workingDirectory: binary.parent.path,
|
||||
environment: <String, String>{'LISTEN_ADDR': ':$port'},
|
||||
);
|
||||
process.stdout.listen((_) {});
|
||||
process.stderr.listen((_) {});
|
||||
process.exitCode.then((_) {
|
||||
_running = false;
|
||||
_process = null;
|
||||
});
|
||||
_process = process;
|
||||
_running = true;
|
||||
return true;
|
||||
} on Object {
|
||||
_running = false;
|
||||
_process = null;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> stop() async {
|
||||
final process = _process;
|
||||
if (process == null) return;
|
||||
_process = null;
|
||||
_running = false;
|
||||
try {
|
||||
process.kill();
|
||||
await process.exitCode.timeout(const Duration(seconds: 3));
|
||||
} on Object {
|
||||
// 进程未能及时退出时忽略,避免阻塞 UI。
|
||||
}
|
||||
}
|
||||
|
||||
String url({int port = 8080}) => 'http://${localIp()}:$port';
|
||||
|
||||
String localIp() => _localIp;
|
||||
|
||||
Future<void> _refreshLocalIp() async {
|
||||
try {
|
||||
final interfaces = await NetworkInterface.list();
|
||||
for (final interface in interfaces) {
|
||||
for (final address in interface.addresses) {
|
||||
if (address.type == InternetAddressType.IPv4 && !address.isLoopback) {
|
||||
_localIp = address.address;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
} on Object {
|
||||
// 网络接口不可用时保留 127.0.0.1。
|
||||
}
|
||||
}
|
||||
|
||||
File? _resolveBinary() {
|
||||
final candidates = <String>[
|
||||
if (Platform.isWindows) 'signaling_server.exe' else 'signaling_server',
|
||||
if (Platform.isWindows) 'ttstd-signaling.exe' else 'ttstd-signaling',
|
||||
];
|
||||
final directories = <Directory>[
|
||||
File(Platform.resolvedExecutable).parent,
|
||||
Directory.current,
|
||||
Directory('${Directory.current.path}${Platform.pathSeparator}signaling_server'),
|
||||
];
|
||||
for (final directory in directories) {
|
||||
for (final name in candidates) {
|
||||
final file = File('${directory.path}${Platform.pathSeparator}$name');
|
||||
if (file.existsSync()) return file;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
enum ConnectionPhase {
|
||||
idle,
|
||||
discovering,
|
||||
registering,
|
||||
probing,
|
||||
direct,
|
||||
relaying,
|
||||
failed,
|
||||
}
|
||||
|
||||
extension ConnectionPhaseX on ConnectionPhase {
|
||||
String get wireName => name;
|
||||
|
||||
String get label => switch (this) {
|
||||
ConnectionPhase.idle => '未连接',
|
||||
ConnectionPhase.discovering => '正在发现设备',
|
||||
ConnectionPhase.registering => '正在查询信令',
|
||||
ConnectionPhase.probing => '正在探测直连',
|
||||
ConnectionPhase.direct => 'P2P 直连',
|
||||
ConnectionPhase.relaying => '信令中转',
|
||||
ConnectionPhase.failed => '连接失败',
|
||||
};
|
||||
|
||||
bool get isBusy => switch (this) {
|
||||
ConnectionPhase.discovering ||
|
||||
ConnectionPhase.registering ||
|
||||
ConnectionPhase.probing =>
|
||||
true,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
bool get isConnected => this == ConnectionPhase.direct || this == ConnectionPhase.relaying;
|
||||
|
||||
static ConnectionPhase fromWire(Object? value) {
|
||||
final name = value is Map ? value['phase']?.toString() : value?.toString();
|
||||
return ConnectionPhase.values.firstWhere(
|
||||
(phase) => phase.wireName == name,
|
||||
orElse: () => ConnectionPhase.idle,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class DeviceInfo {
|
||||
final String id;
|
||||
final String name;
|
||||
final String ip;
|
||||
final int mediaPort;
|
||||
final int controlPort;
|
||||
final String fingerprint;
|
||||
final List<String> capabilities;
|
||||
final String model;
|
||||
final String resolution;
|
||||
final String? signalingUrl;
|
||||
|
||||
const DeviceInfo({
|
||||
required this.id,
|
||||
required this.name,
|
||||
required this.ip,
|
||||
required this.mediaPort,
|
||||
required this.controlPort,
|
||||
required this.fingerprint,
|
||||
this.capabilities = const [],
|
||||
this.model = '',
|
||||
this.resolution = '1920x1080',
|
||||
this.signalingUrl,
|
||||
});
|
||||
|
||||
factory DeviceInfo.fromJson(Map<String, dynamic> json) {
|
||||
return DeviceInfo(
|
||||
id: (json['deviceId'] ?? json['id'] ?? '').toString(),
|
||||
name: (json['name'] ?? json['deviceId'] ?? '未命名设备').toString(),
|
||||
ip: (json['ip'] ?? '').toString(),
|
||||
mediaPort: (json['mediaPort'] is num ? json['mediaPort'] as num : 41000).toInt(),
|
||||
controlPort: (json['controlPort'] is num ? json['controlPort'] as num : 41001).toInt(),
|
||||
fingerprint: (json['fp'] ?? json['fingerprint'] ?? '').toString(),
|
||||
capabilities: (json['cap'] as List<dynamic>? ?? const [])
|
||||
.map((item) => item.toString())
|
||||
.toList(growable: false),
|
||||
model: (json['model'] ?? '').toString(),
|
||||
resolution: (json['res'] ?? '1920x1080').toString(),
|
||||
signalingUrl: json['sig']?.toString(),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'deviceId': id,
|
||||
'name': name,
|
||||
'ip': ip,
|
||||
'mediaPort': mediaPort,
|
||||
'controlPort': controlPort,
|
||||
'fp': fingerprint,
|
||||
'cap': capabilities,
|
||||
'model': model,
|
||||
'res': resolution,
|
||||
if (signalingUrl != null) 'sig': signalingUrl,
|
||||
};
|
||||
|
||||
bool supports(String capability) => capabilities.contains(capability);
|
||||
|
||||
String get shortFingerprint {
|
||||
final cleaned = fingerprint.replaceFirst('sha256:', '');
|
||||
return cleaned.length > 12 ? '${cleaned.substring(0, 12)}…' : cleaned;
|
||||
}
|
||||
|
||||
static List<DeviceInfo> listFromJson(Object? raw) {
|
||||
if (raw is! List) return const [];
|
||||
return raw
|
||||
.whereType<Map<dynamic, dynamic>>()
|
||||
.map((item) => DeviceInfo.fromJson(Map<String, dynamic>.from(item)))
|
||||
.toList(growable: false);
|
||||
}
|
||||
}
|
||||
|
||||
class AppSettings {
|
||||
final String signalingUrl;
|
||||
final bool useLocalSignaling;
|
||||
final bool localSignalingEnabled;
|
||||
final int localSignalingPort;
|
||||
final bool preferH265;
|
||||
final bool audioEnabled;
|
||||
final bool clipboardSync;
|
||||
final bool fileTransfer;
|
||||
final int bitrateMbps;
|
||||
|
||||
const AppSettings({
|
||||
this.signalingUrl = 'http://192.168.1.5:8080',
|
||||
this.useLocalSignaling = true,
|
||||
this.localSignalingEnabled = true,
|
||||
this.localSignalingPort = 8080,
|
||||
this.preferH265 = false,
|
||||
this.audioEnabled = true,
|
||||
this.clipboardSync = true,
|
||||
this.fileTransfer = true,
|
||||
this.bitrateMbps = 8,
|
||||
});
|
||||
|
||||
static const defaults = AppSettings();
|
||||
|
||||
String get signalingModeLabel => useLocalSignaling ? '本机信令' : '外部信令';
|
||||
|
||||
AppSettings copyWith({
|
||||
String? signalingUrl,
|
||||
bool? useLocalSignaling,
|
||||
bool? localSignalingEnabled,
|
||||
int? localSignalingPort,
|
||||
bool? preferH265,
|
||||
bool? audioEnabled,
|
||||
bool? clipboardSync,
|
||||
bool? fileTransfer,
|
||||
int? bitrateMbps,
|
||||
}) {
|
||||
return AppSettings(
|
||||
signalingUrl: signalingUrl ?? this.signalingUrl,
|
||||
useLocalSignaling: useLocalSignaling ?? this.useLocalSignaling,
|
||||
localSignalingEnabled: localSignalingEnabled ?? this.localSignalingEnabled,
|
||||
localSignalingPort: localSignalingPort ?? this.localSignalingPort,
|
||||
preferH265: preferH265 ?? this.preferH265,
|
||||
audioEnabled: audioEnabled ?? this.audioEnabled,
|
||||
clipboardSync: clipboardSync ?? this.clipboardSync,
|
||||
fileTransfer: fileTransfer ?? this.fileTransfer,
|
||||
bitrateMbps: bitrateMbps ?? this.bitrateMbps,
|
||||
);
|
||||
}
|
||||
|
||||
factory AppSettings.fromJson(Map<String, dynamic> json) {
|
||||
return AppSettings(
|
||||
signalingUrl: (json['signalingUrl'] ?? defaults.signalingUrl).toString(),
|
||||
useLocalSignaling: json['useLocalSignaling'] as bool? ?? defaults.useLocalSignaling,
|
||||
localSignalingEnabled:
|
||||
json['localSignalingEnabled'] as bool? ?? defaults.localSignalingEnabled,
|
||||
localSignalingPort:
|
||||
(json['localSignalingPort'] is num ? json['localSignalingPort'] as num : 8080).toInt(),
|
||||
preferH265: json['preferH265'] as bool? ?? defaults.preferH265,
|
||||
audioEnabled: json['audioEnabled'] as bool? ?? defaults.audioEnabled,
|
||||
clipboardSync: json['clipboardSync'] as bool? ?? defaults.clipboardSync,
|
||||
fileTransfer: json['fileTransfer'] as bool? ?? defaults.fileTransfer,
|
||||
bitrateMbps: (json['bitrateMbps'] is num ? json['bitrateMbps'] as num : 8).toInt(),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'signalingUrl': signalingUrl,
|
||||
'useLocalSignaling': useLocalSignaling,
|
||||
'localSignalingEnabled': localSignalingEnabled,
|
||||
'localSignalingPort': localSignalingPort,
|
||||
'preferH265': preferH265,
|
||||
'audioEnabled': audioEnabled,
|
||||
'clipboardSync': clipboardSync,
|
||||
'fileTransfer': fileTransfer,
|
||||
'bitrateMbps': bitrateMbps,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,380 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:ffi';
|
||||
import 'dart:io';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:ffi/ffi.dart';
|
||||
|
||||
/// Rust Core 的 ffi 通道。桌面端通过 cdylib 直接调用,测试环境可注入桩实现。
|
||||
class NativeCore {
|
||||
NativeCore({DynamicLibrary? library}) : _library = library ?? _openLibrary();
|
||||
|
||||
static const int ok = 0;
|
||||
static const int errBufferTooSmall = -1;
|
||||
static const int errInvalidArgument = -2;
|
||||
static const int errCrypto = -3;
|
||||
static const int errCodec = -4;
|
||||
|
||||
static const List<String> _libraryNames = [
|
||||
'ttstdconnect_core.dll',
|
||||
'libttstdconnect_core.so',
|
||||
'libttstdconnect_core.dylib',
|
||||
];
|
||||
|
||||
final DynamicLibrary _library;
|
||||
bool _disposed = false;
|
||||
|
||||
static DynamicLibrary _openLibrary() {
|
||||
final errors = <String>[];
|
||||
for (final name in _libraryNames) {
|
||||
try {
|
||||
return DynamicLibrary.open(name);
|
||||
} on Object catch (error) {
|
||||
errors.add('$name: $error');
|
||||
}
|
||||
}
|
||||
final folder = File(Platform.resolvedExecutable).parent.path;
|
||||
for (final name in _libraryNames) {
|
||||
final path = '$folder${Platform.pathSeparator}$name';
|
||||
if (File(path).existsSync()) {
|
||||
try {
|
||||
return DynamicLibrary.open(path);
|
||||
} on Object catch (error) {
|
||||
errors.add('$path: $error');
|
||||
}
|
||||
}
|
||||
}
|
||||
throw UnsupportedError(
|
||||
'无法加载 Rust Core 动态库。请先把 cdylib 放到应用目录或系统库路径。\n${errors.join('\n')}',
|
||||
);
|
||||
}
|
||||
|
||||
late final DartVersionFn version = _library
|
||||
.lookup<NativeFunction<NativeVersionFn>>('ttstd_core_version')
|
||||
.asFunction();
|
||||
late final DartAbiRevisionFn abiRevision = _library
|
||||
.lookup<NativeFunction<NativeAbiRevisionFn>>('ttstd_core_abi_revision')
|
||||
.asFunction();
|
||||
late final DartEcdhGenerateFn _ecdhGenerate = _library
|
||||
.lookup<NativeFunction<NativeEcdhGenerateFn>>('ttstd_ecdh_generate')
|
||||
.asFunction();
|
||||
late final DartEcdhAgreeFn _ecdhAgree = _library
|
||||
.lookup<NativeFunction<NativeEcdhAgreeFn>>('ttstd_ecdh_agree')
|
||||
.asFunction();
|
||||
late final DartEcdhFreeFn _ecdhFree = _library
|
||||
.lookup<NativeFunction<NativeEcdhFreeFn>>('ttstd_ecdh_free')
|
||||
.asFunction();
|
||||
late final DartDeriveSubkeyFn _deriveSubkey = _library
|
||||
.lookup<NativeFunction<NativeDeriveSubkeyFn>>('ttstd_derive_subkey')
|
||||
.asFunction();
|
||||
late final DartMediaEncodeFn _mediaEncode = _library
|
||||
.lookup<NativeFunction<NativeMediaEncodeFn>>('ttstd_media_encode')
|
||||
.asFunction();
|
||||
late final DartMediaDecodeFn _mediaDecode = _library
|
||||
.lookup<NativeFunction<NativeMediaDecodeFn>>('ttstd_media_decode')
|
||||
.asFunction();
|
||||
late final DartControlNewFn _controlNew = _library
|
||||
.lookup<NativeFunction<NativeControlNewFn>>('ttstd_control_channel_new')
|
||||
.asFunction();
|
||||
late final DartControlFreeFn _controlFree = _library
|
||||
.lookup<NativeFunction<NativeControlFreeFn>>('ttstd_control_channel_free')
|
||||
.asFunction();
|
||||
late final DartControlEncodePingFn _controlEncodePing = _library
|
||||
.lookup<NativeFunction<NativeControlEncodePingFn>>('ttstd_control_encode_ping')
|
||||
.asFunction();
|
||||
late final DartControlDecodeFn _controlDecode = _library
|
||||
.lookup<NativeFunction<NativeControlDecodeFn>>('ttstd_control_decode')
|
||||
.asFunction();
|
||||
late final DartDemoStartFn _demoStart = _library
|
||||
.lookup<NativeFunction<NativeDemoStartFn>>('ttstd_demo_start')
|
||||
.asFunction();
|
||||
late final DartDemoStopFn _demoStop = _library
|
||||
.lookup<NativeFunction<NativeDemoStopFn>>('ttstd_demo_stop')
|
||||
.asFunction();
|
||||
late final DartDemoStatusFn _demoStatus = _library
|
||||
.lookup<NativeFunction<NativeDemoStatusFn>>('ttstd_demo_status')
|
||||
.asFunction();
|
||||
|
||||
bool get isAvailable => !_disposed;
|
||||
|
||||
String get versionString => version().cast<Utf8>().toDartString();
|
||||
|
||||
EcdhKeyPair generateKeyPair() {
|
||||
final public = calloc<Uint8>(65);
|
||||
try {
|
||||
final handle = _ecdhGenerate(public, 65);
|
||||
if (handle <= 0) {
|
||||
throw NativeCoreException('ttstd_ecdh_generate', handle);
|
||||
}
|
||||
return EcdhKeyPair(this, handle, _copy(public, 65));
|
||||
} finally {
|
||||
calloc.free(public);
|
||||
}
|
||||
}
|
||||
|
||||
Uint8List deriveSubkey(List<int> secret, String label) {
|
||||
return _withBytes(secret, (secretPtr) {
|
||||
return _withUtf8(label, (labelPtr) {
|
||||
final out = calloc<Uint8>(32);
|
||||
try {
|
||||
final written = _deriveSubkey(
|
||||
secretPtr,
|
||||
secret.length,
|
||||
labelPtr.cast(),
|
||||
label.length,
|
||||
out,
|
||||
32,
|
||||
);
|
||||
_check(written, 'ttstd_derive_subkey');
|
||||
return _copy(out, written);
|
||||
} finally {
|
||||
calloc.free(out);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
Uint8List mediaEncode(int pts, int flags, List<int> key, List<int> payload) {
|
||||
return _withBytes(key, (keyPtr) {
|
||||
return _withBytes(payload, (payloadPtr) {
|
||||
final capacity = 13 + payload.length + 4;
|
||||
final out = calloc<Uint8>(capacity);
|
||||
try {
|
||||
final written = _mediaEncode(
|
||||
pts,
|
||||
flags,
|
||||
keyPtr,
|
||||
payloadPtr,
|
||||
payload.length,
|
||||
out,
|
||||
capacity,
|
||||
);
|
||||
_check(written, 'ttstd_media_encode');
|
||||
return _copy(out, written);
|
||||
} finally {
|
||||
calloc.free(out);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
Map<String, dynamic> mediaDecode(List<int> packet, List<int> key) {
|
||||
return _withBytes(packet, (packetPtr) {
|
||||
return _withBytes(key, (keyPtr) {
|
||||
final out = calloc<Uint8>(256);
|
||||
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>;
|
||||
} finally {
|
||||
calloc.free(out);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
SecureChannel createSecureChannel(List<int> key) {
|
||||
return _withBytes(key, (keyPtr) {
|
||||
final handle = _controlNew(keyPtr);
|
||||
if (handle <= 0) throw NativeCoreException('ttstd_control_channel_new', handle);
|
||||
return SecureChannel(this, handle);
|
||||
});
|
||||
}
|
||||
|
||||
bool startDemoServer({int controlPort = 41001, int videoPort = 41000, int audioPort = 41002}) {
|
||||
return _demoStart(controlPort, videoPort, audioPort) == ok;
|
||||
}
|
||||
|
||||
void stopDemoServer() => _demoStop();
|
||||
|
||||
Map<String, dynamic> demoStatus() {
|
||||
final out = calloc<Uint8>(8192);
|
||||
try {
|
||||
final written = _demoStatus(out, 8192);
|
||||
_check(written, 'ttstd_demo_status');
|
||||
return jsonDecode(_copy(out, written).toString()) as Map<String, dynamic>;
|
||||
} finally {
|
||||
calloc.free(out);
|
||||
}
|
||||
}
|
||||
|
||||
void dispose() => _disposed = true;
|
||||
|
||||
void _check(int code, String symbol) {
|
||||
if (code < 0) throw NativeCoreException(symbol, code);
|
||||
}
|
||||
|
||||
static Uint8List _copy(Pointer<Uint8> ptr, int length) {
|
||||
final result = Uint8List(length);
|
||||
for (var i = 0; i < length; i++) {
|
||||
result[i] = ptr[i];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
static T _withBytes<T>(List<int> bytes, T Function(Pointer<Uint8>) body) {
|
||||
final ptr = calloc<Uint8>(bytes.length);
|
||||
try {
|
||||
for (var i = 0; i < bytes.length; i++) {
|
||||
ptr[i] = bytes[i];
|
||||
}
|
||||
return body(ptr);
|
||||
} finally {
|
||||
calloc.free(ptr);
|
||||
}
|
||||
}
|
||||
|
||||
static T _withUtf8<T>(String text, T Function(Pointer<Uint8>) body) {
|
||||
final ptr = text.toNativeUtf8();
|
||||
try {
|
||||
return body(ptr.cast());
|
||||
} finally {
|
||||
calloc.free(ptr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class NativeCoreException implements Exception {
|
||||
const NativeCoreException(this.symbol, this.code);
|
||||
|
||||
final String symbol;
|
||||
final int code;
|
||||
|
||||
@override
|
||||
String toString() => 'NativeCore 调用失败 ($symbol): $code';
|
||||
}
|
||||
|
||||
class EcdhKeyPair {
|
||||
EcdhKeyPair(this._core, this._handle, this.publicBytes);
|
||||
|
||||
final NativeCore _core;
|
||||
final int _handle;
|
||||
final Uint8List publicBytes;
|
||||
bool _consumed = false;
|
||||
|
||||
Uint8List agree(List<int> peerPublic) {
|
||||
if (_consumed) throw StateError('ECDH 句柄已被消费');
|
||||
_consumed = true;
|
||||
return _withBytesExternal(peerPublic, (ptr) {
|
||||
final out = calloc<Uint8>(32);
|
||||
try {
|
||||
final written = _core._ecdhAgree(_handle, ptr, peerPublic.length, out, 32);
|
||||
if (written < 0) throw NativeCoreException('ttstd_ecdh_agree', written);
|
||||
return NativeCore._copy(out, written);
|
||||
} finally {
|
||||
calloc.free(out);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void free() {
|
||||
if (_consumed) return;
|
||||
_consumed = true;
|
||||
_core._ecdhFree(_handle);
|
||||
}
|
||||
|
||||
static T _withBytesExternal<T>(List<int> bytes, T Function(Pointer<Uint8>) body) {
|
||||
final ptr = calloc<Uint8>(bytes.length);
|
||||
try {
|
||||
for (var i = 0; i < bytes.length; i++) {
|
||||
ptr[i] = bytes[i];
|
||||
}
|
||||
return body(ptr);
|
||||
} finally {
|
||||
calloc.free(ptr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class SecureChannel {
|
||||
SecureChannel(this._core, this._handle);
|
||||
|
||||
final NativeCore _core;
|
||||
final int _handle;
|
||||
bool _disposed = false;
|
||||
|
||||
Uint8List encodePing(int sequence, int timestamp) {
|
||||
final out = calloc<Uint8>(512);
|
||||
try {
|
||||
final written = _core._controlEncodePing(_handle, sequence, timestamp, out, 512);
|
||||
if (written < 0) throw NativeCoreException('ttstd_control_encode_ping', written);
|
||||
return NativeCore._copy(out, written);
|
||||
} finally {
|
||||
calloc.free(out);
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, dynamic> decode(List<int> frame) {
|
||||
return EcdhKeyPair._withBytesExternal(frame, (framePtr) {
|
||||
final out = calloc<Uint8>(256);
|
||||
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>;
|
||||
} finally {
|
||||
calloc.free(out);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_core._controlFree(_handle);
|
||||
}
|
||||
}
|
||||
|
||||
typedef NativeVersionFn = Pointer<Utf8> Function();
|
||||
typedef DartVersionFn = Pointer<Utf8> Function();
|
||||
typedef NativeAbiRevisionFn = Int32 Function();
|
||||
typedef DartAbiRevisionFn = int Function();
|
||||
typedef NativeEcdhGenerateFn = Int64 Function(Pointer<Uint8>, UintPtr);
|
||||
typedef DartEcdhGenerateFn = int Function(Pointer<Uint8>, int);
|
||||
typedef NativeEcdhAgreeFn = Int32 Function(
|
||||
Int64, Pointer<Uint8>, UintPtr, Pointer<Uint8>, UintPtr,
|
||||
);
|
||||
typedef DartEcdhAgreeFn = int Function(
|
||||
int, Pointer<Uint8>, int, Pointer<Uint8>, int,
|
||||
);
|
||||
typedef NativeEcdhFreeFn = Void Function(Int64);
|
||||
typedef DartEcdhFreeFn = void Function(int);
|
||||
typedef NativeDeriveSubkeyFn = Int32 Function(
|
||||
Pointer<Uint8>, UintPtr, Pointer<Uint8>, UintPtr, Pointer<Uint8>, UintPtr,
|
||||
);
|
||||
typedef DartDeriveSubkeyFn = int Function(
|
||||
Pointer<Uint8>, int, Pointer<Uint8>, int, Pointer<Uint8>, int,
|
||||
);
|
||||
typedef NativeMediaEncodeFn = Int32 Function(
|
||||
Uint64, Uint8, Pointer<Uint8>, Pointer<Uint8>, UintPtr, Pointer<Uint8>, UintPtr,
|
||||
);
|
||||
typedef DartMediaEncodeFn = int Function(
|
||||
int, int, Pointer<Uint8>, Pointer<Uint8>, int, Pointer<Uint8>, int,
|
||||
);
|
||||
typedef NativeMediaDecodeFn = Int32 Function(
|
||||
Pointer<Uint8>, UintPtr, Pointer<Uint8>, Pointer<Uint8>, UintPtr,
|
||||
);
|
||||
typedef DartMediaDecodeFn = int Function(
|
||||
Pointer<Uint8>, int, Pointer<Uint8>, Pointer<Uint8>, int,
|
||||
);
|
||||
typedef NativeControlNewFn = Int64 Function(Pointer<Uint8>);
|
||||
typedef DartControlNewFn = int Function(Pointer<Uint8>);
|
||||
typedef NativeControlFreeFn = Void Function(Int64);
|
||||
typedef DartControlFreeFn = void Function(int);
|
||||
typedef NativeControlEncodePingFn = Int32 Function(
|
||||
Int64, Uint16, Uint64, Pointer<Uint8>, UintPtr,
|
||||
);
|
||||
typedef DartControlEncodePingFn = int Function(
|
||||
int, int, int, Pointer<Uint8>, int,
|
||||
);
|
||||
typedef NativeControlDecodeFn = Int32 Function(
|
||||
Int64, Pointer<Uint8>, UintPtr, Pointer<Uint8>, UintPtr,
|
||||
);
|
||||
typedef DartControlDecodeFn = int Function(
|
||||
int, Pointer<Uint8>, int, Pointer<Uint8>, int,
|
||||
);
|
||||
typedef NativeDemoStartFn = Int32 Function(Uint16, Uint16, Uint16);
|
||||
typedef DartDemoStartFn = int Function(int, int, int);
|
||||
typedef NativeDemoStopFn = Void Function();
|
||||
typedef DartDemoStopFn = void Function();
|
||||
typedef NativeDemoStatusFn = Int32 Function(Pointer<Uint8>, UintPtr);
|
||||
typedef DartDemoStatusFn = int Function(Pointer<Uint8>, int);
|
||||
@@ -0,0 +1,101 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class ControlToolbar extends StatelessWidget {
|
||||
const ControlToolbar({super.key, required this.enabled, required this.onEvent});
|
||||
|
||||
final bool enabled;
|
||||
final void Function(String type, Map<String, dynamic> payload) onEvent;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
const Icon(Icons.gamepad),
|
||||
const SizedBox(width: 8),
|
||||
Text('远程控制', style: Theme.of(context).textTheme.titleSmall),
|
||||
const Spacer(),
|
||||
if (!enabled)
|
||||
Text('连接后可用', style: Theme.of(context).textTheme.labelSmall),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
_Action(
|
||||
icon: Icons.touch_app,
|
||||
label: '点击中心',
|
||||
enabled: enabled,
|
||||
onPressed: () => onEvent('touch', {
|
||||
'action': 0,
|
||||
'pointerId': 1,
|
||||
'x': 960,
|
||||
'y': 540,
|
||||
'pressure': 800,
|
||||
}),
|
||||
),
|
||||
_Action(
|
||||
icon: Icons.arrow_back,
|
||||
label: '返回',
|
||||
enabled: enabled,
|
||||
onPressed: () => onEvent('key', {'action': 0, 'keycode': 4, 'modifiers': 0}),
|
||||
),
|
||||
_Action(
|
||||
icon: Icons.home,
|
||||
label: '主页',
|
||||
enabled: enabled,
|
||||
onPressed: () => onEvent('key', {'action': 0, 'keycode': 3, 'modifiers': 0}),
|
||||
),
|
||||
_Action(
|
||||
icon: Icons.mouse,
|
||||
label: '滚轮向下',
|
||||
enabled: enabled,
|
||||
onPressed: () => onEvent('wheel', {'deltaX': 0, 'deltaY': -1, 'buttons': 0}),
|
||||
),
|
||||
_Action(
|
||||
icon: Icons.content_paste,
|
||||
label: '发送剪贴板',
|
||||
enabled: enabled,
|
||||
onPressed: () => onEvent('clipboard', {'text': 'TTSTD Connect'}),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _Action extends StatelessWidget {
|
||||
const _Action({
|
||||
required this.icon,
|
||||
required this.label,
|
||||
required this.enabled,
|
||||
required this.onPressed,
|
||||
});
|
||||
|
||||
final IconData icon;
|
||||
final String label;
|
||||
final bool enabled;
|
||||
final VoidCallback onPressed;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return OutlinedButton.icon(
|
||||
onPressed: enabled ? onPressed : null,
|
||||
icon: Icon(icon, size: 18),
|
||||
label: Text(label),
|
||||
style: OutlinedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../core/models.dart';
|
||||
|
||||
class DeviceList extends StatelessWidget {
|
||||
const DeviceList({
|
||||
super.key,
|
||||
required this.devices,
|
||||
required this.selectedId,
|
||||
required this.onSelected,
|
||||
required this.onRefresh,
|
||||
this.refreshing = false,
|
||||
this.shrinkWrap = false,
|
||||
});
|
||||
|
||||
final List<DeviceInfo> devices;
|
||||
final String? selectedId;
|
||||
final ValueChanged<DeviceInfo> onSelected;
|
||||
final VoidCallback onRefresh;
|
||||
final bool refreshing;
|
||||
final bool shrinkWrap;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.devices_other, size: 20, color: theme.colorScheme.primary),
|
||||
const SizedBox(width: 8),
|
||||
Text('可连接设备', style: theme.textTheme.titleMedium),
|
||||
const Spacer(),
|
||||
Text('${devices.length} 台', style: theme.textTheme.bodySmall),
|
||||
IconButton(
|
||||
tooltip: '重新发现',
|
||||
onPressed: onRefresh,
|
||||
icon: refreshing
|
||||
? const SizedBox(
|
||||
width: 16,
|
||||
height: 16,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Icon(Icons.refresh),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (shrinkWrap)
|
||||
_buildList()
|
||||
else
|
||||
Expanded(child: _buildList()),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildList() {
|
||||
if (devices.isEmpty) return _EmptyState(onRefresh: onRefresh);
|
||||
return ListView.separated(
|
||||
shrinkWrap: shrinkWrap,
|
||||
physics: shrinkWrap ? const NeverScrollableScrollPhysics() : null,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
itemCount: devices.length,
|
||||
separatorBuilder: (_, __) => const SizedBox(height: 8),
|
||||
itemBuilder: (context, index) => _DeviceCard(
|
||||
device: devices[index],
|
||||
selected: devices[index].id == selectedId,
|
||||
onTap: () => onSelected(devices[index]),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _DeviceCard extends StatelessWidget {
|
||||
const _DeviceCard({required this.device, required this.selected, required this.onTap});
|
||||
|
||||
final DeviceInfo device;
|
||||
final bool selected;
|
||||
final VoidCallback onTap;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return Card(
|
||||
clipBehavior: Clip.antiAlias,
|
||||
color: selected ? theme.colorScheme.primaryContainer : null,
|
||||
child: InkWell(
|
||||
onTap: onTap,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
CircleAvatar(
|
||||
backgroundColor: selected ? theme.colorScheme.primary : theme.colorScheme.surfaceContainerHighest,
|
||||
foregroundColor: selected ? theme.colorScheme.onPrimary : theme.colorScheme.onSurface,
|
||||
child: const Icon(Icons.android),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(device.name, style: theme.textTheme.titleSmall),
|
||||
const SizedBox(height: 2),
|
||||
Text('${device.ip}:${device.controlPort} · ${device.model}',
|
||||
style: theme.textTheme.bodySmall,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (selected) Icon(Icons.check_circle, color: theme.colorScheme.primary),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Wrap(
|
||||
spacing: 6,
|
||||
runSpacing: 4,
|
||||
children: [
|
||||
for (final capability in device.capabilities.take(4))
|
||||
Chip(
|
||||
visualDensity: VisualDensity.compact,
|
||||
label: Text(capability, style: theme.textTheme.labelSmall),
|
||||
padding: EdgeInsets.zero,
|
||||
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text('指纹 ${device.shortFingerprint} · ${device.resolution}',
|
||||
style: theme.textTheme.labelSmall?.copyWith(color: theme.colorScheme.outline)),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _EmptyState extends StatelessWidget {
|
||||
const _EmptyState({required this.onRefresh});
|
||||
|
||||
final VoidCallback onRefresh;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Icon(Icons.wifi_find, size: 48),
|
||||
const SizedBox(height: 12),
|
||||
const Text('未发现设备'),
|
||||
const SizedBox(height: 4),
|
||||
Text('确认手机与主控端处于同一网段', style: Theme.of(context).textTheme.bodySmall),
|
||||
const SizedBox(height: 12),
|
||||
OutlinedButton.icon(
|
||||
onPressed: onRefresh,
|
||||
icon: const Icon(Icons.refresh),
|
||||
label: const Text('重新扫描'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class VideoView extends StatelessWidget {
|
||||
const VideoView({
|
||||
super.key,
|
||||
this.textureId,
|
||||
this.connected = false,
|
||||
this.resolution = '1920x1080',
|
||||
this.pts,
|
||||
});
|
||||
|
||||
final int? textureId;
|
||||
final bool connected;
|
||||
final String resolution;
|
||||
final int? pts;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return AspectRatio(
|
||||
aspectRatio: 16 / 9,
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
child: DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: [
|
||||
theme.colorScheme.surfaceContainerHighest,
|
||||
theme.colorScheme.surfaceContainerLowest,
|
||||
],
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
),
|
||||
),
|
||||
child: Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
if (textureId != null)
|
||||
Texture(textureId: textureId!)
|
||||
else
|
||||
Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(Icons.connected_tv, size: 72, color: theme.colorScheme.primary.withValues(alpha: 0.6)),
|
||||
const SizedBox(height: 12),
|
||||
Text(connected ? '视频通道已建立' : '等待投屏画面',
|
||||
style: theme.textTheme.titleMedium),
|
||||
const SizedBox(height: 4),
|
||||
Text('H.264/H.265 → External Texture',
|
||||
style: theme.textTheme.bodySmall),
|
||||
],
|
||||
),
|
||||
Positioned(
|
||||
top: 12,
|
||||
left: 12,
|
||||
child: _Badge(
|
||||
icon: Icons.videocam,
|
||||
label: resolution,
|
||||
color: connected ? theme.colorScheme.primary : theme.colorScheme.outline,
|
||||
),
|
||||
),
|
||||
if (pts != null)
|
||||
Positioned(
|
||||
top: 12,
|
||||
right: 12,
|
||||
child: _Badge(icon: Icons.timer, label: 'PTS $pts', color: theme.colorScheme.outline),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _Badge extends StatelessWidget {
|
||||
const _Badge({required this.icon, required this.label, required this.color});
|
||||
|
||||
final IconData icon;
|
||||
final String label;
|
||||
final Color color;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black54,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(icon, size: 14, color: color),
|
||||
const SizedBox(width: 6),
|
||||
Text(label, style: const TextStyle(color: Colors.white, fontSize: 12)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../core/models.dart';
|
||||
|
||||
class ConnectBar extends StatelessWidget {
|
||||
const ConnectBar({
|
||||
super.key,
|
||||
required this.phase,
|
||||
required this.device,
|
||||
required this.onConnect,
|
||||
required this.onDisconnect,
|
||||
});
|
||||
|
||||
final ConnectionPhase phase;
|
||||
final DeviceInfo? device;
|
||||
final VoidCallback onConnect;
|
||||
final VoidCallback onDisconnect;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final connected = phase.isConnected;
|
||||
final busy = phase.isBusy;
|
||||
final discovered = phase != ConnectionPhase.idle;
|
||||
final handshaken = phase == ConnectionPhase.probing ||
|
||||
phase == ConnectionPhase.direct ||
|
||||
phase == ConnectionPhase.relaying;
|
||||
final color = switch (phase) {
|
||||
ConnectionPhase.direct || ConnectionPhase.relaying => theme.colorScheme.primary,
|
||||
ConnectionPhase.failed => theme.colorScheme.error,
|
||||
_ => theme.colorScheme.outline,
|
||||
};
|
||||
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 10,
|
||||
height: 10,
|
||||
decoration: BoxDecoration(color: color, shape: BoxShape.circle),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(phase.label, style: theme.textTheme.titleSmall),
|
||||
Text(
|
||||
device == null ? '请从左侧选择一台设备' : '${device!.name} · ${device!.ip}',
|
||||
style: theme.textTheme.bodySmall,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
FilledButton.icon(
|
||||
onPressed: device == null || busy ? null : (connected ? onDisconnect : onConnect),
|
||||
icon: Icon(connected ? Icons.link_off : Icons.play_arrow),
|
||||
label: Text(connected ? '断开' : '连接'),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (busy) ...[
|
||||
const SizedBox(height: 12),
|
||||
const LinearProgressIndicator(),
|
||||
],
|
||||
const SizedBox(height: 12),
|
||||
Row(
|
||||
children: [
|
||||
_StepDone(active: discovered, label: '发现'),
|
||||
_StepDivider(active: handshaken),
|
||||
_StepDone(active: handshaken, label: '握手'),
|
||||
_StepDivider(active: connected),
|
||||
_StepDone(active: connected, label: '媒体'),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _StepDone extends StatelessWidget {
|
||||
const _StepDone({required this.active, required this.label});
|
||||
|
||||
final bool active;
|
||||
final String label;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(active ? Icons.task_alt : Icons.radio_button_unchecked,
|
||||
size: 16, color: active ? theme.colorScheme.primary : theme.colorScheme.outline),
|
||||
const SizedBox(width: 4),
|
||||
Text(label, style: theme.textTheme.labelSmall),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _StepDivider extends StatelessWidget {
|
||||
const _StepDivider({required this.active});
|
||||
|
||||
final bool active;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Expanded(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8),
|
||||
child: Divider(thickness: 2, color: active ? Theme.of(context).colorScheme.primary : null),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../core/bridge.dart';
|
||||
import '../../core/models.dart';
|
||||
|
||||
class SettingsPage extends StatefulWidget {
|
||||
const SettingsPage({
|
||||
super.key,
|
||||
required this.settings,
|
||||
required this.bridge,
|
||||
});
|
||||
|
||||
final AppSettings settings;
|
||||
final SenderBridge bridge;
|
||||
|
||||
@override
|
||||
State<SettingsPage> createState() => _SettingsPageState();
|
||||
}
|
||||
|
||||
class _SettingsPageState extends State<SettingsPage> {
|
||||
late final TextEditingController _signalingUrl;
|
||||
late final TextEditingController _localPort;
|
||||
late bool _useLocalSignaling;
|
||||
late bool _localSignalingEnabled;
|
||||
late bool _localRunning;
|
||||
late bool _preferH265;
|
||||
late bool _audioEnabled;
|
||||
late bool _clipboardSync;
|
||||
late bool _fileTransfer;
|
||||
late int _bitrateMbps;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_signalingUrl = TextEditingController(text: widget.settings.signalingUrl);
|
||||
_localPort = TextEditingController(text: '${widget.settings.localSignalingPort}');
|
||||
_useLocalSignaling = widget.settings.useLocalSignaling;
|
||||
_localSignalingEnabled = widget.settings.localSignalingEnabled;
|
||||
_localRunning = widget.bridge.isLocalSignalingRunning;
|
||||
_preferH265 = widget.settings.preferH265;
|
||||
_audioEnabled = widget.settings.audioEnabled;
|
||||
_clipboardSync = widget.settings.clipboardSync;
|
||||
_fileTransfer = widget.settings.fileTransfer;
|
||||
_bitrateMbps = widget.settings.bitrateMbps;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_signalingUrl.dispose();
|
||||
_localPort.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
int get _port {
|
||||
final parsed = int.tryParse(_localPort.text.trim());
|
||||
return parsed != null && parsed >= 1 && parsed <= 65535 ? parsed : 8080;
|
||||
}
|
||||
|
||||
void _snack(String message) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
|
||||
}
|
||||
}
|
||||
|
||||
void _setLocalServer(bool enabled) {
|
||||
setState(() => _localSignalingEnabled = enabled);
|
||||
}
|
||||
|
||||
Future<void> _save() async {
|
||||
if (!_useLocalSignaling && _signalingUrl.text.trim().isEmpty) {
|
||||
_snack('请填写外部信令服务器地址');
|
||||
return;
|
||||
}
|
||||
if (int.tryParse(_localPort.text.trim()) == null) {
|
||||
_snack('本机端口必须是数字');
|
||||
return;
|
||||
}
|
||||
|
||||
if (_localSignalingEnabled) {
|
||||
if (!_localRunning || _port != widget.settings.localSignalingPort) {
|
||||
await widget.bridge.stopLocalSignaling();
|
||||
final started = await widget.bridge.startLocalSignaling(_port);
|
||||
if (!mounted) return;
|
||||
setState(() => _localRunning = started);
|
||||
if (!started) _snack('本机信令服务启动失败');
|
||||
}
|
||||
} else if (_localRunning) {
|
||||
await widget.bridge.stopLocalSignaling();
|
||||
if (!mounted) return;
|
||||
setState(() => _localRunning = false);
|
||||
}
|
||||
|
||||
if (!mounted) return;
|
||||
Navigator.of(context).pop(AppSettings(
|
||||
signalingUrl: _signalingUrl.text.trim(),
|
||||
useLocalSignaling: _useLocalSignaling,
|
||||
localSignalingEnabled: _localSignalingEnabled,
|
||||
localSignalingPort: _port,
|
||||
preferH265: _preferH265,
|
||||
audioEnabled: _audioEnabled,
|
||||
clipboardSync: _clipboardSync,
|
||||
fileTransfer: _fileTransfer,
|
||||
bitrateMbps: _bitrateMbps,
|
||||
));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('设置')),
|
||||
body: ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Icon(Icons.dns, color: theme.colorScheme.primary),
|
||||
const SizedBox(width: 8),
|
||||
Text('信令服务器', style: theme.textTheme.titleMedium),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
SwitchListTile(
|
||||
title: const Text('使用本机信令服务器'),
|
||||
subtitle: const Text('默认开启;安装包内置独立 Go 信令服务'),
|
||||
value: _useLocalSignaling,
|
||||
onChanged: (value) => setState(() => _useLocalSignaling = value),
|
||||
),
|
||||
if (_useLocalSignaling) ...[
|
||||
SwitchListTile(
|
||||
title: const Text('开启本机信令服务'),
|
||||
subtitle: Text(
|
||||
!_localSignalingEnabled
|
||||
? '已关闭'
|
||||
: (_localRunning ? '服务运行中' : '保存设置后启动'),
|
||||
style: TextStyle(
|
||||
color: _localSignalingEnabled && _localRunning
|
||||
? theme.colorScheme.primary
|
||||
: theme.colorScheme.error,
|
||||
),
|
||||
),
|
||||
value: _localSignalingEnabled,
|
||||
onChanged: _setLocalServer,
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: TextField(
|
||||
controller: _localPort,
|
||||
keyboardType: TextInputType.number,
|
||||
decoration: const InputDecoration(
|
||||
labelText: '本机监听端口',
|
||||
hintText: '8080',
|
||||
prefixIcon: Icon(Icons.numbers),
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Text(
|
||||
'本机地址:${widget.bridge.localSignalingUrl(_port)}\n手机端扫码或手动填写该地址即可注册。',
|
||||
style: theme.textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
if (!_localSignalingEnabled)
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
|
||||
child: Text(
|
||||
'本机服务已关闭,但当前仍选择“使用本机信令服务器”,设备列表将不可用。',
|
||||
style: theme.textTheme.bodySmall?.copyWith(color: theme.colorScheme.error),
|
||||
),
|
||||
),
|
||||
] else ...[
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: TextField(
|
||||
controller: _signalingUrl,
|
||||
decoration: const InputDecoration(
|
||||
labelText: '外部信令服务器',
|
||||
hintText: 'http://192.168.1.5:8080',
|
||||
prefixIcon: Icon(Icons.cloud),
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Text(
|
||||
'跨网段时通过自部署信令服务器交换地址。',
|
||||
style: theme.textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const Divider(height: 32),
|
||||
SwitchListTile(
|
||||
title: const Text('优先使用 H.265'),
|
||||
subtitle: const Text('带宽更省,要求被控端支持'),
|
||||
value: _preferH265,
|
||||
onChanged: (value) => setState(() => _preferH265 = value),
|
||||
),
|
||||
SwitchListTile(
|
||||
title: const Text('启用音频'),
|
||||
subtitle: const Text('AudioPlaybackCapture / OPUS'),
|
||||
value: _audioEnabled,
|
||||
onChanged: (value) => setState(() => _audioEnabled = value),
|
||||
),
|
||||
SwitchListTile(
|
||||
title: const Text('剪贴板同步'),
|
||||
subtitle: const Text('通过控制通道双向同步文本'),
|
||||
value: _clipboardSync,
|
||||
onChanged: (value) => setState(() => _clipboardSync = value),
|
||||
),
|
||||
SwitchListTile(
|
||||
title: const Text('允许文件传输'),
|
||||
subtitle: const Text('复用 TLS 会话,支持分片续传'),
|
||||
value: _fileTransfer,
|
||||
onChanged: (value) => setState(() => _fileTransfer = value),
|
||||
),
|
||||
const Divider(height: 32),
|
||||
ListTile(
|
||||
title: const Text('投屏码率'),
|
||||
subtitle: Text('$_bitrateMbps Mbps · 1080p 建议 6–10 Mbps'),
|
||||
),
|
||||
Slider(
|
||||
min: 2,
|
||||
max: 20,
|
||||
divisions: 18,
|
||||
value: _bitrateMbps.toDouble(),
|
||||
label: '$_bitrateMbps Mbps',
|
||||
onChanged: (value) => setState(() => _bitrateMbps = value.round()),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
FilledButton.icon(
|
||||
onPressed: _save,
|
||||
icon: const Icon(Icons.save),
|
||||
label: const Text('保存设置'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,409 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'core/bridge.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;
|
||||
Timer? _demoStatusTimer;
|
||||
|
||||
List<DeviceInfo> _devices = SenderBridge.mockDevices;
|
||||
DeviceInfo? _selected = SenderBridge.mockDevices.first;
|
||||
ConnectionPhase _phase = ConnectionPhase.idle;
|
||||
AppSettings _settings = AppSettings.defaults;
|
||||
String _effectiveSignalingUrl = AppSettings.defaults.signalingUrl;
|
||||
bool _localSignalingRunning = false;
|
||||
bool _refreshing = false;
|
||||
Map<String, dynamic>? _selfTest;
|
||||
Map<String, dynamic> _demoStatus = const <String, dynamic>{'running': false};
|
||||
String? _nativeError;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
try {
|
||||
_nativeCore = NativeCore();
|
||||
} on Object catch (error) {
|
||||
_nativeError = error.toString();
|
||||
}
|
||||
_bridge = SenderBridge(nativeCore: _nativeCore);
|
||||
_bridge.watchPhase().listen((phase) {
|
||||
if (mounted) setState(() => _phase = phase);
|
||||
});
|
||||
_applySignalingSettings();
|
||||
_refreshDevices();
|
||||
_runSelfTest();
|
||||
_demoStatusTimer = Timer.periodic(
|
||||
const Duration(seconds: 1),
|
||||
(_) => _refreshDemoStatus(),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_demoStatusTimer?.cancel();
|
||||
_bridge.stopDemoServer();
|
||||
_bridge.stopLocalSignaling();
|
||||
_nativeCore?.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _runSelfTest() {
|
||||
if (_nativeCore == null) return;
|
||||
try {
|
||||
final result = _bridge.runCryptoSelfTest();
|
||||
if (mounted) setState(() => _selfTest = result);
|
||||
} on Object catch (error) {
|
||||
if (mounted) setState(() => _nativeError = error.toString());
|
||||
}
|
||||
}
|
||||
|
||||
void _refreshDemoStatus() {
|
||||
if (_nativeCore == null || !mounted) return;
|
||||
try {
|
||||
final status = _bridge.demoStatus();
|
||||
setState(() => _demoStatus = status);
|
||||
} on Object catch (_) {
|
||||
// 动态库不可用时忽略轮询错误。
|
||||
}
|
||||
}
|
||||
|
||||
void _toggleDemoServer() {
|
||||
if (_nativeCore == null) return;
|
||||
try {
|
||||
final running = _demoStatus['running'] == true;
|
||||
if (running) {
|
||||
_bridge.stopDemoServer();
|
||||
} else {
|
||||
_bridge.startDemoServer();
|
||||
}
|
||||
_refreshDemoStatus();
|
||||
} on Object catch (error) {
|
||||
if (mounted) setState(() => _nativeError = error.toString());
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
Future<void> _refreshDevices() async {
|
||||
if (_refreshing) return;
|
||||
setState(() => _refreshing = true);
|
||||
final devices = await _bridge.discover();
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_devices = devices;
|
||||
if (_selected == null || !devices.any((device) => device.id == _selected!.id)) {
|
||||
_selected = devices.isEmpty ? null : devices.first;
|
||||
}
|
||||
_refreshing = false;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _connect() async {
|
||||
final device = _selected;
|
||||
if (device == null) return;
|
||||
setState(() => _phase = ConnectionPhase.probing);
|
||||
await _bridge.connect(device);
|
||||
if (!mounted) return;
|
||||
setState(() => _phase = ConnectionPhase.direct);
|
||||
}
|
||||
|
||||
Future<void> _disconnect() async {
|
||||
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;
|
||||
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 _buildNativeDemoCard() {
|
||||
final native = _nativeCore;
|
||||
final test = _selfTest;
|
||||
final status = _demoStatus;
|
||||
final running = status['running'] == true;
|
||||
final connected = status['peerConnected'] == true;
|
||||
final keyEstablished = status['keyEstablished'] == true;
|
||||
final events = (status['events'] as List<dynamic>? ?? const <dynamic>[])
|
||||
.map((item) => item.toString())
|
||||
.toList();
|
||||
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
const Icon(Icons.bolt_outlined, size: 18),
|
||||
const SizedBox(width: 8),
|
||||
const Text('Rust Core 协议自检', style: TextStyle(fontWeight: FontWeight.bold)),
|
||||
const Spacer(),
|
||||
if (native != null)
|
||||
TextButton(
|
||||
onPressed: _toggleDemoServer,
|
||||
child: Text(running ? '停止 demo 服务' : '启动 demo 服务'),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (_nativeError != null)
|
||||
Text(
|
||||
_nativeError!,
|
||||
style: TextStyle(color: Theme.of(context).colorScheme.error, fontSize: 12),
|
||||
)
|
||||
else if (native == null)
|
||||
const Text('未加载 Rust Core 动态库(桌面端编译后自动可用)。')
|
||||
else
|
||||
Text(
|
||||
'版本 ${native.versionString} · ABI ${native.abiRevision()} · '
|
||||
'ECDH ${test?['ecdhMatch'] == true ? '一致' : '未验证'} · '
|
||||
'控制帧 ${test?['controlFrameBytes'] ?? '-'} B · '
|
||||
'媒体包 ${test?['mediaPacketBytes'] ?? '-'} B',
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'demo 服务:${running ? '运行中' : '已停止'} · '
|
||||
'被控端 ${connected ? '已连接' : '未连接'} · '
|
||||
'${keyEstablished ? '会话密钥已建立' : '等待 ECDH'} · '
|
||||
'密钥 ${status['controlKey'] ?? '----'}',
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
if (events.isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: Text(
|
||||
events.take(5).join('\n'),
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(fontSize: 11),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildStage() {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
VideoView(
|
||||
textureId: null,
|
||||
connected: _phase.isConnected,
|
||||
resolution: _selected?.resolution ?? '1920x1080',
|
||||
),
|
||||
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),
|
||||
_buildNativeDemoCard(),
|
||||
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,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user