接入声网四路视频

This commit is contained in:
2026-11-21 14:52:13 +08:00
parent 04fffd2267
commit 739d588a16
26 changed files with 1637 additions and 15 deletions

View File

@@ -0,0 +1,17 @@
import 'package:flutter/widgets.dart';
import 'pv_agora_session.dart';
/// Page owns the session lifecycle; camera widgets listen independently so a
/// video event never rebuilds the vehicle controls or the whole HUD.
class PvAgoraScope extends InheritedWidget {
const PvAgoraScope({super.key, required this.session, required super.child});
final PvAgoraSession session;
static PvAgoraSession of(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<PvAgoraScope>()!.session;
@override
bool updateShouldNotify(PvAgoraScope oldWidget) =>
session != oldWidget.session;
}

View File

@@ -0,0 +1,193 @@
import 'dart:async';
import 'package:agora_rtc_engine/agora_rtc_engine.dart' as agora;
import 'package:flutter/foundation.dart';
import '../../domain/video/pv_agora_config.dart';
/// One engine / one channel per remote-control page. All camera views share it.
/// Lifecycle operations are serialized so rapid source/config changes cannot
/// initialize another engine before the previous one has finished releasing.
class PvAgoraSession extends ChangeNotifier {
PvAgoraSession({agora.RtcEngine Function()? createEngine})
: _createEngine = createEngine ?? agora.createAgoraRtcEngine;
final agora.RtcEngine Function() _createEngine;
agora.RtcEngine? _engine;
agora.RtcEngineEventHandler? _handler;
Future<void> _pending = Future.value();
Timer? _timeout;
int _generation = 0;
bool _disposed = false;
bool joined = false;
String? message;
String? tokenWarning;
PvAgoraConfig? config;
final Map<int, agora.RemoteVideoState> _videoStates = {};
agora.RtcEngine? get engine => _engine;
int get generation => _generation;
bool hasVideo(int uid) =>
joined &&
_videoStates[uid] == agora.RemoteVideoState.remoteVideoStateDecoding;
void _notify() {
if (!_disposed) notifyListeners();
}
Future<void> connect(PvAgoraConfig next) {
final validation = next.validate();
if (validation != null) return Future.error(ArgumentError(validation));
final generation = ++_generation;
config = next;
joined = false;
message = '正在连接声网频道…';
tokenWarning = null;
_videoStates.clear();
_timeout?.cancel();
_notify();
return _pending = _pending.then((_) async {
await _release();
if (_disposed || generation != _generation) return;
bool current() => !_disposed && generation == _generation;
try {
final engine = _createEngine();
_engine = engine;
await engine.initialize(
agora.RtcEngineContext(
appId: next.appId,
channelProfile:
agora.ChannelProfileType.channelProfileLiveBroadcasting,
),
);
if (!current()) return;
await engine.enableVideo();
await engine.enableLocalVideo(false);
await engine.enableLocalAudio(false);
if (!current()) return;
final handler = agora.RtcEngineEventHandler(
onJoinChannelSuccess: (_, _) {
if (!current()) return;
joined = true;
message = null;
_timeout?.cancel();
_notify();
},
onUserOffline: (_, uid, reason) {
if (!current()) return;
_videoStates.remove(uid);
_notify();
},
onRemoteVideoStateChanged: (_, uid, state, reason, elapsed) {
if (!current()) return;
_videoStates[uid] = state;
_notify();
},
onConnectionStateChanged: (_, state, reason) {
if (!current()) return;
if (state == agora.ConnectionStateType.connectionStateConnected) {
joined = true;
message = null;
_timeout?.cancel();
} else {
joined = false;
_videoStates.clear();
message = state == agora.ConnectionStateType.connectionStateFailed
? '声网连接失败,请核对配置和 Token'
: '声网连接中断,正在重新连接…';
}
_notify();
},
onTokenPrivilegeWillExpire: (_, token) {
if (!current()) return;
tokenWarning = 'Token 即将过期,请在视频源设置中更新';
_notify();
},
onRequestToken: (_) {
if (!current()) return;
joined = false;
_videoStates.clear();
message = 'Token 已过期,请在视频源设置中更新';
_notify();
},
onError: (error, detail) {
if (!current()) return;
joined = false;
_videoStates.clear();
// SDK details can contain credentials; never display/log them.
message = '声网连接异常(${error.value()}),请核对配置和 Token';
_timeout?.cancel();
_notify();
},
);
_handler = handler;
engine.registerEventHandler(handler);
_timeout = Timer(const Duration(seconds: 15), () {
if (!current() || joined) return;
message = '连接超时,请检查网络或在视频源设置中更新 Token 后重试';
_notify();
});
await engine.joinChannel(
token: next.token,
channelId: next.channel,
uid: next.viewerUid,
options: const agora.ChannelMediaOptions(
clientRoleType: agora.ClientRoleType.clientRoleAudience,
autoSubscribeVideo: true,
autoSubscribeAudio: false,
publishCameraTrack: false,
publishMicrophoneTrack: false,
),
);
} catch (_) {
if (current()) {
_timeout?.cancel();
joined = false;
message = '声网连接失败,请检查配置、网络及 Token 有效期';
_notify();
}
await _release();
}
});
}
Future<void> disconnect() {
++_generation;
_timeout?.cancel();
joined = false;
message = null;
_videoStates.clear();
_notify();
return _pending = _pending.then((_) => _release());
}
Future<void> _release() async {
final engine = _engine;
final handler = _handler;
_engine = null;
_handler = null;
if (engine == null) return;
try {
if (handler != null) engine.unregisterEventHandler(handler);
} catch (_) {
/* Still release if unregistering fails. */
}
try {
await engine.leaveChannel();
} catch (_) {
/* An engine that never joined still needs releasing. */
}
try {
await engine.release();
} catch (_) {
/* No UI callbacks during teardown. */
}
}
@override
void dispose() {
_disposed = true;
unawaited(disconnect());
super.dispose();
}
}