// A PODCAST PLAYS IN THE APP'S ONE AUDIO PLAYER (owner, 4 Nov 2026: "as // well as Spotify podcasts"). An episode's audio streams from its // publisher's own address (the object reads the feed, never the phone); tap // an episode and the core's player deals it (`shell.player` `play`, with the // rest of its show unplayed after it) and this instrument plays its answer // in ONE `AVPlayer` for the whole app, with Apple's player // (`AVPlayerViewController`, as a film's) over it. Dismissed, it plays on — // in the background, with the screen locked — and the lock screen and // Control Centre show it and reach it (`SystemNowPlaying`: play, pause, the // core's skip back and forward, the scrubber). // // Every rule is the core's (`shell_player_kinds`): where it starts // (`resume_at_s`), what it plays from (`file` kept here, else `stream`), the // skip, and when it is played. This reports where it stands every // `save_every_s` while it plays, at a pause and as it leaves (`listened`), // and the core writes the episode's place and `played`. At its end the core // moves on to the show's next. // // A SHOW'S RADIO plays it too (`podcast.radio`, `DeckRadioPlaying`): the // radio's button plays its episode here without Apple's player over it, and // the radio draws where it stands from what the player publishes // (`PodcastNowPlaying`): which episode of which show, playing or not, how far. import CottonKit import CottonValues import SwiftUI #if os(iOS) import AVFoundation import AVKit import CottonVoice import CryptoKit import UIKit #endif /// Where the app's one podcast player stands, as a show's radio draws it: /// the episode it holds and its show, whether it plays, how far and how /// long. Published by the player (`PodcastPlayback`), never kept anywhere. @MainActor @Observable final class PodcastNowPlaying { /// The episode held: its table and record, and its show's record. struct Held: Equatable { let table: String let id: String let podcast: String? } private(set) var held: Held? private(set) var playing = false private(set) var loading = false private(set) var elapsed: Double = 0 private(set) var duration: Double = 0 func hold(_ held: Held?) { self.held = held elapsed = 0 duration = 0 playing = false loading = held != nil } func stand(playing: Bool, elapsed: Double, duration: Double) { self.playing = playing loading = false if elapsed.isFinite { self.elapsed = max(0, elapsed) } if duration.isFinite, duration > 0 { self.duration = duration } } /// The player holds an episode of the show `podcast`. func holds(show podcast: String) -> Bool { held?.podcast == podcast } } // MARK: - What this phone keeps of an episode /// What this device keeps of one episode (`episodes.here.read`): its file. struct EpisodeHere: Equatable, Sendable { enum State: String, Sendable { case keeping, kept } var state: State? var file: String? } /// The core's device-local store of episodes (`phone::episodes`): never /// synced, so a file only this phone has is never another's. struct EpisodeHereStore: Sendable { let core: any CottonCalling private struct Wire: Decodable { let state: String? let file: String? } func read(_ url: String) async throws -> EpisodeHere { let wire = try await core.call(CottonMethod.episodesHereRead, ["url": RecordValue.text(url)], as: Wire.self) return EpisodeHere(state: wire.state.flatMap(EpisodeHere.State.init(rawValue:)), file: wire.file) } func keeping(_ url: String) async throws { try await write(url, ["state": .text(EpisodeHere.State.keeping.rawValue)]) } func kept(_ url: String, file: String) async throws { try await write(url, ["state": .text(EpisodeHere.State.kept.rawValue), "file": .text(file)]) } func forget(_ url: String) async throws { try await write(url, ["state": .null, "file": .null]) } private func write(_ url: String, _ fields: [String: RecordValue]) async throws { var request = fields request["url"] = .text(url) _ = try await core.callJSON(CottonMethod.episodesHereWrite, request) } } /// Where kept episodes live: one folder, never backed up (the publisher has /// the file), each named by its address's digest. enum EpisodeFiles { /// The folder, under Application Support. static let name = "Podcasts" static func folder() -> URL? { guard let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first else { return nil } var folder = base.appendingPathComponent(name, isDirectory: true) try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) var values = URLResourceValues() values.isExcludedFromBackup = true try? folder.setResourceValues(values) return folder } /// The file's name for the audio at `address`: its digest and the /// address's own extension (`mp3` when it names none). static func name(for address: String) -> String { #if os(iOS) let digest = SHA256.hash(data: Data(address.utf8)).map { String(format: "%02x", $0) }.joined() #else let digest = String(address.hashValue, radix: 16) #endif let ext = URL(string: address).map(\.pathExtension).flatMap { $0.isEmpty || $0.count > 5 ? nil : $0.lowercased() } ?? "mp3" return "\(digest).\(ext)" } /// The kept file named `file`, when it is still there. static func url(_ file: String?) -> URL? { guard let file, let folder = folder() else { return nil } let url = folder.appendingPathComponent(file) return FileManager.default.fileExists(atPath: url.path) ? url : nil } } /// An episode's record as `records.get` answers it: its columns. struct EpisodeRecordRead: Decodable { let data: [String: RecordValue] } #if os(iOS) // MARK: - The player /// The app's one audio player for episodes: what the core's player answers /// playing, one at a time, playing on whether or not Apple's player is up /// over it. @MainActor final class PodcastPlayback: NSObject, AVPlayerViewControllerDelegate { static let shared = PodcastPlayback() /// The episode the core answered playing. private(set) var loaded: PlayerPlaying? /// Where it stands, as a show's radio draws it. let now = PodcastNowPlaying() private let player = AVPlayer() private let centre = SystemNowPlaying() private var controller: AVPlayerViewController? private var core: (any CottonCalling)? private var say: (String) -> Void = { _ in } private var ticking: Any? private var rate: NSKeyValueObservation? private var status: NSKeyValueObservation? private var ending: NSObjectProtocol? /// What was heard of the play under way, and where it last reported. private var heard: PlayHeard? private var reported: Double = 0 /// Apple's player goes up over the next episode the core answers. private var presents = false /// The art shown over Apple's player, which draws nothing for audio. private let art = UIImageView() /// Paused because a microphone opened (`VoiceAudioSession`): resumed /// when it closes. Ducked speech is still speech, so an episode pauses. private var pausedForListening = false private var listening: [NSObjectProtocol] = [] private override init() { super.init() listening = [ NotificationCenter.default.addObserver(forName: VoiceAudioSession.willListen, object: nil, queue: .main) { [weak self] _ in MainActor.assumeIsolated { guard let self, self.player.timeControlStatus != .paused 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() } }, ] player.allowsExternalPlayback = true art.contentMode = .scaleAspectFit centre.connect(NowPlayingCommands( play: { [weak self] in self?.resume() }, pause: { [weak self] in self?.pause() }, toggle: { [weak self] in self?.toggle() }, next: {}, previous: {}, seek: { [weak self] to in self?.seek(to: to) }, skip: { [weak self] by in self?.skip(by) })) ticking = player.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: 600), queue: .main) { [weak self] now in MainActor.assumeIsolated { self?.tick(now.seconds) } } rate = player.observe(\.timeControlStatus) { [weak self] observed, _ in let paused = observed.timeControlStatus == .paused Task { @MainActor in self?.changed(paused: paused) } } } /// Plays the episode `item` stands for (`FilmPlayer.audio`), Apple's /// player over it; the one loaded already comes up where it is. func play(_ item: ViewerItem, core: any CottonCalling, say: @escaping (String) -> Void) { guard let record = item.record, FilmPlayer.of(item) == .audio else { return } if let loaded, loaded.table == record.table, loaded.id == record.id { self.core = core self.say = say present() if player.timeControlStatus == .paused { resume() } return } ask(table: record.table, id: record.id, presents: true, core: core, say: say) } /// Plays the episode `id` of `table` from where the core says, with no /// player over it: a show's radio's button. The one loaded already plays /// on, or resumes. func play(table: String, id: String, core: any CottonCalling, say: @escaping (String) -> Void) { if let loaded, loaded.table == table, loaded.id == id { if player.timeControlStatus == .paused { resume() } return } ask(table: table, id: id, presents: false, core: core, say: say) } /// The core deals the episode; every instrument takes its answer. private func ask(table: String, id: String, presents: Bool, core: any CottonCalling, say: @escaping (String) -> Void) { self.core = core self.say = say var request: [String: RecordValue] = ["op": .text("play"), "table": .text(table), "id": .text(id)] // What was playing reports where it stopped before the next one loads. if loaded != nil, let report = leaving("stopped") { request["listened"] = report } self.presents = presents Task { do { Players.took(try await core.call(CottonMethod.shellPlayer, request, as: PlayerAnswer.self)) } catch { say((error as? CottonCallError)?.message ?? ShellLines.line("cards", "podcast.could_not_play")) } } } /// The core's player answered: an episode playing is this player's to /// play; anything else, and what it held stops. func took(_ answer: PlayerAnswer) { guard let episode = answer.playing, episode.kind == "episode" else { if loaded != nil { if let core, let report = leaving("stopped") { Task { _ = try? await core.call(CottonMethod.shellPlayer, ["listened": report], as: PlayerAnswer.self) } } stop() } return } if let refusal = answer.refusal { say(refusal) } if loaded?.id == episode.id { return } Task { await start(episode, words: answer.words) } } private func start(_ episode: PlayerPlaying, words: PlayerAnswer.Words) async { let source: URL if let file = EpisodeFiles.url(episode.file) { source = file } else if let stream = episode.stream.flatMap(URL.init(string:)) { source = stream } else { return say(words.refused) } // Playback: heard with the switch on silent, on with the screen // locked, and spoken word as the system treats it. try? AVAudioSession.sharedInstance().setCategory(.playback, mode: .spokenAudio) try? AVAudioSession.sharedInstance().setActive(true) loaded = episode now.hold(PodcastNowPlaying.Held(table: episode.table, id: episode.id, podcast: episode.podcast)) let playing = AVPlayerItem(url: source) watch(playing, words: words) player.replaceCurrentItem(with: playing) if episode.resumeAt > 0 { await player.seek(to: CMTime(seconds: episode.resumeAt, preferredTimescale: 600), toleranceBefore: .zero, toleranceAfter: .zero) } heard = PlayHeard(table: episode.table, id: episode.id, from: player.currentTime().seconds) reported = player.currentTime().seconds art.image = nil if presents { present() } presents = false player.play() publish() if let key = episode.cover, let core { Task { [weak self, core] in guard let jpeg = await FilmPlayback.artwork(key, core: core), let image = UIImage(data: jpeg), let self, self.loaded?.cover == key else { return } self.art.image = image self.centre.show(art: image) } } else { centre.show(art: nil) } } private func watch(_ playing: AVPlayerItem, words: PlayerAnswer.Words) { status = playing.observe(\.status) { [weak self] observed, _ in guard observed.status == .failed else { return } Task { @MainActor in self?.say(words.refused) } } if let ending { NotificationCenter.default.removeObserver(ending) } ending = NotificationCenter.default.addObserver(forName: AVPlayerItem.didPlayToEndTimeNotification, object: playing, queue: .main) { [weak self] _ in MainActor.assumeIsolated { self?.finished() } } } // MARK: Apple's player over it private func present() { if let controller, controller.presentingViewController != nil { return } let controller = AVPlayerViewController() controller.player = player controller.delegate = self // The lock screen is this player's own (`SystemNowPlaying`). controller.updatesNowPlayingInfoCenter = false controller.allowsPictureInPicturePlayback = false controller.modalPresentationStyle = .fullScreen controller.view.accessibilityIdentifier = "podcast-player" if let overlay = controller.contentOverlayView { art.frame = overlay.bounds art.autoresizingMask = [.flexibleWidth, .flexibleHeight] overlay.addSubview(art) } self.controller = controller FilmPlayback.top()?.present(controller, animated: true) } /// Done or a swipe down: Apple's player goes, the episode plays on. nonisolated func playerViewController(_ playerViewController: AVPlayerViewController, willEndFullScreenPresentationWithAnimationCoordinator coordinator: UIViewControllerTransitionCoordinator) { // Read as the dismissal starts: by its end Apple's player has paused // what it leaves, and this one plays on. let wasPlaying = MainActor.assumeIsolated { self.player.timeControlStatus != .paused } coordinator.animate(alongsideTransition: nil) { context in guard !context.isCancelled else { return } MainActor.assumeIsolated { [weak self] in guard let self else { return } self.controller = nil if wasPlaying, self.player.timeControlStatus == .paused { self.player.play() } } } } // MARK: The controls func resume() { guard loaded != nil else { return } player.play() heard?.jumped(to: player.currentTime().seconds) } func pause() { player.pause() } func toggle() { player.timeControlStatus == .paused ? resume() : pause() } func seek(to seconds: TimeInterval) { let to = max(0, seconds) // The radio's needle stands where it was sent while the player gets there. now.stand(playing: player.timeControlStatus != .paused, elapsed: to, duration: length() ?? 0) heard?.jumped(to: to) player.seek(to: CMTime(seconds: to, preferredTimescale: 600), toleranceBefore: .zero, toleranceAfter: .zero) { [weak self] _ in MainActor.assumeIsolated { self?.publish() } } } /// The core's skip, back (negative) or forward: the lock screen's buttons. func skip(_ by: TimeInterval) { seek(to: player.currentTime().seconds + by) } // MARK: Where it stands private func tick(_ seconds: Double) { guard let loaded, seconds.isFinite else { return } if player.timeControlStatus == .playing { heard?.tick(seconds) } now.stand(playing: player.timeControlStatus != .paused, elapsed: seconds, duration: length() ?? 0) guard abs(seconds - reported) >= loaded.saveEvery else { return } report(at: seconds) publish() } private func changed(paused: Bool) { guard loaded != nil else { return } if paused { report(at: player.currentTime().seconds) } publish() } /// Where it stands, told to the core, which writes the episode's place. private func report(at seconds: Double) { guard let core, let standing = heard?.standing(at: seconds, duration: length(), device: UIDevice.current.model) else { return } reported = seconds Task { _ = try? await core.call(CottonMethod.shellPlayer, ["listened": standing], as: PlayerAnswer.self) } } /// The play's last report, as what plays next is asked for. private func leaving(_ ended: String) -> RecordValue? { heard?.report(ended: ended, at: player.currentTime().seconds, duration: length(), device: UIDevice.current.model) } /// The end: the core writes it played and moves on to the show's next, /// or stops. private func finished() { guard let core, loaded != nil else { return } var request: [String: RecordValue] = ["op": .text("next")] if let report = leaving("finished") { request["listened"] = report } Task { do { Players.took(try await core.call(CottonMethod.shellPlayer, request, as: PlayerAnswer.self)) } catch { say((error as? CottonCallError)?.message ?? ShellLines.line("cards", "podcast.could_not_play")) } } } /// Something else plays, or nothing: this player lets go. private func stop() { player.pause() player.replaceCurrentItem(with: nil) loaded = nil heard = nil now.hold(nil) centre.show(nil) if let controller, controller.presentingViewController != nil, !controller.isBeingDismissed { controller.dismiss(animated: true) } controller = nil } /// The length the player knows, else the core's. private func length() -> Double? { let known = player.currentItem?.duration.seconds if let known, known.isFinite, known > 0 { return known } return (loaded?.duration ?? 0) > 0 ? loaded?.duration : nil } private func publish() { guard let loaded else { return centre.show(nil) } let at = player.currentTime().seconds now.stand(playing: player.timeControlStatus != .paused, elapsed: at.isFinite ? at : now.elapsed, duration: length() ?? 0) centre.show(NowPlayingInfo(title: loaded.title, subtitle: loaded.artist, duration: length() ?? 0, elapsed: max(0, at.isFinite ? at : 0), playing: player.timeControlStatus != .paused, hasNext: false, hasPrevious: false, skips: loaded.skip)) } } // MARK: - Keeping an episode on the phone /// Keep on phone and Remove download (`episode.json`'s acts, the flows the /// root runs): an episode's audio comes down whole on a background session /// that outlives the app, into this phone's podcast folder, and goes again. @MainActor final class EpisodeKeeper: NSObject { static let shared = EpisodeKeeper() fileprivate struct Described: Codable { let address: String; let table: String; let title: String } /// The background session the files come down on. static let session = "cotton.podcasts.keep" /// The column an episode's audio is at (`episode.json`). static let audio = "audio_url" private var core: (any CottonCalling)? private var say: ((String) -> Void)? private var session: URLSession? private let delegate = EpisodeKeeperDelegate() private var tasks: [String: URLSessionDownloadTask] = [:] /// The core and the toasts, from the root once a core is open; the /// session made again so what iOS carried while the app was gone lands. func attach(core: any CottonCalling, say: @escaping (String) -> Void) { self.core = core self.say = say guard session == nil else { return } delegate.keeper = self let configuration = URLSessionConfiguration.background(withIdentifier: Self.session) configuration.sessionSendsLaunchEvents = true let session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: .main) self.session = session session.getAllTasks { found in let carried = found.compactMap { $0 as? URLSessionDownloadTask } Task { @MainActor [weak self] in for task in carried { if let address = Self.described(task)?.address { self?.tasks[address] = task } } } } } /// Keep on phone: the episode named by `origin`'s record comes down. func keep(table: String, id: String) async -> Bool { guard let core, let session, let record = try? await core.call(CottonMethod.recordsGet, ["table": RecordValue.text(table), "id": .text(id)], as: EpisodeRecordRead.self), let address = record.data[Self.audio]?.text, let url = URL(string: address) else { return false } do { try await EpisodeHereStore(core: core).keeping(address) } catch { say?((error as? CottonCallError)?.message ?? ShellLines.line("cards", "podcast.could_not_keep")) return false } let task = session.downloadTask(with: url) let described = Described(address: address, table: table, title: record.data["title"]?.text ?? "") task.taskDescription = String(decoding: (try? JSONEncoder().encode(described)) ?? Data(), as: UTF8.self) tasks[address] = task task.resume() return true } /// Remove download: what is coming down stops, the file goes, and the /// episode streams again. func remove(table: String, id: String) async -> Bool { guard let core, let record = try? await core.call(CottonMethod.recordsGet, ["table": RecordValue.text(table), "id": .text(id)], as: EpisodeRecordRead.self), let address = record.data[Self.audio]?.text else { return false } tasks[address]?.cancel() tasks[address] = nil let store = EpisodeHereStore(core: core) if let file = EpisodeFiles.url((try? await store.read(address))?.file) { try? FileManager.default.removeItem(at: file) } do { try await store.forget(address) return true } catch { say?((error as? CottonCallError)?.message ?? ShellLines.line("cards", "podcast.could_not_keep")) return false } } fileprivate static func described(_ task: URLSessionTask) -> Described? { guard let text = task.taskDescription else { return nil } return try? JSONDecoder().decode(Described.self, from: Data(text.utf8)) } /// The file is here, moved into the folder before the session takes it /// back; written as kept through the core. fileprivate func landed(_ task: URLSessionDownloadTask, at location: URL) { guard let address = Self.described(task)?.address else { return } tasks[address] = nil let name = EpisodeFiles.name(for: address) guard let folder = EpisodeFiles.folder() else { return failed(address) } let target = folder.appendingPathComponent(name) try? FileManager.default.removeItem(at: target) do { try FileManager.default.moveItem(at: location, to: target) } catch { return failed(address) } guard let core else { return } Task { [say] in do { try await EpisodeHereStore(core: core).kept(address, file: name) } catch { say?(ShellLines.line("cards", "podcast.could_not_keep")) } } } fileprivate func ended(_ task: URLSessionTask, error: Error?) { guard let error, let address = Self.described(task)?.address else { return } tasks[address] = nil // Cancelled is Remove download's own doing. if (error as NSError).code == NSURLErrorCancelled { return } failed(address) } private func failed(_ address: String) { say?(ShellLines.line("cards", "podcast.could_not_keep")) if let core { Task { try? await EpisodeHereStore(core: core).forget(address) } } } } /// The background session's delegate: the file is moved at once (the session /// deletes it when the call returns), the rest handed to the keeper on the /// main actor (the session's queue is main). private final class EpisodeKeeperDelegate: NSObject, URLSessionDownloadDelegate, @unchecked Sendable { weak var keeper: EpisodeKeeper? func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { // A server's refusal lands as a file too: only a whole answer is kept. if let http = downloadTask.response as? HTTPURLResponse, !(200..<300).contains(http.statusCode) { MainActor.assumeIsolated { keeper?.ended(downloadTask, error: URLError(.badServerResponse)) } return } MainActor.assumeIsolated { keeper?.landed(downloadTask, at: location) } } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { MainActor.assumeIsolated { keeper?.ended(task, error: error) } } } #endif