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);
|
||||
Reference in new issue
Block a user