import UIKit @preconcurrency import VolcEngineRTC /// 可替换的双路图传播放器;测试注入内存替身,不初始化 RTC 或连接设备。 @MainActor protocol DroneDockLivePlaying: AnyObject { /// 设置只读几何事件出口;不触发播放、连接或任务状态刷新。 func setGeometryHandler(_ handler: (@MainActor (DroneDockLiveGeometry) -> Void)?) /// 同一播放会话可增补或更新凭证,不重建未变化的房间。 func start(_ configurations: [DroneDockVolcLiveConfiguration], in view: UIView, onEvent: @escaping @MainActor (DroneDockLivePlaybackEvent) -> Void) /// 只关闭本机订阅,不向设备发送停止推流指令。 func stop() } extension DroneDockLivePlaying { /// 旧播放器替身无需实现诊断能力。 func setGeometryHandler(_ handler: (@MainActor (DroneDockLiveGeometry) -> Void)?) {} } /// 通过双路接收器播放真实图传,生命周期由任务页管理。 @MainActor final class DroneDockVolcLivePlayer: DroneDockLivePlaying { private let receiver = DroneDockLiveReceiver(makeEngine: DroneDockVolcEngineAdapter.make) /// 几何事件与业务播放事件分离,不改变播放状态机。 func setGeometryHandler(_ handler: (@MainActor (DroneDockLiveGeometry) -> Void)?) { receiver.setGeometryHandler(handler) } /// 两种构建均通过同一接收器播放当前任务的图传。 func start(_ configurations: [DroneDockVolcLiveConfiguration], in view: UIView, onEvent: @escaping @MainActor (DroneDockLivePlaybackEvent) -> Void) { receiver.start(configurations, in: view, onEvent: onEvent) } /// 释放本机播放资源,不发送任何设备控制请求。 func stop() { receiver.stop() } } /// 一个 RTC 引擎接收两个房间,机巢先接入,无人机有帧后覆盖,停流后恢复机巢。 @MainActor final class DroneDockLiveReceiver: DroneDockLivePlaying { private var engine: (any DroneDockRTCReceivingEngine)? private let makeEngine: (String, @escaping @Sendable (DroneDockVolcEvent) -> Void) -> (any DroneDockRTCReceivingEngine)? private let firstFrameDelay: @Sendable () async throws -> Void /// 正式页面注入 SDK 适配器;测试注入内存接收端。 init(makeEngine: @escaping (String, @escaping @Sendable (DroneDockVolcEvent) -> Void) -> (any DroneDockRTCReceivingEngine)?, firstFrameDelay: @escaping @Sendable () async throws -> Void = { try await Task.sleep(for: .seconds(20)) }) { self.makeEngine = makeEngine self.firstFrameDelay = firstFrameDelay } private weak var container: UIView? private var sources: [String: DroneDockVolcSource] = [:] private var configurations: [DroneDockVolcLiveConfiguration] = [] private var selection = DroneDockLiveSourceSelection() private var displayedRole: String? private var allowsDroneConnection = false private var failedRoles: Set = [] private var generation = UUID() private var onEvent: (@MainActor (DroneDockLivePlaybackEvent) -> Void)? private var onGeometry: (@MainActor (DroneDockLiveGeometry) -> Void)? /// 复用调用方的任务诊断会话,不在接收器中另建日志通道。 func setGeometryHandler(_ handler: (@MainActor (DroneDockLiveGeometry) -> Void)?) { onGeometry = handler } /// 加入只收视频的房间;同一来源只更新 Token,避免后台重查导致画面闪断。 func start(_ configurations: [DroneDockVolcLiveConfiguration], in view: UIView, onEvent: @escaping @MainActor (DroneDockLivePlaybackEvent) -> Void) { guard let first = configurations.first else { stop(); return } if container !== view || self.configurations.first?.appID != first.appID { stop() } self.onEvent = onEvent self.container = view self.configurations = configurations if engine == nil { let generation = generation guard let engine = makeEngine(first.appID, { [weak self] event in Task { @MainActor [weak self] in guard let self, self.generation == generation else { return } self.receive(event) } }) else { stop(); onEvent(.failed("图传播放器初始化失败")); return } self.engine = engine } for role in Array(sources.keys) { guard let source = sources[role] else { continue } let replacement = configurations.first { $0.role == role } if replacement?.roomID != source.configuration.roomID || replacement?.userID != source.configuration.userID { removeSource(role) } } if let airport = configurations.first(where: { $0.role == "airport" }) { connect(airport) } else { allowsDroneConnection = true } connectDroneIfAllowed() if sources.isEmpty { stop(); onEvent(.failed("无法加入图传房间,请重试")); return } displaySelectedSource() } /// 离页释放两路订阅及同一个引擎,迟到回调由会话及房间身份拦截。 func stop() { generation = UUID() onEvent = nil for role in Array(sources.keys) { removeSource(role) } engine?.destroy() engine = nil container = nil configurations = [] selection = DroneDockLiveSourceSelection() displayedRole = nil allowsDroneConnection = false failedRoles = [] } private func connect(_ configuration: DroneDockVolcLiveConfiguration) { let role = configuration.role guard configuration.expiresAt.timeIntervalSinceNow > 5 else { removeSource(role) failedRoles.insert(role) if role == "airport" { allowsDroneConnection = true } return } if let source = sources[role] { guard source.configuration != configuration else { return } guard source.room.updateToken(configuration.token) == 0 else { removeSource(role) connect(configuration) return } source.configuration = configuration scheduleExpiry(source) return } guard let container else { return } let generation = generation let sourceID = UUID() guard let room = engine?.makeRoom(configuration.roomID, onEvent: { [weak self] event in Task { @MainActor [weak self] in guard let self, self.generation == generation, self.sources[role]?.id == sourceID else { return } self.receive(event) } }) else { failedRoles.insert(role) if role == "airport" { allowsDroneConnection = true } return } let view = UIView(frame: container.bounds) view.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.backgroundColor = .black view.isHidden = true container.addSubview(view) let source = DroneDockVolcSource(id: sourceID, configuration: configuration, room: room, view: view) sources[role] = source let result = room.join(configuration) guard result == 0 else { removeSource(role) failedRoles.insert(role) if role == "airport" { allowsDroneConnection = true } return } // 机巢无首帧时不能无限等待,仍尝试无人机;已连房间继续等待发布事件。 let delay = firstFrameDelay source.timeoutTask = Task { @MainActor [weak self] in do { try await delay() } catch { return } guard !Task.isCancelled, let self, self.generation == generation, self.sources[role]?.id == sourceID else { return } // 首帧等待超时只开放另一路;不能销毁仍在等待发布的房间或取消补取参数。 self.markReady(false, source: source) } scheduleExpiry(source) } private func connectDroneIfAllowed() { guard allowsDroneConnection, let drone = configurations.first(where: { $0.role == "drone" }) else { return } connect(drone) } private func scheduleExpiry(_ source: DroneDockVolcSource) { source.expiryTask?.cancel() let role = source.configuration.role, sourceID = source.id, generation = generation let delay = max(1, source.configuration.expiresAt.timeIntervalSinceNow) source.expiryTask = Task { @MainActor [weak self] in try? await Task.sleep(for: .seconds(delay)) guard !Task.isCancelled, let self, self.generation == generation, self.sources[role]?.id == sourceID else { return } self.removeSource(role) self.displaySelectedSource() if self.sources.isEmpty { let callback = self.onEvent self.stop() callback?(.expired) } } } private func removeSource(_ role: String) { selection.setReady(false, role: role) guard let source = sources.removeValue(forKey: role) else { return } source.timeoutTask?.cancel() source.expiryTask?.cancel() if let streamID = source.streamID { _ = engine?.setVideoView(nil, streamID: streamID) } source.room.destroy() source.view.removeFromSuperview() } private func receive(_ event: DroneDockVolcEvent) { switch event { case .published(let id, let roomID, let published): guard !id.isEmpty, let source = source(in: roomID) else { return } if !published { guard source.streamID == id else { return } _ = engine?.setVideoView(nil, streamID: id) _ = source.room.subscribeVideo(id, subscribe: false) source.streamID = nil source.frameGeometry = nil source.reportedFirstFrame = false markReady(false, source: source) return } guard source.streamID == nil else { return } source.streamID = id let render = engine?.setVideoView(source.view, streamID: id) let subscribe = source.room.subscribeVideo(id, subscribe: true) if render != 0 || subscribe != 0 { sourceFailed(source.configuration.role, message: "图传订阅失败(\(render ?? -1)/\(subscribe)),请重试") } case .frame(let id, let roomID, let geometry): guard let source = source(in: roomID), source.streamID == id else { return } if let geometry { updateFrameGeometry(geometry, source: source, isFirstFrame: true) } markReady(true, source: source) case .videoSizeChanged(let id, let roomID, let geometry): guard let source = source(in: roomID), source.streamID == id else { return } updateFrameGeometry(geometry, source: source, isFirstFrame: false) case .videoState(let id, let roomID, let state): guard let source = source(in: roomID), source.streamID == id else { return } switch state { case .decoding: markReady(true, source: source) case .stopped, .frozen, .failed: markReady(false, source: source) default: break } case .roomFailed(let roomID, let code): guard let source = source(in: roomID) else { return } sourceFailed(source.configuration.role, message: "图传入房失败(\(code)),请重试") case .connectionLost: for source in sources.values { selection.setReady(false, role: source.configuration.role) } displaySelectedSource() case .failed(let code): let callback = onEvent stop() callback?(.failed("图传连接失败(\(code)),请重试")) } } private func source(in roomID: String) -> DroneDockVolcSource? { sources.values.first { $0.configuration.roomID == roomID } } private func updateFrameGeometry(_ geometry: DroneDockVideoFrameGeometry, source: DroneDockVolcSource, isFirstFrame: Bool) { let changed = source.frameGeometry != geometry source.frameGeometry = geometry if isFirstFrame, !source.reportedFirstFrame { source.reportedFirstFrame = true emitGeometry(source, trigger: "first_frame") } else if changed { emitGeometry(source, trigger: "video_size_changed") } } private func emitGeometry(_ source: DroneDockVolcSource, trigger: String) { guard let streamID = source.streamID, let container else { return } onGeometry?(DroneDockLiveGeometry(trigger: trigger, role: source.configuration.role, roomID: source.configuration.roomID, streamID: streamID, frame: source.frameGeometry, containerWidth: Double(source.view.bounds.width), containerHeight: Double(source.view.bounds.height), hostWidth: Double(container.bounds.width), hostHeight: Double(container.bounds.height), isSelected: selection.selectedRole == source.configuration.role, sdkVersion: engine?.sdkVersion)) } private func markReady(_ ready: Bool, source: DroneDockVolcSource) { selection.setReady(ready, role: source.configuration.role) if ready { failedRoles.remove(source.configuration.role) source.timeoutTask?.cancel(); source.timeoutTask = nil } displaySelectedSource() if source.configuration.role == "airport" { allowsDroneConnection = true connectDroneIfAllowed() } } private func sourceFailed(_ role: String, message: String) { failedRoles.insert(role) selection.setReady(false, role: role) if role == "airport" { allowsDroneConnection = true; connectDroneIfAllowed() } displaySelectedSource() if selection.selectedRole == nil, Set(configurations.map(\.role)).isSubset(of: failedRoles) { let callback = onEvent stop() callback?(.failed(message)) } } private func displaySelectedSource() { let role = selection.selectedRole for source in sources.values { source.view.isHidden = source.configuration.role != role } if let role, let view = sources[role]?.view { container?.bringSubviewToFront(view) } guard displayedRole != role else { return } displayedRole = role if let role, let source = sources[role] { emitGeometry(source, trigger: "source_changed") } onEvent?(.sourceChanged(role)) } } /// 每路独立持有房间、画布及超时;引擎由外层统一管理,避免销毁另一条流。 @MainActor private final class DroneDockVolcSource { let id: UUID var configuration: DroneDockVolcLiveConfiguration let room: any DroneDockRTCReceivingRoom let view: UIView var streamID: String? var frameGeometry: DroneDockVideoFrameGeometry? var reportedFirstFrame = false var timeoutTask: Task? var expiryTask: Task? init(id: UUID, configuration: DroneDockVolcLiveConfiguration, room: any DroneDockRTCReceivingRoom, view: UIView) { self.id = id; self.configuration = configuration; self.room = room; self.view = view } } /// SDK 工作线程只转交值类型事件;事件带房间和流身份以隔离两路回调。 enum DroneDockVolcEvent: Sendable { case published(String, String, Bool) case frame(String, String, DroneDockVideoFrameGeometry? = nil) case videoSizeChanged(String, String, DroneDockVideoFrameGeometry) case videoState(String, String, ByteRTCRemoteVideoState) case roomFailed(String, Int) case connectionLost case failed(Int) } /// SDK 回调桥接,不采集音视频,不处理设备控制消息。 final class DroneDockVolcDelegate: NSObject, ByteRTCEngineDelegate, ByteRTCRoomDelegate { private let emit: @Sendable (DroneDockVolcEvent) -> Void init(emit: @escaping @Sendable (DroneDockVolcEvent) -> Void) { self.emit = emit } func rtcRoom(_ rtcRoom: ByteRTCRoom, onUserPublishStreamVideo streamId: String, info: ByteRTCStreamInfo, isPublish: Bool) { emit(.published(streamId, info.roomId, isPublish)) } func rtcRoom(_ rtcRoom: ByteRTCRoom, onRoomStateChanged roomId: String, withUid uid: String, state: Int, extraInfo: String) { if state != 0 { emit(.roomFailed(roomId, state)) } } func rtcEngine(_ engine: ByteRTCEngine, onFirstRemoteVideoFrameDecoded streamId: String, info: ByteRTCStreamInfo, withFrameInfo frameInfo: ByteRTCVideoFrameInfo) { // 未展示的画布也能解码,不能依赖被隐藏视图的 rendered 回调判断首帧。 emit(.frame(streamId, info.roomId, Self.geometry(frameInfo))) } func rtcEngine(_ engine: ByteRTCEngine, onRemoteVideoSizeChanged streamId: String, info: ByteRTCStreamInfo, withFrameInfo frameInfo: ByteRTCVideoFrameInfo) { emit(.videoSizeChanged(streamId, info.roomId, Self.geometry(frameInfo))) } private static func geometry(_ frameInfo: ByteRTCVideoFrameInfo) -> DroneDockVideoFrameGeometry { DroneDockVideoFrameGeometry(width: frameInfo.width, height: frameInfo.height, rotation: frameInfo.rotation.rawValue) } func rtcEngine(_ engine: ByteRTCEngine, onRemoteVideoStateChanged streamId: String, info: ByteRTCStreamInfo, withVideoState state: ByteRTCRemoteVideoState, withVideoStateReason reason: ByteRTCRemoteVideoStateChangeReason) { emit(.videoState(streamId, info.roomId, state)) } func rtcEngine(_ engine: ByteRTCEngine, onError errorCode: ByteRTCErrorCode) { emit(.failed(errorCode.rawValue)) } func rtcEngine(_ engine: ByteRTCEngine, onConnectionStateChanged state: ByteRTCConnectionState) { if state == .reconnecting { emit(.connectionLost) } if state == .failed { emit(.failed(state.rawValue)) } } }