// A FILM PLAYS WITH APPLE'S PLAYER (owner, 4 Nov 2026: "stream it on my // phone … download it and keep it on my phone"; Cinemas definition, 5 Nov // 2026, section 5). Play, Play from the start and a tap on a film's card all // ask the core's one player (`shell.player` `play`): a film its own file, a // series its episode in progress with the episodes after it as the queue. // Its answer (`playing`, kind `film`) opens full screen in // `AVPlayerViewController` — the system's controls, AirPlay, picture in // picture, the lock screen — playing what the core names: the bundle this // phone kept, the whole file it kept, or the address the object signs (the // core mints it, and signs it again when its stream refuses it, on // `refresh_link`). On an AirPlay TV a sealed film plays from the phone's // Wi-Fi address, or through the phone, as the core answers `route` // (FilmRouting.swift). // // Every rule is the core's (`shell_player_kinds`): where it starts, the // subtitles and audio (`tracks`), when it is watched, and the next episode // (the queue, counted in for `next_after_s`). This reports where it stands // every `save_every_s` while it plays, at a pause and as it leaves // (`listened`): the core writes the resume point and the watch row. The // player comes up on the tap, over the title's picture and a spinner, and // nothing of ours animates over the film; one Subtitles button opens // Cinemas' own sheet. The next episode's count says "Next episode in 8" // over its end unless "Stay here" is tapped. The film stops when the phone locks or // the app goes; picture in picture and AirPlay play on. // // Anything else that plays — a clip shared in — is still the one viewer's // (`ViewerPlayerPage`). A podcast episode's audio plays in the app's one // audio player (`PodcastPlayback`). `FilmPlayer.of` is the only place that // decides. import CottonFaces import CottonKit import SwiftUI #if os(iOS) import AVFoundation import AVKit import Network import UIKit #endif /// Which player a thing the viewer was asked to show plays in. enum FilmPlayer: Equatable { /// A film's or an episode's record: what plays is the core's to say /// (`shell.player`), in Apple's player. case cinema /// The one viewer, from the whole file on disk (a picture, a document, a /// short clip). case viewer /// The app's one audio player (`PodcastPlayback`): a podcast episode, /// whose player column holds the publisher's web address, never a key. case audio /// The tables whose records play in Apple's player. static let tables: Set = ["film", "film_episode"] static func of(_ item: ViewerItem) -> FilmPlayer { if let record = item.record, tables.contains(record.table) { return .cinema } guard item.kind == .video else { return .viewer } return remote(item.key) ? .audio : .viewer } /// Whether `key` is a web address rather than an object key: what the /// one audio player plays from its publisher. static func remote(_ key: String?) -> Bool { guard let key = key?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() else { return false } return key.hasPrefix("https://") || key.hasPrefix("http://") } } /// A film's file as the object keeps it: an HLS master the Mac made, or a /// file kept whole (`films//whole.`). enum FilmKey { /// Whether `key` names an HLS master. static func streams(_ key: String?) -> Bool { guard let key else { return false } return key.trimmingCharacters(in: .whitespacesAndNewlines).lowercased().hasSuffix(".m3u8") } } // MARK: - What this phone keeps of a film /// What this device keeps of one film's file (`films.here.read`): the /// bundle a stream was kept as, or a whole file in the media store. struct FilmHere: Equatable, Sendable { enum State: String, Sendable { case keeping, kept } var bookmark: Data? var state: State? } /// The core's device-local store of films (`phone::films`): never synced. struct FilmHereStore: Sendable { let core: any CottonCalling private struct Wire: Decodable { let bookmark: String? let state: String? } func read(_ key: String) async throws -> FilmHere { let wire = try await core.call(CottonMethod.filmsHereRead, ["key": RecordValue.text(key)], as: Wire.self) return FilmHere(bookmark: wire.bookmark.flatMap { Data(base64Encoded: $0) }, state: wire.state.flatMap(FilmHere.State.init(rawValue:))) } /// Its file is coming down. func keeping(_ key: String) async throws { try await write(key, ["state": .text(FilmHere.State.keeping.rawValue)]) } /// A stream's bundle is here, at `bookmark`. func kept(_ key: String, bookmark: Data) async throws { try await write(key, ["state": .text(FilmHere.State.kept.rawValue), "bookmark": .text(bookmark.base64EncodedString())]) } /// A whole file landed at `file`: the core moves it into the store and keeps it. func adopt(_ key: String, from file: URL) async throws { try await write(key, ["state": .text(FilmHere.State.kept.rawValue), "from": .text(file.path)]) } /// Nothing of it is kept, or coming down, any more. func forget(_ key: String) async throws { try await write(key, ["state": .null]) } /// A whole file's Remove download: this phone's copy goes. func remove(_ key: String) async throws { _ = try await core.callJSON(CottonMethod.filmsRemove, ["key": RecordValue.text(key)]) } private func write(_ key: String, _ fields: [String: RecordValue]) async throws { var request = fields request["key"] = .text(key) _ = try await core.callJSON(CottonMethod.filmsHereWrite, request) } } /// The object's signed address for a film's file (`media.stream`). struct FilmStreamGrant: Decodable, Sendable { let url: String let expires_at: String static func mint(_ key: String, core: any CottonCalling) async throws -> URL { let grant = try await core.call(CottonMethod.mediaStream, ["key": RecordValue.text(key)], as: FilmStreamGrant.self) guard let url = URL(string: grant.url) else { throw CottonCallError(code: "unreadable", message: ShellLines.line("cards", "film.could_not_play")) } return url } } /// A kept bundle's place on disk, from its bookmark; nil when it is gone. enum FilmBundle { static func url(_ bookmark: Data?) -> URL? { guard let bookmark else { return nil } var stale = false guard let url = try? URL(resolvingBookmarkData: bookmark, bookmarkDataIsStale: &stale), FileManager.default.fileExists(atPath: url.path) else { return nil } return url } } #if os(iOS) // MARK: - The player /// One film on screen, in Apple's player, presented full screen over the /// whole app. Held while it plays or floats in picture in picture; the next /// episode plays in the same player. @MainActor final class FilmPlayback: NSObject, AVPlayerViewControllerDelegate { /// The film playing now; one at a time. private(set) static var current: FilmPlayback? private static var core: (any CottonCalling)? private static var say: ((String) -> Void)? // MARK: Prepared ahead (PLAYER START, RELAY 2; NEXT-HIDDEN2 item 9) /// The core's answer to `prepare`: whether it fetched the film's first window. private struct Prepared: Decodable, Sendable { var prepared: Bool? } /// A film's or an episode's page opened: the core fetches its first window from the object while the page is read /// (on mobile data, with films kept to Wi-Fi, it fetches nothing), so Play opens from what it holds. /// `hidden`: the title is on a page inside You › Hidden, where only the hidden titles are found (HIDE NEXT 2). static func prepare(table: String, id: String, hidden: Bool = false) { guard let core, table == "film" || table == "film_episode" else { return } var request: [String: RecordValue] = ["op": .text("prepare"), "table": .text(table), "id": .text(id), "network": .text(FilmNetwork.kind), "constrained": .bool(FilmNetwork.constrained)] if hidden { request["hidden"] = .bool(true) } inOrder { let started = ContinuousClock.now let prepared = try? await core.call(CottonMethod.shellPlayer, request, as: Prepared.self) let ms = Int((ContinuousClock.now - started) / .milliseconds(1)) PlayClock.note("prepare \(table) on \(FilmNetwork.kind): \(prepared?.prepared.map(String.init) ?? "refused"), answered in \(ms) ms") } } /// The page left: its prepared windows go. static func unprepare() { guard let core else { return } inOrder { _ = try? await core.call(CottonMethod.shellPlayer, ["op": RecordValue.text("unprepare")], as: JSONValue.self) } } /// The app gone to the background, or a film stopped: every film's prepared windows go. static func release() { guard let core else { return } inOrder { _ = try? await core.call(CottonMethod.shellPlayer, ["op": RecordValue.text("release")], as: JSONValue.self) } } /// Prepare, unprepare and release reach the core in the order they were asked: a film closing lets go (`release`) /// as Home shows again and prepares its Featured, and the release must not land after that prepare. private static var lastAsk: Task? /// After a film stops: the app prepares again what its screen shows. static var released: (@MainActor () -> Void)? private static func inOrder(_ ask: @escaping @MainActor () async -> Void) { let before = lastAsk lastAsk = Task { @MainActor in await before?.value await ask() } } /// Whether anything plays now (picture in picture, the TV): the background then lets nothing go. static var isPlaying: Bool { current != nil } /// The poster on the lock screen, longest side. static let artworkPixels = 1024 /// The core and the toasts, from the root once a core is open. /// Where the player's words are said: an app with its own toast (Cinemas) says them there, not the shell's. static func speak(_ say: @escaping (String) -> Void) { Self.say = say } static func attach(core: any CottonCalling, say: @escaping (String) -> Void) { self.core = core self.say = say } /// A film's or an episode's record, dealt by the core's player and /// played from where it says: a tap on its card. /// /// The player comes up on the tap itself, over `cover` (the title's picture, when the screen has it) with a /// spinner, and the core is asked behind it (NEXT.md, 26 Nov: it took 4 to 8 s, waiting on everything first). static func ask(table: String, id: String, at seconds: Double? = nil, cover: UIImage? = nil, hidden: Bool = false) async { PlayClock.tap() guard let core, let say else { return } current?.end(clearing: false) let playback = FilmPlayback(core: core, say: say) playback.opening = true current = playback playback.present(waiting: cover) var request: [String: RecordValue] = ["op": .text("play"), "table": .text(table), "id": .text(id)] // Played from inside You › Hidden: the core finds it among the hidden titles (a hidden title is no record to // any other read: without this, Play and Carry on in Hidden were refused "no such record"). if hidden { request["hidden"] = .bool(true) } // Play from the start: the same play at 0 (CONTRACT-2 "A title"). if let seconds { request["at_s"] = .number(seconds) } // Cotton slow or not answering (the server taking 2 to 10 s, or none): the player stays up, says so, and asks // again, until it plays or he closes it. A refusal that is the film's own (it cannot play here) ends it. let began = ContinuousClock.now var tries = 0 while !playback.ended { do { #if COTTON_DEV try await FilmThrottle.coreAsk() #endif let answer = try await core.call(CottonMethod.shellPlayer, request, as: PlayerAnswer.self) PlayClock.mark("core answered shell.player play") guard !playback.ended else { return } if FilmSlow.again(answer, since: began) { PlayClock.note("the core could not reach the film: asked again") tries += 1 playback.slow.on() try? await Task.sleep(for: FilmSlow.wait(tries)) continue } Players.took(answer) return } catch { guard !playback.ended else { return } if FilmSlow.again(error) { PlayClock.note("the core did not answer: asked again") tries += 1 playback.slow.on() try? await Task.sleep(for: FilmSlow.wait(tries)) continue } playback.end(clearing: false) say((error as? CottonCallError)?.message ?? ShellLines.line("cards", "film.could_not_play")) return } } } /// The core's player answered: a film playing is this player's (the one /// on screen plays the next episode itself); anything else ends it. static func took(_ answer: PlayerAnswer) { guard let film = answer.playing, film.kind == "film" else { current?.end(clearing: false) return } if let refusal = answer.refusal { say?(refusal) } if let current, current.opening, !current.ended { current.opening = false Task { await current.start(answer) } return } if let current, current.playing?.id == film.id { return current.answered(answer) } guard let core, let say else { return } current?.end(clearing: false) let playback = FilmPlayback(core: core, say: say) current = playback Task { await playback.start(answer) } } /// "Cotton is slow right now · trying again", over the picture while the film waits on Cotton. let slow = FilmSlow() private var slowWatch: Task? private var failures = 0 private(set) var playing: PlayerPlaying? /// The core's last answer: what plays after this one. private var answer: PlayerAnswer? /// The film whose next episode is prepared already. private var preparedNext: String? /// A hidden title plays (the core's `discreet`): its name and poster now-playing never shows. private var secret = false private var artwork: Data? /// Whether Hidden is open now, as Cinemas says. static var hiddenOpen: (@MainActor () -> Bool)? /// What the lock screen's now-playing (and a TV's) says of the film: its name and poster, or for a hidden title /// "Cinemas" and no picture, Hidden open or shut (HIDE FROM SCREEN 3: someone else may be looking, or he casts). private func shown() { guard let item = player.currentItem else { return } let veiled = secret let said = Self.nowPlaying(hidden: secret, open: Self.hiddenOpen?() ?? false, title: playing?.marquee, artwork: artwork, veil: ShellLines.line("cinemas", "stream.hidden_now_playing")) item.externalMetadata = Self.metadata(title: said.title, artwork: said.artwork) #if COTTON_DEV PlayClock.note("now-playing says \(veiled ? "the veil" : "its title")\(artwork != nil && !veiled ? ", with its poster" : "")") #endif } /// What now-playing says: the film's name and poster, or for a hidden title the veil and no picture, whether Hidden /// is open or not (`open` is kept for the callers; it no longer lifts the veil). nonisolated static func nowPlaying(hidden: Bool, open: Bool, title: String?, artwork: Data?, veil: String) -> (title: String?, artwork: Data?) { hidden ? (veil, nil) : (title, artwork) } /// Hidden opened or shut: what now-playing says follows. static func hiddenChanged() { current?.shown() } /// The data changed (a category hidden or shown, on this phone or synced in from another): the core is asked where /// the play stands, so the veil follows within a second, not at the next play. static func dataChanged() { current?.recheck() } /// `shell.player {}`: reports nothing and writes nothing; its answer says whether what plays is discreet now. private func recheck() { guard let id = playing?.id, !ended else { return } Task { [core] in guard let answer = try? await core.call(CottonMethod.shellPlayer, [String: RecordValue](), as: PlayerAnswer.self) else { return } self.follow(answer, playing: id) } } /// An answer about the film still playing: discreet as the core now says. Turned discreet, now-playing loses its /// title and poster at once, and a film floating in picture-in-picture closes, so a hidden title's picture never /// stays out over Home or another app. private func follow(_ answer: PlayerAnswer, playing id: String) { guard !ended, playing?.id == id, let film = answer.playing, film.id == id else { return } self.answer = answer let turn = Self.turned(veiled: secret, floating: floating, discreet: film.discreet == true) guard turn.veiled != secret else { return } secret = turn.veiled shown() if turn.close { closeFloating() } } /// What an answer about the playing film turns: the veil as the core says, and whether a floating window closes /// (only when it has just turned discreet). nonisolated static func turned(veiled: Bool, floating: Bool, discreet: Bool) -> (veiled: Bool, close: Bool) { (discreet, discreet && !veiled && floating) } /// Its little window goes, and the film with it (where it stood is told to the core first). private func closeFloating() { #if COTTON_DEV PlayClock.note("picture-in-picture closed: the film is hidden now") #endif controller.allowsPictureInPicturePlayback = false end(clearing: true) player.replaceCurrentItem(with: nil) controller.player = nil } /// How near its end an episode prepares the next. static let prepareNextAt: Double = 60 private let core: any CottonCalling private let say: (String) -> Void private let controller = AVPlayerViewController() private let player = AVPlayer() private var ticking: Any? private var watchers: [NSObjectProtocol] = [] private var status: NSKeyValueObservation? /// The first frame on screen (PlayClock). private var framed: NSKeyValueObservation? private var control: NSKeyValueObservation? /// A film on a TV: what the core answered for the route, and its watch. private var routing = FilmRouting() private var external: NSKeyValueObservation? private var checkTask: Task? /// The item is being replaced where it stands: no report of the new one's nought. private var replaying = false /// What was heard of this play, and where it last reported. private var heard: PlayHeard? private var reported: Double = 0 /// Up on the tap, the core's answer not yet in: the answer that comes is this player's. private var opening = false /// The title's picture and a spinner over the picture, until its first frame. private var waiting: UIView? private var nextCount: UIView? private var nextTask: Task? /// A refused stream asked to be signed again, its answer not yet in. private var relinking = false private var floating = false private var ended = false /// The film's own subtitles (FilmSubtitles.swift): its cues drawn here while shifted, the timing control. private lazy var cues = FilmSubtitleCues(player: player) /// The one button of ours over the picture: Subtitles, Cinemas' own sheet (find, make, give, the tracks). private var subtitlesButton: UIView? private var subtitlesHide: Task? /// The choice last told to the core, or read from it: a selection the player makes itself is told once. private var toldChoice: PlayerPlaying.Tracks.SubtitleChoice? private var choosing = false /// The film's subtitle tracks as the player lists them, once its asset said. private var legibleGroup: AVMediaSelectionGroup? /// Each of those tracks' own names (the master's NAME, "French (made on your Mac)"), in the group's order. private var legibleNames: [String] = [] private init(core: any CottonCalling, say: @escaping (String) -> Void) { self.core = core self.say = say super.init() } private func start(_ answer: PlayerAnswer) async { // Playback: heard with the switch on silent, a long film's route for // AirPlay. The app keeps no background audio for it. try? AVAudioSession.sharedInstance().setCategory(.playback, mode: .moviePlayback, policy: .longFormVideo) try? AVAudioSession.sharedInstance().setActive(true) PlayClock.mark("audio session active") guard await open(answer) else { return end(clearing: true) } if controller.presentingViewController == nil { present(waiting: nil) } offerSubtitles() player.play() } /// The answer's film as the player's item, where the core says it /// starts, its tracks chosen; false when it cannot be played. private func open(_ answer: PlayerAnswer) async -> Bool { guard let film = answer.playing, let asset = await asset(film) else { Log.write("film: nothing to play — playing \(answer.playing != nil), file \(answer.playing?.file ?? "none"), stream \(answer.playing?.stream == nil ? "none" : "given"), bundle \(answer.playing?.bundle != nil), refusal \(answer.refusal ?? "none")") if answer.refusal == nil { say(answer.words.refused) } return false } PlayClock.mark(asset.url.isFileURL ? "file found on this phone" : "stream address in hand") guard !ended else { return false } self.answer = answer playing = film // Discreet follows the core's answer (anything hidden that plays), never where the play began. secret = film.discreet == true // Already on a TV: the core says how before anything loads, so the TV // is handed the Wi-Fi address first, never this phone's 127.0.0.1. var from = asset var then: [FilmRouting.Act] = [] if let ask = routing.opening(onTV: Self.onAirPlay || player.isExternalPlaybackActive) { let route = await routed(ask, at: film.resumeAt, paused: false) guard !ended else { return false } let first = routing.first(route) if let url = first.from { from = AVURLAsset(url: url) } // Kept from the TV before the item is there to hand it. let tv = first.acts.filter { if case .allowTV = $0 { true } else { false } } perform(tv) then = first.acts.filter { !tv.contains($0) } } #if COTTON_DEV if ProcessInfo.processInfo.arguments.contains("-play-no-wait") { player.automaticallyWaitsToMinimizeStalling = false } #endif load(from) PlayClock.mark("item made") if let item = player.currentItem { cues.follow(item) } cues.shift(film.tracks?.offsetMs ?? 0) // Where it resumes: asked of the item before it plays, never waited on here (the player starts there). It may // start up to a keyframe earlier (at most 10 s): an exact place on a stream first fetches and decodes all // from that keyframe, seconds before any picture (26 Nov, timed). if film.resumeAt > 0 { player.currentItem?.seek(to: CMTime(seconds: film.resumeAt, preferredTimescale: 600), toleranceBefore: CMTime(seconds: Self.resumeEarlier, preferredTimescale: 600), toleranceAfter: .zero) { _ in Task { @MainActor in PlayClock.mark("seeked to the resume point") } } } // The subtitles and audio chosen alongside: reading the tracks waits on the stream's header, never the // first frame. Task { [weak self] in await self?.choose(from, film.tracks) PlayClock.mark("tracks read and chosen") } reported = film.resumeAt heard = PlayHeard(table: film.table, id: film.id, from: reported) perform(then) return true } /// What the core named: the kept bundle, the kept whole file, or the /// address it signed. private func asset(_ film: PlayerPlaying) async -> AVURLAsset? { if let bundle = FilmBundle.url(film.bundle.flatMap { Data(base64Encoded: $0) }) { return AVURLAsset(url: bundle) } if let key = film.file, let file = await CoreAttachmentStore(core: core).localURL(for: key) { return AVURLAsset(url: file) } #if COTTON_DEV return film.stream.flatMap(URL.init(string:)).map { AVURLAsset(url: FilmThrottle.route($0)) } #else return film.stream.flatMap(URL.init(string:)).map { AVURLAsset(url: $0) } #endif } /// `asset` as the player's item, with the lock screen's title and poster. private func load(_ asset: AVURLAsset) { let item = AVPlayerItem(asset: asset) player.replaceCurrentItem(with: item) follow(item) artwork = nil shown() guard let poster = playing?.cover else { return } Task { [weak self, core] in guard let artwork = await Self.artwork(poster, core: core), let self, self.player.currentItem === item else { return } self.artwork = artwork self.shown() } } /// The subtitles and the audio the core's tracks name, where the film /// carries them: the film's own choice (a track, or off), else subtitles /// in the cinema's language (the phone's when none is named; none when /// off), the audio in its. private func choose(_ asset: AVURLAsset, _ tracks: PlayerPlaying.Tracks?) async { guard let item = player.currentItem, let tracks else { return } if let legible = try? await asset.loadMediaSelectionGroup(for: .legible) { var names: [String] = [] for option in legible.options { names.append(await Self.name(of: option)) } let offered = zip(legible.options, names).map { FilmSubtitlePick.Offered(language: $0.extendedLanguageTag ?? $0.locale?.identifier, name: $1) } legibleGroup = legible legibleNames = names toldChoice = tracks.choice choosing = true let pick = FilmSubtitlePick.pick(offered, tracks: tracks, phone: Locale.preferredLanguages.first, allowsOff: legible.allowsEmptySelection) // A track or Off chosen here stands as chosen: left to the player's own criteria, a track in the // audio's language shows its forced lines only (French over French speech showed nothing). player.appliesMediaSelectionCriteriaAutomatically = pick == .leave switch pick { case .off: item.select(nil, in: legible) case .option(let index): item.select(legible.options[index], in: legible) case .leave: break } choosing = false } if let language = tracks.audioLanguage, let audible = try? await asset.loadMediaSelectionGroup(for: .audible), let option = AVMediaSelectionGroup.mediaSelectionOptions(from: audible.options, with: Locale(identifier: language)).first { item.select(option, in: audible) } } /// A subtitle track's own name: the master's NAME (its title), else the player's name for it (often only the language). private static func name(of option: AVMediaSelectionOption) async -> String { if let title = AVMetadataItem.metadataItems(from: option.commonMetadata, filteredByIdentifier: .commonIdentifierTitle).first, let text = try? await title.load(.stringValue), !text.isEmpty { return text } return option.displayName } /// The system player, up at once; until the first frame, `cover` and a spinner stand over the picture. private func present(waiting cover: UIImage?) { controller.player = player controller.delegate = self controller.allowsPictureInPicturePlayback = true controller.canStartPictureInPictureAutomaticallyFromInline = false controller.updatesNowPlayingInfoCenter = true controller.modalPresentationStyle = .fullScreen controller.view.accessibilityIdentifier = "film-player" controller.overrideUserInterfaceStyle = .dark Self.top()?.present(controller, animated: true) PlayClock.mark("player presented") if let overlay = controller.contentOverlayView { let host = UIHostingController(rootView: FilmWaiting(cover: cover)) host.view.backgroundColor = .clear host.view.isUserInteractionEnabled = false host.view.frame = overlay.bounds host.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] overlay.addSubview(host.view) waiting = host.view cues.place(in: overlay) let note = UIHostingController(rootView: FilmSlowNote(slow: slow)) note.view.backgroundColor = .clear note.view.isUserInteractionEnabled = false note.view.frame = overlay.bounds note.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] overlay.addSubview(note.view) } // No picture after a few seconds: say so, while it keeps coming. slowWatch?.cancel() slowWatch = Task { [weak self] in try? await Task.sleep(for: FilmSlow.after) guard let self, !Task.isCancelled, !self.ended, self.waiting != nil else { return } PlayClock.note("no picture after \(FilmSlow.after): said slow") self.slow.on() } framed = controller.observe(\.isReadyForDisplay, options: [.initial, .new]) { [weak self] observed, _ in guard observed.isReadyForDisplay else { return } Task { @MainActor in #if COTTON_DEV if let item = self?.player.currentItem, let event = item.accessLog()?.events.last { let host = (item.asset as? AVURLAsset)?.url.host() ?? "file" PlayClock.mark("from \(host): \(Int(event.observedBitrate / 1000)) kbit/s observed, \(event.numberOfBytesTransferred / 1024) KB in, startup \(String(format: "%.2f", event.startupTime)) s") } #endif PlayClock.mark("first frame", last: true) self?.slowWatch?.cancel() self?.slow.off() self?.failures = 0 guard let shown = self?.waiting else { return } self?.waiting = nil UIView.animate(withDuration: 0.2, animations: { shown.alpha = 0 }, completion: { _ in shown.removeFromSuperview() }) } } } // MARK: The film's own subtitles /// The selection the player made, told to the core when it is the person's (not this player's own choosing). private func selectionChanged(_ item: AVPlayerItem) { guard !choosing, !ended, let group = legibleGroup else { return } let chosen: PlayerPlaying.Tracks.SubtitleChoice if let option = item.currentMediaSelection.selectedMediaOption(in: group) { let index = group.options.firstIndex(of: option) let name = index.flatMap { legibleNames.indices.contains($0) ? legibleNames[$0] : nil } ?? option.displayName chosen = .track(language: option.extendedLanguageTag ?? option.locale?.identifier ?? "und", name: name) } else { chosen = .off } guard chosen != toldChoice else { return } toldChoice = chosen let said: RecordValue switch chosen { case .off: said = .text("off") case .track(let language, let name): said = .object(["language": .text(language), "name": .text(name)]) } let request: [String: RecordValue] = ["op": .text("subtitles"), "choice": said] Task { [core] in _ = try? await core.call(CottonMethod.shellPlayer, request, as: PlayerAnswer.self) } } /// Subtitles, the one button of ours over the picture (NEXT-PLAYER.md, 26 Nov): Cinemas' own sheet, where the /// film's subtitles are found, made or given and its tracks listed. Picking a track or Off, and the audio, stay /// the system player's own menu. Shown with each tap, then let go with the player's controls. static var subtitlesSheet: (@MainActor (PlayerPlaying) -> UIViewController?)? private func offerSubtitles() { guard subtitlesButton == nil, let film = playing, Self.subtitlesSheet != nil else { return } let host = UIHostingController(rootView: FilmSubtitlesButton(label: ShellLines.line("cinemas", "home.act_subtitles")) { [weak self] in self?.openSubtitles(film) }) host.view.backgroundColor = .clear host.view.translatesAutoresizingMaskIntoConstraints = false controller.view.addSubview(host.view) NSLayoutConstraint.activate([ host.view.trailingAnchor.constraint(equalTo: controller.view.safeAreaLayoutGuide.trailingAnchor, constant: -12), host.view.topAnchor.constraint(equalTo: controller.view.safeAreaLayoutGuide.topAnchor, constant: Self.playerTopRow), ]) subtitlesButton = host.view let tap = UITapGestureRecognizer(target: self, action: #selector(tapped)) tap.cancelsTouchesInView = false tap.delegate = FilmTapsAlongside.shared controller.view.addGestureRecognizer(tap) showSubtitlesButton() } @objc private func tapped() { showSubtitlesButton() } private func showSubtitlesButton() { guard let button = subtitlesButton else { return } subtitlesHide?.cancel() UIView.animate(withDuration: 0.2) { button.alpha = 1 } subtitlesHide = Task { [weak self] in try? await Task.sleep(for: .seconds(4)) guard !Task.isCancelled else { return } UIView.animate(withDuration: 0.3) { self?.subtitlesButton?.alpha = 0 } } } private func openSubtitles(_ film: PlayerPlaying) { guard let sheet = Self.subtitlesSheet?(playing ?? film) else { return } controller.present(sheet, animated: true) } /// How much earlier than its place a film may resume, to start on a keyframe. static let resumeEarlier: Double = 10 /// The player's own top row (Close, AirPlay, mute) stands this far under the status bar while its controls show: /// the Subtitles button hangs below it, never under its buttons. static let playerTopRow: CGFloat = 56 // MARK: Watching it play private func follow(_ item: AVPlayerItem) { if ticking == nil { ticking = player.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: 600), queue: .main) { [weak self] now in MainActor.assumeIsolated { self?.tick(now.seconds) } } } if control == nil { control = player.observe(\.timeControlStatus) { [weak self] observed, _ in let status = observed.timeControlStatus let stalled = status == .waitingToPlayAtSpecifiedRate && observed.reasonForWaitingToPlay != .noItemToPlay Task { @MainActor in if status == .paused { self?.paused() } self?.stalled(stalled, playing: status == .playing) } } } if external == nil { external = player.observe(\.isExternalPlaybackActive, options: [.initial, .new]) { [weak self] observed, _ in let active = observed.isExternalPlaybackActive Task { @MainActor in if active { self?.externalBegan() } else { self?.routeChanged() } } } } status = item.observe(\.status) { [weak self] observed, _ in if observed.status == .readyToPlay { Task { @MainActor in PlayClock.mark("item ready to play") } } guard observed.status == .failed else { return } Task { @MainActor in self?.failed(observed) } } watchers.forEach(NotificationCenter.default.removeObserver) watchers = [ NotificationCenter.default.addObserver(forName: AVPlayerItem.newErrorLogEntryNotification, object: item, queue: .main) { [weak self] _ in MainActor.assumeIsolated { self?.logged(item) } }, NotificationCenter.default.addObserver(forName: AVPlayerItem.didPlayToEndTimeNotification, object: item, queue: .main) { [weak self] _ in MainActor.assumeIsolated { self?.finished() } }, NotificationCenter.default.addObserver(forName: AVPlayerItem.timeJumpedNotification, object: item, queue: .main) { [weak self] _ in MainActor.assumeIsolated { guard let self else { return } self.heard?.jumped(to: self.player.currentTime().seconds) self.cues.jumped() } }, // A track picked in the player's subtitle menu (or Off) is the film's: told to the core, kept on its row. NotificationCenter.default.addObserver(forName: AVPlayerItem.mediaSelectionDidChangeNotification, object: item, queue: .main) { [weak self] _ in MainActor.assumeIsolated { self?.selectionChanged(item) } }, // The route left AirPlay: the film comes back to the phone. NotificationCenter.default.addObserver(forName: AVAudioSession.routeChangeNotification, object: nil, queue: .main) { [weak self] _ in MainActor.assumeIsolated { self?.routeChanged() } }, // Locked or sent home: the film stops (no background audio for // a film); picture in picture and AirPlay play on. NotificationCenter.default.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: .main) { [weak self] _ in MainActor.assumeIsolated { guard let self, !self.floating, !self.player.isExternalPlaybackActive else { return } self.player.pause() } }, ] } private func tick(_ seconds: Double) { guard let playing, seconds.isFinite, !replaying else { return } if player.timeControlStatus == .playing { heard?.tick(seconds) } // The next episode, prepared in the last minute, so it starts from what is fetched. if preparedNext != playing.id, let next = answer?.following.first, let length = length(), length - seconds < Self.prepareNextAt { preparedNext = playing.id Self.prepare(table: next.table, id: next.id) } guard abs(seconds - reported) >= playing.saveEvery else { return } report(at: seconds) } /// Paused: where it stands is told. /// Waiting on the film's bytes for a few seconds after it played: say Cotton is slow, until the picture moves. private func stalled(_ waiting: Bool, playing: Bool) { guard waiting else { if waiting == false, waitingSince != nil { waitingSince = nil } if self.waiting == nil { slowWatch?.cancel(); slow.off() } return } guard self.waiting == nil, waitingSince == nil else { return } waitingSince = .now slowWatch?.cancel() slowWatch = Task { [weak self] in try? await Task.sleep(for: FilmSlow.after) guard let self, !Task.isCancelled, !self.ended, self.waitingSince != nil else { return } PlayClock.note("waiting on the film for \(FilmSlow.after): said slow") self.slow.on() } } private var waitingSince: ContinuousClock.Instant? private func paused() { guard !ended, !replaying else { return } report(at: player.currentTime().seconds) } private func length() -> Double? { let known = player.currentItem?.duration.seconds return known.flatMap { $0.isFinite && $0 > 0 ? $0 : nil } } /// Where it stands, told to the core, which writes the resume point and /// the watch row. private func report(at seconds: Double) { guard let standing = heard?.standing(at: seconds, duration: length(), device: UIDevice.current.model) else { return } reported = seconds let id = playing?.id Task { [core] in guard let answer = try? await core.call(CottonMethod.shellPlayer, ["listened": standing], as: PlayerAnswer.self), let id else { return } self.follow(answer, playing: id) } } /// The core answered while this film plays: a fresh link, or the next. private func answered(_ answer: PlayerAnswer) { self.answer = answer } /// The end of the film: the core hears it finished; the next episode, /// where the queue holds one, is counted in for the core's seconds. private func finished() { guard let report = heard?.report(ended: "finished", at: player.currentTime().seconds, duration: length(), device: UIDevice.current.model) else { return } Task { guard let answer = try? await core.call(CottonMethod.shellPlayer, ["listened": report], as: PlayerAnswer.self), !self.ended else { return } self.answer = answer guard let next = answer.following.first, let film = answer.playing, film.nextAfter > 0 else { return } countNext(next, seconds: Int(film.nextAfter)) } } // MARK: The next episode /// "Next episode in 10" over the player's end, counting down; "Stay /// here" puts it away, "Next episode" plays it now. private func countNext(_ next: PlayerFollowing, seconds: Int) { nextTask?.cancel() nextCount?.removeFromSuperview() let count = FilmNextCount(started: Date(), seconds: seconds, next: { [weak self] in self?.playNext() }, stay: { [weak self] in self?.stay() }) let host = UIHostingController(rootView: count) host.view.backgroundColor = .clear host.view.translatesAutoresizingMaskIntoConstraints = false controller.view.addSubview(host.view) NSLayoutConstraint.activate([ host.view.leadingAnchor.constraint(equalTo: controller.view.leadingAnchor), host.view.trailingAnchor.constraint(equalTo: controller.view.trailingAnchor), host.view.centerYAnchor.constraint(equalTo: controller.view.centerYAnchor), ]) nextCount = host.view nextTask = Task { [weak self] in try? await Task.sleep(for: .seconds(seconds)) guard !Task.isCancelled else { return } self?.playNext() } } private func stay() { nextTask?.cancel() nextTask = nil nextCount?.removeFromSuperview() nextCount = nil } /// The next episode: the core moves on, and it plays in the same player. private func playNext() { stay() Task { do { let answer = try await core.call(CottonMethod.shellPlayer, ["op": RecordValue.text("next")], as: PlayerAnswer.self) if let refusal = answer.refusal { say(refusal) } guard answer.playing?.kind == "film", await open(answer) else { return } player.play() } catch { say((error as? CottonCallError)?.message ?? ShellLines.line("cards", "film.could_not_play")) } } } // MARK: A stream's address running out /// A segment or playlist refused 403: the signed address ran out. The /// core signs it again, or says it will not. private func logged(_ item: AVPlayerItem) { guard item.errorLog()?.events.last?.errorStatusCode == 403 else { return } relink() } private func failed(_ item: AVPlayerItem) { // On a TV, a film that fails plays through the phone: never an error. if let ask = routing.failed() { return route(ask) } let refused = item.errorLog()?.events.contains { $0.errorStatusCode == 403 } ?? false let last = item.errorLog()?.events.last Log.write("film: failed — \(item.error.map { String(describing: $0) } ?? "no error"); log \(last?.errorStatusCode ?? 0) \(last?.errorDomain ?? "") \(last?.errorComment ?? ""); stream \(playing?.stream.flatMap(URL.init(string:))?.host ?? "none")") // A sealed whole film plays from the core's own door on this phone // (R6). iOS takes a suspended app's listener back, so a film that // stops there is asked again: the core offers it at the door it // opens in its place, and refuses in the film's words when the door // it named still stands. let ownDoor = playing?.stream.flatMap(URL.init(string:))?.host == "127.0.0.1" if refused || ownDoor, playing?.stream != nil { // Most often Cotton was slow and the relay gave up: say so and try again, the same address first (its door // still stands), then a new one from the core. failures += 1 slow.on() return retry() } say(answer?.words.refused ?? ShellLines.line("cards", "film.could_not_play")) } /// The film again where it stood, after a wait that grows to 10 s: the same address, or every other time a fresh /// one from the core. Until it plays or he closes it. private func retry() { let at = player.currentTime() let tries = failures Task { [weak self] in try? await Task.sleep(for: FilmSlow.wait(tries)) guard let self, !self.ended else { return } PlayClock.note("film failed \(tries) time(s): tried again") if tries % 2 == 1, let url = (self.player.currentItem?.asset as? AVURLAsset)?.url { self.load(AVURLAsset(url: url)) await self.player.seek(to: at, toleranceBefore: .zero, toleranceAfter: .zero) self.player.play() } else { self.relink() } } } private func relink() { guard !relinking, !ended, playing?.stream != nil else { return } relinking = true let at = player.currentTime() let wasPlaying = player.timeControlStatus != .paused Task { defer { relinking = false } do { let answer = try await core.call(CottonMethod.shellPlayer, ["op": RecordValue.text("refresh_link")], as: PlayerAnswer.self) if answer.refusal != nil, slow.shown { // Asked again too soon, or Cotton still slow: keep trying while he waits. failures += 1 return retry() } if let refusal = answer.refusal { return say(refusal) } guard let film = answer.playing, film.id == playing?.id, let url = film.stream.flatMap(URL.init(string:)), !ended else { return } self.answer = answer playing = film load(AVURLAsset(url: url)) await player.seek(to: at, toleranceBefore: .zero, toleranceAfter: .zero) heard?.jumped(to: at.seconds) if wasPlaying { player.play() } } catch { if slow.shown, FilmSlow.again(error) { failures += 1 return retry() } say((error as? CottonCallError)?.message ?? ShellLines.line("cards", "film.could_not_play")) } } } // MARK: A film on a TV (FilmRouting.swift) /// Whether the phone's sound goes out over AirPlay now. private static var onAirPlay: Bool { AVAudioSession.sharedInstance().currentRoute.outputs.contains { $0.portType == .airPlay } } /// Apple's player began playing to a TV: the core says how. private func externalBegan() { guard !ended, playing != nil, let ask = routing.began() else { return } route(ask) } /// The route changed: left AirPlay (the sound off it, and Apple's player /// no longer handing the film to a TV), the film comes back to the phone. private func routeChanged() { guard !ended, !Self.onAirPlay, !player.isExternalPlaybackActive else { return } checkTask?.cancel() let (ask, acts) = routing.cameBack() perform(acts) if let ask { route(ask) } } /// Stop on TV: the core hears the film came back to the phone, whatever the sound's route still says. fileprivate func leftTV() { guard !ended else { return } checkTask?.cancel() let (ask, acts) = routing.cameBack() perform(acts.filter { if case .allowTV = $0 { false } else { true } }) if let ask { route(ask) } } /// Ask the core what the film does on the route `to`, and do it. A core /// that does not answer leaves the film playing through the phone. private func route(_ to: String) { let id = playing?.id let at = player.currentTime().seconds let paused = player.timeControlStatus == .paused Task { let route = await routed(to, at: at, paused: paused) guard !ended, playing?.id == id else { return } perform(routing.took(route)) } } /// The core's answer for the route `to`, told where the film stands and /// whether the person paused it (the core watches that it advances on a /// TV); through the phone when it does not answer. private func routed(_ to: String, at: Double, paused: Bool) async -> PlayerRoute { var request: [String: RecordValue] = ["op": .text("route"), "to": .text(to), "paused": .bool(paused)] if at.isFinite { request["at_s"] = .number(at) } let answer = try? await core.call(CottonMethod.shellPlayer, request, as: PlayerAnswer.self) return answer?.route ?? PlayerRoute(to: .phone, stream: nil, checkAfterS: nil, said: nil) } private func perform(_ acts: [FilmRouting.Act]) { for act in acts { switch act { case .play(let url): replay(AVURLAsset(url: url)) case .playHere: guard let film = playing else { continue } Task { if let here = await asset(film), !ended { replay(here) } } case .allowTV(let allowed): player.allowsExternalPlayback = allowed player.usesExternalPlaybackWhileExternalScreenIsActive = false case .check(let after): checkTask?.cancel() checkTask = Task { [weak self] in try? await Task.sleep(for: .seconds(after)) guard !Task.isCancelled, let self, !self.ended, let ask = self.routing.checking() else { return } self.route(ask) } case .say(let words): say(words) } } } /// `asset` in place of what plays, where it stands, its tracks chosen. private func replay(_ asset: AVURLAsset) { let at = player.currentTime() let wasPlaying = player.timeControlStatus != .paused replaying = true load(asset) Task { await choose(asset, playing?.tracks) await player.seek(to: at, toleranceBefore: .zero, toleranceAfter: .zero) heard?.jumped(to: at.seconds) replaying = false if wasPlaying { player.play() } } } // MARK: Leaving it /// Done, the close button or a swipe down: back to the deck where it was. nonisolated func playerViewController(_ playerViewController: AVPlayerViewController, willEndFullScreenPresentationWithAnimationCoordinator coordinator: UIViewControllerTransitionCoordinator) { coordinator.animate(alongsideTransition: nil) { context in guard !context.isCancelled else { return } MainActor.assumeIsolated { [weak self] in guard let self, !self.floating else { return } self.end(clearing: true) } } } nonisolated func playerViewControllerWillStartPictureInPicture(_ playerViewController: AVPlayerViewController) { MainActor.assumeIsolated { floating = true } } nonisolated func playerViewControllerDidStopPictureInPicture(_ playerViewController: AVPlayerViewController) { MainActor.assumeIsolated { floating = false // Closed from its little window rather than brought back. if controller.presentingViewController == nil { end(clearing: true) } } } /// The little window's expand: the full screen again. nonisolated func playerViewController(_ playerViewController: AVPlayerViewController, restoreUserInterfaceForPictureInPictureStopWithCompletionHandler completionHandler: @escaping (Bool) -> Void) { let done = FilmRestore(completionHandler) MainActor.assumeIsolated { guard controller.presentingViewController == nil, let top = Self.top() else { return done.call(true) } top.present(controller, animated: true) { done.call(true) } } } /// It stops, where it stood told to the core; left by the person, the /// player clears too (something else playing has moved it already). func end(clearing: Bool) { guard !ended else { return } ended = true stay() checkTask?.cancel() external = nil let at = player.currentTime().seconds player.pause() var request: [String: RecordValue] = clearing ? ["op": .text("clear")] : [:] if let report = heard?.report(ended: "stopped", at: at, duration: length(), device: UIDevice.current.model) { request["listened"] = report } if !request.isEmpty { Task { [core] in _ = try? await core.call(CottonMethod.shellPlayer, request, as: PlayerAnswer.self) } } // Stopped: its windows, and any prepared, go; then what is on screen (Home's Featured, the title's page) is // prepared again, after the release. Self.release() Self.released?() if let ticking { player.removeTimeObserver(ticking) } ticking = nil cues.stop() subtitlesHide?.cancel() status = nil control = nil watchers.forEach(NotificationCenter.default.removeObserver) watchers = [] // A refusal can come before the player has finished coming up (the core answers in milliseconds): it goes once // it is up, never mid-way, which would take the screen under it along. if controller.isBeingPresented, let coming = controller.transitionCoordinator { coming.animate(alongsideTransition: nil) { [controller] _ in controller.dismiss(animated: true) } } else if controller.presentingViewController != nil, !controller.isBeingDismissed { controller.dismiss(animated: true) } if Self.current === self { Self.current = nil } } // MARK: Helpers static func metadata(title: String?, artwork: Data?) -> [AVMetadataItem] { var items: [AVMetadataItem] = [] if let title, !title.isEmpty { let said = AVMutableMetadataItem() said.identifier = .commonIdentifierTitle said.value = title as NSString said.extendedLanguageTag = "und" items.append(said) } if let artwork { let picture = AVMutableMetadataItem() picture.identifier = .commonIdentifierArtwork picture.value = artwork as NSData picture.dataType = kCMMetadataBaseDataType_JPEG as String picture.extendedLanguageTag = "und" items.append(picture) } return items } /// The poster as JPEG, for the lock screen. static func artwork(_ key: String, core: any CottonCalling) async -> Data? { let media = PhotosMediaSource(core: core) var answer = await media.answer(for: key, tier: .largest) if answer == nil, (try? await media.ensure(key)) != nil { answer = await media.answer(for: key, tier: .largest) } guard let answer else { return nil } let pixels = artworkPixels return await Task.detached(priority: .utility) { PhotosImageFile.image(key: key, rung: answer.rung, atPath: answer.path, maxPixel: pixels)?.jpegData(compressionQuality: 0.85) }.value } /// The view controller on top of the key window: what the film is /// presented over. static func keyWindow() -> UIWindow? { UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene } .flatMap(\.windows).first(where: \.isKeyWindow) } static func top() -> UIViewController? { var top = keyWindow()?.rootViewController while let presented = top?.presentedViewController, !presented.isBeingDismissed { top = presented } return top } } /// The player's own taps go on while a tap shows the Subtitles button. private final class FilmTapsAlongside: NSObject, UIGestureRecognizerDelegate { static let shared = FilmTapsAlongside() func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -> Bool { true } } /// The system's completion for bringing the player back, carried onto the /// main actor it is called on. private final class FilmRestore: @unchecked Sendable { private let handler: (Bool) -> Void init(_ handler: @escaping (Bool) -> Void) { self.handler = handler } func call(_ restored: Bool) { handler(restored) } } /// The next episode's count over the player's end, in Cinemas' look: "Next episode in 8" on a dark card, and under /// it "Stay here" and "Next episode". With Reduce Motion only its number changes. struct FilmNextCount: View { let started: Date /// The core's count (`next_after_s`). let seconds: Int let next: @MainActor () -> Void let stay: @MainActor () -> Void @Environment(\.accessibilityReduceMotion) private var reduceMotion @Environment(\.dynamicTypeSize) private var typeSize var body: some View { TimelineView(.periodic(from: started, by: 1)) { context in let left = max(0, seconds - Int(max(0, context.date.timeIntervalSince(started)).rounded(.down))) VStack(alignment: .leading, spacing: 14) { Text(ShellLines.line("cinemas", "player.next_in", ["seconds": String(left)])) .font(CinemasFonts.sans(17, 700)) .foregroundStyle(CinemasInk.ink) .contentTransition(reduceMotion ? .identity : .numericText(countsDown: true)) .animation(reduceMotion ? nil : .default, value: left) // Side by side, or at the accessibility sizes one above the other, so no word breaks. let buttons = typeSize.isAccessibilitySize ? AnyLayout(VStackLayout(spacing: 10)) : AnyLayout(HStackLayout(spacing: 10)) buttons { CinemasButton(label: ShellLines.line("cinemas", "player.next"), icon: "forward.end.fill", height: 44) { next() } .accessibilityIdentifier("film-next-play") CinemasButton(label: ShellLines.line("cinemas", "player.cancel_next"), style: .outline, height: 44) { stay() } .accessibilityIdentifier("film-next-stay") } } .padding(18) .frame(maxWidth: 420) .background(RoundedRectangle(cornerRadius: 18, style: .continuous).fill(CinemasInk.raised.opacity(0.96))) .padding(.horizontal, 16) } .frame(maxWidth: .infinity) .environment(\.colorScheme, .dark) // A container, so its own id never covers its buttons' ids. .accessibilityElement(children: .contain) .accessibilityIdentifier("film-next-count") } } /// Until the first frame: the title's picture, dimmed, and a spinner; nothing of ours animates over the film itself. struct FilmWaiting: View { let cover: UIImage? var body: some View { ZStack { Color.black if let cover { Image(uiImage: cover).resizable().scaledToFit().opacity(0.45) } ProgressView().controlSize(.large).tint(.white) } .ignoresSafeArea() .accessibilityHidden(true) } } /// The Subtitles button over the picture: round, blurred, the size of the player's own buttons, named for VoiceOver. struct FilmSubtitlesButton: View { let label: String let open: () -> Void var body: some View { Button(action: open) { Image(systemName: "captions.bubble") .font(.system(size: 17, weight: .semibold)) .foregroundStyle(.white) .frame(width: 44, height: 44) .background(.ultraThinMaterial, in: Circle()) } .buttonStyle(.plain) .environment(\.colorScheme, .dark) .accessibilityLabel(Text(label)) .accessibilityIdentifier("film-subtitles-open") } } enum FilmNextCountKnobs { /// The count's room: the plate and its two buttons. static let height: CGFloat = 240 } // MARK: - What a screen over the app reads of a film on a TV /// Cinemas' TV bar and remote (CONTRACT-2 "The TV"): the film playing on a TV now, and the few acts a remote takes. /// Read only; every rule of where it plays stays in the core and in the player above. extension FilmPlayback { struct OnTV: Equatable, Sendable { let table: String let id: String let title: String let caption: String? /// The art's media key: a film's poster, an episode's still. let cover: String? let at: Double let length: Double let paused: Bool } /// The film playing on a TV now; nil when nothing plays on one. static var onTV: OnTV? { guard let playback = current, !playback.ended, let film = playback.playing, playback.player.isExternalPlaybackActive || (onAirPlay && playback.player.allowsExternalPlayback) else { return nil } let at = playback.player.currentTime().seconds return OnTV(table: film.table, id: film.id, title: film.title, caption: film.caption, cover: film.cover, at: at.isFinite ? at : 0, length: film.duration, paused: playback.player.timeControlStatus == .paused) } static func pauseOrPlay() { guard let player = current?.player else { return } if player.timeControlStatus == .paused { player.play() } else { player.pause() } } static func skip(by seconds: Double) { guard let player = current?.player else { return } let to = max(0, player.currentTime().seconds + seconds) player.seek(to: CMTime(seconds: to, preferredTimescale: 600)) } static func seek(to seconds: Double) { guard let player = current?.player else { return } player.seek(to: CMTime(seconds: max(0, seconds), preferredTimescale: 600)) } /// Stop on TV, or Watch on phone: the picture leaves the TV for this phone, where the film stands at the same /// second; it waits paused unless he asked to watch it here (owner, 18 Nov 2026: it never plays by itself). static func leaveTV(watchHere: Bool) { guard let playback = current else { return } if !watchHere { playback.player.pause() } // The core is told the film came back to the phone (`shell.player` route "phone"), as when the TV lets go; // the sound may stay on the TV's speakers, so the leaving is not waited for from the route. playback.leftTV() playback.player.allowsExternalPlayback = false if watchHere { show() playback.player.play() } } /// A track the remote offers: subtitles or sound, by the stream's own names. struct TrackChoice: Equatable, Sendable, Identifiable { let id: Int let name: String let chosen: Bool } /// The stream's subtitle tracks (`.legible`) or sound tracks (`.audible`), the chosen one ticked. static func tracks(_ kind: AVMediaCharacteristic) async -> [TrackChoice] { guard let item = current?.player.currentItem, let group = try? await item.asset.loadMediaSelectionGroup(for: kind) else { return [] } let chosen = item.currentMediaSelection.selectedMediaOption(in: group) return group.options.enumerated().map { TrackChoice(id: $0.offset, name: $0.element.displayName, chosen: $0.element == chosen) } } /// Chooses track `index` of `kind`, or none (subtitles off) for nil. static func choose(_ index: Int?, _ kind: AVMediaCharacteristic) async { guard let item = current?.player.currentItem, let group = try? await item.asset.loadMediaSelectionGroup(for: kind) else { return } item.select(index.flatMap { group.options.indices.contains($0) ? group.options[$0] : nil }, in: group) } /// Apple's player again, over the app, while the film plays on the TV. static func show() { guard let playback = current, playback.controller.presentingViewController == nil else { return } top()?.present(playback.controller, animated: true) } } /// Tap to first frame, step by step (NEXT.md, 26 Nov: the player took 4 to 8 s). Each step is written to the app's /// log with the milliseconds since the tap, as `play-clock: +123 ms `, and, in a Dev build, to /// `Library/Caches/play-clock.log` so a walk can read the table back. @MainActor enum PlayClock { private static var began: ContinuousClock.Instant? private static var steps: [(String, Int)] = [] static func tap() { began = .now steps = [] mark("tap") } /// A line outside any tap's timing (a page's prepare), written as the steps are. static func note(_ what: String) { write("play-clock: \(what)") } static func mark(_ step: String, last: Bool = false) { guard let began else { return } let ms = Int((ContinuousClock.now - began) / .milliseconds(1)) steps.append((step, ms)) write("play-clock: +\(ms) ms \(step)") if last { Self.began = nil } } private static func write(_ line: String) { Log.write(line) #if COTTON_DEV if let caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first { let file = caches.appendingPathComponent("play-clock.log") let text = line + "\n" if let handle = try? FileHandle(forWritingTo: file) { handle.seekToEndOfFile() handle.write(Data(text.utf8)) try? handle.close() } else { try? Data(text.utf8).write(to: file) } } #endif } } #endif /// The kind of network this phone is on, for `prepare`: "wifi" (Wi-Fi or a wire), else "cellular". Watched from the /// first ask on. enum FilmNetwork { nonisolated(unsafe) private static let monitor: NWPathMonitor = { let monitor = NWPathMonitor() monitor.start(queue: DispatchQueue(label: "film-network", qos: .utility)) return monitor }() /// Starts watching (the first path takes a moment to come). static func watch() { _ = monitor } static var kind: String { let path = monitor.currentPath // A Wi-Fi that is a phone's hotspot (expensive), or Low Data Mode (constrained), is mobile data's to keep to. guard !path.isExpensive, !path.isConstrained else { return "cellular" } return path.usesInterfaceType(.wifi) || path.usesInterfaceType(.wiredEthernet) ? "wifi" : "cellular" } /// Low Data Mode is on for the network in use. static var constrained: Bool { monitor.currentPath.isConstrained } /// Whether the phone has a network at all. static var currentStatus: NWPath.Status { monitor.currentPath.status } }