Mulberry/App/Audio/UniversalEngine.swift

302 lines
11 KiB
Swift

import AVFoundation
/// One AVAudioPlayerNode fed from a chain of sources (gapless: the next song's audio is queued right behind).
final class Deck {
let node = AVAudioPlayerNode()
private let q: DispatchQueue
private var gen = 0
private var source: AudioSource?
private var inFlight = 0
private let chunk: AVAudioFrameCount = 8192
private let maxInFlight = 6
/// Called on the deck queue when the current source ends; returns the next song's source (gapless) or nil.
var onSourceEnd: ((Int) -> (AudioSource, Int)?)?
/// Where each scheduled item starts: (queue index, node sample, start frame in song).
private(set) var marks: [(index: Int, at: AVAudioFramePosition, offset: AVAudioFramePosition)] = []
private var scheduled: AVAudioFramePosition = 0
private var drained = false
var onDrained: (() -> Void)?
init(name: String) { q = DispatchQueue(label: "mulberry.deck." + name, qos: .userInitiated) }
func load(_ src: AudioSource, index: Int, from frame: AVAudioFramePosition) {
q.sync {
gen += 1
node.stop()
node.reset()
source = src
src.seek(to: frame)
inFlight = 0
scheduled = 0
drained = false
marks = [(index, 0, frame)]
fill(gen)
}
}
func stop() {
q.sync {
gen += 1
node.stop()
source = nil
marks = []
}
}
var loaded: Bool { q.sync { !marks.isEmpty } }
private func fill(_ g: Int) {
while g == gen && inFlight < maxInFlight, let src = source {
guard let buf = AVAudioPCMBuffer(pcmFormat: Decoder.format, frameCapacity: chunk) else { return }
if !src.read(into: buf) {
if let (next, idx) = onSourceEnd?(marks.last?.index ?? -1) {
source = next
marks.append((idx, scheduled, 0))
continue
}
source = nil
if inFlight == 0 { finish(g) }
return
}
inFlight += 1
scheduled += AVAudioFramePosition(buf.frameLength)
node.scheduleBuffer(buf, completionCallbackType: .dataPlayedBack) { [weak self] _ in
guard let self else { return }
self.q.async {
guard g == self.gen else { return }
self.inFlight -= 1
if self.source != nil { self.fill(g) } else if self.inFlight == 0 { self.finish(g) }
}
}
}
}
private func finish(_ g: Int) {
guard !drained, g == gen else { return }
drained = true
DispatchQueue.main.async { [weak self] in self?.onDrained?() }
}
private var playedSamples: AVAudioFramePosition {
guard let nt = node.lastRenderTime, nt.isSampleTimeValid,
let pt = node.playerTime(forNodeTime: nt) else { return 0 }
return max(0, pt.sampleTime)
}
/// (queue index, seconds into that song) for what is audible now.
func now() -> (Int, Double)? {
let s = playedSamples
var cur: (Int, Double)?
q.sync {
for m in marks where m.at <= s { cur = (m.index, Double(s - m.at + m.offset) / Decoder.rate) }
}
return cur
}
}
/// "Universal" / "Sound FX" engine: AVAudioEngine fed by Apple decoders or FFmpeg, with a 10-band EQ.
@MainActor
final class UniversalEngine: PlaybackEngine {
var onAdvance: ((Int) -> Void)?
var onEnded: (() -> Void)?
var onFailed: ((String) -> Void)?
static let eqFreqs: [Float] = [31, 62, 125, 250, 500, 1000, 2000, 4000, 8000, 16000]
private let engine = AVAudioEngine()
private let eq = AVAudioUnitEQ(numberOfBands: 10)
private let deckMixer = AVAudioMixerNode()
private var decks = [Deck(name: "a"), Deck(name: "b")]
private var active = 0
private var lastIndex = -1
private var currentSong: Song?
private var basePos: Double = 0
private var volume: Float = 1
private var playing = false
var eqAllowed = false { didSet { applyEQ() } }
/// What comes next gaplessly; written on main, read on deck queues.
final class Plan: @unchecked Sendable {
private let lock = NSLock()
private var after = -1
private var next: (Song, Int)?
func set(after: Int, _ n: (Song, Int)?) { lock.lock(); self.after = after; next = n; lock.unlock() }
func get(after: Int) -> (Song, Int)? { lock.lock(); defer { lock.unlock() }; return after == self.after ? next : nil }
}
private let plan = Plan()
init(spectrum: Spectrum) {
for (i, b) in eq.bands.enumerated() {
b.filterType = .parametric
b.frequency = UniversalEngine.eqFreqs[i]
b.bandwidth = 1
b.bypass = false
}
// The EQ has a single input, so both decks meet in a mixer first (a second connect to the EQ would
// silently disconnect the first deck: "player started when in a disconnected state").
engine.attach(deckMixer)
engine.attach(eq)
for (i, d) in decks.enumerated() {
engine.attach(d.node)
engine.connect(d.node, to: deckMixer, fromBus: 0, toBus: i, format: Decoder.format)
}
engine.connect(deckMixer, to: eq, format: Decoder.format)
engine.connect(eq, to: engine.mainMixerNode, format: Decoder.format)
engine.mainMixerNode.installTap(onBus: 0, bufferSize: 1024, format: nil) { buf, _ in spectrum.feed(buf) }
engine.prepare()
for (i, d) in decks.enumerated() {
d.onSourceEnd = { [plan] last in
guard let (song, n) = plan.get(after: last), let src = Decoder.open(song) else { return nil }
return (src, n)
}
d.onDrained = { [weak self] in MainActor.assumeIsolated { self?.drained(i) } }
}
NotificationCenter.default.addObserver(forName: .AVAudioEngineConfigurationChange, object: engine, queue: .main) { [weak self] _ in
MainActor.assumeIsolated {
guard let self, self.playing else { return }
Log.i("universal: configuration change, restarting")
if self.start() { _ = self.safePlay(self.decks[self.active].node) }
}
}
applyEQ()
}
func applyEQ() {
let p = Prefs.shared
eq.bypass = !(eqAllowed && p.eqOn)
for (i, b) in eq.bands.enumerated() where i < p.eqBands.count { b.gain = Float(p.eqBands[i]) }
}
/// Starts the engine; false (and logged) if iOS refuses.
@discardableResult
private func start() -> Bool {
if engine.isRunning { return true }
Log.i("universal: starting engine, output \(engine.outputNode.outputFormat(forBus: 0))")
do {
try engine.start()
return true
} catch {
Log.e("universal: engine start failed: \(error.localizedDescription) — retrying")
engine.stop()
engine.reset()
engine.prepare()
do { try engine.start(); return true } catch {
Log.e("universal: engine start failed again: \(error.localizedDescription)")
onFailed?("Couldn't start audio: \(error.localizedDescription)")
return false
}
}
}
private func drained(_ d: Int) {
guard d == active, playing else { return }
onEnded?()
}
func load(_ song: Song, index: Int, at: Double, volume: Float) -> Bool {
stop()
guard let src = Decoder.open(song) else { Log.e("universal: can't open \(song.fileName)"); return false }
active = 0
lastIndex = index
currentSong = song
basePos = at
self.volume = volume
decks[0].load(src, index: index, from: AVAudioFramePosition(at * Decoder.rate))
decks[0].node.volume = volume
Log.i("universal: load #\(index) \(song.fileName) at \(Int(at))s")
return true
}
func setNext(_ song: Song?, index: Int, volume: Float) {
plan.set(after: lastIndex, song.map { ($0, index) })
}
/// node.play() throws an NSException when the engine isn't really running; catch, restart once, report.
private func safePlay(_ node: AVAudioPlayerNode) -> Bool {
if let err = mulberry_try({ node.play() }) {
Log.e("universal: play threw \(err) (running=\(engine.isRunning)) — restarting engine")
engine.stop()
guard start() else { return false }
if let err2 = mulberry_try({ node.play() }) {
Log.e("universal: play threw again: \(err2)")
onFailed?("Couldn't start playback (\(err2))")
return false
}
}
return true
}
func play(fade: Bool, volume: Float) {
self.volume = volume
guard start() else { return }
let node = decks[active].node
node.volume = fade ? 0 : volume
guard safePlay(node) else { return }
playing = true
if fade { rampVolume(from: 0, to: volume, ms: 220) { node.volume = $0 } }
}
func pause(fade: Bool) {
basePos = position
playing = false
let node = decks[active].node
decks[1 - active].stop()
if fade {
rampVolume(from: node.volume, to: 0, ms: 220, set: { node.volume = $0 }) { [weak self] in
guard let self, !self.playing else { return }
node.pause()
}
} else {
node.pause()
}
}
func stop() {
playing = false
decks.forEach { $0.stop() }
}
func seek(_ t: Double) {
guard let song = currentSong, let src = Decoder.open(song) else { return }
basePos = t
decks[1 - active].stop()
decks[active].load(src, index: lastIndex, from: AVAudioFramePosition(t * Decoder.rate))
decks[active].node.volume = volume
if playing { _ = safePlay(decks[active].node) }
}
var position: Double {
guard playing, let (_, t) = decks[active].now() else { return basePos }
return t
}
/// Queue index audible right now (differs from the loaded one after a gapless hand-over).
var audibleIndex: Int? { decks[active].now()?.0 }
func crossfade(to song: Song, index: Int, seconds: Double, volume: Float) -> Bool {
guard let src = Decoder.open(song), start() else { return false }
let old = decks[active]
active = 1 - active
lastIndex = index
currentSong = song
let nd = decks[active]
nd.load(src, index: index, from: 0)
nd.node.volume = 0
guard safePlay(nd.node) else { active = 1 - active; return false }
self.volume = volume
let ms = seconds * 1000
rampVolume(from: old.node.volume, to: 0, ms: ms, set: { old.node.volume = $0 }) { old.stop() }
rampVolume(from: 0, to: volume, ms: ms) { nd.node.volume = $0 }
return true
}
func setVolume(_ v: Float) { volume = v; decks[active].node.volume = v }
/// Called by the Player's timer to report gapless hand-overs (decks only expose them by position).
func pollAdvance() {
guard playing, let i = audibleIndex, i != lastIndex else { return }
if let (song, n) = plan.get(after: lastIndex), n == i { currentSong = song }
lastIndex = i
onAdvance?(i)
}
}