Yandex Music client for Apple TV

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.
This commit is contained in:
2026-09-17 20:38:19 +03:00
commit acd50280bc
70 changed files with 4588 additions and 0 deletions
+11
View File
@@ -0,0 +1,11 @@
import Foundation
/// Playback position, published separately from `PlayerController`.
///
/// It ticks five times a second. Anything observing it re-renders that often,
/// so only the transport bar and the lyrics watch it.
@MainActor
final class PlaybackClock: ObservableObject {
@Published var currentTime: Double = 0
@Published var duration: Double = 0
}
@@ -0,0 +1,116 @@
import MediaPlayer
import UIKit
/// Feeds the tvOS Now Playing card and the Siri Remote.
///
/// `MPNowPlayingInfoCenter.playbackState` is entitlement-gated and rejected for
/// third-party apps, so playback state travels through `playbackRate` instead.
extension PlayerController {
func configureRemoteCommands() {
let center = MPRemoteCommandCenter.shared()
// Declaring which commands exist is what makes the Control Center card
// and the screensaver overlay draw the right buttons.
for command in [
center.seekForwardCommand, center.seekBackwardCommand,
center.skipForwardCommand, center.skipBackwardCommand,
center.ratingCommand, center.likeCommand, center.dislikeCommand,
center.bookmarkCommand, center.changeRepeatModeCommand,
center.changeShuffleModeCommand, center.enableLanguageOptionCommand,
] {
command.isEnabled = false
}
for command in [
center.playCommand, center.pauseCommand, center.togglePlayPauseCommand,
center.nextTrackCommand, center.previousTrackCommand,
center.changePlaybackPositionCommand,
] {
command.isEnabled = true
}
center.playCommand.addTarget { [weak self] _ in
Task { @MainActor in
guard self?.isPlaying == false else { return }
self?.togglePlayPause()
}
return .success
}
center.pauseCommand.addTarget { [weak self] _ in
Task { @MainActor in
guard self?.isPlaying == true else { return }
self?.togglePlayPause()
}
return .success
}
center.togglePlayPauseCommand.addTarget { [weak self] _ in
Task { @MainActor in self?.togglePlayPause() }
return .success
}
center.nextTrackCommand.addTarget { [weak self] _ in
Task { @MainActor in self?.next() }
return .success
}
center.previousTrackCommand.addTarget { [weak self] _ in
Task { @MainActor in self?.previous() }
return .success
}
center.changePlaybackPositionCommand.addTarget { [weak self] event in
guard let event = event as? MPChangePlaybackPositionCommandEvent else { return .commandFailed }
Task { @MainActor in self?.seek(to: event.positionTime) }
return .success
}
}
func updateNowPlaying() {
let center = MPNowPlayingInfoCenter.default()
guard let track = current else {
center.nowPlayingInfo = nil
return
}
var info: [String: Any] = [
MPMediaItemPropertyTitle: track.displayTitle,
MPMediaItemPropertyArtist: track.artistNames,
MPMediaItemPropertyPlaybackDuration: clock.duration,
MPNowPlayingInfoPropertyElapsedPlaybackTime: clock.currentTime,
MPNowPlayingInfoPropertyPlaybackRate: isPlaying ? 1.0 : 0.0,
MPNowPlayingInfoPropertyDefaultPlaybackRate: 1.0,
MPNowPlayingInfoPropertyMediaType: MPNowPlayingInfoMediaType.audio.rawValue,
MPNowPlayingInfoPropertyIsLiveStream: false,
MPNowPlayingInfoPropertyExternalContentIdentifier: track.trackID,
]
if let album = track.albums?.first?.title {
info[MPMediaItemPropertyAlbumTitle] = album
}
if !queue.isEmpty {
info[MPNowPlayingInfoPropertyPlaybackQueueCount] = queue.count
info[MPNowPlayingInfoPropertyPlaybackQueueIndex] = index
}
center.nowPlayingInfo = info
loadArtwork(for: track)
}
/// Something else on tvOS can clear the card; put it back if it is gone.
func repairNowPlayingIfNeeded() {
guard let track = current else { return }
let published = MPNowPlayingInfoCenter.default().nowPlayingInfo?[MPMediaItemPropertyTitle] as? String
guard published != track.displayTitle else { return }
updateNowPlaying()
}
private func loadArtwork(for track: Track) {
guard let url = track.coverURL(size: 300) else { return }
let trackID = track.trackID
Task {
guard let image = await ImageCache.shared.image(for: url),
current?.trackID == trackID
else { return }
var info = MPNowPlayingInfoCenter.default().nowPlayingInfo ?? [:]
info[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { _ in image }
MPNowPlayingInfoCenter.default().nowPlayingInfo = info
}
}
}
+112
View File
@@ -0,0 +1,112 @@
import Foundation
/// Rotor stations are an endless chain: the server hands out a batch, the
/// client reports what happened to each track, and asks for more by naming the
/// last one it played.
extension PlayerController {
private static let clientName = "appletv-yamusek"
private static func resumeKey(_ station: String) -> String {
"rotorResume.\(station)"
}
func startRotor(station: String, name: String) {
isLoading = true
Task {
// Announce the start before asking for tracks, and continue from
// where this station left off; otherwise it replays its opening.
await YMClient.shared.rotorFeedback(
station: station,
type: "radioStarted",
from: Self.clientName
)
let resume = UserDefaults.standard.string(forKey: Self.resumeKey(station))
guard let result = try? await YMClient.shared.rotorTracks(station: station, queue: resume) else {
stopForEmptyStation()
return
}
var tracks = result.sequence.compactMap(\.track)
if let resume, tracks.count > 1, tracks.first?.trackID == resume {
tracks.removeFirst()
}
guard !tracks.isEmpty else {
stopForEmptyStation()
return
}
rotorBatchID = result.batchId
setQueue(tracks, source: .rotor(station: station, name: name))
}
}
/// Saved on start rather than on finish: a few seconds of listening is
/// enough for the station to move on next time.
func reportRotorTrackStarted() {
guard case let .rotor(station, _) = source, let track = current else { return }
let id = track.trackID
let batch = rotorBatchID
UserDefaults.standard.set(id, forKey: Self.resumeKey(station))
Task {
await YMClient.shared.rotorFeedback(
station: station,
type: "trackStarted",
trackID: id,
batchID: batch
)
}
}
func reportTrackEnded(skipped: Bool) {
guard case let .rotor(station, _) = source, let track = current else { return }
let id = track.trackID
let batch = rotorBatchID
let played = clock.currentTime
Task {
await YMClient.shared.rotorFeedback(
station: station,
type: skipped ? "skip" : "trackFinished",
trackID: id,
batchID: batch,
totalPlayedSeconds: played
)
}
}
/// Fetches the next batch while a couple of tracks are still queued.
func topUpRotorIfNeeded() {
guard case let .rotor(station, _) = source, queue.count - index <= 2 else { return }
let last = queue.last?.trackID
Task {
guard let result = try? await YMClient.shared.rotorTracks(station: station, queue: last) else { return }
rotorBatchID = result.batchId ?? rotorBatchID
appendToQueue(result.sequence.compactMap(\.track))
}
}
/// The queue ran dry; pull more and keep going.
func extendRotor(station: String, name: String) {
isLoading = true
let last = queue.last?.trackID
Task {
guard let result = try? await YMClient.shared.rotorTracks(station: station, queue: last) else {
stopForEmptyStation()
return
}
rotorBatchID = result.batchId ?? rotorBatchID
let before = queue.count
appendToQueue(result.sequence.compactMap(\.track))
guard queue.count > before else {
stopForEmptyStation()
return
}
startPlaying(at: before)
}
}
}
+350
View File
@@ -0,0 +1,350 @@
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()
}
}