import AVFoundation import Accelerate import Foundation import HydraulophoneCore import OSLog struct NativeOpusSnapshot { let position: TimeInterval let duration: TimeInterval let isPlaying: Bool let hasEnded: Bool let bufferedRange: ClosedRange? } /// One continuous PCM output clock, with separate decoders for the current and /// next track. About six seconds of audio are scheduled across the boundary. @MainActor final class NativeOpusAudioEngine { private(set) var lastScheduledGain: Float = 1 var normalizationEnabled = true var hasPreparedSuccessor: Bool { next != nil || boundary != nil } var onSnapshot: (@MainActor (NativeOpusSnapshot) -> Void)? var onFailure: (@MainActor (Error) -> Void)? var onTransition: (@MainActor (NativeOpusPreparedTrack) -> Void)? private(set) var snapshot = NativeOpusSnapshot( position: 0, duration: 0, isPlaying: false, hasEnded: false, bufferedRange: nil) private let engine = AVAudioEngine() private let node = AVAudioPlayerNode() private var current: NativeOpusPreparedTrack? private var rendering: NativeOpusPreparedTrack? private var next: NativeOpusPreparedTrack? private struct Boundary { let track: NativeOpusPreparedTrack let position: TimeInterval let trackStart: TimeInterval } private var boundary: Boundary? private var pumpTask: Task? private var seekOperation: Task? private var monitorTask: Task? private var configurationObserver: NSObjectProtocol? private var generation = 0 private var renderGeneration = 0 private var wantsPlayback = false private var ready = false private var renderEnded = false private var queuedFrames = 0 private var scheduledFrames: Int64 = 0 private var timelineStart: TimeInterval = 0 private var scheduledEnd: TimeInterval = 0 private var position: TimeInterval = 0 private var activeTrackStart: TimeInterval = 0 private let logger = Logger(subsystem: "com.hydraulophone", category: "native-opus") init() { engine.attach(node) configurationObserver = NotificationCenter.default.addObserver( forName: .AVAudioEngineConfigurationChange, object: engine, queue: .main ) { [weak self] _ in Task { @MainActor [weak self] in guard let self, self.ready, self.wantsPlayback else { return } self.onFailure?(NativeOpusError.engineUnavailable) } } } deinit { seekOperation?.cancel() pumpTask?.cancel() monitorTask?.cancel() if let configurationObserver { NotificationCenter.default.removeObserver(configurationObserver) } } func prepare(stream: PlaybackResolvedStream, cache: TrackCacheStore? = nil) async throws { stop() let token = generation let prepared = try await NativeOpusPreparedTrack.prepare(stream: stream, cache: cache) do { try checkGeneration(token) } catch { prepared.cancel() throw error } current = prepared rendering = prepared engine.connect(node, to: engine.mainMixerNode, format: prepared.firstChunk.buffer.format) engine.prepare() schedule(prepared.firstChunk) ready = true publish() startPump(token: token) startMonitor(token: token) logger.notice("native_opus ready duration=\(prepared.duration)") } /// The controller validates queue identity before installing a prepared head. func enqueueNext(_ prepared: NativeOpusPreparedTrack) -> Bool { guard ready, boundary == nil else { prepared.cancel() return false } next?.cancel() next = prepared logger.notice("gapless next_ready=true") return true } /// AVAudioPlayerNode cannot remove selected future buffers. If the successor /// is already scheduled, pause immediately and ask the controller to reseek /// the current source, which flushes those buffers before accepting a new one. @discardableResult func discardNext() -> Bool { next?.cancel() next = nil guard let boundary else { return false } updatePosition() node.pause() pumpTask?.cancel() boundary.track.cancel() self.boundary = nil pendingSuccessorError = nil return true } func updateCurrentLoudness(_ metadata: AudioLoudnessMetadata) { current?.loudness = metadata } func play() throws { guard ready else { throw NativeOpusError.engineUnavailable } wantsPlayback = true if !engine.isRunning { try engine.start() } if queuedFrames > 0 { node.play() } publish() } func pause() { updatePosition() wantsPlayback = false node.pause() publish() } func seek(to target: TimeInterval) async throws -> Bool { let previous = seekOperation previous?.cancel() let operation = Task { @MainActor [weak self] in _ = try? await previous?.value try Task.checkCancellation() guard let self else { throw CancellationError() } return try await self.performSeek(to: target) } seekOperation = operation return try await withTaskCancellationHandler( operation: { try await operation.value }, onCancel: { operation.cancel() }) } private func performSeek(to target: TimeInterval) async throws -> Bool { guard ready, let current else { throw NativeOpusError.engineUnavailable } let wasBuffered = snapshot.bufferedRange?.contains(target) ?? false generation &+= 1 let token = generation let oldPump = pumpTask oldPump?.cancel() pumpTask = nil monitorTask?.cancel() node.stop() renderGeneration &+= 1 _ = discardNext() queuedFrames = 0 scheduledFrames = 0 renderEnded = false position = target activeTrackStart = 0 timelineStart = target scheduledEnd = target rendering = current publish() await oldPump?.value try checkGeneration(token) try await current.pcm.seek(to: target) try checkGeneration(token) if let first = try await current.pcm.nextChunk() { try checkGeneration(token) schedule(first) } else { renderEnded = true } try checkGeneration(token) startPump(token: token) startMonitor(token: token) publish() logger.notice("native_opus seek target=\(target) buffered=\(wasBuffered)") return wasBuffered } func stop() { ready = false generation &+= 1 renderGeneration &+= 1 pumpTask?.cancel() pumpTask = nil seekOperation?.cancel() seekOperation = nil monitorTask?.cancel() monitorTask = nil node.stop() engine.stop() current?.cancel() rendering?.cancel() next?.cancel() boundary?.track.cancel() current = nil rendering = nil next = nil boundary = nil pendingSuccessorError = nil queuedFrames = 0 scheduledFrames = 0 position = 0 timelineStart = 0 activeTrackStart = 0 scheduledEnd = 0 wantsPlayback = false renderEnded = false } private func startPump(token: Int) { pumpTask = Task { @MainActor [weak self] in do { while !Task.isCancelled { guard let self, self.generation == token, let rendering = self.rendering else { return } if self.renderEnded { if self.boundary == nil, let next = self.next, self.queuedFrames > 0 { self.next = nil let end = self.scheduledEnd self.boundary = Boundary( track: next, position: end, trackStart: end - next.firstChunk.timestamp) self.rendering = next self.renderEnded = false self.schedule(next.firstChunk) self.logger.notice( "gapless boundary_scheduled=true queued_frames=\(self.queuedFrames)") continue } self.publish() if self.queuedFrames == 0 { return } try await Task.sleep(for: .milliseconds(50)) continue } if self.queuedFrames >= 6 * 48_000 { try await Task.sleep(for: .milliseconds(100)) continue } guard let chunk = try await rendering.pcm.nextChunk() else { try self.checkGeneration(token) self.renderEnded = true let start = self.boundary?.trackStart ?? self.activeTrackStart rendering.decodedDuration = max(0, self.scheduledEnd - start) continue } try self.checkGeneration(token) self.schedule(chunk) if self.wantsPlayback { if !self.engine.isRunning { try self.engine.start() } if !self.node.isPlaying { self.node.play() } } } } catch is CancellationError { return } catch { guard !Task.isCancelled, let self, self.generation == token else { return } // A failure in the not-yet-audible successor must not cut off this track. if self.boundary != nil { self.renderEnded = true self.logger.notice("gapless successor_read_failed=true") self.pendingSuccessorError = error } else { self.onFailure?(error) } } } } private var pendingSuccessorError: Error? /// Scale each track's own PCM before scheduling. A shared mixer gain would /// change both tracks while buffers straddle a gapless boundary. Keep the /// original decoded head untouched so it can never be normalized twice. private func normalizedBuffer(for chunk: NativeOpusPCMChunk) -> AVAudioPCMBuffer { var gain = normalizationEnabled ? AudioNormalizationGainPolicy.linearGain(for: rendering?.loudness) : 1 lastScheduledGain = gain guard gain != 1, let source = chunk.buffer.floatChannelData, let output = AVAudioPCMBuffer( pcmFormat: chunk.buffer.format, frameCapacity: chunk.buffer.frameLength), let channels = output.floatChannelData else { return chunk.buffer } output.frameLength = chunk.buffer.frameLength for channel in 0..= boundary.position - 0.5 / 48_000 { self.promote(boundary) // Promotion can cause the controller to replace/stop this engine. guard self.renderGeneration == renderToken else { return } } if self.queuedFrames == 0 { self.position = self.scheduledEnd self.node.stop() self.renderGeneration &+= 1 } self.publish() } } } private func promote(_ boundary: Boundary) { let previous = current current = boundary.track activeTrackStart = boundary.trackStart position = max(position, boundary.position) self.boundary = nil previous?.cancel() updatePosition() snapshot = makeSnapshot() logger.notice("gapless transition=true node_restarted=false") #if DEBUG FileHandle.standardOutput.write( Data("Hydraulophone gapless transition node_restarted=false\n".utf8)) #endif onTransition?(boundary.track) if let error = pendingSuccessorError { pendingSuccessorError = nil onFailure?(error) } } private func startMonitor(token: Int) { monitorTask?.cancel() monitorTask = Task { @MainActor [weak self] in while !Task.isCancelled { do { try await Task.sleep(for: .milliseconds(250)) } catch { return } guard let self, self.generation == token else { return } self.updatePosition() self.publish() } } } private func updatePosition() { guard node.isPlaying, queuedFrames > 0, let renderTime = node.lastRenderTime, let time = node.playerTime(forNodeTime: renderTime), time.sampleRate > 0 else { return } position = max( position, min(scheduledEnd, timelineStart + Double(max(0, time.sampleTime)) / time.sampleRate) ) } private func makeSnapshot() -> NativeOpusSnapshot { let duration = current?.duration ?? 0 let localPosition = max(0, position - activeTrackStart) let currentEnd = min(scheduledEnd, boundary?.position ?? scheduledEnd) - activeTrackStart return NativeOpusSnapshot( position: min(localPosition, duration > 0 ? duration : localPosition), duration: duration, isPlaying: wantsPlayback && engine.isRunning && node.isPlaying && queuedFrames > 0, hasEnded: renderEnded && queuedFrames == 0 && boundary == nil, bufferedRange: queuedFrames > 0 ? localPosition...max(localPosition, currentEnd) : nil) } private func publish() { snapshot = makeSnapshot() onSnapshot?(snapshot) } private func checkGeneration(_ token: Int) throws { try Task.checkCancellation() guard generation == token else { throw CancellationError() } } }