SPB Git

Repository Public

AudioEngine.swift 32.5 KB 653 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Audio/AudioEngine.swift3// Description: Two-deck playback engine on AVAudioEngine: gapless scheduling, crossfade, equaliser, stall handling.4import Foundation5import AVFoundation6import Accelerate7import AudioToolbox89public struct EngineSettings: Sendable, Equatable {10    public static let eqFrequencies: [Float] = [32, 64, 125, 250, 500, 1000, 2000, 4000, 8000, 16000]11    public var volume: Float = 112    public var eqEnabled = false13    public var eqGains: [Float] = Array(repeating: 0, count: 10)      // dB, −12…+1214    public var preampDB: Float = 015    /// Seconds of overlap between two tracks; 0 = tracks follow each other without overlap (gapless scheduling).16    public var crossfade: Double = 017    /// No equaliser, no loudness gain, no crossfade: the decoded samples reach the output mixer untouched.18    public var directMode = false19    public init() {}20}2122public enum EngineEvent: Sendable {23    case ready(token: UUID, info: DecoderInfo)24    /// The engine moved on by itself to the track prepared with `prepareNext`.25    case advanced(to: UUID)26    /// The current track ended and nothing was prepared after it.27    case finished(token: UUID)28    case failed(token: UUID, error: String, offline: Bool)29    case outputChanged30}3132public struct EngineStatus: Sendable, Equatable {33    public var token: UUID?34    public var position: Double = 035    public var duration: Double = 036    public var isPlaying = false37    public var isBuffering = false38    public var info: DecoderInfo?39    public var bufferedFraction: Double = 040    public var outputSampleRate: Double = 041    public var hasNextPrepared = false42}4344/// Playback engine built on AVAudioEngine. It knows nothing about tracks, queues or the network: it is handed byte45/// sources and tokens.46///47/// Two decks (player → mixer) feed a pre-mixer, an equaliser and the main mixer. The current track plays on one48/// deck; the next one is prepared on the other and started at the exact sample where the current one ends (no gap),49/// or earlier with a volume ramp (crossfade). Each deck decodes on its own queue, so a source waiting for the50/// network never blocks the controls.51public final class AudioEngine: @unchecked Sendable {52    private final class Deck: @unchecked Sendable {53        let player = AVAudioPlayerNode()54        let mixer = AVAudioMixerNode()55        let queue: DispatchQueue56        var decoder: AudioDecoder?57        var source: ByteSource?58        var token: UUID?59        var generation = 060        var baseFrame: Int64 = 0            // file frame at which the player's timeline starts61        var scheduledFrames: Int64 = 0      // frames handed to the player since baseFrame62        var pending = 063        var eof = false64        var loading = false65        var stalled = false                 // paused by the engine because it ran out of decoded audio66        var started = false                 // play() was called for this content67        var gain: Float = 168        var lastPosition: Double = 069        var connectedFormat: AVAudioFormat?70        var endedGeneration = -171        var typeHint: AudioFileTypeID = 072        var flac: FLACIndex?73        var flacChecked = false74        init(_ name: String) { queue = DispatchQueue(label: "spmusic.audio.decode.\(name)", qos: .userInitiated) }75    }7677    private let engine = AVAudioEngine()78    private let preMixer = AVAudioMixerNode()79    private let eq = AVAudioUnitEQ(numberOfBands: 10)80    private let decks = [Deck("a"), Deck("b")]81    private var activeIndex = 082    private var active: Deck { decks[activeIndex] }83    private var idle: Deck { decks[1 - activeIndex] }84    private let lock = NSRecursiveLock()85    private var settings = EngineSettings()86    private var wantPlaying = false87    private var transitioning = false88    private var fade: (start: Date, duration: Double)?89    private var timer: DispatchSourceTimer?90    private let timerQueue = DispatchQueue(label: "spmusic.audio.timer", qos: .userInitiated)91    private let callbackQueue = DispatchQueue(label: "spmusic.audio.callbacks", qos: .userInitiated)92    private var continuations: [UUID: AsyncStream<EngineEvent>.Continuation] = [:]93    private var configObserver: NSObjectProtocol?94    private let offlineFormat: AVAudioFormat?95    private var outputMuted = false96    private var tap: (@Sendable (AVAudioPCMBuffer) -> Void)?97    private static let bufferSeconds = 0.2598    private static let maxPending = 899100    /// `offlineFormat` puts the engine in manual rendering mode (tests): nothing reaches a device, `render` pulls the audio.101    public init(offlineFormat: AVAudioFormat? = nil) {102        self.offlineFormat = offlineFormat103        if let offlineFormat { try? engine.enableManualRenderingMode(.offline, format: offlineFormat, maximumFrameCount: 4096) }104        engine.attach(preMixer); engine.attach(eq)105        for d in decks { engine.attach(d.player); engine.attach(d.mixer) }106        for (i, f) in EngineSettings.eqFrequencies.enumerated() {107            let b = eq.bands[i]; b.filterType = .parametric; b.frequency = f; b.bandwidth = 1; b.gain = 0; b.bypass = false108        }109        eq.bypass = true110        connectGraph()111        if offlineFormat == nil {112            configObserver = NotificationCenter.default.addObserver(forName: .AVAudioEngineConfigurationChange, object: engine, queue: nil) { [weak self] _ in self?.configurationChanged() }113        }114    }115116    deinit {117        if let configObserver { NotificationCenter.default.removeObserver(configObserver) }118        timer?.cancel()119        for d in decks { d.source?.cancel() }120        engine.stop()121    }122123    public func events() -> AsyncStream<EngineEvent> {124        let id = UUID()125        return AsyncStream(bufferingPolicy: .bufferingNewest(64)) { c in126            lock.withLock { continuations[id] = c }127            c.onTermination = { [weak self] _ in self?.lock.withLock { self?.continuations[id] = nil } }128        }129    }130    private func emit(_ e: EngineEvent) { let cs = lock.withLock { Array(continuations.values) }; for c in cs { c.yield(e) } }131132    // MARK: Graph133134    private var outputFormat: AVAudioFormat { offlineFormat ?? engine.outputNode.outputFormat(forBus: 0) }135    private var processingFormat: AVAudioFormat {136        let rate = outputFormat.sampleRate > 0 ? outputFormat.sampleRate : 44100137        return AVAudioFormat(standardFormatWithSampleRate: rate, channels: 2)!138    }139    public var outputSampleRate: Double { lock.withLock { outputFormat.sampleRate } }140    public var outputAudioUnit: AudioUnit? { offlineFormat == nil ? engine.outputNode.audioUnit : nil }141142    private func connectGraph() {143        let fmt = processingFormat144        for d in decks {145            engine.connect(d.player, to: d.mixer, format: d.connectedFormat ?? fmt)146            engine.connect(d.mixer, to: preMixer, format: fmt)147        }148        engine.connect(preMixer, to: eq, format: fmt)149        engine.connect(eq, to: engine.mainMixerNode, format: fmt)150        engine.mainMixerNode.outputVolume = outputMuted ? 0 : settings.volume151    }152153    private func ensureRunning() {154        guard !engine.isRunning else { return }155        engine.prepare()156        do { try engine.start() } catch { Log.info("audio", "engine start failed: \(error.localizedDescription)") }157    }158159    /// Mutes what reaches the device while leaving the signal measurable by `setTap` (functional tests on a real device).160    public func setOutputMuted(_ muted: Bool) { lock.withLock { outputMuted = muted; engine.mainMixerNode.outputVolume = muted ? 0 : settings.volume } }161162    /// Observes the mixed signal before the equaliser and the output volume.163    public func setTap(_ block: (@Sendable (AVAudioPCMBuffer) -> Void)?) {164        lock.withLock {165            preMixer.removeTap(onBus: 0)166            tap = block167            if let block { preMixer.installTap(onBus: 0, bufferSize: 2048, format: nil) { buffer, _ in block(buffer) } }168        }169    }170171    public func apply(_ s: EngineSettings) {172        lock.withLock {173            settings = s174            engine.mainMixerNode.outputVolume = outputMuted ? 0 : max(0, min(1, s.volume))175            let useEQ = s.eqEnabled && !s.directMode176            eq.bypass = !useEQ177            eq.globalGain = useEQ ? max(-12, min(12, s.preampDB)) : 0178            for (i, g) in s.eqGains.prefix(10).enumerated() { eq.bands[i].gain = max(-12, min(12, g)) }179        }180    }181    public var currentSettings: EngineSettings { lock.withLock { settings } }182183    private func configurationChanged() {184        // The output device or its format changed and the system stopped the engine: rebuild and resume where we were.185        lock.lock()186        let deck = active187        let wasPlaying = wantPlaying188        let position = currentPosition(deck)189        let hadTrack = deck.decoder != nil190        resetDeck(idle, cancelSource: true)191        transitioning = false; fade = nil192        deck.generation += 1193        let gen = deck.generation194        deck.player.stop(); deck.pending = 0; deck.scheduledFrames = 0; deck.eof = false; deck.stalled = false; deck.started = false195        connectGraph()196        lock.unlock()197        emit(.outputChanged)198        guard hadTrack else { return }199        deck.source?.interruptReads()200        deck.queue.async { [self] in201            deck.source?.resumeReads()202            lock.lock()203            guard deck.generation == gen, let dec = deck.decoder else { lock.unlock(); return }204            let frame = Int64(position * dec.info.sampleRate)205            try? dec.seek(toFrame: frame)206            deck.baseFrame = frame; deck.lastPosition = position207            if wasPlaying { ensureRunning(); deck.player.play(); deck.started = true }208            lock.unlock()209            pump(deck, gen)210        }211    }212213    /// Switches the device the engine plays to. Returns false when Core Audio refuses.214    @discardableResult215    public func setOutputDevice(_ deviceID: AudioDeviceID) -> Bool {216        guard let unit = outputAudioUnit else { return false }217        var id = deviceID218        let wasRunning = engine.isRunning219        if wasRunning { engine.stop() }220        let status = AudioUnitSetProperty(unit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &id, UInt32(MemoryLayout<AudioDeviceID>.size))221        configurationChanged()222        return status == noErr223    }224225    // MARK: Transport226227    private func resetDeck(_ d: Deck, cancelSource: Bool) {228        d.generation += 1229        d.player.stop()230        if cancelSource { d.source?.cancel(); d.source = nil; d.decoder = nil; d.token = nil; d.lastPosition = 0; d.flac = nil; d.flacChecked = false }231        d.pending = 0; d.scheduledFrames = 0; d.eof = false; d.loading = false; d.stalled = false; d.started = false; d.baseFrame = 0232        d.mixer.outputVolume = 1233    }234235    /// Replaces whatever is playing with this source. `gainDB` is the loudness-normalisation gain (0 = none).236    public func load(token: UUID, source: ByteSource, typeHint: AudioFileTypeID, gainDB: Float = 0, startAt: Double = 0, autoplay: Bool) {237        lock.lock()238        resetDeck(idle, cancelSource: true)239        transitioning = false; fade = nil240        let deck = active241        resetDeck(deck, cancelSource: true)242        deck.token = token; deck.source = source; deck.loading = true; deck.typeHint = typeHint243        deck.gain = settings.directMode ? 1 : powf(10, gainDB / 20)244        deck.lastPosition = startAt245        wantPlaying = autoplay246        let gen = deck.generation247        lock.unlock()248        open(deck, gen: gen, typeHint: typeHint, startAt: startAt, isNext: false)249        startTimer()250    }251252    /// Prepares the track that follows the current one, so it can start without a gap (or with a crossfade).253    public func prepareNext(token: UUID, source: ByteSource, typeHint: AudioFileTypeID, gainDB: Float = 0) {254        lock.lock()255        guard !transitioning else { lock.unlock(); source.cancel(); return }256        let deck = idle257        resetDeck(deck, cancelSource: true)258        deck.token = token; deck.source = source; deck.loading = true; deck.typeHint = typeHint259        deck.gain = settings.directMode ? 1 : powf(10, gainDB / 20)260        let gen = deck.generation261        lock.unlock()262        open(deck, gen: gen, typeHint: typeHint, startAt: 0, isNext: true)263    }264265    public func cancelNext() { lock.withLock { if !transitioning { resetDeck(idle, cancelSource: true) } } }266    public var preparedToken: UUID? { lock.withLock { transitioning ? nil : idle.token } }267268    private func open(_ deck: Deck, gen: Int, typeHint: AudioFileTypeID, startAt: Double, isNext: Bool) {269        guard let source = deck.source, let token = deck.token else { return }270        deck.queue.async { [self] in271            do {272                var dec = try AudioDecoder(source: source, typeHint: typeHint)273                let frame = Int64(max(0, startAt) * dec.info.sampleRate)274                if frame > 0 { dec = try positioned(deck, source: source, existing: dec, frame: frame) }275                // Reconnecting a player to another format waits for a render cycle: it is done without the engine's lock276                // (only this queue ever reconnects this deck), so that rendering and the controls carry on meanwhile.277                if lock.withLock({ deck.generation == gen && deck.connectedFormat != dec.processingFormat }) {278                    setReconnecting(1)279                    engine.disconnectNodeOutput(deck.player)280                    engine.connect(deck.player, to: deck.mixer, format: dec.processingFormat)281                    setReconnecting(-1)282                    lock.withLock { deck.connectedFormat = dec.processingFormat }283                }284                lock.lock()285                guard deck.generation == gen else { lock.unlock(); dec.close(); return }286                deck.decoder = dec; deck.baseFrame = frame; deck.loading = false287                if !isNext, wantPlaying { ensureRunning(); deck.player.play(); deck.started = true }288                lock.unlock()289                if !isNext { emit(.ready(token: token, info: dec.info)) }290                pump(deck, gen)291            } catch {292                let stillWanted = lock.withLock { deck.generation == gen }293                guard stillWanted else { return }294                if isNext { lock.withLock { resetDeck(deck, cancelSource: true) } }       // the current track simply ends with nothing prepared295                else { emit(.failed(token: token, error: Self.describe(error), offline: Self.isNetwork(error))) }296            }297        }298    }299300    /// On the deck's queue, without the lock: a decoder positioned at `frame`.301    ///302    /// For a FLAC file that is still arriving, decoding restarts at a frame boundary just before the target (found by303    /// FLACIndex) instead of letting Core Audio read its way there from the start of the file — which would wait for304    /// every byte before the target to be downloaded.305    private func positioned(_ deck: Deck, source: ByteSource, existing: AudioDecoder, frame: Int64) throws -> AudioDecoder {306        if !source.isLocal, source.bufferedFraction < 1, deck.typeHint == kAudioFileFLACType || deck.typeHint == 0 {307            var index = lock.withLock { deck.flac }308            if index == nil, !lock.withLock({ deck.flacChecked }) {309                index = try? FLACIndex.parse(source)310                lock.withLock { deck.flac = index; deck.flacChecked = true }311            }312            if let index, frame > Int64(index.sampleRate) * 5 {313                let at = try index.locate(sample: frame, in: source)314                if at.byteOffset > index.audioStart {315                    let slice = FLACSliceSource(base: source, headerLength: index.audioStart, sliceStart: at.byteOffset)316                    let dec = try AudioDecoder(source: slice, typeHint: kAudioFileFLACType)317                    try dec.seek(toFrame: frame - at.sample)318                    return dec319                }320            }321        }322        // Back to (or staying with) a decoder over the whole file.323        let whole = existing.isSlice ? try AudioDecoder(source: source, typeHint: deck.typeHint) : existing324        try whole.seek(toFrame: frame)325        return whole326    }327328    static func isNetwork(_ error: Error) -> Bool {329        if let e = error as? SourceError { return e == .stalled || e == .unavailable(502) || e == .unavailable(503) || e == .unavailable(504) }330        return APIClient.isOffline(error)331    }332    static func describe(_ error: Error) -> String {333        switch error {334        case SourceError.stalled: "Le serveur ne répond plus."335        case SourceError.unauthenticated: "La session a expiré."336        case SourceError.unavailable(let s): s == 404 ? "Ce titre n’est plus sur le serveur." : "Le serveur a répondu \(s)."337        case SourceError.corrupt: "Le fichier reçu est corrompu."338        case DecoderError.cannotOpen, DecoderError.unsupportedFormat: "Ce format audio n’est pas pris en charge sur ce Mac."339        case is DecoderError: "Le fichier audio est illisible."340        default: (error as NSError).localizedDescription341        }342    }343344    /// Decodes ahead on the deck's queue and hands buffers to its player, keeping about two seconds scheduled.345    private func pump(_ deck: Deck, _ gen: Int) {346        deck.queue.async { [self] in347            while true {348                lock.lock()349                guard deck.generation == gen, !deck.eof, deck.pending < Self.maxPending, let dec = deck.decoder else { lock.unlock(); return }350                let gain = deck.gain351                lock.unlock()352                let capacity = AVAudioFrameCount(dec.info.sampleRate * Self.bufferSeconds)353                guard let buffer = AVAudioPCMBuffer(pcmFormat: dec.processingFormat, frameCapacity: capacity) else { return }354                let n: AVAudioFrameCount355                do { n = try dec.read(into: buffer) }356                catch {357                    if case SourceError.interrupted = error { return }358                    if case SourceError.cancelled = error { return }359                    let token = lock.withLock { deck.generation == gen ? deck.token : nil }360                    if let token {361                        let isCurrent = lock.withLock { deck === active }362                        if isCurrent { emit(.failed(token: token, error: Self.describe(error), offline: Self.isNetwork(error))) }363                        else { lock.withLock { resetDeck(deck, cancelSource: true) } }364                    }365                    return366                }367                if gain != 1, n > 0, let channels = buffer.floatChannelData {368                    var g = gain369                    for c in 0..<Int(buffer.format.channelCount) { vDSP_vsmul(channels[c], 1, &g, channels[c], 1, vDSP_Length(n)) }370                }371                lock.lock()372                guard deck.generation == gen else { lock.unlock(); return }373                if n == 0 {374                    deck.eof = true375                    scheduleEnd(deck, gen)376                    lock.unlock()377                    return378                }379                deck.pending += 1; deck.scheduledFrames += Int64(n)380                // Completion handlers run on a thread that AVAudioPlayerNode.stop() waits for: they must never wait for our lock.381                deck.player.scheduleBuffer(buffer, completionCallbackType: .dataConsumed) { [weak self] _ in self?.fromPlayer { $0.consumed(deck, gen) } }382                // Enough audio is decoded again after a stall: resume.383                if deck.stalled, deck.pending >= 3 || deck.eof { deck.stalled = false; if wantPlaying, deck === active { deck.player.play() } }384                lock.unlock()385            }386        }387    }388389    /// Runs a player completion handler on a queue of its own. The handler arrives on a thread that belongs to390    /// AVAudioEngine (the one `AVAudioPlayerNode.stop()` waits for, or the rendering thread): taking the engine's391    /// lock there can deadlock against a thread that holds the lock and is calling into AVAudioEngine. The work is392    /// short and never runs on the decoding queues, which may be waiting for the network.393    private func fromPlayer(_ work: @escaping @Sendable (AudioEngine) -> Void) {394        callbackQueue.async { [weak self] in if let self { work(self) } }395    }396397    private func consumed(_ deck: Deck, _ gen: Int) {398        lock.lock()399        guard deck.generation == gen else { lock.unlock(); return }400        deck.pending = max(0, deck.pending - 1)401        // Out of decoded audio before the end of the file (the network is behind): hold the timeline until more arrives.402        if deck.pending == 0, !deck.eof, deck.started, wantPlaying, offlineFormat == nil {403            deck.lastPosition = currentPosition(deck)404            deck.player.pause(); deck.stalled = true405        }406        lock.unlock()407        pump(deck, gen)408    }409410    /// Called with the lock held when a deck's file is fully scheduled.411    private func scheduleEnd(_ deck: Deck, _ gen: Int) {412        guard let dec = deck.decoder, let silence = AVAudioPCMBuffer(pcmFormat: dec.processingFormat, frameCapacity: 64) else { return }413        silence.frameLength = 64414        // A short silent buffer whose "played back" callback marks the real end of the track.415        deck.player.scheduleBuffer(silence, completionCallbackType: .dataPlayedBack) { [weak self] _ in self?.fromPlayer { $0.ended(deck, gen) } }416        if deck === active, settings.crossfade <= 0 || settings.directMode { startNextAtEnd(of: deck) }417    }418419    /// Gapless: starts the prepared deck at the sample where `deck` runs out.420    private func startNextAtEnd(of deck: Deck) {421        let next = idle422        guard !transitioning, next.decoder != nil, next.token != nil, wantPlaying, let dec = deck.decoder else { return }423        guard let nodeTime = deck.player.lastRenderTime, let playerTime = Self.playerTime(deck.player) else { return }424        let remaining = max(0, Double(deck.scheduledFrames - playerTime.sampleTime) / dec.info.sampleRate)425        next.mixer.outputVolume = 1426        if offlineFormat == nil, nodeTime.isHostTimeValid {427            next.player.play(at: AVAudioTime(hostTime: nodeTime.hostTime + AVAudioTime.hostTime(forSeconds: remaining)))428        } else if nodeTime.isSampleTimeValid {429            // Manual rendering: every node shares the engine's timeline, each counted at its own output rate.430            let rate = next.player.outputFormat(forBus: 0).sampleRate431            let now = Double(nodeTime.sampleTime) / nodeTime.sampleRate432            next.player.play(at: AVAudioTime(sampleTime: AVAudioFramePosition(((now + remaining) * rate).rounded()), atRate: rate))433        } else { return }434        next.started = true435        transitioning = true436    }437438    private func ended(_ deck: Deck, _ gen: Int) {439        lock.lock()440        guard deck.generation == gen, deck.endedGeneration != gen else { lock.unlock(); return }441        deck.endedGeneration = gen442        let token = deck.token443        if transitioning, deck === active {444            // The prepared deck is already sounding (or about to): it becomes the current one.445            completeTransition()446            lock.unlock()447            return448        }449        guard deck === active else { lock.unlock(); return }450        // Nothing prepared, or it could not be scheduled in time: start it now if it is there, else report the end.451        let next = idle452        if next.decoder != nil, let nextToken = next.token, wantPlaying {453            resetDeck(deck, cancelSource: true)454            activeIndex = 1 - activeIndex455            next.mixer.outputVolume = 1456            ensureRunning(); next.player.play(); next.started = true457            lock.unlock()458            emit(.advanced(to: nextToken))459            return460        }461        deck.lastPosition = deck.decoder?.info.duration ?? deck.lastPosition462        wantPlaying = false463        lock.unlock()464        if let token { emit(.finished(token: token)) }465    }466467    /// With the lock held: the idle deck (already started) becomes the active one.468    private func completeTransition() {469        let old = active470        activeIndex = 1 - activeIndex471        transitioning = false; fade = nil472        resetDeck(old, cancelSource: true)473        active.mixer.outputVolume = 1474        if let token = active.token { let t = token; DispatchQueue.global().async { [weak self] in self?.emit(.advanced(to: t)) } }475    }476477    private func startTimer() {478        guard offlineFormat == nil else { return }479        lock.lock(); defer { lock.unlock() }480        guard timer == nil else { return }481        let t = DispatchSource.makeTimerSource(queue: timerQueue)482        t.schedule(deadline: .now() + 0.05, repeating: 0.05)483        t.setEventHandler { [weak self] in self?.tick() }484        timer = t; t.resume()485    }486487    /// Crossfade: starts the prepared deck when the current track has `crossfade` seconds left, then ramps both volumes.488    public func tick() {489        lock.lock(); defer { lock.unlock() }490        checkEnd()491        let deck = active, next = idle492        if let f = fade {493            let x = Float(min(1, max(0, Date().timeIntervalSince(f.start) / max(0.05, f.duration))))494            deck.mixer.outputVolume = cos(x * .pi / 2); next.mixer.outputVolume = sin(x * .pi / 2)     // equal power495            if x >= 1 { completeTransition() }496            return497        }498        guard wantPlaying, !transitioning, settings.crossfade > 0, !settings.directMode, let dec = deck.decoder, next.decoder != nil, next.token != nil, deck.started, !deck.stalled else { return }499        let remaining = dec.info.duration - currentPosition(deck)500        guard dec.info.duration > settings.crossfade * 2, remaining > 0.05, remaining <= settings.crossfade else { return }501        next.mixer.outputVolume = 0502        ensureRunning(); next.player.play(); next.started = true503        transitioning = true504        fade = (Date(), remaining)505    }506507    public func play() {508        lock.lock(); defer { lock.unlock() }509        wantPlaying = true510        let deck = active511        guard deck.decoder != nil else { return }512        ensureRunning()513        if !deck.stalled { deck.player.play(); deck.started = true }514        if transitioning { idle.player.play() }515    }516517    public func pause() {518        lock.lock(); defer { lock.unlock() }519        wantPlaying = false520        let deck = active521        deck.lastPosition = currentPosition(deck)522        deck.player.pause()523        if transitioning { idle.player.pause() }524    }525526    public func stop() {527        lock.lock(); defer { lock.unlock() }528        wantPlaying = false; transitioning = false; fade = nil529        for d in decks { resetDeck(d, cancelSource: true) }530    }531532    public func seek(to seconds: Double) {533        lock.lock()534        let deck = active535        guard let dec = deck.decoder else { deck.lastPosition = seconds; lock.unlock(); return }536        if transitioning { transitioning = false; fade = nil; resetDeck(idle, cancelSource: true); deck.mixer.outputVolume = 1 }537        let target = max(0, min(seconds, max(0, dec.info.duration - 0.05)))538        deck.generation += 1539        let gen = deck.generation540        deck.player.stop()541        deck.pending = 0; deck.scheduledFrames = 0; deck.eof = false; deck.stalled = false; deck.started = false542        deck.lastPosition = target543        let frame = Int64(target * dec.info.sampleRate)544        deck.baseFrame = frame545        let source = deck.source546        lock.unlock()547        source?.interruptReads()548        deck.queue.async { [self] in549            source?.resumeReads()550            lock.lock()551            guard deck.generation == gen else { lock.unlock(); return }552            lock.unlock()553            var replacement: AudioDecoder?554            do { if let source { replacement = try positioned(deck, source: source, existing: dec, frame: frame) } else { try dec.seek(toFrame: frame) } }555            catch { Log.info("audio", "seek failed: \(error)") }556            lock.lock()557            guard deck.generation == gen else { lock.unlock(); if let replacement, replacement !== dec { replacement.close() }; return }558            if let replacement, replacement !== dec { deck.decoder = replacement }559            if wantPlaying { ensureRunning(); deck.player.play(); deck.started = true }560            lock.unlock()561            pump(deck, gen)562        }563    }564565    /// The player's own timeline, or nil when it is not rendering (AVFoundation raises on an invalid node time).566    private static func playerTime(_ player: AVAudioPlayerNode) -> AVAudioTime? {567        guard let nt = player.lastRenderTime, nt.isSampleTimeValid || nt.isHostTimeValid else { return nil }568        guard let pt = player.playerTime(forNodeTime: nt), pt.isSampleTimeValid else { return nil }569        return pt570    }571572    private func currentPosition(_ deck: Deck) -> Double {573        guard let dec = deck.decoder else { return deck.lastPosition }574        guard deck.started, !deck.stalled, deck.player.isPlaying, let t = Self.playerTime(deck.player) else { return deck.lastPosition }575        let p = Double(deck.baseFrame + max(0, t.sampleTime)) / dec.info.sampleRate576        let clamped = min(max(0, p), dec.info.duration > 0 ? dec.info.duration : p)577        deck.lastPosition = clamped578        return clamped579    }580581    /// The end of a track is normally signalled by the player's "played back" callback; this notices it from the582    /// timeline as well, so the engine never depends on that callback alone.583    private func checkEnd() {584        let deck = active585        guard deck.eof, deck.pending == 0, deck.started, deck.endedGeneration != deck.generation, let t = Self.playerTime(deck.player), t.sampleTime >= deck.scheduledFrames else { return }586        ended(deck, deck.generation)587    }588589    public func status() -> EngineStatus {590        lock.lock(); defer { lock.unlock() }591        checkEnd()592        // In a gapless transition the new deck takes over as soon as it actually renders.593        if transitioning, fade == nil, let pt = Self.playerTime(idle.player), pt.sampleTime > 0, active.eof, active.pending == 0 {594            completeTransition()595        }596        let deck = active597        var s = EngineStatus()598        s.token = deck.token599        s.info = deck.decoder?.info600        s.duration = deck.decoder?.info.duration ?? 0601        s.position = currentPosition(deck)602        s.isPlaying = wantPlaying603        s.isBuffering = wantPlaying && (deck.loading || deck.stalled || (deck.pending == 0 && !deck.eof && deck.decoder != nil))604        s.bufferedFraction = deck.source?.bufferedFraction ?? 0605        s.outputSampleRate = outputFormat.sampleRate606        s.hasNextPrepared = idle.decoder != nil && !transitioning607        return s608    }609610    // MARK: Offline rendering (tests)611612    /// True when every loaded deck has decoded audio waiting (or reached its end): rendering now will not underrun.613    private let reconnectLock = NSLock()614    private var reconnectingCount = 0615    private func setReconnecting(_ delta: Int) { reconnectLock.withLock { reconnectingCount += delta } }616    /// True while a deck is being connected to a new format, which only completes when the engine renders.617    public var isReconnecting: Bool { reconnectLock.withLock { reconnectingCount > 0 } }618619    public func isFed() -> Bool {620        if isReconnecting { return false }621        // Let delivered completion handlers and the decoding they trigger finish first (bounded: a decoding queue may622        // be waiting for the network, or for a render).623        for _ in 0..<2 {624            for q in [callbackQueue] + decks.map(\.queue) {625                let done = DispatchSemaphore(value: 0)626                q.async { done.signal() }627                _ = done.wait(timeout: .now() + 0.05)628            }629        }630        if isReconnecting { return false }631        lock.lock(); defer { lock.unlock() }632        return decks.allSatisfy { $0.token == nil || (!$0.loading && ($0.eof || $0.pending >= 3)) }633    }634635    /// Pulls `frames` of mixed audio in manual rendering mode. Returns nil when the engine cannot render.636    public func render(frames: AVAudioFrameCount) -> AVAudioPCMBuffer? {637        guard offlineFormat != nil else { return nil }638        lock.lock(); ensureRunning(); lock.unlock()639        guard let buffer = AVAudioPCMBuffer(pcmFormat: engine.manualRenderingFormat, frameCapacity: frames) else { return nil }640        var done: AVAudioFrameCount = 0641        guard let out = AVAudioPCMBuffer(pcmFormat: engine.manualRenderingFormat, frameCapacity: frames) else { return nil }642        while done < frames {643            let n = min(engine.manualRenderingMaximumFrameCount, frames - done)644            guard let status = try? engine.renderOffline(n, to: buffer), status == .success else { break }645            for c in 0..<Int(out.format.channelCount) { memcpy(out.floatChannelData![c] + Int(done), buffer.floatChannelData![c], Int(buffer.frameLength) * MemoryLayout<Float>.size) }646            done += buffer.frameLength647            if buffer.frameLength == 0 { break }648        }649        out.frameLength = done650        return out651    }652}653
Files main
Menu

Theme