// 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.importAccelerateimport AVFoundationimportCottonValuesimportFoundationimport 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.structPlayerKnobs: Equatable, Sendable {var crossfade: Double = 0var gapless = truevar speed: Double = 1init() {}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.enumSongMeter {/// Nought VU, in dBFS of the channel's mean square.staticlet zeroVU: Double = -18/// The meter's scale, in VU: the face's painted marks (`HifiDeck`).staticlet quietest: Double = -40staticlet loudest: Double = 3/// The level a channel at `rms` (full scale one) reads.staticfunc level(rms: Float) -> Double {guard rms.isFinite, rms > 0else { return0 }let vu = 20 * log10(Double(rms)) - zeroVUreturn min(1, max(0, (vu - quietest) / (loudest - quietest))) }/// A buffer's two levels; a mono one reads the same on both.staticfunc level(_ buffer: AVAudioPCMBuffer) -> TrackLevel {guardlet channels = buffer.floatChannelData, buffer.frameLength > 0else { returnTrackLevel(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 }returnTrackLevel(left: level(rms: rms(0)), right: level(rms: rms(1))) }}@MainActorfinalclassSongEngine {/// A song as one deck holds it: its file and where it sits on the deck's clock.privatestructSegment {let song: QueuedSonglet 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: AVAudioFramePositionlet gain: Doublevar frames: AVAudioFramePosition { file.length - from }var rate: Double { file.processingFormat.sampleRate }var duration: Double { Double(file.length) / rate } }privatefinalclassDeck {let player = AVAudioPlayerNode()let bus: AVAudioNodeBusvar 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 = 1init(bus: AVAudioNodeBus) { self.bus = bus } }/// The song after the one playing, as it was handed over.privatestructFollowing {let song: QueuedSonglet file: AVAudioFilelet gain: Double }privatestaticlet log = Logger(subsystem: "com.cottondb.music", category: "engine")let engine = AVAudioEngine()privatelet decks = [Deck(bus: 0), Deck(bus: 1)]privatelet bus = AVAudioMixerNode()privatelet lift = AVAudioUnitEQ(numberOfBands: 0)privatelet speedUnit = AVAudioUnitTimePitch()privatelet limiter = AVAudioUnitEffect(audioComponentDescription: AudioComponentDescription( componentType: kAudioUnitType_Effect, componentSubType: kAudioUnitSubType_PeakLimiter, componentManufacturer: kAudioUnitManufacturer_Apple, componentFlags: 0, componentFlagsMask: 0))privatelet levels = OSAllocatedUnfairLock(initialState: TrackLevel(left: 0, right: 0))/// The deck the song playing is on.privatevar live = 0privatevar following: Following?/// The crossfade under way: the deck going and the one coming.privatevar fading: (out: Int, in: Int)?private(set) var knobs = PlayerKnobs()privatelet 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.privatevar 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 != niliflet 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 staticfunc metering(_ levels: OSAllocatedUnfairLock<TrackLevel>) -> AVAudioNodeTapBlock { { buffer, _ inlet level = SongMeter.level(buffer) levels.withLock { $0 = level } } }private nonisolated staticfunc ending(_ engine: SongEngine, deck index: Int, generation: Int, song id: String) -> AVAudioPlayerNodeCompletionHandler { { [weak engine] _ inDispatchQueue.main.async {MainActor.assumeIsolated {guardlet engine, engine.decks[index].generation == generation else { return } engine.ended(id, on: engine.decks[index]) } } } }// MARK: What it holdsprivatevar 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 {guardlet segment else { return0 }iflet held {if !engine.isRunning || rendered(decks[live]) == held.rendered { return held.position }self.held = nil }returnSelf.position(of: segment, at: sampleTime(decks[live])) }/// The deck's last render, on its own node clock.privatefunc rendered(_ deck: Deck) -> AVAudioFramePosition? {guardlet node = deck.player.lastRenderTime, node.isSampleTimeValid else { returnnil }return node.sampleTime }/// The song stands at `position` until its deck renders again.privatefunc 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) }privatestaticfunc 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) }privatefunc sampleTime(_ deck: Deck) -> AVAudioFramePosition? {guardlet node = deck.player.lastRenderTime, node.isSampleTimeValid,let time = deck.player.playerTime(forNodeTime: node) else { returnnil }return time.sampleTime }// MARK: The knobsfunc set(_ knobs: PlayerKnobs) {let before = self.knobsself.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).staticfuncopen(_ 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)")returnnil } }/// `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 != nilelse { return }if !engine.isRunning { engine.prepare()do { try engine.start() } catch {returnSelf.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) {guardlet segment else { return }let follows = followinglet 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)iflet 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() {iflet fading { return turn(fading) }guard knobs.crossfade > 0, engine.isRunning, let segment, let following else { return }let left = segment.duration - elapsedguard left <= knobs.crossfade, left > 0else { return }let coming = 1 - livelet 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 = nillet went = segment.song.id live = coming held = nil balance()if engine.isRunning { deck.player.play() } onFinished(went, true) }// MARK: Insideprivatefunc schedule(_ song: QueuedSong, file: AVAudioFile, on deck: Deck, from seconds: Double, gain: Double? = nil) {let format = file.processingFormatif !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) }privatefunc append(_ segment: Segment, on deck: Deck) { deck.segments.append(segment)let generation = deck.generationlet id = segment.song.idlet 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)) }privatefunc ended(_ id: String, on deck: Deck) {guardlet index = deck.segments.firstIndex(where: { $0.song.id == id }) else { return } deck.segments.remove(at: index)let wasLive = decks[live] === deckiflet 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) }iflet following, crossDeckEnd(following) {return onFinished(id, true) } onFinished(id, false) }/// A song in another shape starts on the other deck as the first ends.privatefunc crossDeckEnd(_ following: Following) -> Bool {let coming = 1 - livelet 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() }returntrue }privatefunc turn(_ fading: (out: Int, in: Int)) {let length = max(0.1, knobs.crossfade)let into = elapsed / lengthlet 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) } }privatefunc finishFade(_ fading: (out: Int, in: Int)) { stopDeck(decks[fading.out]) decks[fading.in].fade = 1self.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.privatefunc 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.privatefunc unschedule() {let deck = decks[live]guard deck.segments.count > 1, let first = deck.segments.first else { return }let at = elapsedlet 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() } }privatefunc stopDeck(_ deck: Deck) { deck.generation += 1 deck.player.stop() deck.segments = [] deck.fade = 1 }privatefunc stopAll() { fading = nil held = nilfor deck in decks { stopDeck(deck) } }privatestaticfunc same(_ one: AVAudioFormat?, _ other: AVAudioFormat) -> Bool {guardlet one else { returnfalse }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.manualRenderingFormatguardlet 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) } }}