远程遥控开发中

This commit is contained in:
CC
2026-01-21 13:27:55 +08:00
parent 32b702fb6d
commit 8c39f0daf8
45 changed files with 1994 additions and 245 deletions

View File

@@ -0,0 +1,118 @@
// import 'dart:io';
// import 'package:flutter/foundation.dart';
// import 'package:flutter/material.dart';
// import 'package:flutter_inappwebview/flutter_inappwebview.dart';
// import 'package:maibu_satabot_v2/core/domain/entities/user_entity.dart';
// import 'package:maibu_satabot_v2/features/devices/domain/entities/device_entity.dart';
//
// class MyVideoPlayer extends StatefulWidget {
// final String deviceIp;
// final DeviceEntity device;
// final UserEntity user;
//
// const MyVideoPlayer({
// Key? key,
// required this.deviceIp,
// required this.device,
// required this.user,
// }) : super(key: key);
//
// @override
// State<MyVideoPlayer> createState() => _MyVideoPlayerState();
// }
//
// class _MyVideoPlayerState extends State<MyVideoPlayer> {
// InAppLocalhostServer? _localServer;
// InAppWebViewController? _webViewController;
// bool _isServerRunning = false;
// int? actualPort;
//
// @override
// void initState() {
// super.initState();
// _startServer();
// }
//
// Future<void> _startServer() async {
// int availablePort = 0;
// try {
// var socket = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
// availablePort = socket.port;
// await socket.close();
// } catch (e) {
// availablePort = 8080;
// }
//
// _localServer = InAppLocalhostServer(port: availablePort);
// await _localServer!.start();
// actualPort = availablePort;
//
// if (mounted) {
// setState(() {
// _isServerRunning = true;
// });
// }
// }
//
// @override
// void dispose() {
// _localServer?.close();
// super.dispose();
// }
//
// @override
// Widget build(BuildContext context) {
// // 防止父级因其他状态 setState 导致视频闪烁
// if (!_isServerRunning) {
// return const Center(child: CircularProgressIndicator(color: Colors.white));
// }
//
// // [性能关键] RepaintBoundary 必须包裹渲染密集型的 WebView
// return RepaintBoundary(
// child: InAppWebView(
// initialUrlRequest: URLRequest(
// url: WebUri("http://localhost:$actualPort/assets/www/webrtc/playwebrtc.html"),
// ),
// initialSettings: InAppWebViewSettings(
// // 1. 基础播放设置
// javaScriptEnabled: true,
// mediaPlaybackRequiresUserGesture: false,
// allowsInlineMediaPlayback: true,
// preferredContentMode: UserPreferredContentMode.MOBILE,
//
// // 2. 性能与重绘优化
// supportZoom: false,
// disableHorizontalScroll: true,
// disableVerticalScroll: true,
// hardwareAcceleration: true, // 开启硬件加速
// offscreenPreRaster: false, // 禁用离屏预渲染以节省内存
// useHybridComposition: true,
// // 3. 内存与日志优化 (6.x 正确配置)
// isInspectable: false, // 生产环境关闭 Web 检查器
// cacheMode: CacheMode.LOAD_NO_CACHE, // 禁用缓存,WebRTC 不需要缓存
// useShouldInterceptRequest: false, // 减少 Dart 与 Native 桥接通信
// ),
// onWebViewCreated: (controller) => _webViewController = controller,
// onPermissionRequest: (controller, request) async {
// return PermissionResponse(
// resources: request.resources,
// action: PermissionResponseAction.GRANT,
// );
// },
// onLoadStop: (controller, url) {
// _initWebRTC(widget.deviceIp, widget.device.deviceName, widget.user.token);
// },
// // --- 彻底屏蔽 Console 日志,防止垃圾产生 ---
// onConsoleMessage: (controller, consoleMessage) {
// // 这里什么都不写,直接拦截并消耗掉 JS 层的日志
// // 防止海量 WebRTC 日志传回 Flutter 触发 GC
// },
// ),
// );
// }
//
// void _initWebRTC(String deviceIp, String deviceId, String token) {
// final streamUrl = "webrtc://$deviceIp/live/livestream/$deviceId?token=$token";
// _webViewController?.evaluateJavascript(source: "setStreamUrl('$streamUrl')");
// }
// }

View File

@@ -0,0 +1,331 @@
import 'dart:convert';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_webrtc/flutter_webrtc.dart';
import 'package:http/http.dart' as http;
class WebRTCLocalPlayer extends StatefulWidget {
final String streamUrl;
final bool showLeftPip;
final bool showRightPip;
const WebRTCLocalPlayer({
super.key,
required this.streamUrl,
this.showLeftPip = true,
this.showRightPip = true,
});
@override
State<WebRTCLocalPlayer> createState() => _WebRTCLocalPlayerState();
}
class _WebRTCLocalPlayerState extends State<WebRTCLocalPlayer> {
final RTCVideoRenderer _renderer = RTCVideoRenderer();
RTCPeerConnection? _peerConnection;
bool _isInitialized = false;
bool _isFrontMain = true;
// 使用 ValueNotifier 配合局部刷新,提升拖拽性能
final ValueNotifier<Offset> _leftPosNotifier = ValueNotifier(
const Offset(20, 80),
);
final ValueNotifier<Offset> _rightPosNotifier = ValueNotifier(
const Offset(200, 80),
);
bool _isPosInitialized = false;
@override
void initState() {
super.initState();
_prepareAndConnect();
}
Future<void> _prepareAndConnect() async {
try {
await _renderer.initialize();
if (!mounted) return;
await _initWebRTCConnection();
setState(() => _isInitialized = true);
} catch (e) {
debugPrint("初始化失败: $e");
}
}
Future<void> _initWebRTCConnection() async {
_peerConnection = await createPeerConnection({
"sdpSemantics": "unified-plan",
"iceServers": [
{"urls": "stun:stun.l.google.com:19302"},
],
});
await _peerConnection!.addTransceiver(
kind: RTCRtpMediaType.RTCRtpMediaTypeVideo,
init: RTCRtpTransceiverInit(direction: TransceiverDirection.RecvOnly),
);
_peerConnection!.onTrack = (RTCTrackEvent event) {
if (event.track.kind == 'video' && event.streams.isNotEmpty) {
if (mounted) setState(() => _renderer.srcObject = event.streams[0]);
}
};
try {
RTCSessionDescription offer = await _peerConnection!.createOffer({
'offerToReceiveVideo': 1,
});
await _peerConnection!.setLocalDescription(offer);
Uri uri = Uri.parse(
widget.streamUrl.replaceFirst('webrtc://', 'http://'),
);
String apiUrl = "http://${uri.host}:1985/rtc/v1/play/";
final response = await http.post(
Uri.parse(apiUrl),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({
"api": apiUrl,
"streamurl": widget.streamUrl,
"clientip": null,
"sdp": offer.sdp,
}),
);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
await _peerConnection!.setRemoteDescription(
RTCSessionDescription(data['sdp'], 'answer'),
);
}
} catch (e) {
debugPrint("信令错误: $e");
}
}
@override
void dispose() {
_peerConnection?.dispose();
_renderer.srcObject = null;
_renderer.dispose();
_leftPosNotifier.dispose();
_rightPosNotifier.dispose();
super.dispose();
}
// 四分屏裁剪视图
Widget _buildQuadrantView({required Alignment alignment}) {
if (!_isInitialized || _renderer.srcObject == null)
return Container(color: Colors.black);
return RepaintBoundary(
child: ClipRect(
child: FractionallySizedBox(
widthFactor: 2.0,
heightFactor: 2.0,
alignment: alignment,
child: RTCVideoView(
_renderer,
objectFit: RTCVideoViewObjectFit.RTCVideoViewObjectFitCover,
mirror: false,
),
),
),
);
}
// 主视角的矩形边缘羽化效果
Widget _buildMainViewWithFeathering() {
return ShaderMask(
shaderCallback: (Rect bounds) {
return const LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.transparent,
Colors.white,
Colors.white,
Colors.transparent,
],
stops: [0.0, 0.15, 0.85, 1.0],
).createShader(bounds);
},
blendMode: BlendMode.dstIn,
child: ShaderMask(
shaderCallback: (Rect bounds) {
return const LinearGradient(
begin: Alignment.centerLeft,
end: Alignment.centerRight,
colors: [
Colors.transparent,
Colors.white,
Colors.white,
Colors.transparent,
],
stops: [0.0, 0.05, 0.95, 1.0],
).createShader(bounds);
},
blendMode: BlendMode.dstIn,
child: _buildQuadrantView(
alignment: _isFrontMain ? Alignment.topLeft : Alignment.topRight,
),
),
);
}
@override
Widget build(BuildContext context) {
if (!_isInitialized)
return const Scaffold(
backgroundColor: Colors.black,
body: Center(child: CircularProgressIndicator()),
);
return Scaffold(
backgroundColor: Colors.black,
body: LayoutBuilder(
builder: (context, constraints) {
final double pipW = constraints.maxWidth / 5;
final double pipH = pipW * 9 / 16;
// 核心:处理 Windows 窗口大小变化时的坐标修正
Future.microtask(() {
if (!mounted) return;
_correctPosition(_leftPosNotifier, constraints, pipW, pipH);
_correctPosition(_rightPosNotifier, constraints, pipW, pipH);
});
if (!_isPosInitialized) {
_leftPosNotifier.value = const Offset(20, 80);
_rightPosNotifier.value = Offset(
constraints.maxWidth - pipW - 20,
80,
);
_isPosInitialized = true;
}
return Stack(
children: [
// ① 背景虚化层(背景两侧模糊,模拟视觉聚焦)
Positioned.fill(
child: Stack(
children: [
_buildQuadrantView(
alignment: _isFrontMain
? Alignment.topLeft
: Alignment.topRight,
),
Positioned.fill(
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 45, sigmaY: 45),
child: Container(color: Colors.black.withOpacity(0.55)),
),
),
],
),
),
// ② 主视频层
Center(
child: GestureDetector(
onDoubleTap: () =>
setState(() => _isFrontMain = !_isFrontMain),
child: AspectRatio(
aspectRatio: 16 / 9,
child: _buildMainViewWithFeathering(),
),
),
),
// ③ 悬浮小窗 - 解决阻尼感的 1:1 稳定拖拽
if (widget.showLeftPip)
_buildFastPip(
_leftPosNotifier,
Alignment.bottomLeft,
constraints,
pipW,
pipH,
),
if (widget.showRightPip)
_buildFastPip(
_rightPosNotifier,
Alignment.bottomRight,
constraints,
pipW,
pipH,
),
],
);
},
),
);
}
void _correctPosition(
ValueNotifier<Offset> notifier,
BoxConstraints constraints,
double w,
double h,
) {
double maxX = (constraints.maxWidth - w).clamp(0.0, double.infinity);
double maxY = (constraints.maxHeight - h).clamp(0.0, double.infinity);
double newX = notifier.value.dx.clamp(0.0, maxX);
double newY = notifier.value.dy.clamp(0.0, maxY);
if (notifier.value.dx != newX || notifier.value.dy != newY) {
notifier.value = Offset(newX, newY);
}
}
// 极致丝滑的局部刷新组件
Widget _buildFastPip(
ValueNotifier<Offset> notifier,
Alignment align,
BoxConstraints constraints,
double w,
double h,
) {
return ValueListenableBuilder<Offset>(
valueListenable: notifier,
builder: (context, pos, child) {
return Positioned(
left: pos.dx,
top: pos.dy,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onPanUpdate: (details) {
// 关键修正:使用 notifier.value.dx 替换 pos.dx,消除位移丢失导致的阻尼感
final double nextX = (notifier.value.dx + details.delta.dx).clamp(
0.0,
(constraints.maxWidth - w).clamp(0.0, double.infinity),
);
final double nextY = (notifier.value.dy + details.delta.dy).clamp(
0.0,
(constraints.maxHeight - h).clamp(0.0, double.infinity),
);
notifier.value = Offset(nextX, nextY);
},
child: child!,
),
);
},
child: Container(
width: w,
height: h,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.5),
blurRadius: 20,
offset: const Offset(0, 8),
),
],
),
clipBehavior: Clip.antiAlias,
child: _buildQuadrantView(alignment: align),
),
);
}
}