PulseCanvas / app · pulsecanvas.ai / Sources / PulseCanvas / RadioController.swift
| 1 | import Combine |
| 2 | import Foundation |
| 3 | |
| 4 | @MainActor |
| 5 | final class RadioController: ObservableObject { |
| 6 | let visualizer = RenderState() |
| 7 | @Published private(set) var catalog: RadioCatalog? |
| 8 | @Published private(set) var stations: [RadioStation] = [] |
| 9 | @Published private(set) var stationID = "all-music" |
| 10 | @Published private(set) var currentIndex: Int? |
| 11 | @Published private(set) var isActive = false |
| 12 | @Published private(set) var isLoading = false |
| 13 | @Published private(set) var isCatalogLoading = false |
| 14 | @Published private(set) var catalogError: String? |
| 15 | @Published private(set) var status = String(localized: "Choose a radio library to begin") |
| 16 | var visualizerGroup: VisualizerRandomizerGroup { presets.randomizerGroup } |
| 17 | @Published private(set) var favoriteSongsOnly = false |
| 18 | @Published private(set) var visualizerChoices: [Int] = [] |
| 19 | var usesFavorites: Bool { visualizerGroup == .favorites && visualizerChoices.contains { presets.isFavorite($0) } } |
| 20 | var canRandomizeVisualizer: Bool { !isLoading && visualizerChoices.contains { $0 != visualizer.scene } } |
| 21 | var visualizerGroupMessage: String? { |
| 22 | if let message = presets.favoritesFallbackMessage { return message } |
| 23 | guard visualizerChoices.isEmpty else { return nil } |
| 24 | return visualizerGroup == .favorites |
| 25 | ? "No favorite visualizers in this pool. Add a heart or choose another group." |
| 26 | : "No visualizers in this group. Choose another group or change the visualizer pool." |
| 27 | } |
| 28 | var musicGroupID: String { isPersonalMusic ? "my-music" : favoriteSongsOnly ? "favorite-songs" : stationID } |
| 29 | var eligibleTrackIndices: [Int] { |
| 30 | guard let catalog else { return [] } |
| 31 | let favorites = Set(favoriteSongs.map(\.id)) |
| 32 | return catalog.tracks.indices.filter { !favoriteSongsOnly || favorites.contains(catalog.tracks[$0].id) } |
| 33 | } |
| 34 | @Published private(set) var sceneTitle = "" |
| 35 | @Published private(set) var favoriteSongs: [FavoriteRadioSong] = [] |
| 36 | @Published private(set) var favoritePlaybackError: String? |
| 37 | private let favoriteSongsKey = "PulseCanvas.radio.favoriteSongs.v1" |
| 38 | @Published var volume: Float = 0.7 { |
| 39 | didSet { |
| 40 | defaults.set(volume, forKey: "PulseCanvas.radio.volume") |
| 41 | if isActive { audio?.volume = volume } |
| 42 | } |
| 43 | } |
| 44 | @Published var barsPerVisualizer: Int = 4 { |
| 45 | didSet { |
| 46 | guard Self.barChoices.contains(barsPerVisualizer) else { barsPerVisualizer = 4; return } |
| 47 | defaults.set(barsPerVisualizer, forKey: "PulseCanvas.radio.bars") |
| 48 | if isActive && !isLoading { rebuildVisuals() } |
| 49 | } |
| 50 | } |
| 51 | static let barChoices = [1, 2, 4, 8, 16] |
| 52 | @Published var shuffle = true { didSet { queue.reset(); discardPrefetch() } } |
| 53 | @Published private(set) var sourceText: String |
| 54 | var studioMusicSource: URL { (isPersonalMusic ? nil : directoryURL) ?? URL(string: sourceText) ?? URL(string: "https://radio.pulsecanvas.si/stations.json")! } |
| 55 | var studioMusicFolderBookmark: Data? { defaults.data(forKey: "PulseCanvas.radio.folderBookmark") } |
| 56 | var studioMusicLibrary: RadioLibrary { library } |
| 57 | @Published private(set) var isPersonalMusic = false |
| 58 | @Published private(set) var folderImportNotice: String? |
| 59 | var hasPersonalMusic: Bool { defaults.url(forKey: PersonalRadioMusic.catalogKey) != nil } |
| 60 | private var personalImportTask: Task<Void, Never>? |
| 61 | var canFavoriteCurrentSong: Bool { !isPersonalMusic } |
| 62 | private(set) var segments: [StudioSegment] = [] |
| 63 | let soundtrackInstalled = PassthroughSubject<Void, Never>() |
| 64 | var currentTrack: RadioTrack? { currentIndex.flatMap { catalog?.tracks.indices.contains($0) == true ? catalog?.tracks[$0] : nil } } |
| 65 | var stationTitle: String { if isPersonalMusic { return catalog?.title ?? String(localized: "My music folder") }; return stations.first { $0.id == stationID }?.title ?? catalog?.title ?? String(localized: "All Music") } |
| 66 | var canStart: Bool { !eligibleTrackIndices.isEmpty && !visualizerChoices.isEmpty && !isCatalogLoading } |
| 67 | var canSeek: Bool { isActive && hasRadioAudio && !isLoading } |
| 68 | private let library: RadioLibrary |
| 69 | private let defaults: UserDefaults |
| 70 | private let presets: ProjectMPresets |
| 71 | private var directoryURL: URL? |
| 72 | private var catalogURL: URL? |
| 73 | private var catalogAccess: SecurityScopedAccess? |
| 74 | private var queue = RadioQueue() |
| 75 | private var task: Task<Void, Never>? |
| 76 | private var prefetch: Task<Void, Never>? |
| 77 | private var upcomingIndex: Int? |
| 78 | private var preparedNext: (index: Int, audio: PreparedSoundtrack)? |
| 79 | private var revision = UUID() |
| 80 | private var wantsPlayback = true |
| 81 | private var requestedIndex: Int? |
| 82 | private var hasRadioAudio = false |
| 83 | private var refreshingFavorites = false |
| 84 | private var visualFavoritesObserver: AnyCancellable? |
| 85 | private var visualPoolObserver: AnyCancellable? |
| 86 | private var visualCatalogObserver: AnyCancellable? |
| 87 | private var playedVisualizers = Set<Int>() |
| 88 | private weak var audio: AudioController? |
| 89 | private var snapshot: Snapshot? |
| 90 | private struct Snapshot { |
| 91 | let prepared: PreparedSoundtrack? |
| 92 | let url: URL? |
| 93 | let bookmark: Data? |
| 94 | let progress: Double |
| 95 | let title: String |
| 96 | let loop: Bool |
| 97 | let volume: Float |
| 98 | } |
| 99 | |
| 100 | init(library: RadioLibrary = RadioLibrary(), defaults: UserDefaults = .standard, presets: ProjectMPresets? = nil) { |
| 101 | self.library = library; self.defaults = defaults; self.presets = presets ?? .shared |
| 102 | sourceText = defaults.string(forKey: "PulseCanvas.radio.catalogURL") |
| 103 | ?? Bundle.main.object(forInfoDictionaryKey: "PulseCanvasRadioCatalogURL") as? String |
| 104 | ?? "https://radio.pulsecanvas.si/stations.json" |
| 105 | if let data = defaults.data(forKey: favoriteSongsKey), data.count <= 8_000_000, |
| 106 | let saved = try? JSONDecoder().decode([FavoriteRadioSong].self, from: data), saved.count <= 2_000 { |
| 107 | var seen = Set<String>() |
| 108 | favoriteSongs = saved.filter { $0.isValid && seen.insert($0.id).inserted } |
| 109 | } |
| 110 | visualizerChoices = self.presets.eligibleScenes |
| 111 | favoriteSongsOnly = defaults.bool(forKey: "PulseCanvas.radio.favoriteSongsOnly.v1") |
| 112 | let bars = defaults.integer(forKey: "PulseCanvas.radio.bars") |
| 113 | barsPerVisualizer = Self.barChoices.contains(bars) ? bars : 4 |
| 114 | if let savedVolume = defaults.object(forKey: "PulseCanvas.radio.volume") as? NSNumber { |
| 115 | let value = savedVolume.floatValue |
| 116 | volume = value.isFinite ? min(1, max(0, value)) : 0.7 |
| 117 | } |
| 118 | visualFavoritesObserver = self.presets.$favoriteIDs.dropFirst().sink { [weak self] _ in |
| 119 | // @Published sends before storing the new set; read it on the next turn. |
| 120 | Task { @MainActor [weak self] in |
| 121 | guard let self, self.presets.pool.enabled, self.presets.pool.favoritesOnly else { return } |
| 122 | self.refreshVisualizerGroup() |
| 123 | } |
| 124 | } |
| 125 | visualPoolObserver = self.presets.$pool.dropFirst().sink { [weak self] _ in |
| 126 | Task { @MainActor [weak self] in |
| 127 | guard let self else { return } |
| 128 | self.refreshVisualizerGroup() |
| 129 | } |
| 130 | } |
| 131 | visualCatalogObserver = self.presets.$entries.dropFirst().sink { [weak self] _ in |
| 132 | Task { @MainActor [weak self] in self?.refreshVisualizerGroup() } |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | func selectVisualizerGroup(_ group: VisualizerRandomizerGroup) { |
| 137 | presets.setRandomizerGroup(group) |
| 138 | refreshVisualizerGroup() |
| 139 | } |
| 140 | |
| 141 | /// Keep transport and bar boundaries intact; replace an out-of-group current look immediately. |
| 142 | private func refreshVisualizerGroup() { |
| 143 | visualizerChoices = presets.eligibleScenes |
| 144 | guard isActive, !isLoading, let audio else { return } |
| 145 | let available = visualizerChoices |
| 146 | if !available.isEmpty, !available.contains(visualizer.scene), |
| 147 | let index = StudioTimeline.index(at: audio.playbackSeconds, in: segments), |
| 148 | let scene = available.randomElement() { |
| 149 | segments[index].scene = scene |
| 150 | sceneTitle = "" |
| 151 | follow(time: audio.playbackSeconds) |
| 152 | } |
| 153 | rebuildVisuals(keepingCurrent: true) |
| 154 | } |
| 155 | |
| 156 | func selectMusicGroup(_ id: String, startPlayback: Bool = false) { |
| 157 | if id == "my-music" { usePersonalMusic(startPlayback: startPlayback); return } |
| 158 | if isPersonalMusic { |
| 159 | favoriteSongsOnly = id == "favorite-songs" |
| 160 | defaults.set(favoriteSongsOnly, forKey: "PulseCanvas.radio.favoriteSongsOnly.v1") |
| 161 | let station = favoriteSongsOnly ? "all-music" : id |
| 162 | loadCatalog(at: studioMusicSource, preferredStationID: station, startPlayback: isActive || startPlayback) |
| 163 | return |
| 164 | } |
| 165 | let favorites = id == "favorite-songs" |
| 166 | favoriteSongsOnly = favorites |
| 167 | defaults.set(favorites, forKey: "PulseCanvas.radio.favoriteSongsOnly.v1") |
| 168 | queue.reset(); discardPrefetch() |
| 169 | let station = favorites ? "all-music" : id |
| 170 | defaults.set(station, forKey: "PulseCanvas.radio.station") |
| 171 | selectStation(station, startPlayback: startPlayback) |
| 172 | if startPlayback, !isCatalogLoading { start() } |
| 173 | if isActive, !isCatalogLoading, let currentIndex, let catalog, let catalogURL { |
| 174 | prepareNextTrack(after: currentIndex, catalog: catalog, catalogURL: catalogURL) |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | func playFavoriteStation() { selectMusicGroup("favorite-songs", startPlayback: true) } |
| 179 | |
| 180 | var canSkipStation: Bool { !isCatalogLoading && stations.contains { $0.id != musicGroupID } } |
| 181 | |
| 182 | func nextStation() { |
| 183 | guard canSkipStation else { return } |
| 184 | let index = stations.firstIndex { $0.id == musicGroupID } |
| 185 | let next = stations[((index ?? -1) + 1) % stations.count] |
| 186 | selectMusicGroup(next.id, startPlayback: true) |
| 187 | } |
| 188 | |
| 189 | func attach(audio: AudioController) { self.audio = audio } |
| 190 | /// Preserve the requested transport state through a temporary download/decode pause. |
| 191 | var isPlaybackRequested: Bool { isLoading ? wantsPlayback : audio?.isPlaying == true } |
| 192 | |
| 193 | func isFavoriteSong(_ track: RadioTrack) -> Bool { favoriteSongs.contains { $0.id == track.id } } |
| 194 | |
| 195 | func toggleFavoriteSong(_ track: RadioTrack) { |
| 196 | _ = setFavoriteSong(id: track.id, favorite: !isFavoriteSong(track)) |
| 197 | } |
| 198 | |
| 199 | @discardableResult |
| 200 | func setFavoriteSong(id: String, favorite: Bool, candidate: FavoriteRadioSong? = nil) -> Bool { |
| 201 | let index = favoriteSongs.firstIndex { $0.id == id } |
| 202 | guard (index != nil) != favorite else { return true } |
| 203 | if let index { |
| 204 | favoriteSongs.remove(at: index) |
| 205 | } else { |
| 206 | let song: FavoriteRadioSong |
| 207 | if let candidate, candidate.id == id { |
| 208 | song = candidate |
| 209 | } else { |
| 210 | guard !isPersonalMusic, let catalogURL, let directoryURL, |
| 211 | let track = catalog?.tracks.first(where: { $0.id == id }) else { return false } |
| 212 | song = FavoriteRadioSong(track: track, sourceURL: directoryURL, catalogURL: catalogURL, |
| 213 | stationID: stationID, folderBookmark: try? catalogAccess?.readOnlyBookmark()) |
| 214 | } |
| 215 | guard favoriteSongs.count < 2_000, song.isValid else { return false } |
| 216 | favoriteSongs.append(song) |
| 217 | } |
| 218 | persistFavoriteSongs() |
| 219 | return true |
| 220 | } |
| 221 | |
| 222 | private func persistFavoriteSongs() { |
| 223 | if let data = try? JSONEncoder().encode(favoriteSongs) { defaults.set(data, forKey: favoriteSongsKey) } |
| 224 | NotificationCenter.default.post(name: .pulseCanvasUserDataChanged, object: nil) |
| 225 | queue.reset(); discardPrefetch() |
| 226 | if isActive, !isLoading, let currentIndex, let catalog, let catalogURL { |
| 227 | prepareNextTrack(after: currentIndex, catalog: catalog, catalogURL: catalogURL) |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | func reloadCloudFavorites() { |
| 232 | guard let data = defaults.data(forKey: favoriteSongsKey), |
| 233 | let songs = try? JSONDecoder().decode([FavoriteRadioSong].self, from: data), songs.count <= 2_000, |
| 234 | songs.allSatisfy(\.isValid) else { return } |
| 235 | favoriteSongs = songs; queue.reset(); discardPrefetch() |
| 236 | } |
| 237 | |
| 238 | func refreshFavoriteSongs() async { |
| 239 | guard !refreshingFavorites else { return } |
| 240 | refreshingFavorites = true |
| 241 | defer { refreshingFavorites = false } |
| 242 | var checked = Set<URL>() |
| 243 | for song in favoriteSongs where checked.insert(song.sourceURL).inserted { |
| 244 | let folder = SecurityScopedAccess.resolve(bookmark: song.folderBookmark, fallback: song.sourceURL.deletingLastPathComponent()) |
| 245 | let source = song.sourceURL.isFileURL ? folder.appendingPathComponent(song.sourceURL.lastPathComponent) : song.sourceURL |
| 246 | let access = source.isFileURL ? SecurityScopedAccess(url: folder) : nil |
| 247 | defer { withExtendedLifetime(access) {} } |
| 248 | guard let complete = try? await library.completeCatalog(at: source), !Task.isCancelled else { continue } |
| 249 | reconcileFavoriteSongs(complete.catalog, source: song.sourceURL, catalogURL: complete.url, station: complete.stationID) |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | private func reconcileFavoriteSongs(_ complete: RadioCatalog, source: URL, catalogURL: URL, station: String) { |
| 254 | let tracks = Dictionary(uniqueKeysWithValues: complete.tracks.map { ($0.id, $0) }) |
| 255 | let retained = favoriteSongs.compactMap { song -> FavoriteRadioSong? in |
| 256 | guard song.sourceURL == source else { return song } |
| 257 | guard let track = tracks[song.id] else { return nil } |
| 258 | return FavoriteRadioSong(track: track, sourceURL: source, catalogURL: catalogURL, |
| 259 | stationID: station, folderBookmark: song.folderBookmark) |
| 260 | } |
| 261 | guard retained != favoriteSongs else { return } |
| 262 | favoriteSongs = retained |
| 263 | persistFavoriteSongs() |
| 264 | } |
| 265 | |
| 266 | func playFavoriteSong(_ song: FavoriteRadioSong) { |
| 267 | guard song.isValid else { return } |
| 268 | favoritePlaybackError = nil |
| 269 | let folder = SecurityScopedAccess.resolve(bookmark: song.folderBookmark, fallback: song.sourceURL.deletingLastPathComponent()) |
| 270 | let source = song.sourceURL.isFileURL ? folder.appendingPathComponent(song.sourceURL.lastPathComponent) : song.sourceURL |
| 271 | loadCatalog(at: source, access: source.isFileURL ? SecurityScopedAccess(url: folder) : nil, |
| 272 | preferredStationID: song.stationID, playTrackID: song.id) |
| 273 | } |
| 274 | |
| 275 | func importMusicFolder(_ folder: URL, into root: URL = PersonalRadioMusic.directory) { |
| 276 | guard !isCatalogLoading else { return } |
| 277 | isCatalogLoading = true; catalogError = nil; folderImportNotice = nil; status = String(localized: "Copying music folder…") |
| 278 | let previous = defaults.url(forKey: PersonalRadioMusic.catalogKey) |
| 279 | personalImportTask = Task { [weak self, library] in |
| 280 | do { |
| 281 | let result = try await library.importMusicFolder(folder, into: root) |
| 282 | guard let self, !Task.isCancelled else { |
| 283 | await library.removePersonalCopy(at: result.url, within: root); return |
| 284 | } |
| 285 | self.folderImportNotice = result.skipped > 0 ? String(localized: "\(result.skipped) unsupported files were skipped.") : nil |
| 286 | self.defaults.set(result.url, forKey: PersonalRadioMusic.catalogKey) |
| 287 | self.isCatalogLoading = false; self.personalImportTask = nil |
| 288 | self.loadCatalog(at: result.url, personal: true, startPlayback: true, skipped: result.skipped) |
| 289 | await library.removePersonalCopy(at: previous, within: root) |
| 290 | } catch { |
| 291 | guard let self, !Task.isCancelled else { return } |
| 292 | self.isCatalogLoading = false; self.catalogError = error.localizedDescription; self.status = error.localizedDescription |
| 293 | } |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | func usePersonalMusic(startPlayback: Bool = true) { |
| 298 | guard let url = defaults.url(forKey: PersonalRadioMusic.catalogKey) else { return } |
| 299 | loadCatalog(at: url, personal: true, startPlayback: startPlayback) |
| 300 | } |
| 301 | |
| 302 | func loadSavedCatalogIfNeeded(refresh: Bool = false) { |
| 303 | if defaults.bool(forKey: PersonalRadioMusic.activeKey), hasPersonalMusic { |
| 304 | if (catalog == nil || refresh) && !isCatalogLoading { usePersonalMusic(startPlayback: false) } |
| 305 | return |
| 306 | } |
| 307 | guard (catalog == nil || refresh), !isCatalogLoading, !sourceText.isEmpty, let url = URL(string: sourceText) else { return } |
| 308 | let bookmark = url.isFileURL ? defaults.data(forKey: "PulseCanvas.radio.folderBookmark") : nil |
| 309 | let directory = SecurityScopedAccess.resolve(bookmark: bookmark, fallback: url.deletingLastPathComponent()) |
| 310 | loadCatalog(at: url.isFileURL ? directory.appendingPathComponent(url.lastPathComponent) : url, |
| 311 | access: url.isFileURL ? SecurityScopedAccess(url: directory) : nil) |
| 312 | } |
| 313 | |
| 314 | /// A stations directory is the public entry point. A direct catalog also works for local testing. |
| 315 | func loadCatalog(at url: URL, access: SecurityScopedAccess? = nil, preferredStationID: String? = nil, playTrackID: String? = nil, personal: Bool = false, startPlayback: Bool = false, skipped: Int = 0) { |
| 316 | leave() |
| 317 | task?.cancel(); revision = UUID(); let token = revision |
| 318 | catalogError = nil; isCatalogLoading = true; status = String(localized: "Loading radio library…") |
| 319 | task = Task { [weak self, library] in |
| 320 | let lease = access |
| 321 | do { |
| 322 | let stationList: [RadioStation] |
| 323 | let stationURL: URL |
| 324 | if url.lastPathComponent == "stations.json" { |
| 325 | let directory = try await library.stations(at: url) |
| 326 | stationList = directory.stations |
| 327 | let savedID = preferredStationID ?? (self?.favoriteSongsOnly == true ? "all-music" : self?.defaults.string(forKey: "PulseCanvas.radio.station")) |
| 328 | let selected = stationList.first { $0.id == savedID } ?? stationList[0] |
| 329 | stationURL = try selected.resolvedURL(relativeTo: url) |
| 330 | } else { |
| 331 | stationList = [RadioStation(id: "all-music", title: "All Music", description: "Every genre, one station", catalog: url.absoluteString)] |
| 332 | stationURL = url |
| 333 | } |
| 334 | let loaded = try await library.catalog(at: stationURL) |
| 335 | try Task.checkCancellation() |
| 336 | guard let self, self.revision == token else { return } |
| 337 | self.catalog = loaded; self.catalogURL = stationURL; self.catalogAccess = lease |
| 338 | self.stations = stationList; self.directoryURL = url |
| 339 | self.stationID = try stationList.first { try $0.resolvedURL(relativeTo: url) == stationURL }?.id ?? stationList[0].id |
| 340 | self.isPersonalMusic = personal |
| 341 | self.defaults.set(personal, forKey: PersonalRadioMusic.activeKey) |
| 342 | if personal { self.favoriteSongsOnly = false } |
| 343 | self.currentIndex = nil; self.queue.reset() |
| 344 | if !personal { |
| 345 | self.sourceText = url.absoluteString |
| 346 | self.defaults.set(url.absoluteString, forKey: "PulseCanvas.radio.catalogURL") |
| 347 | self.defaults.set(try? lease?.readOnlyBookmark(), forKey: "PulseCanvas.radio.folderBookmark") |
| 348 | } |
| 349 | if !personal && (stationList.count == 1 || self.stationID == "all-music") { |
| 350 | self.reconcileFavoriteSongs(loaded, source: url, catalogURL: stationURL, station: self.stationID) |
| 351 | } |
| 352 | self.isCatalogLoading = false; self.status = String(localized: "\(loaded.tracks.count) songs · Ready to play") + (skipped > 0 ? String(localized: " · \(skipped) unsupported files skipped") : "") |
| 353 | Task { [weak self] in await self?.refreshFavoriteSongs() } |
| 354 | if startPlayback { self.start() } |
| 355 | if let playTrackID { |
| 356 | if let index = loaded.tracks.firstIndex(where: { $0.id == playTrackID }) { self.start(at: index) } |
| 357 | else { |
| 358 | self.status = String(localized: "This favorite is no longer available in its radio library.") |
| 359 | self.favoritePlaybackError = self.status |
| 360 | } |
| 361 | } |
| 362 | } catch { |
| 363 | guard let self, self.revision == token else { return } |
| 364 | self.isCatalogLoading = false; self.status = error.localizedDescription; self.catalogError = self.status |
| 365 | if playTrackID != nil { self.favoritePlaybackError = self.status } |
| 366 | } |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | func selectStation(_ id: String, startPlayback: Bool = false) { |
| 371 | guard id != stationID, let station = stations.first(where: { $0.id == id }), let directoryURL, |
| 372 | let url = try? station.resolvedURL(relativeTo: directoryURL) else { return } |
| 373 | let resume = isActive || startPlayback |
| 374 | leave(); revision = UUID(); let token = revision |
| 375 | catalogError = nil; isCatalogLoading = true; status = String(localized: "Loading \(station.title)…") |
| 376 | task = Task { [weak self, library] in |
| 377 | do { |
| 378 | let loaded = try await library.catalog(at: url) |
| 379 | try Task.checkCancellation() |
| 380 | guard let self, self.revision == token else { return } |
| 381 | self.catalog = loaded; self.catalogURL = url; self.stationID = id |
| 382 | self.defaults.set(id, forKey: "PulseCanvas.radio.station") |
| 383 | self.currentIndex = nil; self.queue.reset(); self.isCatalogLoading = false |
| 384 | self.status = String(localized: "\(loaded.tracks.count) songs · Ready to play") |
| 385 | if resume { self.start() } |
| 386 | } catch { |
| 387 | guard let self, self.revision == token else { return } |
| 388 | self.isCatalogLoading = false; self.status = error.localizedDescription; self.catalogError = self.status |
| 389 | } |
| 390 | } |
| 391 | } |
| 392 | |
| 393 | func start(at index: Int? = nil) { |
| 394 | guard canStart, let audio else { return } |
| 395 | if !isActive { |
| 396 | hasRadioAudio = false |
| 397 | snapshot = Snapshot(prepared: audio.retainedSoundtrack(), url: audio.selectedURL, bookmark: audio.soundtrackBookmark, progress: audio.progress, |
| 398 | title: audio.title, loop: audio.loopEnabled, volume: audio.volume) |
| 399 | isActive = true |
| 400 | audio.volume = volume |
| 401 | } |
| 402 | wantsPlayback = true |
| 403 | audio.onSoundtrackFinished = { [weak self] in self?.next() } |
| 404 | guard let selected = index.flatMap({ eligibleTrackIndices.contains($0) ? $0 : nil }) |
| 405 | ?? queuedTrack(after: currentIndex) else { return } |
| 406 | loadTrack(at: selected) |
| 407 | } |
| 408 | |
| 409 | func next() { |
| 410 | guard isActive, let index = upcomingIndex ?? queuedTrack(after: requestedIndex ?? currentIndex) else { return } |
| 411 | loadTrack(at: index) |
| 412 | } |
| 413 | |
| 414 | private func queuedTrack(after current: Int?) -> Int? { |
| 415 | let choices = eligibleTrackIndices |
| 416 | guard let next = queue.next(count: choices.count, current: current.flatMap { choices.firstIndex(of: $0) }, shuffle: shuffle) else { return nil } |
| 417 | return choices[next] |
| 418 | } |
| 419 | |
| 420 | func togglePlayback() { |
| 421 | guard isActive, let audio else { return } |
| 422 | if !isLoading && !hasRadioAudio { start(at: currentIndex); return } |
| 423 | if isLoading { wantsPlayback.toggle(); status = wantsPlayback ? String(localized: "Preparing next song…") : String(localized: "Next song will start paused") } |
| 424 | else { if audio.isPlaying { audio.pause() } else { audio.playFullSoundtrack() }; wantsPlayback = audio.isPlaying } |
| 425 | } |
| 426 | |
| 427 | func seek(fraction: Double) { |
| 428 | guard canSeek, fraction.isFinite, let audio else { return } |
| 429 | audio.seek(fraction: fraction) |
| 430 | follow(time: audio.playbackSeconds) |
| 431 | } |
| 432 | |
| 433 | /// Reroll only within the selected group, without restarting the music. |
| 434 | func randomizeCurrentVisualizer() { |
| 435 | guard isActive, !isLoading, let audio, |
| 436 | let index = StudioTimeline.index(at: audio.playbackSeconds, in: segments) else { return } |
| 437 | let alternatives = visualizerChoices.filter { $0 != visualizer.scene } |
| 438 | let unheard = alternatives.filter { !playedVisualizers.contains($0) } |
| 439 | guard let scene = (unheard.isEmpty ? alternatives : unheard).randomElement() else { return } |
| 440 | segments[index].scene = scene |
| 441 | follow(time: audio.playbackSeconds) |
| 442 | rebuildVisuals(keepingCurrent: true) |
| 443 | } |
| 444 | |
| 445 | func pause() { |
| 446 | wantsPlayback = false; audio?.pause() |
| 447 | if isLoading { task?.cancel(); revision = UUID(); isLoading = false; requestedIndex = nil; status = String(localized: "Radio paused") } |
| 448 | } |
| 449 | |
| 450 | func leave() { |
| 451 | personalImportTask?.cancel(); personalImportTask = nil |
| 452 | task?.cancel(); discardPrefetch(); revision = UUID() |
| 453 | isCatalogLoading = false; isLoading = false; requestedIndex = nil |
| 454 | guard isActive, let audio else { return } |
| 455 | audio.onSoundtrackFinished = nil; audio.pause(); isActive = false |
| 456 | if let saved = snapshot { |
| 457 | if let prepared = saved.prepared { |
| 458 | if audio.install(prepared, title: saved.title) { audio.seek(fraction: saved.progress) } |
| 459 | } else if let url = saved.url { |
| 460 | if audio.load(url: url, bookmark: saved.bookmark) { audio.seek(fraction: saved.progress) } |
| 461 | } else { audio.clear() } |
| 462 | audio.loopEnabled = saved.loop |
| 463 | audio.volume = saved.volume |
| 464 | soundtrackInstalled.send() |
| 465 | } |
| 466 | snapshot = nil; segments = []; hasRadioAudio = false; status = String(localized: "Radio stopped · Your soundtrack restored") |
| 467 | } |
| 468 | |
| 469 | /// App shutdown cancels downloads and completions without reloading the editor song. |
| 470 | func shutdown() { |
| 471 | personalImportTask?.cancel() |
| 472 | task?.cancel(); discardPrefetch(); revision = UUID() |
| 473 | audio?.onSoundtrackFinished = nil; audio?.stop() |
| 474 | isActive = false; isLoading = false; isCatalogLoading = false |
| 475 | requestedIndex = nil; snapshot = nil; segments = []; hasRadioAudio = false |
| 476 | } |
| 477 | |
| 478 | func follow(time: Double) { |
| 479 | guard isActive, let index = StudioTimeline.index(at: time, in: segments) else { return } |
| 480 | let scene = segments[index].scene |
| 481 | playedVisualizers.insert(scene) |
| 482 | guard visualizer.scene != scene || sceneTitle.isEmpty else { return } |
| 483 | visualizer.scene = scene |
| 484 | presets.appearanceForSelection(scene).apply(to: visualizer) |
| 485 | sceneTitle = RenderState.sceneNames[scene] |
| 486 | } |
| 487 | |
| 488 | private func rebuildVisuals(keepingCurrent: Bool = false, previousScene: Int? = nil) { |
| 489 | guard let audio, let plan = audio.segmentPlan(beatsPerSection: barsPerVisualizer * 4) else { return } |
| 490 | visualizerChoices = presets.eligibleScenes |
| 491 | let available = visualizerChoices |
| 492 | if !sceneTitle.isEmpty, let index = StudioTimeline.index(at: audio.playbackSeconds, in: segments) { |
| 493 | var retained = Array(segments.prefix(index + 1)) |
| 494 | let last = retained.removeLast() |
| 495 | let end = keepingCurrent ? last.end : plan.boundaries.first(where: { $0 > audio.playbackSeconds }) ?? audio.duration |
| 496 | retained.append(StudioSegment(start: last.start, end: end, scene: visualizer.scene, bars: barsPerVisualizer)) |
| 497 | let remaining = SongSegmentation(boundaries: [end] + plan.boundaries.filter { $0 > end }, bpm: plan.bpm) |
| 498 | let future = RadioVisualSchedule.make(plan: remaining, pool: available, bars: barsPerVisualizer, |
| 499 | previous: visualizer.scene) |
| 500 | if future.isEmpty, end < audio.duration { |
| 501 | let held = retained.removeLast() |
| 502 | retained.append(StudioSegment(start: held.start, end: audio.duration, scene: held.scene, bars: held.bars)) |
| 503 | } |
| 504 | segments = retained + future |
| 505 | } else { |
| 506 | segments = RadioVisualSchedule.make(plan: plan, pool: available, bars: barsPerVisualizer, |
| 507 | previous: previousScene) |
| 508 | } |
| 509 | follow(time: audio.playbackSeconds) |
| 510 | } |
| 511 | |
| 512 | private func discardPrefetch() { |
| 513 | prefetch?.cancel(); prefetch = nil; upcomingIndex = nil; preparedNext = nil |
| 514 | } |
| 515 | |
| 516 | private func loadTrack(at first: Int) { |
| 517 | guard let audio, let catalog, let catalogURL, eligibleTrackIndices.contains(first) else { return } |
| 518 | let choices = eligibleTrackIndices |
| 519 | let ready = preparedNext?.index == first ? preparedNext?.audio : nil |
| 520 | task?.cancel(); discardPrefetch(); revision = UUID(); let token = revision |
| 521 | requestedIndex = first |
| 522 | audio.pause(); isLoading = true; status = String(localized: "Preparing \(catalog.tracks[first].title)…") |
| 523 | task = Task { [weak self, library] in |
| 524 | var index = first |
| 525 | var attempted = Set<Int>() |
| 526 | while attempted.insert(index).inserted { |
| 527 | do { |
| 528 | let track = catalog.tracks[index] |
| 529 | let prepared: PreparedSoundtrack |
| 530 | if index == first, let ready { prepared = ready } |
| 531 | else { |
| 532 | let url = try await library.localAudio(for: track, catalogURL: catalogURL) |
| 533 | prepared = try await Task.detached(priority: .userInitiated) { try PreparedSoundtrack(url: url) }.value |
| 534 | } |
| 535 | try Task.checkCancellation() |
| 536 | guard let self, self.revision == token, self.isActive else { return } |
| 537 | let previousScene = self.hasRadioAudio ? self.visualizer.scene : nil |
| 538 | guard audio.install(prepared, title: track.title) else { throw RadioError.download } |
| 539 | self.hasRadioAudio = true |
| 540 | self.currentIndex = index; self.requestedIndex = nil; self.isLoading = false |
| 541 | self.segments = []; self.playedVisualizers = []; self.sceneTitle = "" |
| 542 | self.rebuildVisuals(previousScene: previousScene); self.soundtrackInstalled.send() |
| 543 | self.status = "\(track.title) · \(track.genre)" |
| 544 | if self.wantsPlayback { audio.playFullSoundtrack() } |
| 545 | // Download AND analyze the next song while this song plays. |
| 546 | self.prepareNextTrack(after: index, catalog: catalog, catalogURL: catalogURL) |
| 547 | return |
| 548 | } catch { |
| 549 | guard let self, self.revision == token, !Task.isCancelled else { return } |
| 550 | self.status = String(localized: "Skipping \(catalog.tracks[index].title): \(error.localizedDescription)") |
| 551 | guard let position = choices.firstIndex(of: index) else { break } |
| 552 | index = choices[(position + 1) % choices.count] |
| 553 | } |
| 554 | } |
| 555 | guard let self, self.revision == token else { return } |
| 556 | self.isLoading = false; self.requestedIndex = nil; self.wantsPlayback = false |
| 557 | self.status = RadioError.allUnavailable.localizedDescription |
| 558 | } |
| 559 | } |
| 560 | |
| 561 | private func prepareNextTrack(after index: Int, catalog: RadioCatalog, catalogURL: URL) { |
| 562 | guard let nextIndex = queuedTrack(after: index) else { return } |
| 563 | upcomingIndex = nextIndex |
| 564 | let next = catalog.tracks[nextIndex], token = revision |
| 565 | prefetch = Task { [weak self, library] in |
| 566 | do { |
| 567 | let url = try await library.localAudio(for: next, catalogURL: catalogURL) |
| 568 | let prepared = try await Task.detached(priority: .utility) { try PreparedSoundtrack(url: url) }.value |
| 569 | try Task.checkCancellation() |
| 570 | guard let self, self.revision == token else { return } |
| 571 | self.preparedNext = (nextIndex, prepared) |
| 572 | } catch { /* The transition retries and reports failures if needed. */ } |
| 573 | } |
| 574 | } |
| 575 | } |