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?() } } }