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 = ["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) { let asset = item.asset Task { @MainActor [weak self, weak item] in guard let self, let item else { return } do { guard let track = try await asset.loadTracks(withMediaType: .audio).first else { Log.e("standard: no audio track for the visualizer tap") return } self.installTap(item, track) } catch { Log.e("standard: loading tracks for the tap failed: \(error.localizedDescription)") } } } private func installTap(_ item: AVPlayerItem, _ track: AVAssetTrack) { 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.fromOpaque(MTAudioProcessingTapGetStorage(tap)).takeUnretainedValue() spectrum.feed(bufferList, frames: Int(framesOut.pointee)) }) var out: Unmanaged? let status = MTAudioProcessingTapCreate(kCFAllocatorDefault, &callbacks, kMTAudioProcessingTapCreationFlag_PostEffects, &out) guard status == noErr, let tap = out?.takeRetainedValue() else { Log.e("standard: MTAudioProcessingTapCreate failed (\(status))") return } let params = AVMutableAudioMixInputParameters(track: track) params.audioTapProcessor = tap let mix = AVMutableAudioMix() mix.inputParameters = [params] item.audioMix = mix Log.i("standard: visualizer tap attached") } }