// 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.importCottonKitimportCottonValuesimportSwiftUI#if os(iOS)import AVFoundationimport AVKitimportCottonVoiceimportCryptoKitimport 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 @ObservablefinalclassPodcastNowPlaying {/// The episode held: its table and record, and its show's record.structHeld: Equatable {let table: Stringlet id: Stringlet podcast: String? }private(set) var held: Held?private(set) var playing = falseprivate(set) var loading = falseprivate(set) var elapsed: Double = 0private(set) var duration: Double = 0func 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 = falseif 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.structEpisodeHere: Equatable, Sendable {enumState: 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.structEpisodeHereStore: Sendable {let core: any CottonCallingprivatestructWire: Decodable {let state: String?let file: String? }func read(_ url: String) asyncthrows -> EpisodeHere {let wire = tryawait core.call(CottonMethod.episodesHereRead, ["url": RecordValue.text(url)], as: Wire.self)returnEpisodeHere(state: wire.state.flatMap(EpisodeHere.State.init(rawValue:)), file: wire.file) }func keeping(_ url: String) asyncthrows {tryawait write(url, ["state": .text(EpisodeHere.State.keeping.rawValue)]) }func kept(_ url: String, file: String) asyncthrows {tryawait write(url, ["state": .text(EpisodeHere.State.kept.rawValue), "file": .text(file)]) }func forget(_ url: String) asyncthrows {tryawait write(url, ["state": .null, "file": .null]) }privatefunc write(_ url: String, _ fields: [String: RecordValue]) asyncthrows {var request = fields request["url"] = .text(url) _ = tryawait 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.enumEpisodeFiles {/// The folder, under Application Support.staticlet name = "Podcasts"staticfunc folder() -> URL? {guardlet base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first else { returnnil }var folder = base.appendingPathComponent(name, isDirectory: true)try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)var values = URLResourceValues() values.isExcludedFromBackup = truetry? 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).staticfunc name(for address: String) -> String { #if os(iOS)let digest = SHA256.hash(data: Data(address.utf8)).map { String(format: "%02x", $0) }.joined() #elselet digest = String(address.hashValue, radix: 16) #endiflet 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.staticfunc url(_ file: String?) -> URL? {guardlet file, let folder = folder() else { returnnil }let url = folder.appendingPathComponent(file)returnFileManager.default.fileExists(atPath: url.path) ? url : nil }}/// An episode's record as `records.get` answers it: its columns.structEpisodeRecordRead: 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.@MainActorfinalclassPodcastPlayback: NSObject, AVPlayerViewControllerDelegate {staticlet 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()privatelet player = AVPlayer()privatelet centre = SystemNowPlaying()privatevar controller: AVPlayerViewController?privatevar core: (any CottonCalling)?privatevar say: (String) -> Void = { _ in }privatevar ticking: Any?privatevar rate: NSKeyValueObservation?privatevar status: NSKeyValueObservation?privatevar ending: NSObjectProtocol?/// What was heard of the play under way, and where it last reported.privatevar heard: PlayHeard?privatevar reported: Double = 0/// Apple's player goes up over the next episode the core answers.privatevar presents = false/// The art shown over Apple's player, which draws nothing for audio.privatelet art = UIImageView()/// Paused because a microphone opened (`VoiceAudioSession`): resumed/// when it closes. Ducked speech is still speech, so an episode pauses.privatevar pausedForListening = falseprivatevar listening: [NSObjectProtocol] = []privateoverrideinit() {super.init() listening = [NotificationCenter.default.addObserver(forName: VoiceAudioSession.willListen, object: nil, queue: .main) { [weakself] _ inMainActor.assumeIsolated {guardletself, self.player.timeControlStatus != .paused 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() } }, ] player.allowsExternalPlayback = true art.contentMode = .scaleAspectFit centre.connect(NowPlayingCommands( play: { [weakself] inself?.resume() }, pause: { [weakself] inself?.pause() }, toggle: { [weakself] inself?.toggle() }, next: {}, previous: {}, seek: { [weakself] to inself?.seek(to: to) }, skip: { [weakself] by inself?.skip(by) })) ticking = player.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: 600), queue: .main) { [weakself] now inMainActor.assumeIsolated { self?.tick(now.seconds) } } rate = player.observe(\.timeControlStatus) { [weakself] observed, _ inlet paused = observed.timeControlStatus == .pausedTask { @MainActor inself?.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) {guardlet record = item.record, FilmPlayer.of(item) == .audio else { return }iflet loaded, loaded.table == record.table, loaded.id == record.id {self.core = coreself.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) {iflet 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.privatefunc ask(table: String, id: String, presents: Bool, core: any CottonCalling, say: @escaping (String) -> Void) {self.core = coreself.say = sayvar 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 = presentsTask {do {Players.took(tryawait 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) {guardlet episode = answer.playing, episode.kind == "episode"else {if loaded != nil {iflet core, let report = leaving("stopped") {Task { _ = try? await core.call(CottonMethod.shellPlayer, ["listened": report], as: PlayerAnswer.self) } } stop() }return }iflet refusal = answer.refusal { say(refusal) }if loaded?.id == episode.id { return }Task { await start(episode, words: answer.words) } }privatefunc start(_ episode: PlayerPlaying, words: PlayerAnswer.Words) async {let source: URLiflet file = EpisodeFiles.url(episode.file) { source = file } elseiflet 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 = nilif presents { present() } presents = false player.play() publish()iflet key = episode.cover, let core {Task { [weakself, core] inguardlet jpeg = awaitFilmPlayback.artwork(key, core: core), let image = UIImage(data: jpeg), letself,self.loaded?.cover == key else { return }self.art.image = imageself.centre.show(art: image) } } else { centre.show(art: nil) } }privatefunc watch(_ playing: AVPlayerItem, words: PlayerAnswer.Words) { status = playing.observe(\.status) { [weakself] observed, _ inguard observed.status == .failed else { return }Task { @MainActor inself?.say(words.refused) } }iflet ending { NotificationCenter.default.removeObserver(ending) } ending = NotificationCenter.default.addObserver(forName: AVPlayerItem.didPlayToEndTimeNotification, object: playing, queue: .main) { [weakself] _ inMainActor.assumeIsolated { self?.finished() } } }// MARK: Apple's player over itprivatefunc present() {iflet 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"iflet overlay = controller.contentOverlayView { art.frame = overlay.bounds art.autoresizingMask = [.flexibleWidth, .flexibleHeight] overlay.addSubview(art) }self.controller = controllerFilmPlayback.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 inguard !context.isCancelled else { return }MainActor.assumeIsolated { [weakself] inguardletselfelse { return }self.controller = nilif wasPlaying, self.player.timeControlStatus == .paused { self.player.play() } } } }// MARK: The controlsfunc resume() {guard loaded != nilelse { 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) { [weakself] _ inMainActor.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 standsprivatefunc tick(_ seconds: Double) {guardlet 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() }privatefunc changed(paused: Bool) {guard loaded != nilelse { return }if paused { report(at: player.currentTime().seconds) } publish() }/// Where it stands, told to the core, which writes the episode's place.privatefunc report(at seconds: Double) {guardlet core, let standing = heard?.standing(at: seconds, duration: length(), device: UIDevice.current.model) else { return } reported = secondsTask { _ = try? await core.call(CottonMethod.shellPlayer, ["listened": standing], as: PlayerAnswer.self) } }/// The play's last report, as what plays next is asked for.privatefunc 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.privatefunc finished() {guardlet core, loaded != nilelse { return }var request: [String: RecordValue] = ["op": .text("next")]iflet report = leaving("finished") { request["listened"] = report }Task {do {Players.took(tryawait 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.privatefunc stop() { player.pause() player.replaceCurrentItem(with: nil) loaded = nil heard = nil now.hold(nil) centre.show(nil)iflet controller, controller.presentingViewController != nil, !controller.isBeingDismissed { controller.dismiss(animated: true) } controller = nil }/// The length the player knows, else the core's.privatefunc length() -> Double? {let known = player.currentItem?.duration.secondsiflet known, known.isFinite, known > 0 { return known }return (loaded?.duration ?? 0) > 0 ? loaded?.duration : nil }privatefunc publish() {guardlet 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.@MainActorfinalclassEpisodeKeeper: NSObject {staticlet shared = EpisodeKeeper()fileprivatestructDescribed: Codable { let address: String; let table: String; let title: String }/// The background session the files come down on.staticlet session = "cotton.podcasts.keep"/// The column an episode's audio is at (`episode.json`).staticlet audio = "audio_url"privatevar core: (any CottonCalling)?privatevar say: ((String) -> Void)?privatevar session: URLSession?privatelet delegate = EpisodeKeeperDelegate()privatevar 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 = coreself.say = sayguard session == nilelse { return } delegate.keeper = selflet configuration = URLSessionConfiguration.background(withIdentifier: Self.session) configuration.sessionSendsLaunchEvents = truelet session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: .main)self.session = session session.getAllTasks { found inlet carried = found.compactMap { $0 as? URLSessionDownloadTask }Task { @MainActor [weakself] infor task in carried {iflet 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 {guardlet 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 { returnfalse }do {tryawaitEpisodeHereStore(core: core).keeping(address) } catch { say?((error as? CottonCallError)?.message ?? ShellLines.line("cards", "podcast.could_not_keep"))returnfalse }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()returntrue }/// Remove download: what is coming down stops, the file goes, and the/// episode streams again.func remove(table: String, id: String) async -> Bool {guardlet 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 { returnfalse } tasks[address]?.cancel() tasks[address] = nillet store = EpisodeHereStore(core: core)iflet file = EpisodeFiles.url((try? await store.read(address))?.file) {try? FileManager.default.removeItem(at: file) }do {tryawait store.forget(address)returntrue } catch { say?((error as? CottonCallError)?.message ?? ShellLines.line("cards", "podcast.could_not_keep"))returnfalse } }fileprivatestaticfunc described(_ task: URLSessionTask) -> Described? {guardlet text = task.taskDescription else { returnnil }returntry? 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.fileprivatefunc landed(_ task: URLSessionDownloadTask, at location: URL) {guardlet address = Self.described(task)?.address else { return } tasks[address] = nillet name = EpisodeFiles.name(for: address)guardlet folder = EpisodeFiles.folder() else { return failed(address) }let target = folder.appendingPathComponent(name)try? FileManager.default.removeItem(at: target)do {tryFileManager.default.moveItem(at: location, to: target) } catch {return failed(address) }guardlet core else { return }Task { [say] indo {tryawaitEpisodeHereStore(core: core).kept(address, file: name) } catch { say?(ShellLines.line("cards", "podcast.could_not_keep")) } } }fileprivatefunc ended(_ task: URLSessionTask, error: Error?) {guardlet 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) }privatefunc failed(_ address: String) { say?(ShellLines.line("cards", "podcast.could_not_keep"))iflet core { Task { try? awaitEpisodeHereStore(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).privatefinalclassEpisodeKeeperDelegate: NSObject, URLSessionDownloadDelegate, @unchecked Sendable {weakvar 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.iflet 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