PulseCanvas / app · pulsecanvas.ai / scripts / RadioSmoke.swift
| 1 | import AVFoundation |
| 2 | import Combine |
| 3 | import CryptoKit |
| 4 | import Foundation |
| 5 | |
| 6 | @main struct RadioSmoke { |
| 7 | @MainActor static func wait(_ description: String, until condition: () -> Bool) async throws { |
| 8 | for _ in 0..<500 { |
| 9 | if condition() { return } |
| 10 | try await Task.sleep(nanoseconds: 20_000_000) |
| 11 | } |
| 12 | fatalError("Timed out: \(description)") |
| 13 | } |
| 14 | |
| 15 | @MainActor static func main() async throws { |
| 16 | setbuf(stdout, nil) |
| 17 | let temporary = FileManager.default.temporaryDirectory.appendingPathComponent("PulseCanvas-Radio-" + UUID().uuidString) |
| 18 | try FileManager.default.createDirectory(at: temporary, withIntermediateDirectories: true) |
| 19 | defer { try? FileManager.default.removeItem(at: temporary) } |
| 20 | let suite = "PulseCanvas.RadioSmoke." + UUID().uuidString |
| 21 | let defaults = UserDefaults(suiteName: suite)! |
| 22 | defer { defaults.removePersistentDomain(forName: suite) } |
| 23 | let audioDirectory = temporary.appendingPathComponent("audio") |
| 24 | try FileManager.default.createDirectory(at: audioDirectory, withIntermediateDirectories: true) |
| 25 | var tracks: [RadioTrack] = [] |
| 26 | let format = AVAudioFormat(standardFormatWithSampleRate: 44100, channels: 2)! |
| 27 | for index in 0..<3 { |
| 28 | let url = audioDirectory.appendingPathComponent("\(index).m4a") |
| 29 | let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 44100 * 3)! |
| 30 | buffer.frameLength = buffer.frameCapacity |
| 31 | for channel in 0..<2 { for frame in 0..<Int(buffer.frameLength) { |
| 32 | buffer.floatChannelData![channel][frame] = 0.3 * sin(Float(frame) * 2 * .pi * Float(220 + index * 110) / 44100) |
| 33 | } } |
| 34 | do { |
| 35 | let file = try AVAudioFile(forWriting: url, settings: [AVFormatIDKey: kAudioFormatMPEG4AAC, |
| 36 | AVSampleRateKey: 44100, AVNumberOfChannelsKey: 2, AVEncoderBitRateKey: 128000]) |
| 37 | try file.write(from: buffer) |
| 38 | } |
| 39 | let data = try Data(contentsOf: url) |
| 40 | tracks.append(RadioTrack(id: UUID().uuidString, title: "Test song \(index)", genre: "Test", duration: 3, |
| 41 | audio: "audio/\(index).m4a", sha256: SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined(), byteCount: data.count)) |
| 42 | } |
| 43 | let catalogURL = temporary.appendingPathComponent("catalog.json") |
| 44 | let catalog = RadioCatalog(version: 1, title: "Test radio", tracks: tracks) |
| 45 | try JSONEncoder().encode(catalog).write(to: catalogURL) |
| 46 | _ = try RadioCatalog.decode(Data(contentsOf: catalogURL), from: catalogURL) |
| 47 | var bad = try JSONSerialization.jsonObject(with: Data(contentsOf: catalogURL)) as! [String: Any] |
| 48 | var badTracks = bad["tracks"] as! [[String: Any]] |
| 49 | badTracks[0]["audio"] = "../../outside.m4a"; bad["tracks"] = badTracks |
| 50 | do { |
| 51 | _ = try RadioCatalog.decode(JSONSerialization.data(withJSONObject: bad), from: catalogURL) |
| 52 | fatalError("Escaping local audio path accepted") |
| 53 | } catch {} |
| 54 | badTracks[0]["audio"] = "http://example.com/music.m4a"; bad["tracks"] = badTracks |
| 55 | do { |
| 56 | _ = try RadioCatalog.decode(JSONSerialization.data(withJSONObject: bad), from: URL(string: "https://example.com/catalog.json")!) |
| 57 | fatalError("HTTP audio accepted") |
| 58 | } catch {} |
| 59 | print("PASS catalog validation: relative paths, HTTPS requirement and local folder boundaries") |
| 60 | |
| 61 | var queue = RadioQueue(), current: Int? |
| 62 | for _ in 0..<4 { |
| 63 | var round: [Int] = [] |
| 64 | for _ in 0..<15 { |
| 65 | let next = queue.next(count: 15, current: current, shuffle: true)! |
| 66 | precondition(next != current); round.append(next); current = next |
| 67 | } |
| 68 | precondition(Set(round).count == 15) |
| 69 | } |
| 70 | var preferredQueue = RadioQueue() |
| 71 | let preferred: Set<Int> = [2, 5, 9] |
| 72 | let firstRound = (0..<12).map { _ in preferredQueue.next(count: 12, current: nil, shuffle: true, prioritized: preferred)! } |
| 73 | precondition(Set(firstRound.prefix(3)) == preferred && Set(firstRound).count == 12) |
| 74 | for _ in 0..<100 { |
| 75 | let next = preferredQueue.next(count: 12, current: current, shuffle: true, prioritized: preferred)! |
| 76 | precondition(next != current); current = next |
| 77 | } |
| 78 | precondition(preferredQueue.next(count: 0, current: nil, shuffle: true, prioritized: preferred) == nil) |
| 79 | print("PASS favorites-first shuffle: favorite tier first, all station songs once per round, no adjacent repeats") |
| 80 | precondition(queue.next(count: 1, current: 0, shuffle: true) == 0) |
| 81 | precondition(queue.next(count: 0, current: nil, shuffle: false) == nil) |
| 82 | print("PASS shuffle: all songs once per round, no repeat across rounds, one/zero track libraries") |
| 83 | let visualPlan = SongSegmentation(boundaries: (0...18).map(Double.init), bpm: 120) |
| 84 | let visualSchedule = RadioVisualSchedule.make(plan: visualPlan, pool: [10, 18, 22], bars: 4) |
| 85 | for offset in stride(from: 0, to: 18, by: 3) { |
| 86 | precondition(Set(visualSchedule[offset..<offset + 3].map(\.scene)) == [10, 18, 22]) |
| 87 | } |
| 88 | precondition(zip(visualSchedule, visualSchedule.dropFirst()).allSatisfy { $0.scene != $1.scene }) |
| 89 | print("PASS visual shuffle: exhaust the favorites pool before repeating, without adjacent repeats") |
| 90 | let mixedPool = [10, 18, 22, 31, 42] |
| 91 | for favoriteSet: Set<Int> in [[10], [10, 18, 22]] { |
| 92 | for _ in 0..<40 { |
| 93 | let mixed = RadioVisualSchedule.make(plan: visualPlan, pool: mixedPool, bars: 4, favorites: favoriteSet) |
| 94 | precondition(mixed.count == 18 && mixed.first?.start == 0 && mixed.last?.end == 18) |
| 95 | for favorite in favoriteSet { precondition(mixed.filter { $0.scene == favorite }.count == 1) } |
| 96 | precondition(mixed.dropFirst(favoriteSet.count).allSatisfy { !favoriteSet.contains($0.scene) }) |
| 97 | precondition(zip(mixed, mixed.dropFirst()).allSatisfy { $0.scene != $1.scene }) |
| 98 | } |
| 99 | } |
| 100 | let unheard = RadioVisualSchedule.make(plan: visualPlan, pool: mixedPool, bars: 4, |
| 101 | favorites: [10, 18], played: [10], previous: 10) |
| 102 | precondition(!unheard.contains { $0.scene == 10 } && unheard.filter { $0.scene == 18 }.count == 1) |
| 103 | let allFavorite = RadioVisualSchedule.make(plan: visualPlan, pool: [10, 18, 22], bars: 4, favorites: [10, 18, 22]) |
| 104 | precondition(allFavorite.count == 3 && Set(allFavorite.map(\.scene)).count == 3 && allFavorite.last?.end == 18) |
| 105 | let shortPlan = SongSegmentation(boundaries: [0, 1, 2], bpm: 120) |
| 106 | let shortSong = RadioVisualSchedule.make(plan: shortPlan, pool: mixedPool, bars: 4, favorites: [10, 18, 22]) |
| 107 | precondition(shortSong.count == 2 && Set(shortSong.map(\.scene)).count == 2) |
| 108 | print("PASS mixed visuals: one/three favorites once per song, random non-favorite fill, short songs, spent favorites and all-favorite galleries") |
| 109 | |
| 110 | for favorites: Set<Int> in [[], [10], [10, 18, 22], Set(mixedPool)] { |
| 111 | for previous in mixedPool { |
| 112 | for _ in 0..<40 { |
| 113 | let nextSong = RadioVisualSchedule.make(plan: visualPlan, pool: mixedPool, bars: 4, |
| 114 | favorites: favorites, previous: previous) |
| 115 | precondition(nextSong.first?.scene != previous, "A new track must open with a different visualizer") |
| 116 | precondition(nextSong.first?.start == 0 && nextSong.last?.end == 18) |
| 117 | for favorite in favorites { precondition(nextSong.filter { $0.scene == favorite }.count == 1) } |
| 118 | } |
| 119 | } |
| 120 | } |
| 121 | let singleVisual = RadioVisualSchedule.make(plan: visualPlan, pool: [10], bars: 4, favorites: [10], previous: 10) |
| 122 | precondition(singleVisual.first?.scene == 10 && singleVisual.last?.end == 18) |
| 123 | print("PASS track transitions: different opening visual with zero, one, several or all favorites; one-design fallback remains valid") |
| 124 | |
| 125 | let library = RadioLibrary(directory: temporary.appendingPathComponent("cache")) |
| 126 | let cached = try await library.localAudio(for: tracks[0], catalogURL: catalogURL) |
| 127 | try Data("broken cache".utf8).write(to: cached) |
| 128 | let repaired = try await library.localAudio(for: tracks[0], catalogURL: catalogURL) |
| 129 | let repairedData = try Data(contentsOf: repaired), originalData = try Data(contentsOf: audioDirectory.appendingPathComponent("0.m4a")) |
| 130 | precondition(repairedData == originalData) |
| 131 | print("PASS cache integrity: modified cached audio is replaced with verified source") |
| 132 | |
| 133 | let audio = AudioController(), studio = StudioStore(defaults: defaults), render = RenderState() |
| 134 | audio.volume = 0 |
| 135 | precondition(audio.load(url: audioDirectory.appendingPathComponent("0.m4a"))) |
| 136 | audio.seek(fraction: 0.4) |
| 137 | let originalURL = audio.selectedURL, originalProgress = audio.progress |
| 138 | let originalPrepared = audio.retainedSoundtrack()! |
| 139 | studio.isStudio = true |
| 140 | studio.makeTimeline(audio.segmentPlan()!, render: render) |
| 141 | let originalTimeline = studio.segments |
| 142 | let secondCatalogURL = temporary.appendingPathComponent("genre.json") |
| 143 | try JSONEncoder().encode(RadioCatalog(version: 1, title: "A future genre", tracks: [tracks[2]])).write(to: secondCatalogURL) |
| 144 | let stationsURL = temporary.appendingPathComponent("stations.json") |
| 145 | let stations = RadioStationDirectory(version: 1, stations: [ |
| 146 | RadioStation(id: "all-music", title: "All Music", description: "All genres", catalog: "catalog.json"), |
| 147 | RadioStation(id: "future-genre", title: "Future Genre", description: "One genre", catalog: "genre.json")]) |
| 148 | try JSONEncoder().encode(stations).write(to: stationsURL) |
| 149 | _ = try RadioStationDirectory.decode(Data(contentsOf: stationsURL), from: stationsURL) |
| 150 | let music = StudioMusicCatalog(source: stationsURL, library: library) |
| 151 | await music.load() |
| 152 | precondition(music.error == nil && music.tracks.count == 3) |
| 153 | precondition(music.matching(search: "", favoritesOnly: true, favoriteIDs: [tracks[1].id]) == [tracks[1]]) |
| 154 | precondition(music.matching(search: "", favoritesOnly: true, favoriteIDs: []).isEmpty) |
| 155 | precondition(music.matching(search: " SONG 1 ", favoritesOnly: false, favoriteIDs: []) == [tracks[1]]) |
| 156 | precondition(music.matching(search: "Test", favoritesOnly: false, favoriteIDs: []).count == 3) |
| 157 | let pickedAudio = try await music.audio(for: tracks[0]) |
| 158 | let importedAudio = try StudioMusicStorage.copy(pickedAudio, title: "../Picked/song?", into: temporary.appendingPathComponent("StudioMusic")) |
| 159 | precondition(importedAudio.lastPathComponent == "Picked song.m4a") |
| 160 | precondition(importedAudio.path.hasPrefix(temporary.appendingPathComponent("StudioMusic").path + "/")) |
| 161 | try FileManager.default.removeItem(at: pickedAudio) |
| 162 | let studioCopyData = try Data(contentsOf: importedAudio) |
| 163 | let studioAudioFile = try AVAudioFile(forReading: importedAudio) |
| 164 | precondition(studioCopyData == originalData && studioAudioFile.length > 0) |
| 165 | precondition(audio.selectedURL == originalURL && abs(audio.progress - originalProgress) < 0.001 && !audio.isPlaying) |
| 166 | let missingMusic = StudioMusicCatalog(source: temporary.appendingPathComponent("missing-catalog.json"), library: library) |
| 167 | await missingMusic.load() |
| 168 | precondition(missingMusic.error != nil && missingMusic.tracks.isEmpty && !missingMusic.loading) |
| 169 | print("PASS Studio music: complete catalog, favorites/search, permanent named copies survive Radio cache removal, failed catalogs leave playback untouched") |
| 170 | let favorites = ProjectMPresets(defaults: defaults, favoritesBackupDirectory: temporary.appendingPathComponent("favorites")) |
| 171 | favorites.toggleFavorite(NativeEffects.activeIDs[0]); favorites.toggleFavorite(NativeEffects.activeIDs[1]) |
| 172 | let radio = RadioController(library: library, defaults: defaults, presets: favorites) |
| 173 | precondition(radio.shuffle && radio.visualizerGroup == .all && !radio.favoriteSongsOnly, |
| 174 | "New Radio sessions default to all songs and all visuals, not favorites-first") |
| 175 | precondition(radio.visualizerChoices == favorites.availableScenes) |
| 176 | radio.shuffle = false // Preserve deterministic index assertions for the transport suite. |
| 177 | precondition(abs(radio.volume - 0.7) < 0.001, "Radio defaults to 70%, independently of the muted editor") |
| 178 | radio.volume = 0 // Keep the test tones silent; this is an isolated preference suite. |
| 179 | radio.attach(audio: audio) |
| 180 | radio.loadCatalog(at: stationsURL) |
| 181 | try await wait("catalog") { radio.canStart } |
| 182 | precondition(radio.catalogError == nil && !radio.canSeek) |
| 183 | precondition(radio.stations.count == 2 && radio.stationID == "all-music") |
| 184 | radio.start(at: 0) |
| 185 | try await wait("first song") { radio.currentIndex == 0 && !radio.isLoading } |
| 186 | precondition(audio.isPlaying && audio.title == tracks[0].title && studio.isStudio) |
| 187 | let songPosition = audio.playbackSeconds |
| 188 | radio.toggleFavoriteSong(tracks[0]) |
| 189 | precondition(radio.isFavoriteSong(tracks[0]) && radio.favoriteSongs.count == 1) |
| 190 | precondition(audio.isPlaying && radio.currentIndex == 0 && audio.playbackSeconds >= songPosition, |
| 191 | "Favoriting a song must not interrupt playback") |
| 192 | let savedSong = radio.favoriteSongs[0] |
| 193 | let reopened = RadioController(library: library, defaults: defaults, presets: favorites) |
| 194 | precondition(reopened.favoriteSongs.count == 1 && reopened.isFavoriteSong(tracks[0]), "Song favorites must persist across launch") |
| 195 | precondition(reopened.favoriteSongs[0].catalogURL == catalogURL && reopened.favoriteSongs[0].sourceURL == stationsURL) |
| 196 | radio.toggleFavoriteSong(tracks[0]); precondition(radio.favoriteSongs.isEmpty) |
| 197 | radio.toggleFavoriteSong(tracks[0]); precondition(radio.favoriteSongs.count == 1) |
| 198 | precondition(radio.sceneTitle == RenderState.sceneNames[radio.visualizer.scene]) |
| 199 | print("PASS song favorites: save/remove, persisted metadata, independent identities and uninterrupted playback") |
| 200 | precondition(StudioTimeline.valid(radio.segments, sceneCount: RenderState.sceneNames.count)) |
| 201 | precondition(abs(radio.segments.last!.end - audio.duration) < 0.001) |
| 202 | precondition(!radio.usesFavorites && radio.segments.allSatisfy { favorites.availableScenes.contains($0.scene) }) |
| 203 | precondition(radio.segments.allSatisfy { $0.bars == 4 }) |
| 204 | radio.barsPerVisualizer = 1 |
| 205 | precondition(radio.segments.allSatisfy { $0.bars == 1 } && abs(radio.segments.last!.end - audio.duration) < 0.001) |
| 206 | let category = favorites.category(for: NativeEffects.activeIDs[0]) |
| 207 | let timeBefore = audio.playbackSeconds |
| 208 | let timingBefore = radio.segments.map { [$0.start, $0.end] } |
| 209 | radio.selectVisualizerGroup(.category(category)) |
| 210 | precondition(favorites.randomizerGroup == .category(category)) |
| 211 | for _ in 0..<40 { |
| 212 | let before = radio.visualizer.scene |
| 213 | radio.randomizeCurrentVisualizer() |
| 214 | precondition(favorites.category(for: radio.visualizer.scene) == category) |
| 215 | precondition(radio.visualizerChoices.count < 2 || before != radio.visualizer.scene) |
| 216 | } |
| 217 | precondition(radio.segments.map { [$0.start, $0.end] } == timingBefore && audio.playbackSeconds == timeBefore && audio.isPlaying) |
| 218 | precondition(radio.segments.filter { $0.end > timeBefore }.allSatisfy { favorites.category(for: $0.scene) == category }) |
| 219 | print("PASS category dropdown: shared pool, immediate scoped rerolls, scoped scheduled scenes, unchanged music position/boundaries") |
| 220 | radio.selectVisualizerGroup(.favorites) |
| 221 | precondition(radio.usesFavorites && radio.visualizerChoices.count == 2) |
| 222 | let persistent = ProjectMPresets(defaults: defaults, favoritesBackupDirectory: temporary.appendingPathComponent("favorites")) |
| 223 | precondition(persistent.randomizerGroup == .favorites, "The chosen group should persist across launches") |
| 224 | for _ in 0..<20 { |
| 225 | let before = radio.visualizer.scene |
| 226 | radio.randomizeCurrentVisualizer() |
| 227 | precondition(radio.visualizer.scene != before && favorites.isFavorite(radio.visualizer.scene)) |
| 228 | } |
| 229 | precondition(radio.segments.filter { $0.end > timeBefore }.allSatisfy { favorites.isFavorite($0.scene) }) |
| 230 | precondition(studio.segments.map(\.scene) == originalTimeline.map(\.scene), "Radio must not modify saved editor assignments") |
| 231 | favorites.toggleFavorite(NativeEffects.activeIDs[0]) |
| 232 | try await wait("single favorite visualizer") { radio.visualizerChoices.count == 1 } |
| 233 | precondition(favorites.isFavorite(radio.visualizer.scene) && !radio.canRandomizeVisualizer) |
| 234 | let single = radio.visualizer.scene |
| 235 | radio.randomizeCurrentVisualizer(); precondition(radio.visualizer.scene == single) |
| 236 | favorites.toggleFavorite(NativeEffects.activeIDs[1]) |
| 237 | try await wait("empty visual favorites fallback") { radio.visualizerChoices == favorites.availableScenes } |
| 238 | precondition(radio.canStart && !radio.usesFavorites && radio.canRandomizeVisualizer && radio.visualizerGroupMessage != nil && audio.isPlaying) |
| 239 | radio.randomizeCurrentVisualizer(); precondition(radio.visualizer.scene != single) |
| 240 | precondition(favorites.availableScenes.contains(radio.visualizer.scene) && radio.canSeek) |
| 241 | radio.togglePlayback(); precondition(!audio.isPlaying) |
| 242 | radio.seek(fraction: 0.4) |
| 243 | precondition(abs(audio.progress - 0.4) < 0.001 && !audio.isPlaying) |
| 244 | radio.togglePlayback(); radio.seek(fraction: 0.2) |
| 245 | precondition(audio.isPlaying && abs(audio.progress - 0.2) < 0.001) |
| 246 | favorites.toggleFavorite(NativeEffects.activeIDs[0]); favorites.toggleFavorite(NativeEffects.activeIDs[1]) |
| 247 | try await wait("visual favorites restored") { radio.visualizerChoices.count == 2 } |
| 248 | print("PASS favorites dropdown: persistence, saved favorites only, empty-favorites fallback, live updates, pause/resume and seeking") |
| 249 | radio.selectVisualizerGroup(.all) |
| 250 | precondition(!radio.usesFavorites && radio.visualizerChoices == favorites.availableScenes) |
| 251 | print("PASS All restores the entire gallery and leaves Studio assignments and saved appearances unchanged") |
| 252 | audio.seek(fraction: 0.98) |
| 253 | try await wait("end advances even with soundtrack Loop on") { radio.currentIndex == 1 && !radio.isLoading } |
| 254 | precondition(audio.title == tracks[1].title && audio.isPlaying) |
| 255 | precondition(audio.volume == radio.volume, "Song changes must retain the user's radio volume") |
| 256 | radio.togglePlayback(); precondition(!audio.isPlaying) |
| 257 | radio.togglePlayback(); precondition(audio.isPlaying) |
| 258 | radio.start(at: 2) |
| 259 | try await wait("last song") { radio.currentIndex == 2 && !radio.isLoading } |
| 260 | audio.seek(fraction: 0.98) |
| 261 | try await wait("playlist wrap") { radio.currentIndex == 0 && !radio.isLoading } |
| 262 | print("PASS playback: full-song completion, automatic next, playlist wrap, pause/resume and complete Studio coverage") |
| 263 | |
| 264 | let beforeSkip = radio.visualizer.scene |
| 265 | radio.next() |
| 266 | try await wait("manual skip changes visual") { radio.currentIndex == 1 && !radio.isLoading } |
| 267 | precondition(radio.visualizer.scene != beforeSkip && audio.isPlaying) |
| 268 | let beforePausedSkip = radio.visualizer.scene |
| 269 | radio.togglePlayback() |
| 270 | radio.next() |
| 271 | try await wait("paused skip changes visual") { radio.currentIndex == 2 && !radio.isLoading } |
| 272 | precondition(radio.visualizer.scene != beforePausedSkip && !audio.isPlaying) |
| 273 | radio.togglePlayback() |
| 274 | radio.next() |
| 275 | try await wait("return to first song") { radio.currentIndex == 0 && !radio.isLoading } |
| 276 | print("PASS manual skip: next song changes visuals while preserving playing/paused transport state") |
| 277 | |
| 278 | let beforeRapidSkip = radio.visualizer.scene |
| 279 | radio.next(); radio.next() |
| 280 | precondition(radio.isLoading && radio.isPlaybackRequested, "Skipping while playing must keep the Pause transport state during preparation") |
| 281 | try await wait("rapid double skip") { radio.currentIndex == 2 && !radio.isLoading } |
| 282 | precondition(radio.visualizer.scene != beforeRapidSkip) |
| 283 | radio.next(); radio.leave() |
| 284 | try await Task.sleep(nanoseconds: 300_000_000) |
| 285 | precondition(!radio.isActive && !radio.isLoading && !audio.isPlaying && audio.onSoundtrackFinished == nil) |
| 286 | precondition(audio.volume == 0, "Leaving radio must restore the previous editor volume") |
| 287 | precondition(audio.selectedURL?.standardizedFileURL == originalURL?.standardizedFileURL && abs(audio.progress - originalProgress) < 0.001, |
| 288 | "Restore: \(String(describing: audio.selectedURL)) / \(String(describing: originalURL)), progress \(audio.progress) / \(originalProgress)") |
| 289 | precondition(studio.segments.map(\.scene) == originalTimeline.map(\.scene)) |
| 290 | precondition(studio.segments.map(\.end) == originalTimeline.map(\.end)) |
| 291 | precondition(audio.retainedSoundtrack()?.analyzer === originalPrepared.analyzer, |
| 292 | "Returning to Studio must reuse its analyzed song instead of decoding it on the UI actor") |
| 293 | precondition(audio.retainedSoundtrack()?.file === originalPrepared.file) |
| 294 | print("PASS cancellation: rapid skips, paused Studio restore and retained audio file/analysis reuse") |
| 295 | |
| 296 | precondition(radio.canSkipStation) |
| 297 | radio.nextStation() |
| 298 | try await wait("future station") { !radio.isCatalogLoading && radio.stationID == "future-genre" } |
| 299 | try await wait("station skip starts music") { radio.isActive && !radio.isLoading && audio.isPlaying } |
| 300 | radio.nextStation() |
| 301 | try await wait("station skip wraps") { !radio.isCatalogLoading && radio.stationID == "all-music" && radio.isActive && !radio.isLoading } |
| 302 | radio.selectStation("future-genre") |
| 303 | try await wait("restore future station") { !radio.isCatalogLoading && radio.stationID == "future-genre" } |
| 304 | precondition(radio.catalog?.tracks.count == 1 && radio.sourceText == stationsURL.absoluteString) |
| 305 | favorites.toggleFavorite(NativeEffects.activeIDs[0]); favorites.toggleFavorite(NativeEffects.activeIDs[1]) |
| 306 | radio.selectVisualizerGroup(.favorites) |
| 307 | precondition(radio.canStart && radio.visualizerGroupMessage != nil) |
| 308 | radio.start() |
| 309 | try await wait("no favorites fallback") { radio.isActive && !radio.isLoading && audio.isPlaying } |
| 310 | precondition(!radio.usesFavorites && radio.segments.allSatisfy { favorites.availableScenes.contains($0.scene) }) |
| 311 | let fallbackScene = radio.visualizer.scene |
| 312 | radio.randomizeCurrentVisualizer() |
| 313 | precondition(radio.visualizer.scene != fallbackScene && favorites.availableScenes.contains(radio.visualizer.scene)) |
| 314 | radio.leave() |
| 315 | radio.selectVisualizerGroup(.all) |
| 316 | print("PASS station architecture: distinct catalogs, stable directory, persisted station selection and All visualizers") |
| 317 | |
| 318 | radio.selectMusicGroup("favorite-songs") |
| 319 | try await wait("favorite music group") { !radio.isCatalogLoading && radio.stationID == "all-music" } |
| 320 | precondition(radio.favoriteSongsOnly && radio.eligibleTrackIndices == [0]) |
| 321 | defaults.set("future-genre", forKey: "PulseCanvas.radio.station") |
| 322 | let favoriteModeReopened = RadioController(library: library, defaults: defaults, presets: favorites) |
| 323 | favoriteModeReopened.loadSavedCatalogIfNeeded() |
| 324 | try await wait("restore favorite music group") { !favoriteModeReopened.isCatalogLoading && favoriteModeReopened.catalog != nil } |
| 325 | precondition(favoriteModeReopened.favoriteSongsOnly && favoriteModeReopened.stationID == "all-music" |
| 326 | && favoriteModeReopened.eligibleTrackIndices == [0], "Favorites mode must reopen against the whole music library") |
| 327 | radio.start() |
| 328 | try await wait("favorite-only song") { radio.isActive && !radio.isLoading && radio.currentIndex == 0 } |
| 329 | radio.next() |
| 330 | try await wait("favorite-only next") { !radio.isLoading } |
| 331 | precondition(radio.currentIndex == 0, "Favorite songs must never advance to a non-favorite") |
| 332 | radio.toggleFavoriteSong(tracks[0]) |
| 333 | precondition(!radio.canStart && radio.eligibleTrackIndices.isEmpty) |
| 334 | radio.next(); precondition(radio.currentIndex == 0, "Empty song favorites must not fall back to all songs") |
| 335 | radio.toggleFavoriteSong(tracks[0]) |
| 336 | radio.selectMusicGroup("all-music") |
| 337 | precondition(!radio.favoriteSongsOnly && radio.eligibleTrackIndices == [0, 1, 2]) |
| 338 | radio.leave() |
| 339 | print("PASS music dropdown: explicit favorites-only queue, empty favorites, All restores every song") |
| 340 | |
| 341 | radio.playFavoriteStation() |
| 342 | try await wait("play favorites directly from library") { radio.isActive && !radio.isLoading && radio.currentIndex == 0 } |
| 343 | precondition(radio.favoriteSongsOnly && audio.isPlaying) |
| 344 | radio.leave() |
| 345 | radio.selectStation("future-genre") |
| 346 | try await wait("genre before direct favorites playback") { !radio.isCatalogLoading && radio.stationID == "future-genre" } |
| 347 | radio.playFavoriteStation() |
| 348 | try await wait("play favorites from another station") { radio.isActive && !radio.isLoading && radio.currentTrack?.id == tracks[0].id } |
| 349 | precondition(radio.favoriteSongsOnly && radio.stationID == "all-music" && audio.isPlaying) |
| 350 | radio.leave() |
| 351 | radio.selectMusicGroup("all-music") |
| 352 | print("PASS direct Play favorite songs: starts from Library with the full favorites station, including when switching from a genre") |
| 353 | |
| 354 | radio.playFavoriteSong(savedSong) |
| 355 | try await wait("favorite from another station") { radio.isActive && !radio.isLoading && radio.currentTrack?.id == tracks[0].id } |
| 356 | precondition(audio.isPlaying && radio.stationID == "all-music", "Selecting a saved song must switch station and play that exact song") |
| 357 | radio.leave() |
| 358 | radio.selectStation("future-genre") |
| 359 | try await wait("restore genre for refresh") { !radio.isCatalogLoading && radio.stationID == "future-genre" } |
| 360 | print("PASS song favorites: selecting a saved song across stations opens Radio and starts the requested track") |
| 361 | |
| 362 | try JSONEncoder().encode(RadioCatalog(version: 1, title: "Updated without an app release", tracks: tracks)).write(to: secondCatalogURL) |
| 363 | radio.loadSavedCatalogIfNeeded(refresh: true) |
| 364 | try await wait("static JSON refresh") { !radio.isCatalogLoading && radio.catalog?.title == "Updated without an app release" } |
| 365 | precondition(radio.catalog?.tracks.count == 3 && radio.stationID == "future-genre") |
| 366 | radio.start(); radio.shutdown() |
| 367 | try await Task.sleep(nanoseconds: 100_000_000) |
| 368 | precondition(!radio.isActive && !radio.isLoading && !audio.isPlaying && audio.onSoundtrackFinished == nil) |
| 369 | print("PASS static JSON refresh and shutdown: new songs load without a release, pending transitions cannot restart audio") |
| 370 | |
| 371 | // Removal requires a complete, successfully fetched catalog; neither a |
| 372 | // genre subset nor a failed read is evidence of deletion. |
| 373 | precondition(radio.isFavoriteSong(tracks[0]), "A genre subset removed another station's favorite") |
| 374 | let offline = temporary.appendingPathComponent("catalog-offline.json") |
| 375 | try FileManager.default.moveItem(at: catalogURL, to: offline) |
| 376 | await radio.refreshFavoriteSongs() |
| 377 | precondition(radio.isFavoriteSong(tracks[0]), "A failed catalog read removed a favorite") |
| 378 | try FileManager.default.moveItem(at: offline, to: catalogURL) |
| 379 | try JSONEncoder().encode(RadioCatalog(version: 1, title: "Removed first song", tracks: Array(tracks.dropFirst()))).write(to: catalogURL) |
| 380 | let startupCleanup = RadioController(library: library, defaults: defaults, presets: favorites) |
| 381 | await startupCleanup.refreshFavoriteSongs() |
| 382 | precondition(!startupCleanup.isFavoriteSong(tracks[0]) && startupCleanup.catalog == nil && !startupCleanup.isActive, |
| 383 | "Startup cleanup must remove retired songs without opening Radio or starting playback") |
| 384 | let startupReopened = RadioController(library: library, defaults: defaults, presets: favorites) |
| 385 | precondition(!startupReopened.isFavoriteSong(tracks[0]), "Startup song cleanup must be persisted") |
| 386 | radio.playFavoriteSong(savedSong) |
| 387 | try await wait("removed favorite") { !radio.isCatalogLoading && radio.favoritePlaybackError != nil } |
| 388 | precondition(!radio.isFavoriteSong(tracks[0]) && !radio.isActive, "Removed song was retained or played") |
| 389 | let afterRemoval = RadioController(library: library, defaults: defaults, presets: favorites) |
| 390 | precondition(!afterRemoval.isFavoriteSong(tracks[0]), "Removed favorite returned after relaunch") |
| 391 | radio.toggleFavoriteSong(tracks[1]); precondition(radio.isFavoriteSong(tracks[1])) |
| 392 | try JSONEncoder().encode(RadioCatalog(version: 1, title: "Empty library", tracks: [])).write(to: catalogURL) |
| 393 | await radio.refreshFavoriteSongs() |
| 394 | precondition(radio.favoriteSongs.isEmpty, "An empty complete library must remove its remaining favorites") |
| 395 | radio.loadCatalog(at: catalogURL) |
| 396 | try await wait("empty catalog") { !radio.isCatalogLoading } |
| 397 | precondition(!radio.canStart && radio.catalogError == nil) |
| 398 | radio.start(); precondition(!radio.isActive, "An empty library must not start playback") |
| 399 | radio.loadCatalog(at: temporary.appendingPathComponent("missing-catalog.json")) |
| 400 | try await wait("catalog failure") { !radio.isCatalogLoading && radio.catalogError != nil } |
| 401 | radio.loadCatalog(at: catalogURL) |
| 402 | precondition(radio.catalogError == nil, "Retry clears the old loading error immediately") |
| 403 | try await wait("catalog recovery") { !radio.isCatalogLoading } |
| 404 | precondition(radio.catalogError == nil && !radio.canStart, "An empty successful load is not a retry-worthy error") |
| 405 | print("PASS favorite removal: missing songs are pruned and persisted, genre/offline reads preserve valid picks, empty libraries are safe") |
| 406 | |
| 407 | // Every entry passes integrity but contains undecodable audio: retry must be bounded. |
| 408 | let invalidData = Data("Not an audio file".utf8) |
| 409 | let badFile = audioDirectory.appendingPathComponent("bad.m4a") |
| 410 | try invalidData.write(to: badFile) |
| 411 | let invalidTracks = (0..<2).map { index in RadioTrack(id: UUID().uuidString, title: "Unavailable \(index)", genre: "Test", duration: 3, |
| 412 | audio: "audio/bad.m4a", sha256: SHA256.hash(data: invalidData).map { String(format: "%02x", $0) }.joined(), byteCount: invalidData.count) } |
| 413 | try JSONEncoder().encode(RadioCatalog(version: 1, title: "Unavailable", tracks: invalidTracks)).write(to: catalogURL) |
| 414 | radio.loadCatalog(at: catalogURL) |
| 415 | try await wait("unavailable catalog") { radio.canStart && radio.catalog?.title == "Unavailable" } |
| 416 | radio.start() |
| 417 | try await wait("bounded failed library") { !radio.isLoading } |
| 418 | precondition(radio.status == RadioError.allUnavailable.localizedDescription) |
| 419 | radio.leave() |
| 420 | print("PASS failure handling: all-broken playlist stops after one pass") |
| 421 | |
| 422 | // Personal albums are copied, loop as Radio, and never replace Studio's catalog or soundtrack. |
| 423 | let album = temporary.appendingPathComponent("Personal album") |
| 424 | let disc = album.appendingPathComponent("Disc 1") |
| 425 | try FileManager.default.createDirectory(at: disc, withIntermediateDirectories: true) |
| 426 | for index in 0..<3 { |
| 427 | try FileManager.default.copyItem(at: audioDirectory.appendingPathComponent("\(index).m4a"), |
| 428 | to: disc.appendingPathComponent("Song \(index).m4a")) |
| 429 | } |
| 430 | try Data("broken".utf8).write(to: album.appendingPathComponent("broken.mp3")) |
| 431 | try Data("not music".utf8).write(to: album.appendingPathComponent("notes.txt")) |
| 432 | let managed = temporary.appendingPathComponent("PersonalRadio") |
| 433 | let imported = try await library.importMusicFolder(album, into: managed) |
| 434 | let importedCatalog = try await library.catalog(at: imported.url) |
| 435 | precondition(importedCatalog.tracks.count == 3 && imported.skipped == 1) |
| 436 | precondition(importedCatalog.tracks.map(\.title) == ["Song 0", "Song 1", "Song 2"]) |
| 437 | try FileManager.default.removeItem(at: album) |
| 438 | let remoteSource = radio.studioMusicSource |
| 439 | let oldAudioURL = audio.selectedURL |
| 440 | let oldTitle = audio.title |
| 441 | let savedFavorites = radio.favoriteSongs |
| 442 | defaults.set(imported.url, forKey: PersonalRadioMusic.catalogKey) |
| 443 | radio.shuffle = false |
| 444 | radio.usePersonalMusic() |
| 445 | try await wait("personal Radio import") { radio.isActive && !radio.isLoading && !radio.isCatalogLoading } |
| 446 | precondition(radio.isPersonalMusic && radio.stationTitle == "Personal album") |
| 447 | precondition(radio.studioMusicSource == remoteSource && radio.sourceText == remoteSource.absoluteString) |
| 448 | precondition(radio.currentIndex == 0 && audio.title == "Song 0" && audio.isPlaying) |
| 449 | for expected in [1, 2, 0, 1] { |
| 450 | radio.next() |
| 451 | try await wait("personal queue wraps") { !radio.isLoading && radio.currentIndex == expected } |
| 452 | precondition(audio.isPlaying) |
| 453 | } |
| 454 | audio.seek(fraction: 0.98) |
| 455 | try await wait("personal automatic next song") { !radio.isLoading && radio.currentIndex == 2 && audio.isPlaying } |
| 456 | radio.toggleFavoriteSong(radio.currentTrack!) |
| 457 | precondition(radio.favoriteSongs == savedFavorites, "Personal tracks must not enter catalog favorites") |
| 458 | radio.leave() |
| 459 | precondition(audio.selectedURL == oldAudioURL && audio.title == oldTitle) |
| 460 | let reopenedAlbum = RadioController(library: library, defaults: defaults, presets: favorites) |
| 461 | reopenedAlbum.attach(audio: audio) |
| 462 | reopenedAlbum.loadSavedCatalogIfNeeded() |
| 463 | try await wait("personal playlist reopens") { !reopenedAlbum.isCatalogLoading } |
| 464 | precondition(reopenedAlbum.isPersonalMusic && reopenedAlbum.catalog?.tracks.count == 3 && !reopenedAlbum.isActive) |
| 465 | precondition(reopenedAlbum.studioMusicSource == remoteSource) |
| 466 | let emptyAlbum = temporary.appendingPathComponent("Empty album") |
| 467 | try FileManager.default.createDirectory(at: emptyAlbum, withIntermediateDirectories: true) |
| 468 | reopenedAlbum.importMusicFolder(emptyAlbum, into: managed) |
| 469 | try await wait("empty import error") { !reopenedAlbum.isCatalogLoading } |
| 470 | precondition(reopenedAlbum.catalogError != nil && reopenedAlbum.catalog?.tracks.count == 3) |
| 471 | let remainingImports = try FileManager.default.contentsOfDirectory(atPath: managed.path) |
| 472 | precondition(remainingImports.count == 1, |
| 473 | "Failed folder imports must clean partial copies") |
| 474 | try JSONEncoder().encode(catalog).write(to: catalogURL) |
| 475 | reopenedAlbum.selectMusicGroup("all-music", startPlayback: true) |
| 476 | try await wait("return to catalog Radio") { !reopenedAlbum.isCatalogLoading && !reopenedAlbum.isLoading && reopenedAlbum.isActive } |
| 477 | precondition(!reopenedAlbum.isPersonalMusic && !defaults.bool(forKey: PersonalRadioMusic.activeKey)) |
| 478 | reopenedAlbum.leave() |
| 479 | await library.removePersonalCopy(at: catalogURL, within: managed) |
| 480 | precondition(FileManager.default.fileExists(atPath: catalogURL.path), "Cleanup must refuse external catalogs") |
| 481 | await library.removePersonalCopy(at: imported.url, within: managed) |
| 482 | precondition(!FileManager.default.fileExists(atPath: imported.url.path), "Owned collection cleanup must work with plain directory URLs") |
| 483 | print("PASS personal Radio: nested album, corrupt-file skip, managed copy survives source removal, sequential wrap, relaunch, failed-import rollback, Studio isolation, source switching") |
| 484 | |
| 485 | if CommandLine.arguments.count > 1 { |
| 486 | let argument = CommandLine.arguments[1] |
| 487 | let realURL = argument.hasPrefix("https://") ? URL(string: argument)! : URL(fileURLWithPath: argument) |
| 488 | let real = try await library.catalog(at: realURL) |
| 489 | var total = 0.0, slowest = 0.0 |
| 490 | for track in real.tracks { |
| 491 | let url = try await library.localAudio(for: track, catalogURL: realURL) |
| 492 | let start = Date() |
| 493 | let prepared = try await Task.detached { try PreparedSoundtrack(url: url) }.value |
| 494 | let elapsed = Date().timeIntervalSince(start) |
| 495 | slowest = max(slowest, elapsed) |
| 496 | precondition(audio.install(prepared, title: track.title)) |
| 497 | precondition(abs(audio.duration - track.duration) < 0.1) |
| 498 | let plan = audio.segmentPlan()! |
| 499 | studio.segments = []; studio.makeTimeline(plan, render: render) |
| 500 | precondition(StudioTimeline.valid(studio.segments, sceneCount: RenderState.sceneNames.count)) |
| 501 | precondition(plan.boundaries.first == 0 && abs(plan.boundaries.last! - audio.duration) < 0.001) |
| 502 | audio.seek(fraction: 0.5) |
| 503 | precondition(audio.spectrum.max()! > 0) |
| 504 | total += track.duration |
| 505 | print(String(format: "PASS %@: %.2fs preparation, %d clips covering %.2fs", track.title, elapsed, studio.segments.count, audio.duration)) |
| 506 | } |
| 507 | audio.clear() |
| 508 | print(String(format: "PASS all %d real tracks: %.1f minutes, slowest local preparation %.2fs", real.tracks.count, total / 60, slowest)) |
| 509 | } |
| 510 | } |
| 511 | } |