tvOS 17+ SwiftUI client for the unofficial Yandex Music API: rotor stations with feedback, library, search, artist and album pages, synced lyrics, and system Now Playing integration.
351 lines
11 KiB
Swift
351 lines
11 KiB
Swift
import AVFoundation
|
|
import Foundation
|
|
|
|
/// Where the current queue came from. Rotor queues report feedback and refill
|
|
/// themselves; collections just play to the end.
|
|
enum QueueSource: Equatable {
|
|
case none
|
|
case collection(String)
|
|
case rotor(station: String, name: String)
|
|
}
|
|
|
|
@MainActor
|
|
final class PlayerController: ObservableObject {
|
|
static let shared = PlayerController()
|
|
|
|
enum LyricsState: Equatable {
|
|
case idle
|
|
case loading
|
|
case ready
|
|
case unavailable
|
|
}
|
|
|
|
@Published private(set) var queue: [Track] = []
|
|
@Published private(set) var index = 0
|
|
@Published private(set) var isPlaying = false
|
|
@Published private(set) var source: QueueSource = .none
|
|
@Published private(set) var lyrics: Lyrics?
|
|
@Published private(set) var lyricsState: LyricsState = .idle
|
|
@Published private(set) var likedIDs: Set<String> = []
|
|
|
|
let clock = PlaybackClock()
|
|
|
|
var current: Track? { queue.indices.contains(index) ? queue[index] : nil }
|
|
|
|
let player = AVPlayer()
|
|
|
|
var rotorBatchID: String?
|
|
var isLoading = false
|
|
private var didReportStart = false
|
|
|
|
private var timeObserver: Any?
|
|
private var itemObservation: NSKeyValueObservation?
|
|
private var rateObservation: NSKeyValueObservation?
|
|
private var endObserver: NSObjectProtocol?
|
|
private var interruptionObserver: NSObjectProtocol?
|
|
private var resolveTask: Task<Void, Never>?
|
|
private var lyricsTask: Task<Void, Never>?
|
|
private var ticksSinceNowPlayingCheck = 0
|
|
|
|
private init() {
|
|
// Lossless is several times the size of an MP3, and the default
|
|
// "buffer enough never to stall" policy turns that into a long wait
|
|
// before the first note.
|
|
player.automaticallyWaitsToMinimizeStalling = false
|
|
|
|
configureAudioSession()
|
|
configureRemoteCommands()
|
|
observePlayer()
|
|
}
|
|
|
|
// MARK: - Queue
|
|
|
|
func play(tracks: [Track], startAt: Int = 0, source: QueueSource) {
|
|
let playable = tracks.filter { $0.available ?? true }
|
|
guard !playable.isEmpty else { return }
|
|
|
|
// Keep the chosen track selected even if unavailable ones were dropped.
|
|
let anchor = tracks.indices.contains(startAt) ? tracks[startAt].trackID : nil
|
|
|
|
queue = playable
|
|
index = anchor.flatMap { id in playable.firstIndex { $0.trackID == id } } ?? 0
|
|
rotorBatchID = nil
|
|
self.source = source
|
|
loadCurrent()
|
|
}
|
|
|
|
func togglePlayPause() {
|
|
guard player.currentItem != nil else {
|
|
if current != nil { loadCurrent() }
|
|
return
|
|
}
|
|
if isPlaying {
|
|
player.pause()
|
|
} else {
|
|
player.play()
|
|
}
|
|
isPlaying.toggle()
|
|
updateNowPlaying()
|
|
}
|
|
|
|
func next() {
|
|
advance(skipped: true)
|
|
}
|
|
|
|
func previous() {
|
|
guard clock.currentTime <= 5, index > 0 else {
|
|
seek(to: 0)
|
|
return
|
|
}
|
|
index -= 1
|
|
loadCurrent()
|
|
}
|
|
|
|
func seek(to seconds: Double) {
|
|
player.seek(
|
|
to: CMTime(seconds: max(0, seconds), preferredTimescale: 600),
|
|
toleranceBefore: .zero,
|
|
toleranceAfter: .zero
|
|
)
|
|
clock.currentTime = seconds
|
|
updateNowPlaying()
|
|
}
|
|
|
|
/// Called when a track ends or is skipped.
|
|
func advance(skipped: Bool) {
|
|
reportTrackEnded(skipped: skipped)
|
|
|
|
if index + 1 < queue.count {
|
|
index += 1
|
|
loadCurrent()
|
|
topUpRotorIfNeeded()
|
|
} else if case let .rotor(station, name) = source {
|
|
extendRotor(station: station, name: name)
|
|
} else {
|
|
player.pause()
|
|
isPlaying = false
|
|
updateNowPlaying()
|
|
}
|
|
}
|
|
|
|
func appendToQueue(_ tracks: [Track]) {
|
|
let known = Set(queue.map(\.trackID))
|
|
queue.append(contentsOf: tracks.filter { !known.contains($0.trackID) })
|
|
}
|
|
|
|
func startPlaying(at index: Int) {
|
|
self.index = index
|
|
loadCurrent()
|
|
}
|
|
|
|
func setQueue(_ tracks: [Track], source: QueueSource) {
|
|
queue = tracks
|
|
index = 0
|
|
self.source = source
|
|
loadCurrent()
|
|
}
|
|
|
|
func stopForEmptyStation() {
|
|
isLoading = false
|
|
isPlaying = false
|
|
}
|
|
|
|
// MARK: - Likes
|
|
|
|
func isLiked(_ track: Track?) -> Bool {
|
|
guard let track else { return false }
|
|
return likedIDs.contains(track.trackID) || likedIDs.contains(track.id.value)
|
|
}
|
|
|
|
func refreshLikes() async {
|
|
guard let ids = try? await YMClient.shared.likedTrackIDs() else { return }
|
|
likedIDs = ids
|
|
}
|
|
|
|
/// Updates the local set immediately so the heart responds without waiting
|
|
/// on the round trip.
|
|
func toggleLikeCurrent() async {
|
|
guard let track = current else { return }
|
|
let wanted = !isLiked(track)
|
|
do {
|
|
try await YMClient.shared.setLiked(wanted, trackID: track.trackID)
|
|
for id in [track.trackID, track.id.value] {
|
|
if wanted { likedIDs.insert(id) } else { likedIDs.remove(id) }
|
|
}
|
|
} catch {
|
|
log.error("like: \(error.localizedDescription)")
|
|
}
|
|
}
|
|
|
|
// MARK: - Loading
|
|
|
|
private func loadCurrent() {
|
|
guard let track = current else { return }
|
|
|
|
resolveTask?.cancel()
|
|
itemObservation?.invalidate()
|
|
isLoading = true
|
|
clock.currentTime = 0
|
|
clock.duration = track.duration
|
|
didReportStart = false
|
|
updateNowPlaying()
|
|
loadLyrics(for: track)
|
|
|
|
let trackID = track.trackID
|
|
resolveTask = Task { [weak self] in
|
|
do {
|
|
let stream = try await StreamResolver.resolve(trackID: trackID, preferring: .fileInfo)
|
|
guard !Task.isCancelled, let self, self.current?.trackID == trackID else { return }
|
|
self.attach(stream)
|
|
} catch {
|
|
guard !Task.isCancelled, let self else { return }
|
|
log.error("stream \(trackID): \(error.localizedDescription)")
|
|
self.isLoading = false
|
|
self.isPlaying = false
|
|
}
|
|
}
|
|
}
|
|
|
|
private func attach(_ stream: ResolvedStream) {
|
|
let item = AVPlayerItem(url: stream.url)
|
|
// A modest read-ahead instead of racing to fill the whole buffer.
|
|
item.preferredForwardBufferDuration = 10
|
|
|
|
itemObservation = item.observe(\.status, options: [.new]) { [weak self] item, _ in
|
|
Task { @MainActor in
|
|
guard let self else { return }
|
|
switch item.status {
|
|
case .readyToPlay:
|
|
self.isLoading = false
|
|
let duration = item.duration.seconds
|
|
if duration.isFinite, duration > 0 { self.clock.duration = duration }
|
|
self.player.play()
|
|
self.isPlaying = true
|
|
self.reportTrackStarted()
|
|
self.updateNowPlaying()
|
|
case .failed:
|
|
log.error("playback: \(item.error?.localizedDescription ?? "unknown")")
|
|
self.isLoading = false
|
|
self.isPlaying = false
|
|
default:
|
|
break
|
|
}
|
|
}
|
|
}
|
|
player.replaceCurrentItem(with: item)
|
|
}
|
|
|
|
private func loadLyrics(for track: Track) {
|
|
lyricsTask?.cancel()
|
|
lyrics = nil
|
|
|
|
guard track.lyricsInfo?.hasSynced ?? true else {
|
|
lyricsState = .unavailable
|
|
return
|
|
}
|
|
lyricsState = .loading
|
|
|
|
let trackID = track.trackID
|
|
lyricsTask = Task { [weak self] in
|
|
let loaded = try? await LyricsService.load(trackID: trackID)
|
|
guard !Task.isCancelled, let self, self.current?.trackID == trackID else { return }
|
|
if let loaded, loaded.synced, !loaded.lines.isEmpty {
|
|
self.lyrics = loaded
|
|
self.lyricsState = .ready
|
|
} else {
|
|
self.lyricsState = .unavailable
|
|
}
|
|
}
|
|
}
|
|
|
|
private func reportTrackStarted() {
|
|
guard !didReportStart else { return }
|
|
didReportStart = true
|
|
reportRotorTrackStarted()
|
|
}
|
|
|
|
// MARK: - Observation
|
|
|
|
private func observePlayer() {
|
|
timeObserver = player.addPeriodicTimeObserver(
|
|
forInterval: CMTime(seconds: 0.2, preferredTimescale: 600),
|
|
queue: .main
|
|
) { [weak self] time in
|
|
Task { @MainActor in
|
|
guard let self else { return }
|
|
self.clock.currentTime = time.seconds.isFinite ? time.seconds : 0
|
|
if let duration = self.player.currentItem?.duration.seconds,
|
|
duration.isFinite, duration > 0 {
|
|
self.clock.duration = duration
|
|
}
|
|
self.tickNowPlaying()
|
|
}
|
|
}
|
|
|
|
endObserver = NotificationCenter.default.addObserver(
|
|
forName: .AVPlayerItemDidPlayToEndTime,
|
|
object: nil,
|
|
queue: .main
|
|
) { [weak self] _ in
|
|
Task { @MainActor in self?.advance(skipped: false) }
|
|
}
|
|
|
|
// Stay honest if AVPlayer stalls or resumes on its own.
|
|
rateObservation = player.observe(\.timeControlStatus, options: [.new]) { [weak self] player, _ in
|
|
Task { @MainActor in
|
|
guard let self else { return }
|
|
let playing = player.timeControlStatus == .playing
|
|
guard playing != self.isPlaying, !self.isLoading else { return }
|
|
self.isPlaying = playing
|
|
self.updateNowPlaying()
|
|
}
|
|
}
|
|
}
|
|
|
|
private func configureAudioSession() {
|
|
do {
|
|
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
|
|
try AVAudioSession.sharedInstance().setActive(true)
|
|
} catch {
|
|
log.error("audio session: \(error.localizedDescription)")
|
|
}
|
|
|
|
interruptionObserver = NotificationCenter.default.addObserver(
|
|
forName: AVAudioSession.interruptionNotification,
|
|
object: AVAudioSession.sharedInstance(),
|
|
queue: .main
|
|
) { [weak self] note in
|
|
Task { @MainActor in
|
|
guard let self,
|
|
let raw = note.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt,
|
|
let type = AVAudioSession.InterruptionType(rawValue: raw)
|
|
else { return }
|
|
|
|
switch type {
|
|
case .began:
|
|
self.player.pause()
|
|
self.isPlaying = false
|
|
case .ended:
|
|
let options = (note.userInfo?[AVAudioSessionInterruptionOptionKey] as? UInt)
|
|
.map(AVAudioSession.InterruptionOptions.init(rawValue:)) ?? []
|
|
guard options.contains(.shouldResume) else { return }
|
|
try? AVAudioSession.sharedInstance().setActive(true)
|
|
self.player.play()
|
|
self.isPlaying = true
|
|
@unknown default:
|
|
return
|
|
}
|
|
self.updateNowPlaying()
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Republishes Now Playing once a second if the system has dropped it.
|
|
private func tickNowPlaying() {
|
|
ticksSinceNowPlayingCheck += 1
|
|
guard ticksSinceNowPlayingCheck >= 5 else { return }
|
|
ticksSinceNowPlayingCheck = 0
|
|
repairNowPlayingIfNeeded()
|
|
}
|
|
}
|