752 lines
27 KiB
Swift
752 lines
27 KiB
Swift
import AVFoundation
|
|
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
|
|
}
|
|
}
|
|
|
|
@MainActor
|
|
final class Player: ObservableObject {
|
|
static let shared = Player()
|
|
|
|
@Published private(set) var queue: [Song] = []
|
|
@Published private(set) var index = -1
|
|
@Published private(set) var isPlaying = false
|
|
@Published private(set) var duration: Double = 0
|
|
@Published var stopAfterCurrent = false
|
|
@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?
|
|
|
|
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 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 timer: Timer?
|
|
private var crossfading = false
|
|
private var listenStart = Date()
|
|
private var listened: Double = 0
|
|
private var lastTick = Date()
|
|
|
|
static let eqFreqs: [Float] = [31, 62, 125, 250, 500, 1000, 2000, 4000, 8000, 16000]
|
|
|
|
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: Session & remote
|
|
|
|
private func setupSession() {
|
|
let s = AVAudioSession.sharedInstance()
|
|
try? s.setCategory(.playback, mode: .default, policy: .longFormAudio)
|
|
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 }
|
|
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 {
|
|
self.resumeAfterInterruption = false
|
|
self.play()
|
|
}
|
|
}
|
|
}
|
|
nc.addObserver(forName: AVAudioSession.routeChangeNotification, object: nil, queue: .main) { [weak self] n in
|
|
guard let self, let raw = n.userInfo?[AVAudioSessionRouteChangeReasonKey] as? UInt,
|
|
AVAudioSession.RouteChangeReason(rawValue: raw) == .oldDeviceUnavailable else { return }
|
|
MainActor.assumeIsolated {
|
|
if self.prefs.pauseOnDetach && self.isPlaying { self.pause(fade: false) }
|
|
}
|
|
}
|
|
nc.addObserver(forName: .AVAudioEngineConfigurationChange, object: engine, queue: .main) { [weak self] _ in
|
|
MainActor.assumeIsolated {
|
|
guard let self, self.isPlaying else { return }
|
|
try? self.engine.start()
|
|
self.decks[self.active].node.play()
|
|
}
|
|
}
|
|
}
|
|
|
|
private var resumeAfterInterruption = false
|
|
|
|
private func setupRemote() {
|
|
let c = MPRemoteCommandCenter.shared()
|
|
c.playCommand.addTarget { [weak self] _ in self?.play(); return .success }
|
|
c.pauseCommand.addTarget { [weak self] _ in self?.pause(); return .success }
|
|
c.togglePlayPauseCommand.addTarget { [weak self] _ in self?.toggle(); return .success }
|
|
c.nextTrackCommand.addTarget { [weak self] _ in self?.next(); return .success }
|
|
c.previousTrackCommand.addTarget { [weak self] _ in self?.prev(); return .success }
|
|
c.changePlaybackPositionCommand.addTarget { [weak self] e in
|
|
if let e = e as? MPChangePlaybackPositionCommandEvent { self?.seek(e.positionTime) }
|
|
return .success
|
|
}
|
|
c.changeShuffleModeCommand.addTarget { [weak self] _ in self?.setShuffle(!(self?.prefs.shuffle ?? false)); return .success }
|
|
c.changeRepeatModeCommand.addTarget { [weak self] _ in self?.cycleRepeat(); return .success }
|
|
c.likeCommand.addTarget { [weak self] _ in
|
|
if let s = self?.current { PlayStats.shared.setFav(s, !PlayStats.shared.fav(s)) }
|
|
return .success
|
|
}
|
|
}
|
|
|
|
private func updateNowPlaying() {
|
|
guard let s = current else {
|
|
MPNowPlayingInfoCenter.default().nowPlayingInfo = nil
|
|
return
|
|
}
|
|
var info: [String: Any] = [
|
|
MPMediaItemPropertyTitle: s.displayTitle,
|
|
MPMediaItemPropertyArtist: s.displayArtist,
|
|
MPMediaItemPropertyAlbumTitle: s.album,
|
|
MPMediaItemPropertyPlaybackDuration: duration,
|
|
MPNowPlayingInfoPropertyElapsedPlaybackTime: position,
|
|
MPNowPlayingInfoPropertyPlaybackRate: isPlaying ? 1.0 : 0.0,
|
|
MPNowPlayingInfoPropertyPlaybackQueueIndex: index,
|
|
MPNowPlayingInfoPropertyPlaybackQueueCount: queue.count,
|
|
]
|
|
if let img = art {
|
|
info[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: img.size) { _ in img }
|
|
}
|
|
MPNowPlayingInfoCenter.default().nowPlayingInfo = info
|
|
MPNowPlayingInfoCenter.default().playbackState = isPlaying ? .playing : .paused
|
|
}
|
|
|
|
// MARK: Queue (Android MusicService API)
|
|
|
|
func playList(_ list: [Song], start: Int = 0) {
|
|
guard !list.isEmpty else { return }
|
|
queue = list
|
|
rebuildOrder(keep: start)
|
|
load(start, play: true)
|
|
}
|
|
|
|
func playShuffled(_ list: [Song]) {
|
|
guard !list.isEmpty else { return }
|
|
prefs.shuffle = true
|
|
queue = list
|
|
let start = Int.random(in: 0..<list.count)
|
|
rebuildOrder(keep: start)
|
|
load(start, play: true)
|
|
}
|
|
|
|
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) }
|
|
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)
|
|
saveSoon()
|
|
}
|
|
|
|
func removeAt(_ i: Int) {
|
|
guard queue.indices.contains(i) else { return }
|
|
let wasCurrent = i == index
|
|
queue.remove(at: i)
|
|
order = order.filter { $0 != i }.map { $0 > i ? $0 - 1 : $0 }
|
|
if i < index { index -= 1 }
|
|
if wasCurrent {
|
|
if queue.isEmpty { stop(); index = -1 } else { load(min(index, queue.count - 1), play: isPlaying) }
|
|
}
|
|
saveSoon()
|
|
}
|
|
|
|
func move(_ from: Int, _ to: Int) {
|
|
guard queue.indices.contains(from), to >= 0, to <= queue.count 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)
|
|
saveSoon()
|
|
}
|
|
|
|
func clearQueue() {
|
|
stop()
|
|
queue = []
|
|
order = []
|
|
index = -1
|
|
art = nil
|
|
lyrics = nil
|
|
updateNowPlaying()
|
|
publishWidget()
|
|
saveSoon()
|
|
}
|
|
|
|
func jump(_ i: Int) { load(i, play: true) }
|
|
|
|
func setShuffle(_ on: Bool) {
|
|
prefs.shuffle = on
|
|
rebuildOrder(keep: index)
|
|
updatePlan()
|
|
updateNowPlaying()
|
|
publishWidget()
|
|
}
|
|
|
|
func cycleRepeat() {
|
|
prefs.repeatMode = (prefs.repeatMode + 1) % 3
|
|
updatePlan()
|
|
publishWidget()
|
|
}
|
|
|
|
private func rebuildOrder(keep: Int) {
|
|
var o = Array(queue.indices)
|
|
if prefs.shuffle {
|
|
o.shuffle()
|
|
if let p = o.firstIndex(of: keep) { o.swapAt(0, p) }
|
|
}
|
|
order = o
|
|
}
|
|
|
|
/// Next queue index after `i` following shuffle/repeat, or nil at the end.
|
|
func nextIndex(after i: Int, user: Bool) -> Int? {
|
|
guard !queue.isEmpty else { return nil }
|
|
if prefs.repeatMode == 2 && !user { return i }
|
|
guard let p = order.firstIndex(of: i) else { return queue.indices.contains(i + 1) ? i + 1 : nil }
|
|
if p + 1 < order.count { return order[p + 1] }
|
|
return prefs.repeatMode == 1 || user ? order.first : nil
|
|
}
|
|
|
|
// 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
|
|
}
|
|
|
|
func toggle() { isPlaying ? pause() : play() }
|
|
|
|
func play() {
|
|
guard let s = current else {
|
|
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) }
|
|
}
|
|
lastTick = Date()
|
|
startTimer()
|
|
updateNowPlaying()
|
|
publishWidget()
|
|
Scrobbler.shared.nowPlaying(s)
|
|
}
|
|
|
|
func pause(fade: Bool = true) {
|
|
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
|
|
}
|
|
updateNowPlaying()
|
|
publishWidget()
|
|
saveSoon()
|
|
}
|
|
|
|
func stop() {
|
|
isPlaying = false
|
|
stream?.pause()
|
|
stream = nil
|
|
decks.forEach { $0.stop() }
|
|
crossfading = false
|
|
spectrum.reset()
|
|
timer?.invalidate()
|
|
timer = nil
|
|
}
|
|
|
|
func next() {
|
|
finishListen()
|
|
guard let n = nextIndex(after: index, user: true) else { return }
|
|
load(n, play: isPlaying || true)
|
|
}
|
|
|
|
func prev() {
|
|
if position > 3 { seek(0); return }
|
|
finishListen()
|
|
guard let p = order.firstIndex(of: index) else { return }
|
|
let target = p > 0 ? order[p - 1] : (prefs.repeatMode == 1 ? order.last ?? index : index)
|
|
load(target, play: true)
|
|
}
|
|
|
|
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
|
|
}
|
|
basePos = t
|
|
decks[1 - active].stop()
|
|
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()
|
|
}
|
|
|
|
/// Loads queue index `i` on the active deck.
|
|
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
|
|
listenStart = Date()
|
|
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)
|
|
if play {
|
|
try? AVAudioSession.sharedInstance().setActive(true)
|
|
if !engine.isRunning { try? engine.start() }
|
|
decks[0].node.play()
|
|
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) }
|
|
}
|
|
}
|
|
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
|
|
}
|
|
plan.set(after: index, (queue[n], n))
|
|
}
|
|
|
|
/// 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)
|
|
}
|
|
|
|
private func deckDrained(_ d: Int) {
|
|
guard d == active, 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
|
|
}
|
|
if let n = nextIndex(after: index, user: false) {
|
|
load(n, play: true)
|
|
} else {
|
|
pause(fade: false)
|
|
basePos = 0
|
|
seekOnResume = true
|
|
}
|
|
}
|
|
|
|
private var seekOnResume = false
|
|
|
|
private func beginCrossfade(to n: Int) {
|
|
guard !crossfading, queue.indices.contains(n), !queue[n].isStream, let src = Decoder.open(queue[n]) 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
|
|
listenStart = Date()
|
|
listened = 0
|
|
loadArtAndLyrics(queue[n])
|
|
updateNowPlaying()
|
|
publishWidget()
|
|
Scrobbler.shared.nowPlaying(queue[n])
|
|
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?() }
|
|
}
|
|
}
|
|
|
|
private func gain(_ s: Song) -> Float {
|
|
guard prefs.replayGain 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
|
|
|
|
private func startTimer() {
|
|
guard timer == nil else { return }
|
|
timer = Timer.scheduledTimer(withTimeInterval: 0.25, repeats: true) { [weak self] _ in
|
|
MainActor.assumeIsolated { self?.tick() }
|
|
}
|
|
}
|
|
|
|
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) {
|
|
beginCrossfade(to: n)
|
|
}
|
|
if let s = current { Scrobbler.shared.progress(s, listened: listened, duration: duration) }
|
|
if let at = sleepAt, now >= at {
|
|
sleepAt = nil
|
|
fadeOutAndPause()
|
|
}
|
|
if Int(now.timeIntervalSince1970 * 4) % 20 == 0 { saveSoon(); updateNowPlaying() }
|
|
}
|
|
|
|
private func finishListen() {
|
|
guard let s = current 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
|
|
}
|
|
|
|
func sleep(minutes: Int) {
|
|
sleepAtTrackEnd = false
|
|
sleepAt = minutes > 0 ? Date().addingTimeInterval(Double(minutes) * 60) : nil
|
|
}
|
|
|
|
func sleepAtEndOfTrack() {
|
|
sleepAt = nil
|
|
sleepAtTrackEnd = true
|
|
}
|
|
|
|
func cancelSleep() {
|
|
sleepAt = nil
|
|
sleepAtTrackEnd = false
|
|
}
|
|
|
|
private func fadeOutAndPause() {
|
|
let node = decks[active].node
|
|
ramp(node, to: 0, ms: 4000) { [weak self] in self?.pause(fade: false) }
|
|
}
|
|
|
|
// MARK: Art & lyrics
|
|
|
|
private var artToken = 0
|
|
|
|
func loadArtAndLyrics(_ s: Song) {
|
|
artToken += 1
|
|
let tok = artToken
|
|
lyrics = nil
|
|
Task.detached(priority: .userInitiated) {
|
|
let img = Covers.loadFull(s)
|
|
let seed = img.flatMap { Palette.dominant($0.cgImage) }
|
|
await MainActor.run {
|
|
let p = Player.shared
|
|
guard tok == p.artToken else { return }
|
|
p.art = img
|
|
p.seed = seed
|
|
Theme.shared.update()
|
|
p.updateNowPlaying()
|
|
p.publishWidget()
|
|
}
|
|
let lr = Lyrics.load(s)
|
|
await MainActor.run {
|
|
let p = Player.shared
|
|
guard tok == p.artToken else { return }
|
|
p.lyrics = lr
|
|
p.publishWidget()
|
|
}
|
|
}
|
|
}
|
|
|
|
func reloadLyrics(online: Bool) {
|
|
guard let s = current else { return }
|
|
Lyrics.clearCache(s)
|
|
let tok = artToken
|
|
Task.detached {
|
|
let lr = Lyrics.load(s, forceOnline: online)
|
|
await MainActor.run {
|
|
guard tok == Player.shared.artToken else { return }
|
|
Player.shared.lyrics = lr
|
|
}
|
|
}
|
|
}
|
|
|
|
// MARK: Widget snapshot
|
|
|
|
func publishWidget() {
|
|
WidgetBridge.publish(song: current, playing: isPlaying, position: position, duration: duration,
|
|
art: art, palette: Theme.shared.palette, lyrics: lyrics,
|
|
shuffle: prefs.shuffle, repeatMode: prefs.repeatMode)
|
|
}
|
|
|
|
// MARK: Persist queue (Android saveQueue/restoreQueue)
|
|
|
|
private struct Saved: Codable {
|
|
var paths: [String]
|
|
var index: Int
|
|
var position: Double
|
|
}
|
|
|
|
private var saveScheduled = false
|
|
private var queueFile: URL { Library.support.appendingPathComponent("queue.json") }
|
|
|
|
func saveSoon() {
|
|
guard !saveScheduled else { return }
|
|
saveScheduled = true
|
|
DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in
|
|
guard let self else { return }
|
|
self.saveScheduled = false
|
|
let saved = Saved(paths: self.queue.map(\.id), index: self.index, position: self.position)
|
|
if let d = try? JSONEncoder().encode(saved) { try? d.write(to: self.queueFile, options: .atomic) }
|
|
}
|
|
}
|
|
|
|
private func restore() {
|
|
guard prefs.resume, let d = try? Data(contentsOf: queueFile),
|
|
let saved = try? JSONDecoder().decode(Saved.self, from: d) else { return }
|
|
let lib = Library.shared
|
|
let songs = saved.paths.compactMap { lib.song(path: $0) ?? (($0.hasPrefix("http")) ? Song(path: $0) : nil) }
|
|
guard !songs.isEmpty else { return }
|
|
queue = songs
|
|
index = min(max(0, saved.index), songs.count - 1)
|
|
rebuildOrder(keep: index)
|
|
basePos = saved.position
|
|
duration = songs[index].duration
|
|
loadArtAndLyrics(songs[index])
|
|
updateNowPlaying()
|
|
}
|
|
|
|
/// Called when the app enters the background or is terminated.
|
|
func persistNow() {
|
|
let saved = Saved(paths: queue.map(\.id), index: index, position: position)
|
|
if let d = try? JSONEncoder().encode(saved) { try? d.write(to: queueFile, options: .atomic) }
|
|
}
|
|
}
|