// THE MUSIC PLAYER (Cotton Music, 5 Nov 2026): the instrument under the// core's player (`shell.player`), one for the whole app. The core keeps the// queue, the listen rule, the settings row and the face; this plays what it// answers (`now`, the `queue` after it) through the app's own audio engine// (`SongEngine`) and tells it each move: a song finished or skipped, Previous// at where the song stands, a scrub. One call per move, never per frame.//// A song plays from its file on this phone (`read.mediaPath`), else the core// fetches it from the object and opens it into its own store (`media.ensure`:// a person's song is sealed there, R6), the next song's while the one before// plays. Play, Shuffle, Play next and Add to queue come from the// song's, the album's and the artist's acts (`shell.player`, run here as// `play`, `Players`). The settings the core answers are honoured (crossfade,// gapless, speed; each song's gain is the core's), and its sleep timer.//// ONE AUDIO SESSION with the podcasts: starting a song pauses an episode// and the reverse (`NowPlayingClaim`); the lock screen, Control Centre and// headphones reach it through `SystemNowPlaying` (title, artist, album,// cover, where it is, next and previous). A call or Siri pauses it and it// plays on after when the system says so; headphones pulled out pause it.//// MUSIC ALWAYS HAS A PLAYER (music-player-gone, 6 Nov 2026): the core keeps// the song, its queue and where it stands beside the copy. Attached, the// player asks the core and holds the last song resting, paused at its place,// so Listening's first card is the player before anything plays again; a tap// on play loads it there (`resume`). Where a song stands is told to the core// at a pause, every `saveEvery` seconds and as the app leaves the screen. A// song that cannot play here says the core's words on its card, and stays.//// THE LISTEN: what was heard of a play, forward and scrubbing aside, is this// instrument's clock (`PlayHeard`); it is reported once, on the move that// leaves the song (`listened {table, id, seconds, ended}`), and the core decides// whether it was a listen, a skip or nothing.importCottonKitimportCottonVoiceimportCottonValuesimportFoundation#if os(iOS)import AVFoundationimportCryptoKitimport osimport UIKit#endif/// Where the music player stands, as the Listening deck draws it. Published/// by the player (`MusicPlayback`), never kept anywhere.@MainActor @ObservablefinalclassMusicNowPlaying {/// The one player's (`MusicPlayback.now`).staticlet shared = MusicNowPlaying()private(set) var song: QueuedSong?private(set) var playing = falseprivate(set) var loading = falseprivate(set) var elapsed: Double = 0private(set) var duration: Double = 0private(set) var level: TrackLevel?private(set) var hasNext = falseprivate(set) var hasPrevious = false/// Why the song held cannot play here, in the core's words; drawn on its card.private(set) var said: String?/// The hand's ring of faces, as the core answered it.private(set) var faces: [PlayerAnswer.Face] = []func hold(faces: [PlayerAnswer.Face]) {self.faces = faces }func hold(_ song: QueuedSong?, loading: Bool) {ifself.song?.id != song?.id { elapsed = 0 duration = song?.duration ?? 0 said = nil }self.song = songself.loading = loading && song != nilif loading { said = nil }if song == nil { playing = false; level = nil; said = nil } }/// The song held where it rests: paused at `at`, or refused in the core's `words`.func rest(_ song: QueuedSong, at: Double, words: String? = nil) { hold(song, loading: false) playing = false level = nilif at.isFinite { elapsed = max(0, at) } said = words }func stand(playing: Bool, elapsed: Double, duration: Double, level: TrackLevel?, hasNext: Bool, hasPrevious: Bool) {self.playing = playing loading = falseif elapsed.isFinite { self.elapsed = max(0, elapsed) }if duration.isFinite, duration > 0 { self.duration = duration }self.level = playing ? level : nilself.hasNext = hasNextself.hasPrevious = hasPrevious }/// Where it stands as a player face reads it.var play: TrackPlay {guard song != nilelse { return .still }returnTrackPlay(held: true, playing: playing, loading: loading, elapsed: elapsed, duration: duration, level: level) }}enumMusicKnobs {/// The player's clock: meters, elapsed, crossfades, what is heard.staticlet ticksPerSecond: Double = 20/// Where a song's link by its own extension is made, under Caches.staticlet folder = "MusicStream"/// How often, in seconds, where a song stands is told to the core while it plays.staticlet saveEvery: Double = 10}#if os(iOS)@MainActorfinalclassMusicPlayback {staticlet shared = MusicPlayback()var now: MusicNowPlaying { .shared }/// The core's last answer.private(set) var answer: PlayerAnswer?/// The core's sleep timer, while one runs.privatevar sleepsAt: Date?privatestaticlet log = Logger(subsystem: "com.cottondb.music", category: "player")privatevar engine = SongEngine()privatelet centre = SystemNowPlaying()privatevar core: (any CottonCalling)?privatevar say: (String) -> Void = { _ in }privatevar ticking: Timer?/// What was heard of the play under way.privatevar heard: PlayHeard?/// The core's place of the song loaded (`at.index`): a move to another/// place loads, the same place and song plays on.privatevar loadedAt: Int?/// The song files fetched for the queue, by song id, and those coming:/// one fetch per song, however many ask.privatevar files: [String: AVAudioFile] = [:]privatevar fetching: [String: Task<Result<URL, Unplayable>, Never>] = [:]/// Why a song cannot be played here; the words are the core's.enumUnplayable: Error {case offline, locked, unreadable }privatevar observers: [NSObjectProtocol] = []/// Paused because a microphone opened (`VoiceAudioSession`): resumed/// when it closes.privatevar pausedForListening = falseprivatevar listening: [NSObjectProtocol] = []privatevar coverShown: String?/// When where the song stands was last told to the core.privatevar savedAt = Date.distantPastprivateinit() {// A dictation or a spoken command: the song stops so the microphone// does not write the lyrics down, and plays on after. listening = [NotificationCenter.default.addObserver(forName: VoiceAudioSession.willListen, object: nil, queue: .main) { [weakself] _ inMainActor.assumeIsolated {guardletself, self.engine.playing else { return }self.pausedForListening = trueself.pause() } },NotificationCenter.default.addObserver(forName: VoiceAudioSession.didListen, object: nil, queue: .main) { [weakself] _ inMainActor.assumeIsolated {guardletself, self.pausedForListening else { return }self.pausedForListening = falseself.resume() } }, ] centre.connect(NowPlayingCommands( play: { [weakself] inself?.resume() }, pause: { [weakself] inself?.pause() }, toggle: { [weakself] inself?.toggle() }, next: { [weakself] inself?.next() }, previous: { [weakself] inself?.previous() }, seek: { [weakself] to inself?.seek(to: to) })) wire(engine) listenToTheSession() }/// The core and the toasts, from the root once a core is open.func attach(core: any CottonCalling, say: @escaping (String) -> Void) {self.core = coreself.say = say }/// The player the core holds resting (the last song, paused where it/// stood, or the song it offers before any play), asked as Listening/// shows and again as records arrive until one stands; nothing while/// one plays.func restore() async {guardlet core, answer?.now == nil, engine.current == nil,let kept = try? await core.call(CottonMethod.shellPlayer, [String: RecordValue](), as: PlayerAnswer.self), kept.now != nil, answer?.now == nil, engine.current == nilelse { return } take(kept) }/// Where the song stands, told to the core quietly: a pause, a tick, the app leaving.privatefunc save() {guardlet core, engine.current != nil, answer?.now?.id == engine.current?.id else { return } savedAt = Date()let at = engine.elapsedTask { _ = try? await core.call(CottonMethod.shellPlayer, ["op": RecordValue.text("seek"), "at_s": .number(at)], as: PlayerAnswer.self) } }// MARK: Asking the core/// One move told to the core, with the report of the play it leaves; its/// answer played.privatefunc ask(_ op: String?, _ fields: [String: RecordValue] = [:], leaving ended: String? = nil) {guardlet core else { returnSelf.log.fault("the player asked with no core attached") }var request = fieldsiflet op { request["op"] = .text(op) }iflet ended, let report = heard?.report(ended: ended, device: UIDevice.current.model) { request["listened"] = report }Task {do { take(tryawait core.call(CottonMethod.shellPlayer, request, as: PlayerAnswer.self)) } catch {Self.log.error("\(op ?? "ask", privacy: .public) refused: \(String(describing: error), privacy: .public)") say((error as? CottonCallError)?.message ?? error.localizedDescription) } } }/// A song played from here, as its Play act plays it: the core deals it/// with the rest of its album.staticfunc play(song id: String, core: any CottonCalling, say: @escaping (String) -> Void) { shared.attach(core: core, say: say) shared.ask("play", ["table": .text("song"), "id": .text(id)], leaving: "stopped") }/// A list of songs played from here (its cassette): the core deals the/// list in its order, from the song `from` (its first without one).staticfunc play(list id: String, from: String? = nil, core: any CottonCalling, say: @escaping (String) -> Void) { shared.attach(core: core, say: say)var request: [String: RecordValue] = ["table": .text("list"), "id": .text(id)]iflet from { request["from"] = .text(from) } shared.ask("play", request, leaving: "stopped") }/// A play's answer (`Players`): the play it left is reported alone, and/// the answer played; an episode or a film playing stops the music.func took(_ answer: PlayerAnswer) {if answer.playing != nil, engine.current == nil { return }if heard != nil, answer.now?.id != engine.current?.id || answer.at.index != loadedAt { ask(nil, leaving: "stopped") } take(answer) }/// The core's answer played: the song at another place loads, the/// following one is made ready, the settings honoured.privatefunc take(_ answer: PlayerAnswer) {self.answer = answer sleepsAt = answer.sleepsAt now.hold(faces: answer.faces)// An episode's or a film's refusal is its own instrument's to say.iflet refusal = answer.refusal, answer.playing == nil { say(refusal) } engine.set(PlayerKnobs(answer.settings))guardlet song = answer.now else { return stopped() }if answer.resting {// The core holds it resting (kept from before, or its run over): paused at its place, loaded by a play. rest() now.rest(song, at: answer.positionS ?? 0) publish() showCover(song)return }if song.id != engine.current?.id || answer.at.index != loadedAt { loadedAt = answer.at.indexlet at = answer.positionS ?? 0Task { await start(song, at: at) } } else { prepareFollowing() publish() } }// MARK: Movesfunc toggle() { engine.playing ? pause() : resume() }func resume() {guard engine.current != nilelse {// The song rests: the core sets it playing, and it loads where it stood.if answer?.resting == true || now.song != nil { ask("resume") }return } activate() engine.play() heard?.jumped(to: engine.elapsed) tick() publish() }func pause() { engine.pause() tick() publish() save() }/// Next: the core moves on or, at the end of the queue, says nothing/// follows (its `refusal`, said) and the song plays on, its report kept/// for when it is left.func next() {guardlet song = engine.current ?? now.song, let core else { return }let at = loadedAtvar request: [String: RecordValue] = ["op": .text("next")]// The report goes with it; the core writes it only if the song is left.ifvar copy = heard, let report = copy.report(ended: "skipped", device: UIDevice.current.model) { request["listened"] = report }Task {do {let answer = tryawait core.call(CottonMethod.shellPlayer, request, as: PlayerAnswer.self)if answer.now?.id == song.id, answer.at.index == at {// The end of the queue: the play goes on, its report unsent.self.answer = answeriflet refusal = answer.refusal { say(refusal) } } else { heard = nil take(answer) } } catch { say((error as? CottonCallError)?.message ?? error.localizedDescription) } } }/// Previous: the core goes back a song or, a few seconds in, says the/// song starts again (the same place), and it is sought to nought.func previous() {guardlet song = engine.current ?? now.song else { return }let at = loadedAtguardlet core else { return }var request: [String: RecordValue] = ["op": .text("previous"), "at_s": .number(engine.elapsed)]// The report goes with it; the core writes it only if the song is left.ifvar copy = heard, let report = copy.report(ended: "skipped", device: UIDevice.current.model) { request["listened"] = report }Task {do {let answer = tryawait core.call(CottonMethod.shellPlayer, request, as: PlayerAnswer.self)if answer.now?.id == song.id, answer.at.index == at {// Started again: the play goes on, its report unsent.self.answer = answer seek(to: 0) } else { heard = nil take(answer) } } catch { say((error as? CottonCallError)?.message ?? error.localizedDescription) } } }func seek(to seconds: Double) { engine.seek(to: max(0, seconds)) heard?.jumped(to: engine.elapsed) tick() publish() ask("seek", ["at_s": .number(engine.elapsed)]) }// MARK: Starting a songprivatefunc start(_ song: QueuedSong, at seconds: Double = 0) async { now.hold(song, loading: true) publish()let got = await opened(song)guardlet file = got.file else {// Unplayable here: the card stays and says why in the core's words; Next moves on.if answer?.now?.id == song.id { rest() heard = PlayHeard(table: "song", id: song.id) now.rest(song, at: 0, words: got.why) publish() }return }guard answer?.now?.id == song.id else { return } activate() engine.load(song, file: file, at: max(0, seconds)) engine.play() began(song) }/// A song has begun, loaded or joined behind the one before.privatefunc began(_ song: QueuedSong) { heard = PlayHeard(table: "song", id: song.id, from: engine.elapsed) now.hold(song, loading: false) prepareFollowing() startTicking() tick() publish() showCover(song) }/// The song after the one playing: its file fetched, then handed to the/// engine for gapless or a crossfade.privatefunc prepareFollowing() {guardlet following = answer?.queue.first else { return engine.forgetFollowing() }Task {guardlet file = await file(for: following, quietly: true), answer?.queue.first?.id == following.id else { return } engine.prepare(following, file: file) } }/// Nothing loaded, the song held still: a play loads it again.privatefunc rest() { heard = nil loadedAt = nil engine.stop() ticking?.invalidate() ticking = nil }privatefunc stopped() { heard = nil loadedAt = nil engine.stop() ticking?.invalidate() ticking = nil now.hold(nil, loading: false) centre.show(nil) files = [:]// The session stays up for an episode or a film playing in its stead.if answer?.playing == nil { try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation) } }privatefunc wire(_ engine: SongEngine) { engine.onFinished = { [weakself] id, nextStarted inguardletself, let core = self.core else { return }self.files[id] = nilvar request: [String: RecordValue] = ["op": .text("next")]iflet report = self.heard?.report(ended: "finished", device: UIDevice.current.model) { request["listened"] = report }let joined = nextStarted ? self.engine.current : niliflet joined { self.began(joined) }Task {do {let answer = tryawait core.call(CottonMethod.shellPlayer, request, as: PlayerAnswer.self)// Joined gapless or crossfaded in: the song playing is the core's now.iflet joined, answer.now?.id == joined.id { self.loadedAt = answer.at.index }self.take(answer) } catch {Self.log.error("a finished song's next was refused: \(String(describing: error), privacy: .public)") } } } }// MARK: The file/// The song's file opened: kept on this phone, else fetched from the/// object; nil, said in the core's words unless `quietly`, when it/// cannot be played here.privatefunc file(for song: QueuedSong, quietly: Bool = false) async -> AVAudioFile? {await opened(song, quietly: quietly).file }/// The song's file opened, or why not in the core's words.privatefunc opened(_ song: QueuedSong, quietly: Bool = false) async -> (file: AVAudioFile?, why: String?) {ifletopen = files[song.id] { return (open, nil) }guardlet core else { return (nil, answer?.words.refused) }let fetch = fetching[song.id] ?? Task { awaitMusicFiles.url(for: song.file, core: core) } fetching[song.id] = fetchlet result = await fetch.value fetching[song.id] = nilifletopen = files[song.id] { return (open, nil) }let why: Unplayableswitch result {case .success(let url):iflet file = SongEngine.open(url) { files[song.id] = filereturn (file, nil) } why = awaitMusicFiles.locked(url) ? .locked : .unreadablecase .failure(let failed): why = failed }Self.log.error("song \(song.id, privacy: .public) unplayable: \(String(describing: why), privacy: .public)")guardlet words = answer?.words else { return (nil, nil) }let said: Stringswitch why {case .offline: said = words.offlinecase .locked: said = words.lockedcase .unreadable: said = words.refused }if !quietly { say(said) }return (nil, said) }// MARK: The clockprivatefunc startTicking() {guard ticking == nilelse { return }let timer = Timer(timeInterval: 1 / MusicKnobs.ticksPerSecond, repeats: true) { [weakself] _ inMainActor.assumeIsolated { self?.tick() } }RunLoop.main.add(timer, forMode: .common) ticking = timer }privatefunc tick() {// A song resting keeps the place it was left at.guard engine.current != nilelse { return } engine.tick()let elapsed = engine.elapsedif engine.playing { heard?.tick(elapsed) }if engine.playing, let sleepsAt, Date() >= sleepsAt {self.sleepsAt = nil pause()return }if engine.playing, Date().timeIntervalSince(savedAt) >= MusicKnobs.saveEvery { save() } now.stand(playing: engine.playing, elapsed: elapsed, duration: engine.duration > 0 ? engine.duration : (answer?.now?.duration ?? 0), level: engine.level, hasNext: !(answer?.queue.isEmpty ?? true), hasPrevious: (answer?.at.index ?? 0) > 0) }// MARK: The lock screenprivatefunc publish() {guardlet song = answer?.now else { return centre.show(nil) } centre.show(NowPlayingInfo(title: song.title, subtitle: song.artist, album: song.albumTitle, duration: engine.duration > 0 ? engine.duration : (song.duration ?? 0), elapsed: engine.current == nil ? now.elapsed : engine.elapsed, playing: engine.playing, rate: answer?.settings.speed ?? 1, hasNext: !(answer?.queue.isEmpty ?? true), hasPrevious: true)) }privatefunc showCover(_ song: QueuedSong) {guardlet core, coverShown != song.cover else { return } coverShown = song.coverguardlet key = song.cover else { return centre.show(art: nil) }Task {guardlet jpeg = awaitFilmPlayback.artwork(key, core: core), let image = UIImage(data: jpeg),self.answer?.now?.cover == key else { return }self.centre.show(art: image) } }// MARK: The sessionprivatefunc activate() {let session = AVAudioSession.sharedInstance()try? session.setCategory(.playback, mode: .default, policy: .longFormAudio)try? session.setActive(true) }privatefunc listenToTheSession() {let centre = NotificationCenter.defaultlet session = AVAudioSession.sharedInstance() observers.append(centre.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: .main) { [weakself] _ inMainActor.assumeIsolated { self?.save() } }) observers.append(centre.addObserver(forName: AVAudioSession.interruptionNotification, object: session, queue: .main) { [weakself] note inlet info = note.userInfo ?? [:]let kind = (info[AVAudioSessionInterruptionTypeKey] as? UInt).flatMap(AVAudioSession.InterruptionType.init(rawValue:))let options = AVAudioSession.InterruptionOptions(rawValue: info[AVAudioSessionInterruptionOptionKey] as? UInt ?? 0)MainActor.assumeIsolated { self?.interrupted(kind, resume: options.contains(.shouldResume)) } }) observers.append(centre.addObserver(forName: AVAudioSession.routeChangeNotification, object: session, queue: .main) { [weakself] note inlet reason = (note.userInfo?[AVAudioSessionRouteChangeReasonKey] as? UInt).flatMap(AVAudioSession.RouteChangeReason.init(rawValue:))// Headphones pulled out: the music stops rather than come out loud.guard reason == .oldDeviceUnavailable else { return }MainActor.assumeIsolated { self?.pause() } }) observers.append(centre.addObserver(forName: .AVAudioEngineConfigurationChange, object: engine.engine, queue: .main) { [weakself] _ inMainActor.assumeIsolated { self?.rebuilt(again: false) } }) observers.append(centre.addObserver(forName: AVAudioSession.mediaServicesWereResetNotification, object: session, queue: .main) { [weakself] _ inMainActor.assumeIsolated { self?.rebuilt(again: true) } }) }privatevar interruptedWhilePlaying = falseprivatefunc interrupted(_ kind: AVAudioSession.InterruptionType?, resume: Bool) {switch kind {case .began: interruptedWhilePlaying = now.playing pause()case .ended:if interruptedWhilePlaying, resume { self.resume() } interruptedWhilePlaying = falsedefault:break } }/// The output changed under the engine (a new route's shape), or the/// system's media services were reset (a new engine altogether): the/// song is loaded again where it stood, playing if it was.privatefunc rebuilt(again: Bool) {guardlet song = engine.current, let file = files[song.id] else { return }let at = now.elapsedlet wasPlaying = now.playingif again { engine.stop()iflet old = observers.popLast() { NotificationCenter.default.removeObserver(old) } engine = SongEngine() wire(engine) observers.append(NotificationCenter.default.addObserver(forName: .AVAudioEngineConfigurationChange, object: engine.engine, queue: .main) { [weakself] _ inMainActor.assumeIsolated { self?.rebuilt(again: false) } }) }iflet answer { engine.set(PlayerKnobs(answer.settings)) } engine.load(song, file: file, at: at)if wasPlaying { activate(); engine.play() } heard?.jumped(to: at) prepareFollowing() publish() }}/// Where a song's bytes are for the engine: the file on this phone, which/// the core fetches and opens where it is not here yet.enumMusicFiles {staticfunc folder() -> URL? {guardlet base = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first else { returnnil }let folder = base.appendingPathComponent(MusicKnobs.folder, isDirectory: true)try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)return folder }/// The name a song's key is kept under: its digest and the key's own/// extension, which the decoder reads the kind of file by.staticfunc name(for key: String) -> String {let digest = SHA256.hash(data: Data(key.utf8)).map { String(format: "%02x", $0) }.joined()let ext = (key as NSString).pathExtension.lowercased()return ext.isEmpty ? digest : "\(digest).\(ext)" }/// The song's file: on this phone, else fetched by the core into its own/// store (`media.ensure`). A person's song is kept sealed at the object/// (R6) and only the core opens it, so its signed address is never read/// here: the decoder would be handed bytes it cannot read. Offline only/// when nothing was reached, else the object refused it.staticfunc url(for key: String, core: any CottonCalling) async -> Result<URL, MusicPlayback.Unplayable> {guardlet folder = folder() else { return .failure(.unreadable) }let named = folder.appendingPathComponent(name(for: key))let store = CoreAttachmentStore(core: core)var here = await store.localURL(for: key)if here.map({ FileManager.default.fileExists(atPath: $0.path) }) != true {do { here = tryawait store.ensure(for: key) } catchlet refused asCottonCallError {Log.write("music: a song could not be fetched: \(refused.code) \(refused.message)")return .failure(MusicFiles.unreached.contains(refused.code) ? .offline : .unreadable) } catch {Log.write("music: a song could not be fetched: \(error.localizedDescription)")return .failure(.unreadable) } }guardlet here, FileManager.default.fileExists(atPath: here.path) else { return .failure(.unreadable) }// The media store names its files by their bytes: the decoder is// handed a link that carries the song's own extension.if here.pathExtension.lowercased() == named.pathExtension { return .success(here) }try? FileManager.default.removeItem(at: named)do { tryFileManager.default.createSymbolicLink(at: named, withDestinationURL: here) } catch { return .success(here) }return .success(named) }/// The core's words for a fetch that reached nothing (`phone/media.rs`/// `not_fetched`).staticlet unreached: Set<String> = ["offline", "unreachable_server", "mac_away", "no_media_fetch"]/// A file sold locked to one player (FairPlay): refused with its own/// line; its lock is never undone.staticfunc locked(_ url: URL) async -> Bool { (try? await AVURLAsset(url: url).load(.hasProtectedContent)) ?? false }}#endif