Standard playback engine (AVQueuePlayer) by default, Universal/Sound FX for other formats; no crash when the audio engine can't start; watch music subfolders; file log
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
parent
66f4e7e3ea
commit
a65db499f9
10 changed files with 807 additions and 301 deletions
60
App/Audio/Engine.swift
Normal file
60
App/Audio/Engine.swift
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
import AVFoundation
|
||||
|
||||
/// A playback back end. The Player owns the queue and decides which engine plays each song.
|
||||
/// Callbacks are delivered on the main thread.
|
||||
@MainActor
|
||||
protocol PlaybackEngine: AnyObject {
|
||||
/// Gapless hand-over: the engine moved on to the preloaded song at this queue index.
|
||||
var onAdvance: ((Int) -> Void)? { get set }
|
||||
/// The current song finished and nothing was preloaded.
|
||||
var onEnded: (() -> Void)? { get set }
|
||||
/// Playback of the current song failed.
|
||||
var onFailed: ((String) -> Void)? { get set }
|
||||
|
||||
/// Loads a song; returns false if this engine can't open it.
|
||||
func load(_ song: Song, index: Int, at: Double, volume: Float) -> Bool
|
||||
/// Song to continue with seamlessly when the current one ends (nil clears it).
|
||||
func setNext(_ song: Song?, index: Int, volume: Float)
|
||||
func play(fade: Bool, volume: Float)
|
||||
func pause(fade: Bool)
|
||||
func stop()
|
||||
func seek(_ t: Double)
|
||||
/// Seconds into the current song.
|
||||
var position: Double { get }
|
||||
/// Starts `song` underneath the current one and fades between them.
|
||||
func crossfade(to song: Song, index: Int, seconds: Double, volume: Float) -> Bool
|
||||
func setVolume(_ v: Float)
|
||||
}
|
||||
|
||||
enum EngineKind: String, CaseIterable {
|
||||
case standard, universal, fx
|
||||
|
||||
var title: String {
|
||||
switch self {
|
||||
case .standard: return "Standard"
|
||||
case .universal: return "Universal"
|
||||
case .fx: return "Sound FX"
|
||||
}
|
||||
}
|
||||
|
||||
var detail: String {
|
||||
switch self {
|
||||
case .standard: return "Apple's player — best for AirPlay, Bluetooth and battery. Other formats fall back to Universal."
|
||||
case .universal: return "Mulberry's decoder for every format (Ogg, Opus, WMA, APE, DSD…)"
|
||||
case .fx: return "Universal plus the equalizer"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Small helper for volume fades on the main run loop.
|
||||
@MainActor
|
||||
func rampVolume(from start: Float, to target: Float, ms: Double, set: @escaping (Float) -> Void, done: (() -> Void)? = nil) {
|
||||
let steps = max(1, Int(ms / 20))
|
||||
var k = 0
|
||||
Timer.scheduledTimer(withTimeInterval: 0.02, repeats: true) { t in
|
||||
k += 1
|
||||
let f = Float(k) / Float(steps)
|
||||
set(start + (target - start) * min(1, f * f * (3 - 2 * f)))
|
||||
if k >= steps { t.invalidate(); done?() }
|
||||
}
|
||||
}
|
||||
|
|
@ -3,101 +3,8 @@ import MediaPlayer
|
|||
import SwiftUI
|
||||
import Combine
|
||||
|
||||
/// 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)?)?
|
||||
/// Sample offsets (in node time) 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 = []
|
||||
}
|
||||
}
|
||||
|
||||
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?() }
|
||||
}
|
||||
|
||||
/// Current played sample position in node time.
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
/// Queue, transport and everything around playback (Android MusicService). The sound itself comes from a
|
||||
/// PlaybackEngine: Standard (AVQueuePlayer) by default, Universal/Sound FX (AVAudioEngine + FFmpeg) for the rest.
|
||||
@MainActor
|
||||
final class Player: ObservableObject {
|
||||
static let shared = Player()
|
||||
|
|
@ -106,74 +13,93 @@ final class Player: ObservableObject {
|
|||
@Published private(set) var index = -1
|
||||
@Published private(set) var isPlaying = false
|
||||
@Published private(set) var duration: Double = 0
|
||||
@Published var stopAfterCurrent = false
|
||||
@Published var stopAfterCurrent = false { didSet { planNext() } }
|
||||
@Published private(set) var sleepAt: Date?
|
||||
@Published private(set) var sleepAtTrackEnd = false
|
||||
@Published private(set) var art: UIImage?
|
||||
@Published private(set) var seed: UInt32?
|
||||
@Published private(set) var lyrics: Lyrics.Result?
|
||||
@Published private(set) var error: String?
|
||||
/// The engine playing the current song, for display in Now Playing.
|
||||
@Published private(set) var engineName = ""
|
||||
|
||||
let spectrum = Spectrum()
|
||||
private let prefs = Prefs.shared
|
||||
private let engine = AVAudioEngine()
|
||||
private let eq = AVAudioUnitEQ(numberOfBands: 10)
|
||||
private var decks = [Deck(name: "a"), Deck(name: "b")]
|
||||
private var active = 0
|
||||
private lazy var standard = StandardEngine(spectrum: spectrum)
|
||||
private lazy var universal = UniversalEngine(spectrum: spectrum)
|
||||
private var eng: PlaybackEngine?
|
||||
private var loaded = false // the engine holds the current song
|
||||
private var plannedNext: Int? // what the engine has preloaded for gapless
|
||||
private var order: [Int] = [] // play order when shuffled (indices into queue)
|
||||
private var basePos: Double = 0 // position when paused / for streams
|
||||
private var stream: AVPlayer?
|
||||
private var basePos: Double = 0 // position while nothing is loaded
|
||||
private var timer: Timer?
|
||||
private var crossfading = false
|
||||
private var listenStart = Date()
|
||||
private var listened: Double = 0
|
||||
private var lastTick = Date()
|
||||
private var resumeAfterInterruption = false
|
||||
|
||||
static let eqFreqs: [Float] = [31, 62, 125, 250, 500, 1000, 2000, 4000, 8000, 16000]
|
||||
static var eqFreqs: [Float] { UniversalEngine.eqFreqs }
|
||||
|
||||
var current: Song? { queue.indices.contains(index) ? queue[index] : nil }
|
||||
|
||||
private init() {
|
||||
for (i, b) in eq.bands.enumerated() {
|
||||
b.filterType = .parametric
|
||||
b.frequency = Player.eqFreqs[i]
|
||||
b.bandwidth = 1
|
||||
b.bypass = false
|
||||
}
|
||||
engine.attach(eq)
|
||||
for d in decks {
|
||||
engine.attach(d.node)
|
||||
engine.connect(d.node, to: eq, format: Decoder.format)
|
||||
}
|
||||
engine.connect(eq, to: engine.mainMixerNode, format: Decoder.format)
|
||||
applyEQ()
|
||||
engine.mainMixerNode.installTap(onBus: 0, bufferSize: 1024, format: nil) { [spectrum] buf, _ in
|
||||
spectrum.feed(buf)
|
||||
}
|
||||
for (i, d) in decks.enumerated() {
|
||||
d.onSourceEnd = { [plan] last in Player.gaplessNext(plan, after: last) }
|
||||
d.onDrained = { [weak self] in self?.deckDrained(i) }
|
||||
}
|
||||
setupSession()
|
||||
setupRemote()
|
||||
restore()
|
||||
}
|
||||
|
||||
// MARK: Engines
|
||||
|
||||
private func engine(for s: Song) -> PlaybackEngine {
|
||||
let kind = EngineKind(rawValue: prefs.engine) ?? .standard
|
||||
if s.isStream || (kind == .standard && StandardEngine.canPlay(s)) { return standard }
|
||||
universal.eqAllowed = kind == .fx
|
||||
return universal
|
||||
}
|
||||
|
||||
private func wire(_ e: PlaybackEngine) {
|
||||
e.onAdvance = { [weak self] i in self?.advanced(to: i) }
|
||||
e.onEnded = { [weak self] in self?.ended() }
|
||||
e.onFailed = { [weak self] msg in self?.failed(msg) }
|
||||
}
|
||||
|
||||
private func activateSession() {
|
||||
do {
|
||||
try AVAudioSession.sharedInstance().setActive(true)
|
||||
} catch {
|
||||
Log.e("audio session activate failed: \(error.localizedDescription)")
|
||||
}
|
||||
}
|
||||
|
||||
func applyEQ() { universal.applyEQ() }
|
||||
|
||||
/// Called when the engine setting changes: reload the current song on the right engine.
|
||||
func engineChanged() {
|
||||
guard let s = current, loaded else { return }
|
||||
let target = engine(for: s)
|
||||
guard target !== eng else { applyEQ(); return }
|
||||
let pos = position, wasPlaying = isPlaying
|
||||
load(index, play: wasPlaying, at: pos)
|
||||
}
|
||||
|
||||
// MARK: Session & remote
|
||||
|
||||
private func setupSession() {
|
||||
let s = AVAudioSession.sharedInstance()
|
||||
try? s.setCategory(.playback, mode: .default, policy: .longFormAudio)
|
||||
do { try s.setCategory(.playback, mode: .default, policy: .longFormAudio) } catch {
|
||||
Log.e("setCategory failed: \(error.localizedDescription)")
|
||||
try? s.setCategory(.playback)
|
||||
}
|
||||
let nc = NotificationCenter.default
|
||||
nc.addObserver(forName: AVAudioSession.interruptionNotification, object: nil, queue: .main) { [weak self] n in
|
||||
guard let self, let raw = n.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt,
|
||||
let type = AVAudioSession.InterruptionType(rawValue: raw) else { return }
|
||||
let opts = (n.userInfo?[AVAudioSessionInterruptionOptionKey] as? UInt).map(AVAudioSession.InterruptionOptions.init)
|
||||
MainActor.assumeIsolated {
|
||||
if type == .began {
|
||||
if self.isPlaying { self.pause(fade: false); self.resumeAfterInterruption = true }
|
||||
} else if let o = n.userInfo?[AVAudioSessionInterruptionOptionKey] as? UInt,
|
||||
AVAudioSession.InterruptionOptions(rawValue: o).contains(.shouldResume),
|
||||
self.resumeAfterInterruption {
|
||||
} else if opts?.contains(.shouldResume) == true, self.resumeAfterInterruption {
|
||||
self.resumeAfterInterruption = false
|
||||
self.play()
|
||||
}
|
||||
|
|
@ -186,17 +112,16 @@ final class Player: ObservableObject {
|
|||
if self.prefs.pauseOnDetach && self.isPlaying { self.pause(fade: false) }
|
||||
}
|
||||
}
|
||||
nc.addObserver(forName: .AVAudioEngineConfigurationChange, object: engine, queue: .main) { [weak self] _ in
|
||||
nc.addObserver(forName: AVAudioSession.mediaServicesWereResetNotification, object: nil, queue: .main) { [weak self] _ in
|
||||
MainActor.assumeIsolated {
|
||||
guard let self, self.isPlaying else { return }
|
||||
try? self.engine.start()
|
||||
self.decks[self.active].node.play()
|
||||
guard let self else { return }
|
||||
Log.e("media services were reset")
|
||||
let pos = self.position, was = self.isPlaying
|
||||
if self.current != nil { self.load(self.index, play: was, at: pos) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var resumeAfterInterruption = false
|
||||
|
||||
private func setupRemote() {
|
||||
let c = MPRemoteCommandCenter.shared()
|
||||
c.playCommand.addTarget { [weak self] _ in self?.play(); return .success }
|
||||
|
|
@ -257,21 +182,21 @@ final class Player: ObservableObject {
|
|||
}
|
||||
|
||||
func playNext(_ list: [Song]) {
|
||||
defer { updatePlan() }
|
||||
guard current != nil else { playList(list); return }
|
||||
queue.insert(contentsOf: list, at: index + 1)
|
||||
let added = (index + 1)..<(index + 1 + list.count)
|
||||
order = order.map { $0 > index ? $0 + list.count : $0 }
|
||||
if let p = order.firstIndex(of: index) { order.insert(contentsOf: added, at: p + 1) }
|
||||
planNext(force: true)
|
||||
saveSoon()
|
||||
}
|
||||
|
||||
func enqueue(_ list: [Song]) {
|
||||
defer { updatePlan() }
|
||||
guard current != nil else { playList(list); return }
|
||||
let start = queue.count
|
||||
queue.append(contentsOf: list)
|
||||
order.append(contentsOf: start..<queue.count)
|
||||
planNext(force: true)
|
||||
saveSoon()
|
||||
}
|
||||
|
||||
|
|
@ -283,17 +208,20 @@ final class Player: ObservableObject {
|
|||
if i < index { index -= 1 }
|
||||
if wasCurrent {
|
||||
if queue.isEmpty { stop(); index = -1 } else { load(min(index, queue.count - 1), play: isPlaying) }
|
||||
} else {
|
||||
planNext(force: true)
|
||||
}
|
||||
saveSoon()
|
||||
}
|
||||
|
||||
func move(_ from: Int, _ to: Int) {
|
||||
guard queue.indices.contains(from), to >= 0, to <= queue.count else { return }
|
||||
guard queue.indices.contains(from), to >= 0, to <= queue.count, from != to else { return }
|
||||
let cur = current
|
||||
let s = queue.remove(at: from)
|
||||
queue.insert(s, at: to > from ? to - 1 : to)
|
||||
if let cur, let i = queue.firstIndex(where: { $0.id == cur.id }) { index = i }
|
||||
rebuildOrder(keep: index)
|
||||
planNext(force: true)
|
||||
saveSoon()
|
||||
}
|
||||
|
||||
|
|
@ -309,19 +237,19 @@ final class Player: ObservableObject {
|
|||
saveSoon()
|
||||
}
|
||||
|
||||
func jump(_ i: Int) { load(i, play: true) }
|
||||
func jump(_ i: Int) { finishListen(); load(i, play: true) }
|
||||
|
||||
func setShuffle(_ on: Bool) {
|
||||
prefs.shuffle = on
|
||||
rebuildOrder(keep: index)
|
||||
updatePlan()
|
||||
planNext(force: true)
|
||||
updateNowPlaying()
|
||||
publishWidget()
|
||||
}
|
||||
|
||||
func cycleRepeat() {
|
||||
prefs.repeatMode = (prefs.repeatMode + 1) % 3
|
||||
updatePlan()
|
||||
planNext(force: true)
|
||||
publishWidget()
|
||||
}
|
||||
|
||||
|
|
@ -345,11 +273,7 @@ final class Player: ObservableObject {
|
|||
|
||||
// MARK: Transport
|
||||
|
||||
var position: Double {
|
||||
if let stream { return stream.currentTime().seconds.isFinite ? stream.currentTime().seconds : 0 }
|
||||
guard isPlaying, let (_, t) = decks[active].now() else { return basePos }
|
||||
return t
|
||||
}
|
||||
var position: Double { loaded ? (eng?.position ?? basePos) : basePos }
|
||||
|
||||
func toggle() { isPlaying ? pause() : play() }
|
||||
|
||||
|
|
@ -358,22 +282,13 @@ final class Player: ObservableObject {
|
|||
if !Library.shared.songs.isEmpty { playShuffled(Library.shared.songs) }
|
||||
return
|
||||
}
|
||||
if stream != nil {
|
||||
stream?.play()
|
||||
isPlaying = true
|
||||
} else {
|
||||
if decks[active].node.engine == nil || decks[active].marks.isEmpty {
|
||||
load(index, play: true, at: basePos)
|
||||
return
|
||||
}
|
||||
try? AVAudioSession.sharedInstance().setActive(true)
|
||||
if !engine.isRunning { try? engine.start() }
|
||||
let node = decks[active].node
|
||||
node.volume = prefs.fadePause ? 0 : gain(s)
|
||||
node.play()
|
||||
isPlaying = true
|
||||
if prefs.fadePause { ramp(node, to: gain(s), ms: 220) }
|
||||
guard loaded, let eng else {
|
||||
load(index, play: true, at: basePos)
|
||||
return
|
||||
}
|
||||
activateSession()
|
||||
eng.play(fade: prefs.fadePause, volume: gain(s))
|
||||
isPlaying = true
|
||||
lastTick = Date()
|
||||
startTimer()
|
||||
updateNowPlaying()
|
||||
|
|
@ -385,21 +300,8 @@ final class Player: ObservableObject {
|
|||
guard isPlaying else { return }
|
||||
basePos = position
|
||||
isPlaying = false
|
||||
if let stream {
|
||||
stream.pause()
|
||||
} else {
|
||||
let node = decks[active].node
|
||||
if fade && prefs.fadePause {
|
||||
ramp(node, to: 0, ms: 220) { [weak self] in
|
||||
guard let self, !self.isPlaying else { return }
|
||||
node.pause()
|
||||
}
|
||||
} else {
|
||||
node.pause()
|
||||
}
|
||||
decks[1 - active].stop()
|
||||
crossfading = false
|
||||
}
|
||||
crossfading = false
|
||||
eng?.pause(fade: fade && prefs.fadePause)
|
||||
updateNowPlaying()
|
||||
publishWidget()
|
||||
saveSoon()
|
||||
|
|
@ -407,9 +309,9 @@ final class Player: ObservableObject {
|
|||
|
||||
func stop() {
|
||||
isPlaying = false
|
||||
stream?.pause()
|
||||
stream = nil
|
||||
decks.forEach { $0.stop() }
|
||||
eng?.stop()
|
||||
loaded = false
|
||||
plannedNext = nil
|
||||
crossfading = false
|
||||
spectrum.reset()
|
||||
timer?.invalidate()
|
||||
|
|
@ -419,7 +321,7 @@ final class Player: ObservableObject {
|
|||
func next() {
|
||||
finishListen()
|
||||
guard let n = nextIndex(after: index, user: true) else { return }
|
||||
load(n, play: isPlaying || true)
|
||||
load(n, play: true)
|
||||
}
|
||||
|
||||
func prev() {
|
||||
|
|
@ -431,30 +333,21 @@ final class Player: ObservableObject {
|
|||
}
|
||||
|
||||
func seek(_ t: Double) {
|
||||
guard let s = current else { return }
|
||||
let t = max(0, min(duration > 0 ? duration - 0.25 : t, t))
|
||||
if let stream {
|
||||
stream.seek(to: CMTime(seconds: t, preferredTimescale: 1000))
|
||||
return
|
||||
}
|
||||
guard current != nil else { return }
|
||||
let t = max(0, duration > 0 ? min(duration - 0.25, t) : t)
|
||||
basePos = t
|
||||
decks[1 - active].stop()
|
||||
if loaded { eng?.seek(t) }
|
||||
crossfading = false
|
||||
if let src = Decoder.open(s) {
|
||||
decks[active].load(src, index: index, from: AVAudioFramePosition(t * Decoder.rate))
|
||||
decks[active].node.volume = gain(s)
|
||||
if isPlaying { decks[active].node.play() }
|
||||
}
|
||||
updateNowPlaying()
|
||||
publishWidget()
|
||||
}
|
||||
|
||||
/// Loads queue index `i` on the active deck.
|
||||
/// Loads queue index `i` on the engine suited to it.
|
||||
func load(_ i: Int, play: Bool, at start: Double = 0) {
|
||||
guard queue.indices.contains(i) else { return }
|
||||
stop()
|
||||
index = i
|
||||
let s = queue[i]
|
||||
updatePlan()
|
||||
basePos = start
|
||||
duration = s.duration
|
||||
error = nil
|
||||
|
|
@ -462,70 +355,68 @@ final class Player: ObservableObject {
|
|||
listened = 0
|
||||
lastTick = Date()
|
||||
loadArtAndLyrics(s)
|
||||
if s.isStream {
|
||||
let p = AVPlayer(url: s.url)
|
||||
stream = p
|
||||
if play { p.play(); isPlaying = true; startTimer() }
|
||||
} else if let src = Decoder.open(s) {
|
||||
if duration <= 0 { duration = Double(src.frames) / Decoder.rate }
|
||||
active = 0
|
||||
decks[0].load(src, index: i, from: AVAudioFramePosition(start * Decoder.rate))
|
||||
decks[0].node.volume = gain(s)
|
||||
let e = engine(for: s)
|
||||
eng = e
|
||||
wire(e)
|
||||
engineName = e === standard ? "Standard" : (universal.eqAllowed ? "Sound FX" : "Universal")
|
||||
if e.load(s, index: i, at: start, volume: gain(s)) {
|
||||
loaded = true
|
||||
if duration <= 0, let d = Decoder.open(s).map({ Double($0.frames) / Decoder.rate }), d > 0 { duration = d }
|
||||
planNext(force: true)
|
||||
if play {
|
||||
try? AVAudioSession.sharedInstance().setActive(true)
|
||||
if !engine.isRunning { try? engine.start() }
|
||||
decks[0].node.play()
|
||||
activateSession()
|
||||
e.play(fade: false, volume: gain(s))
|
||||
isPlaying = true
|
||||
startTimer()
|
||||
Scrobbler.shared.nowPlaying(s)
|
||||
}
|
||||
} else {
|
||||
error = "Can't play \(s.fileName)"
|
||||
if play, let n = nextIndex(after: i, user: false), n != i {
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) { [weak self] in self?.load(n, play: true) }
|
||||
}
|
||||
failed("Can't play \(s.fileName)")
|
||||
}
|
||||
updateNowPlaying()
|
||||
publishWidget()
|
||||
saveSoon()
|
||||
}
|
||||
|
||||
/// What a deck should play gaplessly after a given queue index. 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()
|
||||
|
||||
/// Refreshes the gapless plan; call after anything that changes what comes next.
|
||||
private func updatePlan() {
|
||||
guard prefs.gapless, prefs.crossfade == 0, !stopAfterCurrent, !sleepAtTrackEnd, stream == nil,
|
||||
let n = nextIndex(after: index, user: false), queue.indices.contains(n), !queue[n].isStream else {
|
||||
plan.set(after: index, nil)
|
||||
return
|
||||
/// Preloads the next song for gapless playback when it's on the same engine.
|
||||
private func planNext(force: Bool = false) {
|
||||
guard let eng, loaded else { return }
|
||||
var want: Int?
|
||||
if prefs.gapless, prefs.crossfade == 0, !stopAfterCurrent, !sleepAtTrackEnd,
|
||||
let n = nextIndex(after: index, user: false), queue.indices.contains(n), engine(for: queue[n]) === eng {
|
||||
want = n
|
||||
}
|
||||
plan.set(after: index, (queue[n], n))
|
||||
guard force || want != plannedNext else { return }
|
||||
plannedNext = want
|
||||
if let want { eng.setNext(queue[want], index: want, volume: gain(queue[want])) } else { eng.setNext(nil, index: -1, volume: 1) }
|
||||
}
|
||||
|
||||
/// Gapless hand-over, called on the deck queue when the playing source runs out.
|
||||
nonisolated private static func gaplessNext(_ plan: Plan, after last: Int) -> (AudioSource, Int)? {
|
||||
guard let (song, n) = plan.get(after: last), let src = Decoder.open(song) else { return nil }
|
||||
return (src, n)
|
||||
/// The engine moved on to the preloaded song by itself.
|
||||
private func advanced(to i: Int) {
|
||||
guard queue.indices.contains(i) else { return }
|
||||
finishListen()
|
||||
index = i
|
||||
plannedNext = nil
|
||||
duration = queue[i].duration
|
||||
listenStart = Date()
|
||||
listened = 0
|
||||
loadArtAndLyrics(queue[i])
|
||||
planNext(force: true)
|
||||
updateNowPlaying()
|
||||
publishWidget()
|
||||
Scrobbler.shared.nowPlaying(queue[i])
|
||||
saveSoon()
|
||||
}
|
||||
|
||||
private func deckDrained(_ d: Int) {
|
||||
guard d == active, isPlaying, !crossfading else { return }
|
||||
/// The current song ran out with nothing preloaded.
|
||||
private func ended() {
|
||||
guard isPlaying, !crossfading else { return }
|
||||
finishListen()
|
||||
if stopAfterCurrent || sleepAtTrackEnd {
|
||||
stopAfterCurrent = false
|
||||
sleepAtTrackEnd = false
|
||||
sleepAt = nil
|
||||
pause(fade: false)
|
||||
basePos = 0
|
||||
if let n = nextIndex(after: index, user: false) { load(n, play: false) }
|
||||
return
|
||||
}
|
||||
|
|
@ -533,62 +424,55 @@ final class Player: ObservableObject {
|
|||
load(n, play: true)
|
||||
} else {
|
||||
pause(fade: false)
|
||||
loaded = false
|
||||
basePos = 0
|
||||
seekOnResume = true
|
||||
publishWidget()
|
||||
}
|
||||
}
|
||||
|
||||
private var seekOnResume = false
|
||||
private func failed(_ msg: String) {
|
||||
Log.e("playback failed: \(msg)")
|
||||
error = msg
|
||||
UIState.shared.show(msg)
|
||||
let failedIndex = index
|
||||
if let n = nextIndex(after: failedIndex, user: false), n != failedIndex {
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) { [weak self] in
|
||||
guard let self, self.index == failedIndex else { return }
|
||||
self.load(n, play: true)
|
||||
}
|
||||
} else {
|
||||
stop()
|
||||
}
|
||||
}
|
||||
|
||||
private func beginCrossfade(to n: Int) {
|
||||
guard !crossfading, queue.indices.contains(n), !queue[n].isStream, let src = Decoder.open(queue[n]) else { return }
|
||||
guard let eng, !crossfading, queue.indices.contains(n), engine(for: queue[n]) === eng else { return }
|
||||
let s = queue[n]
|
||||
guard eng.crossfade(to: s, index: n, seconds: Double(prefs.crossfade), volume: gain(s)) else { return }
|
||||
crossfading = true
|
||||
let old = decks[active]
|
||||
let newIdx = 1 - active
|
||||
let nd = decks[newIdx]
|
||||
nd.load(src, index: n, from: 0)
|
||||
nd.node.volume = 0
|
||||
nd.node.play()
|
||||
let ms = Double(prefs.crossfade) * 1000
|
||||
ramp(old.node, to: 0, ms: ms) { old.stop() }
|
||||
ramp(nd.node, to: gain(queue[n]), ms: ms) { [weak self] in self?.crossfading = false }
|
||||
finishListen()
|
||||
active = newIdx
|
||||
index = n
|
||||
duration = queue[n].duration > 0 ? queue[n].duration : Double(src.frames) / Decoder.rate
|
||||
duration = s.duration
|
||||
listenStart = Date()
|
||||
listened = 0
|
||||
loadArtAndLyrics(queue[n])
|
||||
loadArtAndLyrics(s)
|
||||
updateNowPlaying()
|
||||
publishWidget()
|
||||
Scrobbler.shared.nowPlaying(queue[n])
|
||||
Scrobbler.shared.nowPlaying(s)
|
||||
saveSoon()
|
||||
}
|
||||
|
||||
private func ramp(_ node: AVAudioPlayerNode, to target: Float, ms: Double, done: (() -> Void)? = nil) {
|
||||
let start = node.volume
|
||||
let steps = max(1, Int(ms / 20))
|
||||
var k = 0
|
||||
Timer.scheduledTimer(withTimeInterval: 0.02, repeats: true) { t in
|
||||
k += 1
|
||||
let f = Float(k) / Float(steps)
|
||||
node.volume = start + (target - start) * min(1, f * f * (3 - 2 * f))
|
||||
if k >= steps { t.invalidate(); done?() }
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + Double(prefs.crossfade) + 0.2) { [weak self] in
|
||||
self?.crossfading = false
|
||||
self?.planNext(force: true)
|
||||
}
|
||||
}
|
||||
|
||||
private func gain(_ s: Song) -> Float {
|
||||
guard prefs.replayGain else { return 1 }
|
||||
private func gain(_ s: Song?) -> Float {
|
||||
guard let s, prefs.replayGain, !s.isStream else { return 1 }
|
||||
let t = ReplayGainCache.shared.gain(s)
|
||||
return Float(min(1, pow(10, t / 20)))
|
||||
}
|
||||
|
||||
func applyEQ() {
|
||||
eq.bypass = !prefs.eqOn
|
||||
for (i, b) in eq.bands.enumerated() where i < prefs.eqBands.count { b.gain = Float(prefs.eqBands[i]) }
|
||||
}
|
||||
|
||||
// MARK: Timer: track hand-over, crossfade start, listening time, sleep
|
||||
// MARK: Timer: crossfade start, listening time, sleep
|
||||
|
||||
private func startTimer() {
|
||||
guard timer == nil else { return }
|
||||
|
|
@ -599,26 +483,13 @@ final class Player: ObservableObject {
|
|||
|
||||
private func tick() {
|
||||
guard isPlaying else { return }
|
||||
updatePlan()
|
||||
let now = Date()
|
||||
listened += now.timeIntervalSince(lastTick)
|
||||
lastTick = now
|
||||
// Gapless boundary passed: the deck now plays a different queue index.
|
||||
if !crossfading, let (i, _) = decks[active].now(), i != index, queue.indices.contains(i) {
|
||||
finishListen()
|
||||
index = i
|
||||
duration = queue[i].duration
|
||||
listenStart = now
|
||||
listened = 0
|
||||
loadArtAndLyrics(queue[i])
|
||||
updateNowPlaying()
|
||||
publishWidget()
|
||||
Scrobbler.shared.nowPlaying(queue[i])
|
||||
saveSoon()
|
||||
}
|
||||
if prefs.crossfade > 0, !crossfading, !stopAfterCurrent, !sleepAtTrackEnd, stream == nil, duration > 0,
|
||||
position >= duration - Double(prefs.crossfade), duration > Double(prefs.crossfade) * 2,
|
||||
let n = nextIndex(after: index, user: false) {
|
||||
(eng as? UniversalEngine)?.pollAdvance()
|
||||
planNext()
|
||||
if prefs.crossfade > 0, !crossfading, !stopAfterCurrent, !sleepAtTrackEnd, duration > Double(prefs.crossfade) * 2,
|
||||
position >= duration - Double(prefs.crossfade), let n = nextIndex(after: index, user: false) {
|
||||
beginCrossfade(to: n)
|
||||
}
|
||||
if let s = current { Scrobbler.shared.progress(s, listened: listened, duration: duration) }
|
||||
|
|
@ -630,7 +501,7 @@ final class Player: ObservableObject {
|
|||
}
|
||||
|
||||
private func finishListen() {
|
||||
guard let s = current else { return }
|
||||
guard let s = current, listened > 0 else { return }
|
||||
if listened >= min(30, max(1, duration * 0.5)) { PlayStats.shared.played(s) }
|
||||
Scrobbler.shared.finished(s, listened: listened, started: listenStart)
|
||||
listened = 0
|
||||
|
|
@ -644,16 +515,22 @@ final class Player: ObservableObject {
|
|||
func sleepAtEndOfTrack() {
|
||||
sleepAt = nil
|
||||
sleepAtTrackEnd = true
|
||||
planNext(force: true)
|
||||
}
|
||||
|
||||
func cancelSleep() {
|
||||
sleepAt = nil
|
||||
sleepAtTrackEnd = false
|
||||
planNext(force: true)
|
||||
}
|
||||
|
||||
private func fadeOutAndPause() {
|
||||
let node = decks[active].node
|
||||
ramp(node, to: 0, ms: 4000) { [weak self] in self?.pause(fade: false) }
|
||||
guard let eng else { pause(fade: false); return }
|
||||
let v = gain(current)
|
||||
rampVolume(from: v, to: 0, ms: 4000, set: { eng.setVolume($0) }) { [weak self] in
|
||||
self?.pause(fade: false)
|
||||
eng.setVolume(v)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Art & lyrics
|
||||
|
|
|
|||
|
|
@ -56,13 +56,32 @@ final class Spectrum {
|
|||
/// Called from the audio tap thread.
|
||||
func feed(_ buffer: AVAudioPCMBuffer) {
|
||||
guard let ch = buffer.floatChannelData else { return }
|
||||
let frames = Int(buffer.frameLength)
|
||||
let chans = Int(buffer.format.channelCount)
|
||||
feed((0..<chans).map { UnsafePointer(ch[$0]) }, stride: 1, frames: Int(buffer.frameLength))
|
||||
}
|
||||
|
||||
/// Called from an MTAudioProcessingTap (Float32, interleaved or not).
|
||||
func feed(_ abl: UnsafeMutablePointer<AudioBufferList>, frames: Int) {
|
||||
let list = UnsafeMutableAudioBufferListPointer(abl)
|
||||
guard let first = list.first, first.mData != nil else { return }
|
||||
if list.count == 1 {
|
||||
let chans = max(1, Int(first.mNumberChannels))
|
||||
let base = first.mData!.assumingMemoryBound(to: Float.self)
|
||||
feed((0..<chans).map { UnsafePointer(base + $0) }, stride: chans, frames: frames)
|
||||
} else {
|
||||
let ptrs = list.compactMap { $0.mData.map { UnsafePointer($0.assumingMemoryBound(to: Float.self)) } }
|
||||
feed(ptrs, stride: 1, frames: frames)
|
||||
}
|
||||
}
|
||||
|
||||
private func feed(_ ch: [UnsafePointer<Float>], stride: Int, frames: Int) {
|
||||
guard !ch.isEmpty else { return }
|
||||
let chans = Float(ch.count)
|
||||
lock.lock()
|
||||
for i in 0..<frames {
|
||||
var v: Float = 0
|
||||
for c in 0..<chans { v += ch[c][i] }
|
||||
ring[ringPos] = v / Float(chans) * 32768
|
||||
for c in ch { v += c[i * stride] }
|
||||
ring[ringPos] = v / chans * 32768
|
||||
ringPos = (ringPos + 1) & (Spectrum.n - 1)
|
||||
}
|
||||
let now = CFAbsoluteTimeGetCurrent()
|
||||
|
|
|
|||
205
App/Audio/StandardEngine.swift
Normal file
205
App/Audio/StandardEngine.swift
Normal file
|
|
@ -0,0 +1,205 @@
|
|||
import AVFoundation
|
||||
import MediaToolbox
|
||||
|
||||
/// "Standard" engine: Apple's AVQueuePlayer (like FlacBox's Standard). Gapless through the player's own queue,
|
||||
/// crossfade with a second player, spectrum from an MTAudioProcessingTap.
|
||||
@MainActor
|
||||
final class StandardEngine: PlaybackEngine {
|
||||
var onAdvance: ((Int) -> Void)?
|
||||
var onEnded: (() -> Void)?
|
||||
var onFailed: ((String) -> Void)?
|
||||
|
||||
/// Formats AVFoundation decodes natively on iOS.
|
||||
nonisolated static let nativeExts: Set<String> = ["mp3", "m4a", "m4b", "m4r", "aac", "alac", "mp4", "flac", "wav", "aif",
|
||||
"aiff", "aifc", "caf", "3gp", "amr", "ac3", "eac3", "mp2"]
|
||||
|
||||
nonisolated static func canPlay(_ s: Song) -> Bool {
|
||||
s.isStream || nativeExts.contains((s.path as NSString).pathExtension.lowercased())
|
||||
}
|
||||
|
||||
private let spectrum: Spectrum
|
||||
private var players = [AVQueuePlayer(), AVQueuePlayer()]
|
||||
private var active = 0
|
||||
private var items: [ObjectIdentifier: (index: Int, song: Song)] = [:]
|
||||
private var observers: [NSObjectProtocol] = []
|
||||
private var kvo: [NSKeyValueObservation] = []
|
||||
private var volume: Float = 1
|
||||
|
||||
init(spectrum: Spectrum) {
|
||||
self.spectrum = spectrum
|
||||
for p in players {
|
||||
p.actionAtItemEnd = .advance
|
||||
p.automaticallyWaitsToMinimizeStalling = false
|
||||
kvo.append(p.observe(\.currentItem, options: [.old, .new]) { [weak self] player, change in
|
||||
let old = change.oldValue.flatMap { $0 }.map(ObjectIdentifier.init)
|
||||
let new = change.newValue.flatMap { $0 }.map(ObjectIdentifier.init)
|
||||
Task { @MainActor in self?.itemChanged(player, old: old, new: new) }
|
||||
})
|
||||
}
|
||||
let nc = NotificationCenter.default
|
||||
observers.append(nc.addObserver(forName: AVPlayerItem.didPlayToEndTimeNotification, object: nil, queue: .main) { [weak self] n in
|
||||
guard let item = n.object as? AVPlayerItem else { return }
|
||||
let id = ObjectIdentifier(item)
|
||||
MainActor.assumeIsolated { self?.itemEnded(id) }
|
||||
})
|
||||
observers.append(nc.addObserver(forName: AVPlayerItem.failedToPlayToEndTimeNotification, object: nil, queue: .main) { [weak self] n in
|
||||
let err = (n.userInfo?[AVPlayerItemFailedToPlayToEndTimeErrorKey] as? Error)?.localizedDescription ?? "unknown error"
|
||||
guard let item = n.object as? AVPlayerItem else { return }
|
||||
let id = ObjectIdentifier(item)
|
||||
MainActor.assumeIsolated {
|
||||
guard let self, self.items[id] != nil else { return }
|
||||
Log.e("standard: failed to play to end: \(err)")
|
||||
self.onFailed?(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private var player: AVQueuePlayer { players[active] }
|
||||
|
||||
private func makeItem(_ s: Song) -> AVPlayerItem {
|
||||
let item = AVPlayerItem(asset: AVURLAsset(url: s.url))
|
||||
item.preferredForwardBufferDuration = 10
|
||||
if s.cueIndex > 0 && s.end > s.start {
|
||||
item.forwardPlaybackEndTime = CMTime(seconds: s.end, preferredTimescale: 1000)
|
||||
}
|
||||
if !s.isStream { attachTap(item) }
|
||||
return item
|
||||
}
|
||||
|
||||
private func itemChanged(_ p: AVQueuePlayer, old: ObjectIdentifier?, new: ObjectIdentifier?) {
|
||||
guard p === player, let new, let entry = items[new] else { return }
|
||||
if let old, old != new, items[old] != nil {
|
||||
items[old] = nil
|
||||
if entry.song.cueIndex > 0, let item = p.currentItem {
|
||||
item.seek(to: CMTime(seconds: entry.song.start, preferredTimescale: 1000), completionHandler: nil)
|
||||
}
|
||||
Log.i("standard: gapless advance to #\(entry.index)")
|
||||
onAdvance?(entry.index)
|
||||
}
|
||||
}
|
||||
|
||||
private func itemEnded(_ id: ObjectIdentifier) {
|
||||
// Only the active player's items count (the old one of a crossfade is being torn down).
|
||||
guard items[id] != nil, player.items().contains(where: { ObjectIdentifier($0) == id }) else { return }
|
||||
// Another queued item means the player advances by itself (itemChanged); otherwise the song is done.
|
||||
if !player.items().contains(where: { ObjectIdentifier($0) != id }) {
|
||||
items[id] = nil
|
||||
onEnded?()
|
||||
}
|
||||
}
|
||||
|
||||
func load(_ song: Song, index: Int, at: Double, volume: Float) -> Bool {
|
||||
stop()
|
||||
let item = makeItem(song)
|
||||
items[ObjectIdentifier(item)] = (index, song)
|
||||
player.insert(item, after: nil)
|
||||
let start = (song.cueIndex > 0 ? song.start : 0) + at
|
||||
if start > 0 { item.seek(to: CMTime(seconds: start, preferredTimescale: 1000), toleranceBefore: .zero, toleranceAfter: .zero, completionHandler: nil) }
|
||||
self.volume = volume
|
||||
player.volume = volume
|
||||
Log.i("standard: load #\(index) \(song.fileName) at \(Int(at))s")
|
||||
return true
|
||||
}
|
||||
|
||||
func setNext(_ song: Song?, index: Int, volume: Float) {
|
||||
let p = player
|
||||
for it in p.items().dropFirst() { items[ObjectIdentifier(it)] = nil; p.remove(it) }
|
||||
guard let song, p.currentItem != nil else { return }
|
||||
let item = makeItem(song)
|
||||
items[ObjectIdentifier(item)] = (index, song)
|
||||
p.insert(item, after: p.currentItem)
|
||||
}
|
||||
|
||||
func play(fade: Bool, volume: Float) {
|
||||
self.volume = volume
|
||||
let p = player
|
||||
if fade {
|
||||
p.volume = 0
|
||||
p.play()
|
||||
rampVolume(from: 0, to: volume, ms: 220) { p.volume = $0 }
|
||||
} else {
|
||||
p.volume = volume
|
||||
p.play()
|
||||
}
|
||||
}
|
||||
|
||||
func pause(fade: Bool) {
|
||||
let p = player
|
||||
guard fade else { p.pause(); return }
|
||||
rampVolume(from: p.volume, to: 0, ms: 220, set: { p.volume = $0 }) { [weak self] in
|
||||
p.pause()
|
||||
p.volume = self?.volume ?? 1
|
||||
}
|
||||
players[1 - active].pause()
|
||||
players[1 - active].removeAllItems()
|
||||
}
|
||||
|
||||
func stop() {
|
||||
for p in players { p.pause(); p.removeAllItems() }
|
||||
items = [:]
|
||||
}
|
||||
|
||||
func seek(_ t: Double) {
|
||||
guard let item = player.currentItem, let e = items[ObjectIdentifier(item)] else { return }
|
||||
let base = e.song.cueIndex > 0 ? e.song.start : 0
|
||||
player.seek(to: CMTime(seconds: base + t, preferredTimescale: 1000), toleranceBefore: .zero, toleranceAfter: .zero)
|
||||
}
|
||||
|
||||
var position: Double {
|
||||
guard let item = player.currentItem else { return 0 }
|
||||
let t = player.currentTime().seconds
|
||||
guard t.isFinite else { return 0 }
|
||||
let base = items[ObjectIdentifier(item)].map { $0.song.cueIndex > 0 ? $0.song.start : 0 } ?? 0
|
||||
return max(0, t - base)
|
||||
}
|
||||
|
||||
func crossfade(to song: Song, index: Int, seconds: Double, volume: Float) -> Bool {
|
||||
let old = player
|
||||
let next = players[1 - active]
|
||||
next.removeAllItems()
|
||||
let item = makeItem(song)
|
||||
items[ObjectIdentifier(item)] = (index, song)
|
||||
next.insert(item, after: nil)
|
||||
if song.cueIndex > 0 { item.seek(to: CMTime(seconds: song.start, preferredTimescale: 1000), completionHandler: nil) }
|
||||
next.volume = 0
|
||||
next.play()
|
||||
active = 1 - active
|
||||
self.volume = volume
|
||||
let ms = seconds * 1000
|
||||
rampVolume(from: old.volume, to: 0, ms: ms, set: { old.volume = $0 }) { [weak self] in
|
||||
for it in old.items() { self?.items[ObjectIdentifier(it)] = nil }
|
||||
old.pause()
|
||||
old.removeAllItems()
|
||||
}
|
||||
rampVolume(from: 0, to: volume, ms: ms) { next.volume = $0 }
|
||||
return true
|
||||
}
|
||||
|
||||
func setVolume(_ v: Float) { volume = v; player.volume = v }
|
||||
|
||||
// MARK: Spectrum tap
|
||||
|
||||
private func attachTap(_ item: AVPlayerItem) {
|
||||
guard let track = item.asset.tracks(withMediaType: .audio).first else { return }
|
||||
var callbacks = MTAudioProcessingTapCallbacks(
|
||||
version: kMTAudioProcessingTapCallbacksVersion_0,
|
||||
clientInfo: UnsafeMutableRawPointer(Unmanaged.passUnretained(spectrum).toOpaque()),
|
||||
init: { _, clientInfo, storageOut in storageOut.pointee = clientInfo },
|
||||
finalize: nil,
|
||||
prepare: nil,
|
||||
unprepare: nil,
|
||||
process: { tap, frames, _, bufferList, framesOut, flagsOut in
|
||||
guard MTAudioProcessingTapGetSourceAudio(tap, frames, bufferList, flagsOut, nil, framesOut) == noErr else { return }
|
||||
let spectrum = Unmanaged<Spectrum>.fromOpaque(MTAudioProcessingTapGetStorage(tap)).takeUnretainedValue()
|
||||
spectrum.feed(bufferList, frames: Int(framesOut.pointee))
|
||||
})
|
||||
var out: Unmanaged<MTAudioProcessingTap>?
|
||||
let status = MTAudioProcessingTapCreate(kCFAllocatorDefault, &callbacks, kMTAudioProcessingTapCreationFlag_PostEffects, &out)
|
||||
guard status == noErr, let tap = out?.takeRetainedValue() else { return }
|
||||
let params = AVMutableAudioMixInputParameters(track: track)
|
||||
params.audioTapProcessor = tap
|
||||
let mix = AVMutableAudioMix()
|
||||
mix.inputParameters = [params]
|
||||
item.audioMix = mix
|
||||
}
|
||||
}
|
||||
281
App/Audio/UniversalEngine.swift
Normal file
281
App/Audio/UniversalEngine.swift
Normal file
|
|
@ -0,0 +1,281 @@
|
|||
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 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
|
||||
}
|
||||
engine.attach(eq)
|
||||
for d in decks {
|
||||
engine.attach(d.node)
|
||||
engine.connect(d.node, 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.decks[self.active].node.play() }
|
||||
}
|
||||
}
|
||||
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 }
|
||||
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) })
|
||||
}
|
||||
|
||||
func play(fade: Bool, volume: Float) {
|
||||
self.volume = volume
|
||||
guard start() else { return }
|
||||
let node = decks[active].node
|
||||
node.volume = fade ? 0 : volume
|
||||
node.play()
|
||||
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 { decks[active].node.play() }
|
||||
}
|
||||
|
||||
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
|
||||
nd.node.play()
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
|
@ -38,7 +38,7 @@ final class Library: ObservableObject {
|
|||
|
||||
private var byPath: [String: Song] = [:]
|
||||
private var cacheURL: URL { Library.support.appendingPathComponent("library.json") }
|
||||
private var watcher: DispatchSourceFileSystemObject?
|
||||
private var watchers: [DispatchSourceFileSystemObject] = []
|
||||
private var rescanPending = false
|
||||
|
||||
private init() {
|
||||
|
|
@ -75,15 +75,28 @@ final class Library: ObservableObject {
|
|||
|
||||
// MARK: Scanning
|
||||
|
||||
/// Watches Documents and every folder below it (a directory source only sees its own entries).
|
||||
func startWatching() {
|
||||
let fd = open(Library.root.path, O_EVTONLY)
|
||||
guard fd >= 0 else { return }
|
||||
let src = DispatchSource.makeFileSystemObjectSource(fileDescriptor: fd, eventMask: [.write, .rename, .delete],
|
||||
queue: .main)
|
||||
src.setEventHandler { [weak self] in self?.rescanSoon() }
|
||||
src.setCancelHandler { close(fd) }
|
||||
src.resume()
|
||||
watcher = src
|
||||
watchers.forEach { $0.cancel() }
|
||||
watchers = []
|
||||
var dirs = [Library.root]
|
||||
if let en = FileManager.default.enumerator(at: Library.root, includingPropertiesForKeys: [.isDirectoryKey],
|
||||
options: [.skipsHiddenFiles, .skipsPackageDescendants]) {
|
||||
for case let u as URL in en where (try? u.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true {
|
||||
dirs.append(u)
|
||||
if dirs.count >= 400 { break }
|
||||
}
|
||||
}
|
||||
for dir in dirs {
|
||||
let fd = open(dir.path, O_EVTONLY)
|
||||
guard fd >= 0 else { continue }
|
||||
let src = DispatchSource.makeFileSystemObjectSource(fileDescriptor: fd, eventMask: [.write, .rename, .delete],
|
||||
queue: .main)
|
||||
src.setEventHandler { [weak self] in self?.rescanSoon() }
|
||||
src.setCancelHandler { close(fd) }
|
||||
src.resume()
|
||||
watchers.append(src)
|
||||
}
|
||||
}
|
||||
|
||||
func rescanSoon() {
|
||||
|
|
@ -108,6 +121,8 @@ final class Library: ObservableObject {
|
|||
let lib = Library.shared
|
||||
lib.set(result)
|
||||
lib.scanning = false
|
||||
lib.startWatching() // pick up folders created since the last scan
|
||||
Log.i("scan: \(result.count) songs")
|
||||
if let d = try? JSONEncoder().encode(result) { try? d.write(to: lib.cacheURL, options: .atomic) }
|
||||
Playlists.shared.syncFolder()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -34,6 +34,7 @@ final class Prefs: ObservableObject {
|
|||
@Published var replayGain: Bool { didSet { d.set(replayGain, forKey: "replay_gain") } }
|
||||
@Published var eqBands: [Double] { didSet { d.set(eqBands, forKey: "eq_bands") } }
|
||||
@Published var eqOn: Bool { didSet { d.set(eqOn, forKey: "eq_on") } }
|
||||
@Published var engine: String { didSet { d.set(engine, forKey: "engine") } } // standard/universal/fx
|
||||
|
||||
private init() {
|
||||
let d = UserDefaults.standard
|
||||
|
|
@ -66,5 +67,6 @@ final class Prefs: ObservableObject {
|
|||
replayGain = g("replay_gain", false)
|
||||
eqBands = g("eq_bands", [Double](repeating: 0, count: 10))
|
||||
eqOn = g("eq_on", false)
|
||||
engine = g("engine", "standard")
|
||||
}
|
||||
}
|
||||
|
|
|
|||
33
App/Services/Log.swift
Normal file
33
App/Services/Log.swift
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
import Foundation
|
||||
import os
|
||||
|
||||
/// Small file logger (Library/Caches/mulberry.log, trimmed at 512 KB) so problems can be read over SSH.
|
||||
enum Log {
|
||||
private static let logger = Logger(subsystem: "com.mulberry.player", category: "app")
|
||||
private static let q = DispatchQueue(label: "mulberry.log")
|
||||
private static let url = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]
|
||||
.appendingPathComponent("mulberry.log")
|
||||
private static let fmt: DateFormatter = {
|
||||
let f = DateFormatter()
|
||||
f.dateFormat = "HH:mm:ss.SSS"
|
||||
return f
|
||||
}()
|
||||
|
||||
static func i(_ msg: @autoclosure () -> String) { write("I", msg()) }
|
||||
static func e(_ msg: @autoclosure () -> String) { write("E", msg()) }
|
||||
|
||||
private static func write(_ level: String, _ msg: String) {
|
||||
logger.log("\(level, privacy: .public) \(msg, privacy: .public)")
|
||||
let line = "\(fmt.string(from: Date())) \(level) \(msg)\n"
|
||||
q.async {
|
||||
if let h = try? FileHandle(forWritingTo: url) {
|
||||
h.seekToEndOfFile()
|
||||
h.write(Data(line.utf8))
|
||||
if h.offsetInFile > 512 << 10 { h.truncateFile(atOffset: 0) }
|
||||
try? h.close()
|
||||
} else {
|
||||
try? Data(line.utf8).write(to: url)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -411,6 +411,15 @@ struct EqualizerSheet: View {
|
|||
}
|
||||
.disabled(!prefs.eqOn)
|
||||
.opacity(prefs.eqOn ? 1 : 0.5)
|
||||
if prefs.engine != "fx" {
|
||||
VStack(spacing: 8) {
|
||||
Text("The equalizer works with the Sound FX engine. Standard is Apple's player and has no EQ.")
|
||||
.font(.footnote).foregroundColor(p.cOnSurfaceVar).multilineTextAlignment(.center)
|
||||
Pill(icon: "hifispeaker", title: "Use Sound FX", filled: true) {
|
||||
prefs.engine = "fx"; prefs.eqOn = true; Player.shared.engineChanged()
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer()
|
||||
}
|
||||
.padding(24)
|
||||
|
|
|
|||
|
|
@ -42,6 +42,10 @@ struct SettingsView: View {
|
|||
|
||||
SectionLabel(text: "Playback")
|
||||
Card {
|
||||
MenuRow(icon: "hifispeaker", title: "Playback engine",
|
||||
value: (EngineKind(rawValue: prefs.engine) ?? .standard).title + " — " + (EngineKind(rawValue: prefs.engine) ?? .standard).detail,
|
||||
options: EngineKind.allCases.map { ($0.title, $0.rawValue) },
|
||||
selection: Binding(get: { prefs.engine }, set: { prefs.engine = $0; Player.shared.engineChanged() }))
|
||||
MenuRow(icon: "slider.horizontal.below.rectangle", title: "Crossfade", value: prefs.crossfade == 0 ? "Off" : "\(prefs.crossfade) seconds — songs blend into each other",
|
||||
options: [("Off", "0"), ("2 seconds", "2"), ("3 seconds", "3"), ("5 seconds", "5"), ("8 seconds", "8"), ("12 seconds", "12")],
|
||||
selection: Binding(get: { String(prefs.crossfade) }, set: { prefs.crossfade = Int($0) ?? 0 }))
|
||||
|
|
@ -54,7 +58,8 @@ struct SettingsView: View {
|
|||
MenuRow(icon: "music.note", title: "Hide short clips", value: prefs.minDuration == 0 ? "Off" : "Shorter than \(prefs.minDuration) s",
|
||||
options: [("Off", "0"), ("10 s", "10"), ("20 s", "20"), ("30 s", "30"), ("60 s", "60")],
|
||||
selection: Binding(get: { String(prefs.minDuration) }, set: { prefs.minDuration = Int($0) ?? 0; lib.scan() }))
|
||||
ButtonRow(icon: "slider.vertical.3", title: "Equalizer", sub: prefs.eqOn ? "On" : "Off") { showEQ = true }
|
||||
ButtonRow(icon: "slider.vertical.3", title: "Equalizer",
|
||||
sub: prefs.engine == "fx" ? (prefs.eqOn ? "On" : "Off") : "Needs the Sound FX engine") { showEQ = true }
|
||||
}
|
||||
|
||||
SectionLabel(text: "Lyrics & covers")
|
||||
|
|
|
|||
Loading…
Reference in a new issue