Cotton code
481 lines · 19.4 KB · SwiftRaw
// The music player's own audio engine (Cotton Music, definition section 9):// AVAudioEngine, because Apple's AVPlayer can neither join two songs with no// gap nor lift a quiet one.////   deck A ─┐//            ├─ bus ─ lift ─ speed ─ limiter ─ out//   deck B ─┘    └ the meters' tap//// A song plays on a deck (an `AVAudioPlayerNode`). GAPLESS: the song after it// is scheduled on the same deck right behind it, so the two join on the// sample; when its sound comes in another shape (another sample rate, mono)// it waits on the other deck and starts the moment the first one ends. A// CROSSFADE starts the song after on the other deck that many seconds before// the end and turns one down as the other comes up, equal in power.// LOUDNESS is the gain the core answers for each song (its ReplayGain by// song or album, never lifting its peak past full scale): a quiet song is// lifted by `lift` (an EQ's gain, which goes above unity), a loud one turned// down at its deck; the limiter catches what the tags got wrong. SPEED keeps// the pitch (`AVAudioUnitTimePitch`). The METERS read the bus: each// channel's loudness, ten times… twenty times a second, as a VU meter reads// it (nought VU at −18 dBFS).//// Where a song stands is read off its deck's own clock, so it is right at// any speed and across a gapless join. The engine says when a song has// finished and whether the next one is already playing (`onFinished`); what// plays next is the core's to say (`shell.player`), not the engine's.//// It renders offline too (`offline:`), so the tests play silent songs// through it with no speaker and no clock.import Accelerateimport AVFoundationimport CottonValuesimport Foundationimport os/// The player's knobs the engine honours, as the core answers them/// (`shell.player`'s settings); each song's gain is the core's own.struct PlayerKnobs: Equatable, Sendable {    var crossfade: Double = 0    var gapless = true    var speed: Double = 1    init() {}    init(_ settings: PlayerAnswer.Settings) {        crossfade = settings.crossfadeS        gapless = settings.gapless        speed = settings.speed    }}/// A VU meter's reading of a block of sound, each channel nought to one.enum SongMeter {    /// Nought VU, in dBFS of the channel's mean square.    static let zeroVU: Double = -18    /// The meter's scale, in VU: the face's painted marks (`HifiDeck`).    static let quietest: Double = -40    static let loudest: Double = 3    /// The level a channel at `rms` (full scale one) reads.    static func level(rms: Float) -> Double {        guard rms.isFinite, rms > 0 else { return 0 }        let vu = 20 * log10(Double(rms)) - zeroVU        return min(1, max(0, (vu - quietest) / (loudest - quietest)))    }    /// A buffer's two levels; a mono one reads the same on both.    static func level(_ buffer: AVAudioPCMBuffer) -> TrackLevel {        guard let channels = buffer.floatChannelData, buffer.frameLength > 0 else { return TrackLevel(left: 0, right: 0) }        let count = Int(buffer.format.channelCount)        func rms(_ channel: Int) -> Float {            var value: Float = 0            vDSP_rmsqv(channels[min(channel, count - 1)], buffer.stride, &value, vDSP_Length(buffer.frameLength))            return value        }        return TrackLevel(left: level(rms: rms(0)), right: level(rms: rms(1)))    }}@MainActorfinal class SongEngine {    /// A song as one deck holds it: its file and where it sits on the deck's clock.    private struct Segment {        let song: QueuedSong        let file: AVAudioFile        /// The frame of the file it starts from (a seek's).        let from: AVAudioFramePosition        /// The deck's sample time it starts at.        let begins: AVAudioFramePosition        let gain: Double        var frames: AVAudioFramePosition { file.length - from }        var rate: Double { file.processingFormat.sampleRate }        var duration: Double { Double(file.length) / rate }    }    private final class Deck {        let player = AVAudioPlayerNode()        let bus: AVAudioNodeBus        var format: AVAudioFormat?        var segments: [Segment] = []        /// Each schedule's generation: a stop's completions are not an end.        var generation = 0        /// Its share in a crossfade, nought to one.        var fade: Double = 1        init(bus: AVAudioNodeBus) { self.bus = bus }    }    /// The song after the one playing, as it was handed over.    private struct Following {        let song: QueuedSong        let file: AVAudioFile        let gain: Double    }    private static let log = Logger(subsystem: "com.cottondb.music", category: "engine")    let engine = AVAudioEngine()    private let decks = [Deck(bus: 0), Deck(bus: 1)]    private let bus = AVAudioMixerNode()    private let lift = AVAudioUnitEQ(numberOfBands: 0)    private let speedUnit = AVAudioUnitTimePitch()    private let limiter = AVAudioUnitEffect(audioComponentDescription: AudioComponentDescription(        componentType: kAudioUnitType_Effect, componentSubType: kAudioUnitSubType_PeakLimiter,        componentManufacturer: kAudioUnitManufacturer_Apple, componentFlags: 0, componentFlagsMask: 0))    private let levels = OSAllocatedUnfairLock(initialState: TrackLevel(left: 0, right: 0))    /// The deck the song playing is on.    private var live = 0    private var following: Following?    /// The crossfade under way: the deck going and the one coming.    private var fading: (out: Int, in: Int)?    private(set) var knobs = PlayerKnobs()    private let offline: Bool    /// Where the song stands while its deck's clock cannot say: paused (the    /// engine renders nothing), or sent somewhere and not yet rendered from    /// there. `rendered` is the deck's render time it was set at.    private var held: (position: Double, rendered: AVAudioFramePosition?)?    /// A song finished: its id, and whether the next one is already playing    /// (joined gapless, or crossfading in).    var onFinished: (_ song: String, _ nextStarted: Bool) -> Void = { _, _ in }    /// `offline`: rendered by the caller (`renderOffline`), never to a speaker.    init(offline format: AVAudioFormat? = nil) {        offline = format != nil        if let format {            try? engine.enableManualRenderingMode(.offline, format: format, maximumFrameCount: 512)        }        for deck in decks { engine.attach(deck.player) }        for node in [bus, lift, speedUnit, limiter] as [AVAudioNode] { engine.attach(node) }        let shape = engine.mainMixerNode.outputFormat(forBus: 0)        let stereo = AVAudioFormat(standardFormatWithSampleRate: shape.sampleRate > 0 ? shape.sampleRate : 44_100, channels: 2)        engine.connect(bus, to: lift, format: stereo)        engine.connect(lift, to: speedUnit, format: stereo)        engine.connect(speedUnit, to: limiter, format: stereo)        engine.connect(limiter, to: engine.mainMixerNode, format: stereo)        bus.installTap(onBus: 0, bufferSize: 2048, format: nil, block: Self.metering(levels))    }    // The audio thread calls the tap and the decks' ends: their closures are    // formed here, outside the main actor, so none is checked for it there.    private nonisolated static func metering(_ levels: OSAllocatedUnfairLock<TrackLevel>) -> AVAudioNodeTapBlock {        { buffer, _ in            let level = SongMeter.level(buffer)            levels.withLock { $0 = level }        }    }    private nonisolated static func ending(_ engine: SongEngine, deck index: Int, generation: Int, song id: String) -> AVAudioPlayerNodeCompletionHandler {        { [weak engine] _ in            DispatchQueue.main.async {                MainActor.assumeIsolated {                    guard let engine, engine.decks[index].generation == generation else { return }                    engine.ended(id, on: engine.decks[index])                }            }        }    }    // MARK: What it holds    private var segment: Segment? { decks[live].segments.first }    var current: QueuedSong? { segment?.song }    var playing: Bool { engine.isRunning && current != nil }    var duration: Double { segment?.duration ?? 0 }    /// Seconds into the song playing, off its deck's own clock.    var elapsed: Double {        guard let segment else { return 0 }        if let held {            if !engine.isRunning || rendered(decks[live]) == held.rendered { return held.position }            self.held = nil        }        return Self.position(of: segment, at: sampleTime(decks[live]))    }    /// The deck's last render, on its own node clock.    private func rendered(_ deck: Deck) -> AVAudioFramePosition? {        guard let node = deck.player.lastRenderTime, node.isSampleTimeValid else { return nil }        return node.sampleTime    }    /// The song stands at `position` until its deck renders again.    private func hold(at position: Double) {        held = (position, rendered(decks[live]))    }    /// The meters' reading; nought while nothing sounds.    var level: TrackLevel {        playing ? levels.withLock { $0 } : TrackLevel(left: 0, right: 0)    }    private static func position(of segment: Segment, at time: AVAudioFramePosition?) -> Double {        let into = max(0, (time ?? segment.begins) - segment.begins)        return min(segment.duration, Double(segment.from + into) / segment.rate)    }    private func sampleTime(_ deck: Deck) -> AVAudioFramePosition? {        guard let node = deck.player.lastRenderTime, node.isSampleTimeValid,              let time = deck.player.playerTime(forNodeTime: node) else { return nil }        return time.sampleTime    }    // MARK: The knobs    func set(_ knobs: PlayerKnobs) {        let before = self.knobs        self.knobs = knobs        speedUnit.rate = Float(knobs.speed)        // A gapless join already scheduled undoes itself when the knob is off,        // and a crossfade's start is read again at the next tick.        if before.gapless != knobs.gapless || before.crossfade != knobs.crossfade, let following {            unschedule()            prepare(following.song, file: following.file)        }    }    // MARK: Loading and playing    /// Opens a song's file: nil when it cannot be read here (not audio, or    /// locked: no lock is ever undone).    static func open(_ url: URL) -> AVAudioFile? {        do {            let file = try AVAudioFile(forReading: url)            return file.length > 0 ? file : nil        } catch {            log.error("could not open a song: \(error.localizedDescription, privacy: .public)")            return nil        }    }    /// `song` plays from `seconds`, in place of whatever played; paused    /// until `play()` unless it was playing.    func load(_ song: QueuedSong, file: AVAudioFile, at seconds: Double = 0) {        let wasPlaying = engine.isRunning        stopAll()        following = nil        live = 0        schedule(song, file: file, on: decks[live], from: seconds)        hold(at: segment.map { Double($0.from) / $0.rate } ?? 0)        balance()        if wasPlaying { play() }    }    /// The song after the one playing: joined behind it on the same deck when    /// gapless and its shape allows, else held for a crossfade or the end.    func prepare(_ song: QueuedSong, file: AVAudioFile) {        let gain = song.gain        // A song joined behind before the queue changed comes off first.        if decks[live].segments.count > 1, decks[live].segments.last?.song.id != song.id { unschedule() }        following = Following(song: song, file: file, gain: gain)        let deck = decks[live]        guard deck.segments.last?.song.id != song.id else { return }        guard knobs.crossfade == 0, knobs.gapless, fading == nil, let last = deck.segments.last,              deck.segments.count == 1, Self.same(deck.format, file.processingFormat) else { return }        let begins = last.begins + last.frames        append(Segment(song: song, file: file, from: 0, begins: begins, gain: gain), on: deck)    }    /// Nothing follows the song playing any more (the queue changed).    func forgetFollowing() {        unschedule()        following = nil    }    func play() {        guard current != nil else { return }        if !engine.isRunning {            engine.prepare()            do { try engine.start() } catch {                return Self.log.error("the engine would not start: \(error.localizedDescription, privacy: .public)")            }        }        for deck in decks where !deck.segments.isEmpty && !deck.player.isPlaying { deck.player.play() }    }    func pause() {        if engine.isRunning, current != nil { hold(at: elapsed) }        engine.pause()        levels.withLock { $0 = TrackLevel(left: 0, right: 0) }    }    func stop() {        stopAll()        following = nil        engine.stop()    }    /// The song playing from `seconds`; a crossfade under way ends at once.    func seek(to seconds: Double) {        guard let segment else { return }        let follows = following        let deck = decks[live]        let wasPlaying = engine.isRunning        stopAll()        live = decks.firstIndex { $0 === deck } ?? 0        schedule(segment.song, file: segment.file, on: deck, from: seconds)        hold(at: self.segment.map { Double($0.from) / $0.rate } ?? seconds)        if let follows { prepare(follows.song, file: follows.file) }        balance()        if wasPlaying { play() }    }    /// What the engine does between frames, from the player's clock (twenty    /// times a second): starts a crossfade when the end is near and turns it.    func tick() {        if let fading { return turn(fading) }        guard knobs.crossfade > 0, engine.isRunning, let segment, let following else { return }        let left = segment.duration - elapsed        guard left <= knobs.crossfade, left > 0 else { return }        let coming = 1 - live        let deck = decks[coming]        stopDeck(deck)        schedule(following.song, file: following.file, on: deck, from: 0, gain: following.gain)        deck.fade = 0        decks[live].fade = 1        fading = (out: live, in: coming)        self.following = nil        let went = segment.song.id        live = coming        held = nil        balance()        if engine.isRunning { deck.player.play() }        onFinished(went, true)    }    // MARK: Inside    private func schedule(_ song: QueuedSong, file: AVAudioFile, on deck: Deck, from seconds: Double, gain: Double? = nil) {        let format = file.processingFormat        if !Self.same(deck.format, format) {            engine.disconnectNodeOutput(deck.player)            engine.connect(deck.player, to: bus, fromBus: 0, toBus: deck.bus, format: format)            deck.format = format        }        let from = AVAudioFramePosition(max(0, min(seconds, Double(file.length) / format.sampleRate - 0.05)) * format.sampleRate)        deck.fade = 1        append(Segment(song: song, file: file, from: max(0, from), begins: 0, gain: gain ?? song.gain), on: deck)    }    private func append(_ segment: Segment, on deck: Deck) {        deck.segments.append(segment)        let generation = deck.generation        let id = segment.song.id        let index = Int(deck.bus)        deck.player.scheduleSegment(segment.file, startingFrame: segment.from, frameCount: AVAudioFrameCount(segment.frames),                                    at: nil, completionCallbackType: offline ? .dataRendered : .dataPlayedBack,                                    completionHandler: Self.ending(self, deck: index, generation: generation, song: id))    }    private func ended(_ id: String, on deck: Deck) {        guard let index = deck.segments.firstIndex(where: { $0.song.id == id }) else { return }        deck.segments.remove(at: index)        let wasLive = decks[live] === deck        if let fading, decks[fading.out] === deck {            // The song crossfading out has gone quiet: the fade is done.            finishFade(fading)            return        }        guard wasLive else { return }        if !deck.segments.isEmpty {            // Joined gapless: the next one is already playing.            following = nil            balance()            return onFinished(id, true)        }        if let following, crossDeckEnd(following) {            return onFinished(id, true)        }        onFinished(id, false)    }    /// A song in another shape starts on the other deck as the first ends.    private func crossDeckEnd(_ following: Following) -> Bool {        let coming = 1 - live        let deck = decks[coming]        stopDeck(deck)        schedule(following.song, file: following.file, on: deck, from: 0, gain: following.gain)        self.following = nil        live = coming        held = nil        balance()        if engine.isRunning { deck.player.play() }        return true    }    private func turn(_ fading: (out: Int, in: Int)) {        let length = max(0.1, knobs.crossfade)        let into = elapsed / length        let share = min(1, max(0, into))        decks[fading.out].fade = cos(share * .pi / 2)        decks[fading.in].fade = sin(share * .pi / 2)        balance()        if share >= 1 { finishFade(fading) }    }    private func finishFade(_ fading: (out: Int, in: Int)) {        stopDeck(decks[fading.out])        decks[fading.in].fade = 1        self.fading = nil        balance()    }    /// Each deck's volume and the lift after them: the loudest gain wanted is    /// lifted, each deck turned down from it to its own.    private func balance() {        let gains = decks.compactMap { $0.segments.first?.gain }        let top = max(0, gains.max() ?? 0)        lift.globalGain = Float(min(24, top))        for deck in decks {            let gain = deck.segments.first?.gain ?? 0            deck.player.volume = Float(pow(10, (gain - top) / 20) * deck.fade)        }    }    /// The gapless join scheduled behind the song playing comes off its deck.    private func unschedule() {        let deck = decks[live]        guard deck.segments.count > 1, let first = deck.segments.first else { return }        let at = elapsed        let wasPlaying = engine.isRunning        stopDeck(deck)        schedule(first.song, file: first.file, on: deck, from: at, gain: first.gain)        hold(at: at)        if wasPlaying { deck.player.play() }    }    private func stopDeck(_ deck: Deck) {        deck.generation += 1        deck.player.stop()        deck.segments = []        deck.fade = 1    }    private func stopAll() {        fading = nil        held = nil        for deck in decks { stopDeck(deck) }    }    private static func same(_ one: AVAudioFormat?, _ other: AVAudioFormat) -> Bool {        guard let one else { return false }        return one.sampleRate == other.sampleRate && one.channelCount == other.channelCount    }    // MARK: Offline    /// Renders `seconds` of what plays, offline; the tests' clock.    func render(_ seconds: Double) throws {        guard offline else { return }        let format = engine.manualRenderingFormat        guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: engine.manualRenderingMaximumFrameCount) else { return }        var left = AVAudioFramePosition(seconds * format.sampleRate)        while left > 0 {            let frames = AVAudioFrameCount(min(AVAudioFramePosition(buffer.frameCapacity), left))            let status = try engine.renderOffline(frames, to: buffer)            guard status == .success else { break }            left -= AVAudioFramePosition(frames)        }    }}