USB 摄像头+远程遥控+中英的适配+topic的集成和状态的使用到相应页面

This commit is contained in:
2026-10-20 17:03:37 +08:00
parent 178cd2533c
commit 582242e9aa
144 changed files with 15759 additions and 406 deletions

View File

@@ -4,6 +4,7 @@ import 'dart:io';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:video_player/video_player.dart';
import 'package:shared_preferences/shared_preferences.dart';
@@ -11,26 +12,41 @@ import 'package:shared_preferences/shared_preferences.dart';
import '../../data/onvif_client.dart';
import '../../data/onvif_discovery_service.dart';
import '../../data/onvif_subnet_scanner.dart';
import '../../data/rtsp_link_probe.dart';
import '../../data/rtsp_playback_tuning.dart';
import '../../data/rtsp_url_guesser.dart';
import '../../domain/entities/onvif_camera.dart';
import 'local_camera_state.dart';
/// 本地摄像头(ONVIF 发现 + RTSP 播放)核心 Cubit。
/// 负责:网络检查 → WS-Discovery 搜索 → ONVIF 取 RTSP → video_player(ExoPlayer) 拉流播放 → 断流/失败处理。
class LocalCameraCubit extends Cubit<LocalCameraState> {
LocalCameraCubit({OnvifClient? client})
: _client = client ?? OnvifClient(username: 'admin', password: ''),
///
/// 生命周期由本类自己接管([WidgetsBindingObserver]):退后台 pause、回前台**重拉流**。
/// 原因见 [didChangeAppLifecycleState] 里的 `seekTo(0)` 陷阱,这个不能交给插件默认行为。
class LocalCameraCubit extends Cubit<LocalCameraState>
with WidgetsBindingObserver {
/// [autoPlayFirst]:发现到摄像头后自动选第一路拉流(免手点,供“自动获取”场景)。
/// [autoRecover]:断流 / 缓冲卡死时不留在“请重新连接”,延时自动重拉流。
LocalCameraCubit({
OnvifClient? client,
this.autoPlayFirst = false,
this.autoRecover = false,
}) : _client = client ?? OnvifClient(username: 'admin', password: ''),
super(const LocalCameraState());
final OnvifDiscoveryService _discovery = OnvifDiscoveryService();
final OnvifClient _client;
final bool autoPlayFirst;
final bool autoRecover;
Timer? _recoverTimer;
/// 网段扫描兜底(组播失败时不依赖组播,直接 TCP 探设 ONVIF 设备)。
late final OnvifSubnetScanner _scanner = OnvifSubnetScanner(client: _client);
// ===== 播放器(video_player / Android=ExoPlayer)=====
// ExoPlayer 原生支持 RTSP(RtspMediaSource),默认走 TCP 交错、缓冲小,天然低延迟,
// 不需要 mpv 那套 cache/demuxer 手动调参。
// ExoPlayer 原生支持 RTSP(RtspMediaSource)。注意:Media3 的 RTP 传输**默认是 UDP 单播**,
// 只在“播放未开始且长时间收不到 RTP”时才回退 TCP 交错;要强制 TCP 必须显式 setForceUseRtpTcp(true)。
// 两者已做成运行时可调项(见 RtspPlaybackTuning / 页面调参条)。
VideoPlayerController? _videoController;
VoidCallback? _controllerListener;
@@ -64,6 +80,19 @@ class LocalCameraCubit extends Cubit<LocalCameraState> {
// 延迟,绝不能拿它弹“解码跟不上推流”这种提示(曾经就这样误报过)。
// 真断流自有 hasError 与 isBuffering 的 12s stallTimer 负责,这里只留日志看趋势。
Timer? _lagTimer;
// ===== 链路探针:用上面的增量直接算出“送过来的数据缺不缺”,结论上屏 =====
// 不依赖原生字节计量(TrafficStats 对 USB 以太网网卡不一定统计得到),
// 只拿已经有的 position / buffered 两个读数做差,所以改完热重启即可生效。
// 用 ValueNotifier 而不是放进 state:每 2s 刷一次读数的重建只发生在探针那一行。
final ValueNotifier<RtspLinkSnapshot?> _probe =
ValueNotifier<RtspLinkSnapshot?>(null);
/// 链路探针读数(UI 用 ValueListenableBuilder 监听)。
ValueListenable<RtspLinkSnapshot?> get probe => _probe;
/// ONVIF 声明码率(kbps),由取流那一步带出来,给探针当分母。设备未报则 null。
int? _declaredKbps;
// 推进速率诊断:同一个积压数字可能是两种完全相反的病因——
// pos 推进 ≪ 墙钟 → 解码/渲染停滞(播放追不上)
// buf 推进 > 墙钟 → 媒体时间轴/推流异常
@@ -76,7 +105,9 @@ class LocalCameraCubit extends Cubit<LocalCameraState> {
/// 页面进入时调用:检查网络并自动搜索。
Future<void> start() async {
WidgetsBinding.instance.addObserver(this); // close() 里成对移除
_listenConnectivity();
await _loadTuning();
await _checkNetworkAndDiscover();
}
@@ -165,6 +196,10 @@ class LocalCameraCubit extends Cubit<LocalCameraState> {
message: null,
),
);
// 自动获取模式:不等手点,直接选第一路拉流
if (autoPlayFirst && enriched.isNotEmpty) {
unawaited(selectCamera(enriched.first));
}
} catch (e) {
emit(
state.copyWith(
@@ -180,6 +215,7 @@ class LocalCameraCubit extends Cubit<LocalCameraState> {
/// 候选顺序:① ONVIF 正规 GetStreamUri 结果 → ② RtspUrlGuesser 常见品牌模板。
Future<void> selectCamera(OnvifCamera cam) async {
_userStopped = false;
_recoverTimer?.cancel();
emit(
state.copyWith(
phase: LocalCameraPhase.connecting,
@@ -198,10 +234,19 @@ class LocalCameraCubit extends Cubit<LocalCameraState> {
// 1) 先按 ONVIF 正道取流(能拿到就放到候选第一位)
final urls = <String>[];
String? onvifUrl;
_declaredKbps = null;
try {
onvifUrl = await _client.resolveRtsp(cam.xAddr);
final (String uri, int? kbps) = await _client.resolveRtsp(
cam.xAddr,
profileSelect: _tuning.profileSelect,
);
onvifUrl = uri;
_declaredKbps = kbps;
urls.add(onvifUrl);
debugPrint('🎬 [拉流] ONVIF 解析成功:$onvifUrl');
debugPrint(
'🎬 [拉流] ONVIF 解析成功:$onvifUrl'
'${kbps != null ? '(声明 ${kbps}kbps)' : ''}',
);
} catch (e) {
debugPrint('🎬 [拉流] ONVIF 未给出 RTSP:$e');
}
@@ -263,14 +308,25 @@ class LocalCameraCubit extends Cubit<LocalCameraState> {
showReconnect: true,
),
);
_scheduleRecover(const Duration(seconds: 5));
}
/// 打开单个候选 URL,[timeout] 内完成 initialize() 且首帧就绪即视为成功。
/// ExoPlayer 对 RTSP 直播默认走 TCP 交错、缓冲小;失败/超时则 dispose 后返回 false。
/// 失败/超时则 dispose 后返回 false。传输方式(UDP/TCP)与缓冲水位在此刻由原生侧读调参配置决定。
Future<bool> _tryPlay(String url, {required Duration timeout}) async {
VideoPlayerController? c;
try {
c = VideoPlayerController.networkUrl(Uri.parse(url));
// 调参必须在 initialize 之前下发:LoadControl 与 RtspMediaSource.Factory 都是
// 在创建播放器那一刻读值,晚一步本轮拉流就用的是旧参数。
await _tuning.apply();
c = VideoPlayerController.networkUrl(
Uri.parse(url),
// 关键:关掉插件内置的生命周期观察者,改由本类的 didChangeAppLifecycleState 接管。
// 不设这一项的话,回前台那次 play() 会把直播 seek 回缓冲最前端(延迟棘轮)。
videoPlayerOptions: VideoPlayerOptions(
allowBackgroundPlayback: true,
),
);
await c.initialize().timeout(timeout);
// 直播流 initialize 完成即已连上并拿到分辨率;立即起播
await c.play();
@@ -332,7 +388,11 @@ class LocalCameraCubit extends Cubit<LocalCameraState> {
_controllerListener = null;
try {
await c.dispose();
} catch (_) {}
} catch (e) {
// 这里不能吞:原生没 release 就不会发 RTSP TEARDOWN,摄像头侧的会话会越积越多,
// 表现为“越播越慢”,网线直连的单播杂牌机尤其常见(并发会话路数受限)。
debugPrint('🧹 [释放] controller.dispose 失败(RTSP 会话可能未 TEARDOWN):$e');
}
}
}
@@ -341,51 +401,131 @@ class LocalCameraCubit extends Cubit<LocalCameraState> {
_openWatchdog = null;
}
// ===== 生命周期:后台必须自己管,不能留给 video_player 的默认行为 =====
// 插件内置观察者(allowBackgroundPlayback=false 时创建)在 resumed 调 play(),
// 而 play() 第一行是:
// if (value.position == value.duration) await seekTo(Duration.zero);
// 直播的 duration 恒为 0,position 又被 _updatePosition 钳到 0 → **条件恒成立**,
// 于是每次回前台都会被 seek 到【缓冲里最旧的那一帧】。RTSP 源 isSeekable=false 且没有
// LiveConfiguration(BEHIND_LIVE_WINDOW 那条追赶分支根本不会触发),只能 1x
// 从最旧帧重播 → 延迟当场变成“当时已缓冲的总时长”,且**只增不减(棘轮)**。
// 这就是“卡了一下、重进来就没之前快了”的机制。所以这里显式关掉内置观察者,
// 后台只 pause(pause 不带 seek,安全),回前台直接重建控制器重拉流把时间轴清零。
bool _resumeOnForeground = false;
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// 参数必须叫 state(重写方法不得改名),所以下面访问 Cubit 自己的状态时必须带 this.。
final VideoPlayerController? c = _videoController;
if (state == AppLifecycleState.paused ||
state == AppLifecycleState.hidden) {
if (c != null &&
!c.value.hasError &&
this.state.phase == LocalCameraPhase.playing &&
c.value.isPlaying) {
_resumeOnForeground = true;
unawaited(c.pause());
// 后台期间不要把“断流判定/采样”继续跑:stallTimer 会把正常退后台误判成掉线,
// 而跨过后台的增量做差得出的进给/积压读数必然是假的。
_stallTimer?.cancel();
_stallTimer = null;
_stopLagWatchdog();
debugPrint('🧊 [生命周期] 退后台:已暂停(回前台将重拉流,不进 seek 陷阱)');
}
return;
}
if (state == AppLifecycleState.resumed && _resumeOnForeground) {
_resumeOnForeground = false;
if (_userStopped || isClosed) return;
// 同一条路径同时间只能跑一遍:重拉会 dispose + 新建控制器,
// 两遍同时跑会互相踩掉对方的 controller(表现为一闪就黑、或留下未释放的会话)。
if (this.state.phase == LocalCameraPhase.connecting) return;
debugPrint('🔥 [生命周期] 回前台:重拉流以回到实时边缘');
unawaited(reapplyAndReplay());
}
// inactive / detached 刻意不管:分屏、下拉通知栏、锁屏动画都会发 inactive,
// 据此重拉流只会把正常观看打断。
}
// ===== 延迟水位观测 =====
void _startLagWatchdog() {
_lagTimer?.cancel();
_prevPosMs = -1;
_prevBufMs = -1;
_prevSampleAtMs = 0;
_probe.value = null; // 重拉流后时间轴从头开始,旧读数一律作废
_lagTimer = Timer.periodic(
const Duration(seconds: 2),
(_) => _checkLagWatermark(),
(_) => unawaited(_checkLagWatermark()),
);
}
void _stopLagWatchdog() {
_lagTimer?.cancel();
_lagTimer = null;
_probe.value = null;
}
/// 只读不回写:“缓冲末尾 - 播放位置”= 播放器内部积压(直播时间轴从 0 起算)。
void _checkLagWatermark() {
///
/// ⚠️ position 一律走 `await c.position`(直连原生 getCurrentPosition),
/// 不能用 `c.value.position`:video_player 的 `_updatePosition()` 会把上报位置
/// **钳到 value.duration**,而 RTSP 直播的 duration == Duration.zero,于是
/// `value.position` 永远是 0:探针的“渲染”会恒为 0%(误报渲染停滞),
/// “积压”会等于 buffer 末尾本身(自开播算起的总时长)一路虚高。
Future<void> _checkLagWatermark() async {
final c = _videoController;
if (c == null || _userStopped || isClosed) return;
if (state.phase != LocalCameraPhase.playing || !c.value.isInitialized) return;
if (c.value.buffered.isEmpty) return;
final int bufferedEndMs = c.value.buffered.last.end.inMilliseconds;
final int positionMs = c.value.position.inMilliseconds;
// 直播流的缓冲位置可能取到 C.POSITION_UNSET(Long.MIN_VALUE),经 Duration 转换后
// 会变成荒谬值,只接受合理区间内的读数。
if (bufferedEndMs <= 0 || positionMs < 0) return;
final int lagMs = bufferedEndMs - positionMs;
if (lagMs < 0 || lagMs > _lagSaneMaxMs) {
debugPrint('⏱ [延迟水位] 读数异常(lag=${lagMs}ms),本轮不判定');
return;
if (bufferedEndMs <= 0) return;
// 原生读数:拿不到(已销毁/异常/荒谬值)就标记不可信,本轮只用 feed。
int rawPosMs = -1;
try {
final Duration? p = await c.position;
if (p != null) rawPosMs = p.inMilliseconds;
} catch (_) {
rawPosMs = -1;
}
// await 期间可能已经停播/关页:_probe 一旦 dispose 就不能再写。
if (_userStopped || isClosed) return;
final bool posUsable =
rawPosMs >= 0 && rawPosMs <= _lagSaneMaxMs * 200; // 上限防住 TIME_UNSET 类荒谬值
// 积压只在两个读数都合理时才给;超出合理区间当“不可信”处理,不因此中断采样。
final int lagRaw = posUsable ? bufferedEndMs - rawPosMs : -1;
final int? lagMs = (lagRaw >= 0 && lagRaw <= _lagSaneMaxMs) ? lagRaw : null;
final int nowMs = DateTime.now().millisecondsSinceEpoch;
final int dtMs = _prevSampleAtMs == 0 ? 0 : nowMs - _prevSampleAtMs;
final int dPos = _prevPosMs < 0 ? 0 : positionMs - _prevPosMs;
int? dPos = !posUsable || _prevPosMs < 0 ? null : rawPosMs - _prevPosMs;
final int dBuf = _prevBufMs < 0 ? 0 : bufferedEndMs - _prevBufMs;
_prevPosMs = positionMs;
if (dPos != null && dPos < -50) dPos = null; // 时间轴重置,这一轮不判渲染
_prevPosMs = posUsable ? rawPosMs : -1;
_prevBufMs = bufferedEndMs;
_prevSampleAtMs = nowMs;
debugPrint(
dtMs == 0
? '⏱ [延迟水位] 积压=${lagMs}ms pos=${positionMs}ms buf=${bufferedEndMs}ms'
: '⏱ [延迟水位] 积压=${lagMs}ms | ${dtMs}ms 内 pos推进=${dPos}ms · buf推进=${dBuf}ms',
'⏱ [延迟水位] ${lagMs == null ? '积压=不可信' : '积压=${lagMs}ms'}'
' pos=${posUsable ? '${rawPosMs}ms' : '不可信'} buf=${bufferedEndMs}ms'
'${dtMs == 0 ? '' : ' | ${dtMs}ms 内 pos推进=${dPos == null ? '—' : '${dPos}ms'} · buf推进=${dBuf}ms'}',
);
// 同上:绝对值不当判据,但【增量】是可信的,交给链路探针做分类。
final RtspLinkSnapshot? snap = evaluateLinkSnapshot(
dtMs: dtMs,
dPosMs: dPos,
dBufMs: dBuf,
lagMs: lagMs,
declaredKbps: _declaredKbps,
);
if (snap != null) {
_probe.value = snap;
debugPrint(
'📡 [链路探针] ${snap.verdict.label}|${snap.detail}'
'${snap.estLossPct > 0 ? '|丢帧≈${snap.estLossPct}%' : ''}'
'|${snap.verdict.advice}',
);
}
// 注意:此处故意不对 lagMs 做任何“失败”判定,也绝不 emit disconnected。
// 积压读数受媒体时间轴偏差影响,画面正常时也能涨到几千毫秒,据此提示只会误报。
}
@@ -400,6 +540,24 @@ class LocalCameraCubit extends Cubit<LocalCameraState> {
showReconnect: true,
),
);
// 卡顿(缓冲进度 0% 超 12s)/断流自动刷新:延时重拉,替代手动点“重新连接”
_scheduleRecover(const Duration(seconds: 3));
}
/// 自动恢复调度:仅 [autoRecover] 开启且用户未主动停播时生效。
void _scheduleRecover(Duration delay) {
if (!autoRecover || _userStopped || isClosed) return;
_recoverTimer?.cancel();
_recoverTimer = Timer(delay, () {
if (isClosed || _userStopped) return;
final cam = state.selected;
debugPrint('♻️ [自动恢复] ${cam != null ? '重拉流:${cam.xAddr}' : '无选中摄像头,重新搜索'}');
if (cam != null) {
unawaited(selectCamera(cam));
} else {
unawaited(_checkNetworkAndDiscover());
}
});
}
/// 点击"重新连接":有选中摄像头则重拉流,否则重新搜索。
@@ -412,6 +570,96 @@ class LocalCameraCubit extends Cubit<LocalCameraState> {
await selectCamera(cam);
}
// ===== 直播调参(花屏 / 延迟现场 A/B)=====
RtspPlaybackTuning _tuning = RtspPlaybackTuning.defaults;
/// 当前生效的调参(页面回显用)。
RtspPlaybackTuning get tuning => _tuning;
/// 读回原生插件里**真正生效**的值,用于确认“改了参数到底有没有进插件”。
Future<RtspPlaybackTuning?> readBackTuning() => RtspPlaybackTuning.readBack();
/// 进入页面:恢复上次调参并先下发一次(保证首拉就用对参数)。
Future<void> _loadTuning() async {
_tuning = await RtspPlaybackTuning.load();
emit(state.copyWith(tuning: _tuning));
await _tuning.apply();
}
/// 保存 + 下发一组调参。[reconnect] 为 true 且已在播/曾出画面时,
/// 直接用**当前已解析的 RTSP 地址**重拉一次(跳过发现与取流,方便反复对比)。
Future<void> updateTuning(
RtspPlaybackTuning tuning, {
bool reconnect = true,
}) async {
// 先比一下码流选择有没有变:它决定取哪一路 Profile,不能靠“同一个 URL 重拉”体现。
final bool profileChanged = tuning.profileSelect != _tuning.profileSelect;
_tuning = tuning;
await tuning.save();
emit(state.copyWith(tuning: tuning));
await tuning.apply();
debugPrint('🛠 [调参] 已保存并下发:${tuning.summary}');
if (!reconnect) return;
// 换码流 = 换一路 URL,必须重新走 ONVIF 取流;其余参数只影响播放器本身,
// 用已解析的地址直接重拉更快(避开发现/取流的十秒级耗时)。
final OnvifCamera? cam = state.selected;
if (profileChanged && cam != null) {
await selectCamera(cam);
return;
}
await reapplyAndReplay();
}
/// 恢复默认(Media3 原生行为),并重拉一次以排除自己改坏的参数。
Future<void> resetTuning() async {
await RtspPlaybackTuning.defaults.clearSaved();
await updateTuning(RtspPlaybackTuning.defaults);
}
/// 用当前 rtspUrl 重新拉流(不走发现/取流流程)。没有画面时只存不重连。
Future<void> reapplyAndReplay() async {
final url = state.rtspUrl;
if (url == null) return;
if (state.phase != LocalCameraPhase.playing &&
state.phase != LocalCameraPhase.disconnected &&
state.phase != LocalCameraPhase.playFailed) {
return;
}
_userStopped = false;
emit(
state.copyWith(
phase: LocalCameraPhase.connecting,
playStep: ChainStatus.running,
clearMessage: true,
showReconnect: false,
),
);
await _disposeController();
_armOpenWatchdog();
final ok = await _tryPlay(url, timeout: const Duration(seconds: 8));
_cancelWatchdog();
if (ok) {
emit(
state.copyWith(
phase: LocalCameraPhase.playing,
playStep: ChainStatus.success,
clearMessage: true,
showReconnect: false,
),
);
} else {
emit(
state.copyWith(
phase: LocalCameraPhase.playFailed,
playStep: ChainStatus.failed,
message: '重拉失败:当前参数下未能起播',
showReconnect: true,
),
);
_scheduleRecover(const Duration(seconds: 5));
}
}
/// 返回摄像头列表(重新搜索)。
Future<void> backToList() async {
_userStopped = true;
@@ -630,11 +878,14 @@ class LocalCameraCubit extends Cubit<LocalCameraState> {
@override
Future<void> close() async {
_userStopped = true;
WidgetsBinding.instance.removeObserver(this);
_openWatchdog?.cancel();
_stallTimer?.cancel();
_recoverTimer?.cancel();
_lagTimer?.cancel();
_connectivitySub?.cancel();
await _disposeController();
_probe.dispose();
return super.close();
}
}

View File

@@ -1,5 +1,6 @@
import 'package:equatable/equatable.dart';
import '../../data/rtsp_playback_tuning.dart';
import '../../domain/entities/onvif_camera.dart';
/// 链条每一步的状态
@@ -29,6 +30,7 @@ class LocalCameraState extends Equatable {
final String? rtspUrl;
final String? message; // 提示语
final bool showReconnect; // 是否显示"重新连接"按钮
final RtspPlaybackTuning tuning; // 直播调参(传输方式 / 缓冲水位),设置面板读写
const LocalCameraState({
this.phase = LocalCameraPhase.idle,
@@ -41,6 +43,7 @@ class LocalCameraState extends Equatable {
this.rtspUrl,
this.message,
this.showReconnect = false,
this.tuning = RtspPlaybackTuning.defaults,
});
bool get isPlaying => phase == LocalCameraPhase.playing;
@@ -65,6 +68,7 @@ class LocalCameraState extends Equatable {
String? message,
bool clearMessage = false,
bool? showReconnect,
RtspPlaybackTuning? tuning,
}) {
return LocalCameraState(
phase: phase ?? this.phase,
@@ -77,6 +81,7 @@ class LocalCameraState extends Equatable {
rtspUrl: clearRtsp ? null : (rtspUrl ?? this.rtspUrl),
message: clearMessage ? null : (message ?? this.message),
showReconnect: showReconnect ?? this.showReconnect,
tuning: tuning ?? this.tuning,
);
}
@@ -92,5 +97,6 @@ class LocalCameraState extends Equatable {
rtspUrl,
message,
showReconnect,
tuning,
];
}

View File

@@ -2,9 +2,12 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:video_player/video_player.dart';
import 'package:maibu_satabot_v2/features/pv_control/presentation/pages/pv_control_page.dart';
import '../../domain/entities/onvif_camera.dart';
import '../cubit/local_camera_cubit.dart';
import '../cubit/local_camera_state.dart';
import '../widgets/rtsp_tuning_panel.dart';
/// 本地视频页:ONVIF 自动发现 + RTSP 播放(搜索与播放合一)。
/// 上方为播放器 / 搜索状态 / 摄像头列表,下方为链路状态"链条"实时展示。
@@ -37,7 +40,8 @@ class _LocalCameraViewState extends State<_LocalCameraView> {
return BlocBuilder<LocalCameraCubit, LocalCameraState>(
builder: (context, state) {
return PopScope(
canPop: state.phase != LocalCameraPhase.playing &&
canPop:
state.phase != LocalCameraPhase.playing &&
state.phase != LocalCameraPhase.connecting,
onPopInvokedWithResult: (didPop, result) {
if (!didPop) {
@@ -61,7 +65,10 @@ class _LocalCameraViewState extends State<_LocalCameraView> {
),
title: const Text(
'本地视频',
style: TextStyle(color: Colors.white, fontWeight: FontWeight.w600),
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w600,
),
),
centerTitle: true,
actions: [
@@ -71,12 +78,34 @@ class _LocalCameraViewState extends State<_LocalCameraView> {
icon: const Icon(Icons.refresh, color: Colors.white),
onPressed: () => cubit.runDiscovery(),
),
// 🔥 入口:进入光伏电站机器人远程控制(横屏动态大屏)页面
IconButton(
tooltip: '远程控制',
icon: const Icon(
Icons.sports_esports_outlined,
color: Colors.white,
),
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (_) => const PvControlPage(deviceId: ''),
),
);
},
),
],
),
body: SafeArea(
child: Column(
children: [
Expanded(child: _buildContent(context, cubit, state)),
// 链路探针:只读结论,放在调参条上方(同样不遮住画面)。
RtspLinkProbeBar(probe: cubit.probe),
// 调参条:固定在链路条上方(不放画面上),改完直接重拉流做 A/B。
RtspTuningBar(
tuning: state.tuning,
onOpen: () => showRtspTuningSheet(context, cubit),
),
_buildChain(context, state),
],
),
@@ -128,9 +157,7 @@ class _LocalCameraViewState extends State<_LocalCameraView> {
) {
return Stack(
children: [
Positioned.fill(
child: _buildPlayer(cubit),
),
Positioned.fill(child: _buildPlayer(cubit)),
// 连接中遮罩
if (state.phase == LocalCameraPhase.connecting)
Positioned.fill(
@@ -171,10 +198,7 @@ class _LocalCameraViewState extends State<_LocalCameraView> {
? size.width / size.height
: 16 / 9;
return Center(
child: AspectRatio(
aspectRatio: ratio,
child: VideoPlayer(controller),
),
child: AspectRatio(aspectRatio: ratio, child: VideoPlayer(controller)),
);
}
@@ -229,45 +253,49 @@ class _LocalCameraViewState extends State<_LocalCameraView> {
return Container(
color: dark ? Colors.black.withValues(alpha: 0.65) : Colors.black,
alignment: Alignment.center,
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (spinning)
const SizedBox(
width: 42,
height: 42,
child: CircularProgressIndicator(
color: Color(0xFF165DFF),
strokeWidth: 3,
// FittedBox:嵌入受限高度容器时整组等比缩小,避免「重试」按钮溢出
child: FittedBox(
fit: BoxFit.scaleDown,
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (spinning)
const SizedBox(
width: 42,
height: 42,
child: CircularProgressIndicator(
color: Color(0xFF165DFF),
strokeWidth: 3,
),
)
else
Icon(icon, color: Colors.white54, size: 52),
const SizedBox(height: 18),
Text(
message,
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.white,
fontSize: 15,
height: 1.5,
),
)
else
Icon(icon, color: Colors.white54, size: 52),
const SizedBox(height: 18),
Text(
message,
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.white,
fontSize: 15,
height: 1.5,
),
),
if (actionLabel != null && onAction != null) ...[
const SizedBox(height: 22),
ElevatedButton.icon(
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF165DFF),
foregroundColor: Colors.white,
if (actionLabel != null && onAction != null) ...[
const SizedBox(height: 22),
ElevatedButton.icon(
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF165DFF),
foregroundColor: Colors.white,
),
onPressed: onAction,
icon: const Icon(Icons.refresh, size: 18),
label: Text(actionLabel),
),
onPressed: onAction,
icon: const Icon(Icons.refresh, size: 18),
label: Text(actionLabel),
),
],
],
],
),
),
),
);
@@ -346,7 +374,10 @@ class _ChainNode extends StatelessWidget {
child: loading
? Padding(
padding: const EdgeInsets.all(3),
child: CircularProgressIndicator(color: color, strokeWidth: 3),
child: CircularProgressIndicator(
color: color,
strokeWidth: 3,
),
)
: CircleAvatar(
backgroundColor: color,
@@ -360,7 +391,9 @@ class _ChainNode extends StatelessWidget {
Text(
step.label,
style: TextStyle(
color: step.status == ChainStatus.idle ? Colors.white38 : Colors.white,
color: step.status == ChainStatus.idle
? Colors.white38
: Colors.white,
fontSize: 12,
),
),
@@ -435,7 +468,10 @@ class _CameraTile extends StatelessWidget {
: (camera.manufacturer.isNotEmpty
? camera.manufacturer
: '未知型号'),
style: const TextStyle(color: Colors.white54, fontSize: 13),
style: const TextStyle(
color: Colors.white54,
fontSize: 13,
),
),
],
),

View File

@@ -0,0 +1,353 @@
import 'package:flutter/material.dart';
import '../../data/rtsp_playback_tuning.dart';
/// 调参弹窗用的公共小组件(标题 / 预设档位 / 传输方式 / 毫秒输入框)。
class TuningSectionTitle extends StatelessWidget {
const TuningSectionTitle({super.key, required this.text});
final String text;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Text(
text,
style: const TextStyle(
color: Color(0xFFEDEDED),
fontSize: 13,
fontWeight: FontWeight.w600,
),
),
);
}
}
class TuningHint extends StatelessWidget {
const TuningHint({super.key, required this.text});
final String text;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(top: 6),
child: Text(
text,
// 不用 white38:在 #141414 底上对比度只有 2.3:1,太阳底下根本看不清。
style: const TextStyle(color: Color(0xFF9AA0A6), fontSize: 11, height: 1.5),
),
);
}
}
/// 预设档位:现场试验直接点一个再微调,省得对着数字猜。
class TuningPresetRow extends StatelessWidget {
const TuningPresetRow({super.key, required this.draft, required this.onPick});
final RtspPlaybackTuning draft;
final ValueChanged<RtspPlaybackTuning> onPick;
static const List<(String, RtspPlaybackTuning)> presets = <(String, RtspPlaybackTuning)>[
('原生默认', RtspPlaybackTuning.defaults),
('均衡', RtspPlaybackTuning.balanced),
('抗花屏', RtspPlaybackTuning.antiArtifact),
('低延迟', RtspPlaybackTuning.lowLatency),
];
@override
Widget build(BuildContext context) {
return Wrap(
spacing: 8,
runSpacing: 8,
children: [
for (final p in presets)
_TuningPresetPill(
label: p.$1,
selected: p.$2 == draft,
onTap: () => onPick(p.$2),
),
],
);
}
}
/// 预设档位药丸。
///
/// 之前用的是 ChoiceChip:弹窗底色是写死的深色,而 APP 可能是浅色主题,
/// chip 会拿到「浅色底 + 白色字」这种看不清的组合,且和下面的自绘卡片风格不统一。
/// 自己画可以彻底不依赖主题,也不随用户的浅色/深色设置漂移。
class _TuningPresetPill extends StatelessWidget {
const _TuningPresetPill({
required this.label,
required this.selected,
required this.onTap,
});
final String label;
final bool selected;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(14),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
decoration: BoxDecoration(
color: selected ? const Color(0xFF165DFF) : const Color(0xFF2A2A2A),
borderRadius: BorderRadius.circular(14),
border: Border.all(
color: selected ? const Color(0xFF5B8DEF) : const Color(0xFF4A4A4A),
),
),
child: Text(
label,
style: TextStyle(
color: selected ? Colors.white : const Color(0xFFDDDDDD),
fontSize: 12,
fontWeight: selected ? FontWeight.w600 : FontWeight.w400,
),
),
),
);
}
}
/// UDP / TCP 二选一。用两个可点卡片而不是 Switch,是为了把各自的代价直接写在脸上。
class TuningTransportPicker extends StatelessWidget {
const TuningTransportPicker({super.key, required this.forceTcp, required this.onChanged});
final bool forceTcp;
final ValueChanged<bool> onChanged;
@override
Widget build(BuildContext context) {
return Row(
children: [
Expanded(
child: _TuningTransportOption(
title: 'UDP',
subtitle: '延迟低 / 丢包即花屏',
selected: !forceTcp,
onTap: () => onChanged(false),
),
),
const SizedBox(width: 10),
Expanded(
child: _TuningTransportOption(
title: 'TCP',
subtitle: '画面完整 / 可能卡顿',
selected: forceTcp,
onTap: () => onChanged(true),
),
),
],
);
}
}
class _TuningTransportOption extends StatelessWidget {
const _TuningTransportOption({
required this.title,
required this.subtitle,
required this.selected,
required this.onTap,
});
final String title;
final String subtitle;
final bool selected;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(8),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
decoration: BoxDecoration(
color: selected
? const Color(0xFF165DFF).withValues(alpha: 0.30)
: const Color(0xFF232323),
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: selected
? const Color(0xFF5B8DEF)
: const Color(0xFF3D3D3D),
width: selected ? 1.4 : 1,
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: TextStyle(
color: selected ? Colors.white : const Color(0xFFCCCCCC),
fontSize: 14,
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 2),
Text(
subtitle,
style: const TextStyle(color: Color(0xFF9AA0A6), fontSize: 11),
),
],
),
),
);
}
}
/// 毫秒参数输入框:右侧常驻一句“这个值到底影响什么”,避免瞎填。
class TuningMsField extends StatefulWidget {
const TuningMsField({
super.key,
required this.label,
required this.value,
required this.hint,
required this.onChanged,
this.suffix = 'ms',
});
final String label;
final int value;
final String hint;
final ValueChanged<int> onChanged;
/// 单位后缀。水位类是 ms,缓冲字节类是 KB。
final String suffix;
@override
State<TuningMsField> createState() => _TuningMsFieldState();
}
class _TuningMsFieldState extends State<TuningMsField> {
late final TextEditingController _ctrl =
TextEditingController(text: '${widget.value}');
@override
void didUpdateWidget(covariant TuningMsField oldWidget) {
super.didUpdateWidget(oldWidget);
// 点预设档位时要同步回填输入框;光标还在框里(用户正在输入)时不覆盖。
if (widget.value != oldWidget.value && !_ctrl.selection.isValid) {
_ctrl.text = '${widget.value}';
}
}
@override
void dispose() {
_ctrl.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
widget.label,
style: const TextStyle(color: Color(0xFFCCCCCC), fontSize: 12),
),
const SizedBox(height: 4),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 110,
child: TextField(
controller: _ctrl,
keyboardType: TextInputType.number,
// 浅色主题下默认 cursor 是深色,在深底输入框里几乎看不见。
cursorColor: const Color(0xFF94BFFF),
style: const TextStyle(color: Colors.white, fontSize: 14),
decoration: InputDecoration(
isDense: true,
suffixText: widget.suffix,
suffixStyle: const TextStyle(
color: Color(0xFF9AA0A6),
fontSize: 11,
),
filled: true,
fillColor: const Color(0xFF232323),
contentPadding: const EdgeInsets.symmetric(
horizontal: 10,
vertical: 8,
),
enabledBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Color(0xFF3D3D3D)),
),
focusedBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Color(0xFF5B8DEF)),
),
),
onChanged: (v) => widget.onChanged(int.tryParse(v.trim()) ?? 0),
),
),
const SizedBox(width: 6),
Expanded(
child: Padding(
padding: const EdgeInsets.only(top: 6),
child: Text(
widget.hint,
style: const TextStyle(
color: Color(0xFF9AA0A6),
fontSize: 11,
height: 1.4,
),
),
),
),
],
),
],
),
);
}
}
/// 多选一卡片行:把每个选项的代价直接写在卡片上,比下拉框更适合现场试参数。
class TuningChoiceRow<T> extends StatelessWidget {
const TuningChoiceRow({
super.key,
required this.options,
required this.labelOf,
required this.selected,
required this.onChanged,
this.subtitleOf,
});
final List<T> options;
final String Function(T) labelOf;
final String Function(T)? subtitleOf;
final T selected;
final ValueChanged<T> onChanged;
@override
Widget build(BuildContext context) {
return Row(
children: [
for (int i = 0; i < options.length; i++) ...[
if (i > 0) const SizedBox(width: 8),
Expanded(
child: _TuningTransportOption(
title: labelOf(options[i]),
subtitle: subtitleOf?.call(options[i]) ?? '',
selected: options[i] == selected,
onTap: () => onChanged(options[i]),
),
),
],
],
);
}
}

View File

@@ -0,0 +1,532 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../data/rtsp_link_probe.dart';
import '../../data/rtsp_playback_tuning.dart';
import '../cubit/local_camera_cubit.dart';
import 'rtsp_tuning_fields.dart';
/// 链路条上方的「调参条」:一行显示当前生效策略,点开弹窗慢慢改。
///
/// 放这里而不是画面上:画面区域要留给视频本身,且改完参数会立刻重拉流,
/// 任何浮层都会干扰肉眼判断花屏/延迟的变化。
class RtspTuningBar extends StatelessWidget {
const RtspTuningBar({
super.key,
required this.tuning,
required this.onOpen,
});
final RtspPlaybackTuning tuning;
final VoidCallback onOpen;
@override
Widget build(BuildContext context) {
return Material(
color: const Color(0xFF0A0A0A),
child: InkWell(
onTap: onOpen,
child: Padding(
padding: const EdgeInsets.fromLTRB(12, 8, 8, 8),
child: Row(
children: [
const Icon(Icons.tune, color: Color(0xFF165DFF), size: 18),
const SizedBox(width: 8),
const Text('调参', style: TextStyle(color: Color(0xFFCCCCCC), fontSize: 12)),
const SizedBox(width: 10),
Expanded(
child: Text(
tuning.summary,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: tuning.isDefault
? const Color(0xFF9AA0A6)
: const Color(0xFFFFC53D),
fontSize: 12,
),
),
),
if (!tuning.isDefault)
const Padding(
padding: EdgeInsets.only(right: 6),
child: Text(
'已自定义',
style: TextStyle(color: Color(0xFFFFC53D), fontSize: 11),
),
),
const Icon(Icons.chevron_right, color: Color(0xFF8A8A8A), size: 18),
],
),
),
),
);
}
}
/// 链路探针条:固定在三块信息区最上方,只读不改任何行为。
///
/// 它回答的是“图传送过来的数据到底缺不缺”:
/// 进给率明显低于实时 = 数据没到齐(链路吐不上/丢包,病在图传段);
/// 进给完整但画面仍花 = 数据都收到了还花,不是“不够”而是“内容坏了”。
class RtspLinkProbeBar extends StatelessWidget {
const RtspLinkProbeBar({super.key, required this.probe});
final ValueListenable<RtspLinkSnapshot?> probe;
static Color _colorOf(LinkVerdict v) {
switch (v) {
case LinkVerdict.healthy:
return const Color(0xFF3DDC84);
case LinkVerdict.lightLoss:
return const Color(0xFFFFC53D);
case LinkVerdict.starved:
return const Color(0xFFFF6B4A);
case LinkVerdict.decoderStalled:
return const Color(0xFFB388FF);
case LinkVerdict.backlogGrowing:
return const Color(0xFFFFB74D);
case LinkVerdict.unknown:
return const Color(0xFF8A8A8A);
}
}
static IconData _iconOf(LinkVerdict v) {
switch (v) {
case LinkVerdict.healthy:
return Icons.signal_cellular_alt;
case LinkVerdict.lightLoss:
case LinkVerdict.starved:
return Icons.network_check;
case LinkVerdict.decoderStalled:
return Icons.memory;
case LinkVerdict.backlogGrowing:
return Icons.hourglass_top;
case LinkVerdict.unknown:
return Icons.sensors_off;
}
}
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<RtspLinkSnapshot?>(
valueListenable: probe,
builder: (context, snap, _) {
final LinkVerdict v = snap?.verdict ?? LinkVerdict.unknown;
final Color accent = _colorOf(v);
return Material(
color: const Color(0xFF0A0A0A),
child: Padding(
padding: const EdgeInsets.fromLTRB(12, 6, 12, 7),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(_iconOf(v), color: accent, size: 16),
const SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
snap == null
? '链路探针:采样中(进画面后 2~4 秒出结果)'
: '${v.label} · ${snap.detail}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: accent,
fontSize: 12,
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 2),
Text(
snap == null
? '靠 position/buffered 的增量判断进给完整度,不需重新编译'
: v.advice,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: Color(0xFF9AA0A6),
fontSize: 10.5,
height: 1.35,
),
),
],
),
),
if (snap != null && snap.estLossPct > 0)
Padding(
padding: const EdgeInsets.only(left: 6),
child: Text(
'丢帧≈${snap.estLossPct}%',
style: TextStyle(color: accent, fontSize: 11),
),
),
],
),
),
);
},
);
}
}
/// 弹出调参面板。关闭时 Cubit 已完成「保存 + 下发(+ 视按钮重拉流)」。
///
/// 必须把 Cubit 从调用方的上下文传进来:showModalBottomSheet 走的是
/// Navigator 里的 Overlay,它在页面 BlocProvider 的**上层**,弹窗内部
/// context 原本看不到 LocalCameraCubit,会抛 ProviderNotFoundException。
/// 这里用 BlocProvider.value 把它重新注入到弹窗子树(不负责 dispose)。
Future<void> showRtspTuningSheet(BuildContext context, LocalCameraCubit cubit) {
return showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
backgroundColor: const Color(0xFF141414),
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
),
builder: (context) => BlocProvider.value(
value: cubit,
child: const _RtspTuningSheet(),
),
);
}
class _RtspTuningSheet extends StatefulWidget {
const _RtspTuningSheet();
@override
State<_RtspTuningSheet> createState() => _RtspTuningSheetState();
}
class _RtspTuningSheetState extends State<_RtspTuningSheet> {
late RtspPlaybackTuning _draft;
String _nativeEcho = '';
@override
void initState() {
super.initState();
_draft = context.read<LocalCameraCubit>().tuning;
}
/// 读回原生侧真正生效的值:用来定性「改了到底有没有进插件」。
Future<void> _readBack() async {
final RtspPlaybackTuning? live =
await context.read<LocalCameraCubit>().readBackTuning();
if (!mounted) return;
setState(() {
_nativeEcho = live == null
? '读回失败:调参通道不存在(确认本地覆盖包已生效 / 是否 Android 端)'
: '原生当前生效:TCP=${live.forceRtpTcp} · ${live.minBufferMs}~'
'${live.maxBufferMs}ms · 起播${live.bufferForPlaybackMs}ms · '
'超时${live.rtspTimeoutMs == 0 ? '默认' : '${live.rtspTimeoutMs}ms'} · '
'字节${live.targetBufferBytes == 0 ? '默认' : '${live.targetBufferBytes ~/ 1024}KB'} · '
'${live.decoderMode.label}';
});
}
void _apply({required bool replay}) {
context.read<LocalCameraCubit>().updateTuning(_draft, reconnect: replay);
final ScaffoldMessengerState messenger = ScaffoldMessenger.of(context);
Navigator.of(context).pop();
messenger.showSnackBar(
SnackBar(
content: Text(
replay ? '已应用并重拉流:${_draft.summary}' : '已应用(下次拉流生效):${_draft.summary}',
),
duration: const Duration(seconds: 2),
backgroundColor: const Color(0xFF165DFF),
),
);
}
@override
Widget build(BuildContext context) {
final double maxHeight = MediaQuery.sizeOf(context).height * 0.9;
// 弹窗底色是写死的深色,但 APP 可能跑在浅色主题上:不锁主题的话,
// 没显式给色的控件(按钮文字 / chip / 输入框 / 水波纹)会继承浅色主题的默认色,
// 就出现「白底 + 白字」看不清。只钉本弹窗这一棵子树,不影响全局主题。
return Theme(
data: _darkThemeOf(context),
child: Padding(
padding: EdgeInsets.only(bottom: MediaQuery.viewInsetsOf(context).bottom),
child: ConstrainedBox(
constraints: BoxConstraints(maxHeight: maxHeight),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const _SheetHandle(),
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
child: Row(
children: [
const Expanded(
child: Text(
'直播调参(花屏 / 延迟)',
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w600,
),
),
),
TextButton(
onPressed: () =>
setState(() => _draft = RtspPlaybackTuning.defaults),
style: TextButton.styleFrom(
foregroundColor: const Color(0xFF94BFFF),
),
child: const Text('恢复默认', style: TextStyle(fontSize: 12)),
),
],
),
),
Flexible(child: _buildForm()),
_buildActions(),
],
),
),
),
);
}
/// 把弹窗子树锁到深色主题:保留宿主主题的字号/字体族(随系统无障碍缩放),
/// 只换 brightness / colorScheme / textTheme 这三样决定前景色的东西。
ThemeData _darkThemeOf(BuildContext context) {
final ThemeData base = Theme.of(context);
return base.copyWith(
brightness: Brightness.dark,
colorScheme: ColorScheme.fromSeed(
seedColor: const Color(0xFF165DFF),
brightness: Brightness.dark,
),
textTheme: base.textTheme.apply(
bodyColor: const Color(0xFFE8E8E8),
displayColor: Colors.white,
),
);
}
Widget _buildForm() {
return ListView(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
children: [
const TuningSectionTitle(text: '预设档位(先点一个再微调)'),
TuningPresetRow(
draft: _draft,
onPick: (t) => setState(() => _draft = t),
),
const SizedBox(height: 16),
const TuningSectionTitle(text: '策略一:传输方式(治花屏)'),
TuningTransportPicker(
forceTcp: _draft.forceRtpTcp,
onChanged: (v) => setState(() => _draft = _draft.copyWith(forceRtpTcp: v)),
),
const TuningHint(
text: 'UDP 不重传,空口丢包直接解出马赛克;TCP 会重传把画面补全,'
'代价是弱链路下卡顿与延迟上升。',
),
const SizedBox(height: 16),
const TuningSectionTitle(text: '策略二:缓冲水位(治延迟)'),
TuningMsField(
label: 'minBufferMs(重新加载水位)',
value: _draft.minBufferMs,
hint: 'Media3 有 500ms 硬下限,填更小不生效',
onChanged: (v) => setState(() => _draft = _draft.copyWith(minBufferMs: v)),
),
TuningMsField(
label: 'maxBufferMs(停止加载水位 = 延迟上限)',
value: _draft.maxBufferMs,
hint: '平均积压约 (min+max)/2;越小越跟手,太小易卡',
onChanged: (v) => setState(() => _draft = _draft.copyWith(maxBufferMs: v)),
),
TuningMsField(
label: 'bufferForPlaybackMs(起播所需缓冲)',
value: _draft.bufferForPlaybackMs,
hint: '直播建议 0:首帧到达即渲染',
onChanged: (v) =>
setState(() => _draft = _draft.copyWith(bufferForPlaybackMs: v)),
),
TuningMsField(
label: 'bufferForPlaybackAfterRebufferMs(卡完恢复所需缓冲)',
value: _draft.bufferForPlaybackAfterRebufferMs,
hint: '直播建议 0:避免每次卡完再攒一段',
onChanged: (v) => setState(
() => _draft = _draft.copyWith(bufferForPlaybackAfterRebufferMs: v),
),
),
TuningMsField(
label: 'rtspTimeoutMs(RTSP 超时,0=用默认)',
value: _draft.rtspTimeoutMs,
hint: '过小会在弱链路上误判「流结束」而断流',
onChanged: (v) => setState(() => _draft = _draft.copyWith(rtspTimeoutMs: v)),
),
const SizedBox(height: 16),
_buildStreamAndDecoder(),
const SizedBox(height: 8),
_buildSummary(),
TextButton(
onPressed: _readBack,
child: const Text(
'读回原生实际生效值(验证参数有没有真的进插件)',
style: TextStyle(color: Color(0xFF94BFFF), fontSize: 12),
),
),
],
);
}
/// 策略三:取哪一路码流 + 由谁解码 + 字节上限。
/// 这一区才是「播放层」:前面两项只能决定“坏数据怎么补”,这里决定“拿到的是什么数据”。
Widget _buildStreamAndDecoder() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const TuningSectionTitle(text: '策略三:取流与解码(播放层)'),
TuningChoiceRow<RtspProfileSelect>(
options: RtspProfileSelect.values,
labelOf: (p) => p.label,
selected: _draft.profileSelect,
onChanged: (p) =>
setState(() => _draft = _draft.copyWith(profileSelect: p)),
),
TuningHint(text: '当前:${_draft.profileSelect.desc}。改这一档会重新走 ONVIF 取流(URL 会变)。'),
const SizedBox(height: 12),
TuningChoiceRow<RtspDecoderMode>(
options: RtspDecoderMode.values,
labelOf: (m) => m.label,
selected: _draft.decoderMode,
onChanged: (m) =>
setState(() => _draft = _draft.copyWith(decoderMode: m)),
),
const TuningHint(
text: 'Media3 默认硬解,且硬解初始化失败不会自动回退软解;怀疑解码侧问题时,切软解对比同一画面。',
),
const SizedBox(height: 12),
TuningMsField(
label: 'targetBufferBytes(字节上限,按 KB 填)',
value: _draft.targetBufferBytes ~/ 1024,
suffix: 'KB',
hint: '0 = 用默认(视频约 2MB)。高码率下 2MB 不到 1 秒就撞上限,会频繁 rebuffer,可试 8192',
onChanged: (kb) => setState(
() => _draft = _draft.copyWith(targetBufferBytes: kb < 0 ? 0 : kb * 1024),
),
),
],
);
}
Widget _buildSummary() {
return Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: const Color(0xFF1E1E1E),
borderRadius: BorderRadius.circular(8),
border: Border.all(color: const Color(0xFF3D3D3D)),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'预计稳态积压 ≈ ${_draft.estimatedBacklogMs}ms',
style: const TextStyle(color: Color(0xFF94BFFF), fontSize: 12),
),
const SizedBox(height: 4),
const Text(
'注意:这只是播放器内部水位,不等于肉眼端到端延迟——后端的大头通常在摄像头 GOP / '
'图传编码,而不是这里。',
style: TextStyle(color: Color(0xFF9AA0A6), fontSize: 11, height: 1.4),
),
if (_nativeEcho.isNotEmpty) ...[
const SizedBox(height: 6),
Text(
_nativeEcho,
style: const TextStyle(color: Color(0xFFB8B8B8), fontSize: 11),
),
],
],
),
);
}
// 底部两个按钮必须用同一套尺寸:主题只给 elevatedButtonTheme 设了
// padding(vertical:16, horizontal:24) 与 radius 12,outlinedButton 没被覆盖,
// 两个按钮默认内间距/圆角完全不同 → 一高一矮,看着就别扭。这里显式对齐。
static const EdgeInsets _actionPadding = EdgeInsets.symmetric(
horizontal: 10,
vertical: 12,
);
static const Size _actionMinSize = Size(0, 44);
static const TextStyle _actionText = TextStyle(
fontSize: 13,
fontWeight: FontWeight.w600,
);
static const OutlinedBorder _actionShape = RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(10)),
);
Widget _buildActions() {
return SafeArea(
top: false,
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 12),
child: Row(
children: [
Expanded(
child: OutlinedButton(
onPressed: () => _apply(replay: false),
style: OutlinedButton.styleFrom(
foregroundColor: const Color(0xFFCCCCCC),
backgroundColor: Colors.transparent,
side: const BorderSide(color: Color(0xFF4A4A4A)),
padding: _actionPadding,
minimumSize: _actionMinSize,
textStyle: _actionText,
shape: _actionShape,
),
child: const Text('仅保存 · 下次拉流生效'),
),
),
const SizedBox(width: 10),
Expanded(
child: ElevatedButton(
onPressed: () => _apply(replay: true),
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF165DFF),
foregroundColor: Colors.white,
elevation: 0,
padding: _actionPadding,
minimumSize: _actionMinSize,
textStyle: _actionText,
shape: _actionShape,
),
child: const Text('保存 · 立即重拉流'),
),
),
],
),
),
);
}
}
class _SheetHandle extends StatelessWidget {
const _SheetHandle();
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(top: 8, bottom: 4),
child: Container(
width: 36,
height: 4,
decoration: BoxDecoration(
color: Colors.white24,
borderRadius: BorderRadius.circular(2),
),
),
);
}
}