Cotton code
680 lines · 29.2 KB · SwiftRaw
// 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.import CottonKitimport CottonVoiceimport CottonValuesimport Foundation#if os(iOS)import AVFoundationimport CryptoKitimport osimport UIKit#endif/// Where the music player stands, as the Listening deck draws it. Published/// by the player (`MusicPlayback`), never kept anywhere.@MainActor @Observablefinal class MusicNowPlaying {    /// The one player's (`MusicPlayback.now`).    static let shared = MusicNowPlaying()    private(set) var song: QueuedSong?    private(set) var playing = false    private(set) var loading = false    private(set) var elapsed: Double = 0    private(set) var duration: Double = 0    private(set) var level: TrackLevel?    private(set) var hasNext = false    private(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) {        if self.song?.id != song?.id {            elapsed = 0            duration = song?.duration ?? 0            said = nil        }        self.song = song        self.loading = loading && song != nil        if 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 = nil        if 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 = false        if elapsed.isFinite { self.elapsed = max(0, elapsed) }        if duration.isFinite, duration > 0 { self.duration = duration }        self.level = playing ? level : nil        self.hasNext = hasNext        self.hasPrevious = hasPrevious    }    /// Where it stands as a player face reads it.    var play: TrackPlay {        guard song != nil else { return .still }        return TrackPlay(held: true, playing: playing, loading: loading, elapsed: elapsed, duration: duration, level: level)    }}enum MusicKnobs {    /// The player's clock: meters, elapsed, crossfades, what is heard.    static let ticksPerSecond: Double = 20    /// Where a song's link by its own extension is made, under Caches.    static let folder = "MusicStream"    /// How often, in seconds, where a song stands is told to the core while it plays.    static let saveEvery: Double = 10}#if os(iOS)@MainActorfinal class MusicPlayback {    static let shared = MusicPlayback()    var now: MusicNowPlaying { .shared }    /// The core's last answer.    private(set) var answer: PlayerAnswer?    /// The core's sleep timer, while one runs.    private var sleepsAt: Date?    private static let log = Logger(subsystem: "com.cottondb.music", category: "player")    private var engine = SongEngine()    private let centre = SystemNowPlaying()    private var core: (any CottonCalling)?    private var say: (String) -> Void = { _ in }    private var ticking: Timer?    /// What was heard of the play under way.    private var 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.    private var loadedAt: Int?    /// The song files fetched for the queue, by song id, and those coming:    /// one fetch per song, however many ask.    private var files: [String: AVAudioFile] = [:]    private var fetching: [String: Task<Result<URL, Unplayable>, Never>] = [:]    /// Why a song cannot be played here; the words are the core's.    enum Unplayable: Error {        case offline, locked, unreadable    }    private var observers: [NSObjectProtocol] = []    /// Paused because a microphone opened (`VoiceAudioSession`): resumed    /// when it closes.    private var pausedForListening = false    private var listening: [NSObjectProtocol] = []    private var coverShown: String?    /// When where the song stands was last told to the core.    private var savedAt = Date.distantPast    private init() {        // 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) { [weak self] _ in                MainActor.assumeIsolated {                    guard let self, self.engine.playing else { return }                    self.pausedForListening = true                    self.pause()                }            },            NotificationCenter.default.addObserver(forName: VoiceAudioSession.didListen, object: nil, queue: .main) { [weak self] _ in                MainActor.assumeIsolated {                    guard let self, self.pausedForListening else { return }                    self.pausedForListening = false                    self.resume()                }            },        ]        centre.connect(NowPlayingCommands(            play: { [weak self] in self?.resume() },            pause: { [weak self] in self?.pause() },            toggle: { [weak self] in self?.toggle() },            next: { [weak self] in self?.next() },            previous: { [weak self] in self?.previous() },            seek: { [weak self] to in self?.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 = core        self.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 {        guard let 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 == nil else { return }        take(kept)    }    /// Where the song stands, told to the core quietly: a pause, a tick, the app leaving.    private func save() {        guard let core, engine.current != nil, answer?.now?.id == engine.current?.id else { return }        savedAt = Date()        let at = engine.elapsed        Task { _ = 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.    private func ask(_ op: String?, _ fields: [String: RecordValue] = [:], leaving ended: String? = nil) {        guard let core else { return Self.log.fault("the player asked with no core attached") }        var request = fields        if let op { request["op"] = .text(op) }        if let ended, let report = heard?.report(ended: ended, device: UIDevice.current.model) { request["listened"] = report }        Task {            do {                take(try await 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.    static func 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).    static func 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)]        if let 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.    private func 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.        if let refusal = answer.refusal, answer.playing == nil { say(refusal) }        engine.set(PlayerKnobs(answer.settings))        guard let 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.index            let at = answer.positionS ?? 0            Task { await start(song, at: at) }        } else {            prepareFollowing()            publish()        }    }    // MARK: Moves    func toggle() {        engine.playing ? pause() : resume()    }    func resume() {        guard engine.current != nil else {            // 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() {        guard let song = engine.current ?? now.song, let core else { return }        let at = loadedAt        var request: [String: RecordValue] = ["op": .text("next")]        // The report goes with it; the core writes it only if the song is left.        if var copy = heard, let report = copy.report(ended: "skipped", device: UIDevice.current.model) { request["listened"] = report }        Task {            do {                let answer = try await 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 = answer                    if let 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() {        guard let song = engine.current ?? now.song else { return }        let at = loadedAt        guard let 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.        if var copy = heard, let report = copy.report(ended: "skipped", device: UIDevice.current.model) { request["listened"] = report }        Task {            do {                let answer = try await 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 song    private func start(_ song: QueuedSong, at seconds: Double = 0) async {        now.hold(song, loading: true)        publish()        let got = await opened(song)        guard let 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.    private func 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.    private func prepareFollowing() {        guard let following = answer?.queue.first else { return engine.forgetFollowing() }        Task {            guard let 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.    private func rest() {        heard = nil        loadedAt = nil        engine.stop()        ticking?.invalidate()        ticking = nil    }    private func 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) }    }    private func wire(_ engine: SongEngine) {        engine.onFinished = { [weak self] id, nextStarted in            guard let self, let core = self.core else { return }            self.files[id] = nil            var request: [String: RecordValue] = ["op": .text("next")]            if let report = self.heard?.report(ended: "finished", device: UIDevice.current.model) { request["listened"] = report }            let joined = nextStarted ? self.engine.current : nil            if let joined { self.began(joined) }            Task {                do {                    let answer = try await core.call(CottonMethod.shellPlayer, request, as: PlayerAnswer.self)                    // Joined gapless or crossfaded in: the song playing is the core's now.                    if let 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.    private func 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.    private func opened(_ song: QueuedSong, quietly: Bool = false) async -> (file: AVAudioFile?, why: String?) {        if let open = files[song.id] { return (open, nil) }        guard let core else { return (nil, answer?.words.refused) }        let fetch = fetching[song.id] ?? Task { await MusicFiles.url(for: song.file, core: core) }        fetching[song.id] = fetch        let result = await fetch.value        fetching[song.id] = nil        if let open = files[song.id] { return (open, nil) }        let why: Unplayable        switch result {        case .success(let url):            if let file = SongEngine.open(url) {                files[song.id] = file                return (file, nil)            }            why = await MusicFiles.locked(url) ? .locked : .unreadable        case .failure(let failed):            why = failed        }        Self.log.error("song \(song.id, privacy: .public) unplayable: \(String(describing: why), privacy: .public)")        guard let words = answer?.words else { return (nil, nil) }        let said: String        switch why {        case .offline: said = words.offline        case .locked: said = words.locked        case .unreadable: said = words.refused        }        if !quietly { say(said) }        return (nil, said)    }    // MARK: The clock    private func startTicking() {        guard ticking == nil else { return }        let timer = Timer(timeInterval: 1 / MusicKnobs.ticksPerSecond, repeats: true) { [weak self] _ in            MainActor.assumeIsolated { self?.tick() }        }        RunLoop.main.add(timer, forMode: .common)        ticking = timer    }    private func tick() {        // A song resting keeps the place it was left at.        guard engine.current != nil else { return }        engine.tick()        let elapsed = engine.elapsed        if 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 screen    private func publish() {        guard let 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))    }    private func showCover(_ song: QueuedSong) {        guard let core, coverShown != song.cover else { return }        coverShown = song.cover        guard let key = song.cover else { return centre.show(art: nil) }        Task {            guard let jpeg = await FilmPlayback.artwork(key, core: core), let image = UIImage(data: jpeg),                  self.answer?.now?.cover == key else { return }            self.centre.show(art: image)        }    }    // MARK: The session    private func activate() {        let session = AVAudioSession.sharedInstance()        try? session.setCategory(.playback, mode: .default, policy: .longFormAudio)        try? session.setActive(true)    }    private func listenToTheSession() {        let centre = NotificationCenter.default        let session = AVAudioSession.sharedInstance()        observers.append(centre.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: .main) { [weak self] _ in            MainActor.assumeIsolated { self?.save() }        })        observers.append(centre.addObserver(forName: AVAudioSession.interruptionNotification, object: session, queue: .main) { [weak self] note in            let 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) { [weak self] note in            let 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) { [weak self] _ in            MainActor.assumeIsolated { self?.rebuilt(again: false) }        })        observers.append(centre.addObserver(forName: AVAudioSession.mediaServicesWereResetNotification, object: session, queue: .main) { [weak self] _ in            MainActor.assumeIsolated { self?.rebuilt(again: true) }        })    }    private var interruptedWhilePlaying = false    private func interrupted(_ kind: AVAudioSession.InterruptionType?, resume: Bool) {        switch kind {        case .began:            interruptedWhilePlaying = now.playing            pause()        case .ended:            if interruptedWhilePlaying, resume { self.resume() }            interruptedWhilePlaying = false        default:            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.    private func rebuilt(again: Bool) {        guard let song = engine.current, let file = files[song.id] else { return }        let at = now.elapsed        let wasPlaying = now.playing        if again {            engine.stop()            if let old = observers.popLast() { NotificationCenter.default.removeObserver(old) }            engine = SongEngine()            wire(engine)            observers.append(NotificationCenter.default.addObserver(forName: .AVAudioEngineConfigurationChange, object: engine.engine, queue: .main) { [weak self] _ in                MainActor.assumeIsolated { self?.rebuilt(again: false) }            })        }        if let 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.enum MusicFiles {    static func folder() -> URL? {        guard let base = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first else { return nil }        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.    static func 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.    static func url(for key: String, core: any CottonCalling) async -> Result<URL, MusicPlayback.Unplayable> {        guard let 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 = try await store.ensure(for: key)            } catch let refused as CottonCallError {                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)            }        }        guard let 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 { try FileManager.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`).    static let 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.    static func locked(_ url: URL) async -> Bool {        (try? await AVURLAsset(url: url).load(.hasProtectedContent)) ?? false    }}#endif