// 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.importCottonFacesimportCottonKitimportSwiftUI#if os(iOS)import AVFoundationimport AVKitimportNetworkimport UIKit#endif/// Which player a thing the viewer was asked to show plays in.enumFilmPlayer: 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.staticlet tables: Set<String> = ["film", "film_episode"]staticfunc of(_ item: ViewerItem) -> FilmPlayer {iflet 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.staticfunc remote(_ key: String?) -> Bool {guardlet key = key?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() else { returnfalse }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/<id>/whole.<ext>`).enumFilmKey {/// Whether `key` names an HLS master.staticfunc streams(_ key: String?) -> Bool {guardlet key else { returnfalse }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.structFilmHere: Equatable, Sendable {enumState: String, Sendable { case keeping, kept }var bookmark: Data?var state: State?}/// The core's device-local store of films (`phone::films`): never synced.structFilmHereStore: Sendable {let core: any CottonCallingprivatestructWire: Decodable {let bookmark: String?let state: String? }func read(_ key: String) asyncthrows -> FilmHere {let wire = tryawait core.call(CottonMethod.filmsHereRead, ["key": RecordValue.text(key)], as: Wire.self)returnFilmHere(bookmark: wire.bookmark.flatMap { Data(base64Encoded: $0) }, state: wire.state.flatMap(FilmHere.State.init(rawValue:))) }/// Its file is coming down.func keeping(_ key: String) asyncthrows {tryawait write(key, ["state": .text(FilmHere.State.keeping.rawValue)]) }/// A stream's bundle is here, at `bookmark`.func kept(_ key: String, bookmark: Data) asyncthrows {tryawait 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) asyncthrows {tryawait 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) asyncthrows {tryawait write(key, ["state": .null]) }/// A whole file's Remove download: this phone's copy goes.func remove(_ key: String) asyncthrows { _ = tryawait core.callJSON(CottonMethod.filmsRemove, ["key": RecordValue.text(key)]) }privatefunc write(_ key: String, _ fields: [String: RecordValue]) asyncthrows {var request = fields request["key"] = .text(key) _ = tryawait core.callJSON(CottonMethod.filmsHereWrite, request) }}/// The object's signed address for a film's file (`media.stream`).structFilmStreamGrant: Decodable, Sendable {let url: Stringlet expires_at: Stringstaticfunc mint(_ key: String, core: any CottonCalling) asyncthrows -> URL {let grant = tryawait core.call(CottonMethod.mediaStream, ["key": RecordValue.text(key)], as: FilmStreamGrant.self)guardlet url = URL(string: grant.url) else {throwCottonCallError(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.enumFilmBundle {staticfunc url(_ bookmark: Data?) -> URL? {guardlet bookmark else { returnnil }var stale = falseguardlet url = try? URL(resolvingBookmarkData: bookmark, bookmarkDataIsStale: &stale),FileManager.default.fileExists(atPath: url.path) else { returnnil }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.@MainActorfinalclassFilmPlayback: NSObject, AVPlayerViewControllerDelegate {/// The film playing now; one at a time.private(set) staticvar current: FilmPlayback?privatestaticvar core: (any CottonCalling)?privatestaticvar 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.privatestructPrepared: 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).staticfunc prepare(table: String, id: String, hidden: Bool = false) {guardlet 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.nowlet 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.staticfunc unprepare() {guardlet 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.staticfunc release() {guardlet 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.privatestaticvar lastAsk: Task<Void, Never>?/// After a film stops: the app prepares again what its screen shows.staticvar released: (@MainActor () -> Void)?privatestaticfunc inOrder(_ ask: @escaping @MainActor () async -> Void) {let before = lastAsk lastAsk = Task { @MainActor inawait before?.valueawait ask() } }/// Whether anything plays now (picture in picture, the TV): the background then lets nothing go.staticvar isPlaying: Bool { current != nil }/// The poster on the lock screen, longest side.staticlet 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.staticfunc speak(_ say: @escaping (String) -> Void) { Self.say = say }staticfunc attach(core: any CottonCalling, say: @escaping (String) -> Void) {self.core = coreself.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).staticfunc ask(table: String, id: String, at seconds: Double? = nil, cover: UIImage? = nil, hidden: Bool = false) async {PlayClock.tap()guardlet 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").iflet 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.nowvar tries = 0while !playback.ended {do { #if COTTON_DEVtryawaitFilmThrottle.coreAsk() #endiflet answer = tryawait core.call(CottonMethod.shellPlayer, request, as: PlayerAnswer.self)PlayClock.mark("core answered shell.player play")guard !playback.ended else { return }ifFilmSlow.again(answer, since: began) {PlayClock.note("the core could not reach the film: asked again") tries += 1 playback.slow.on()try? awaitTask.sleep(for: FilmSlow.wait(tries))continue }Players.took(answer)return } catch {guard !playback.ended else { return }ifFilmSlow.again(error) {PlayClock.note("the core did not answer: asked again") tries += 1 playback.slow.on()try? awaitTask.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.staticfunc took(_ answer: PlayerAnswer) {guardlet film = answer.playing, film.kind == "film"else { current?.end(clearing: false)return }iflet refusal = answer.refusal { say?(refusal) }iflet current, current.opening, !current.ended { current.opening = falseTask { await current.start(answer) }return }iflet current, current.playing?.id == film.id { return current.answered(answer) }guardlet core, let say else { return } current?.end(clearing: false)let playback = FilmPlayback(core: core, say: say) current = playbackTask { await playback.start(answer) } }/// "Cotton is slow right now · trying again", over the picture while the film waits on Cotton.let slow = FilmSlow()privatevar slowWatch: Task<Void, Never>?privatevar failures = 0private(set) var playing: PlayerPlaying?/// The core's last answer: what plays after this one.privatevar answer: PlayerAnswer?/// The film whose next episode is prepared already.privatevar preparedNext: String?/// A hidden title plays (the core's `discreet`): its name and poster now-playing never shows.privatevar secret = falseprivatevar artwork: Data?/// Whether Hidden is open now, as Cinemas says.staticvar 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).privatefunc shown() {guardlet item = player.currentItem else { return }let veiled = secretlet 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_DEVPlayClock.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 staticfunc 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.staticfunc 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.staticfunc dataChanged() { current?.recheck() }/// `shell.player {}`: reports nothing and writes nothing; its answer says whether what plays is discreet now.privatefunc recheck() {guardlet id = playing?.id, !ended else { return }Task { [core] inguardlet 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.privatefunc follow(_ answer: PlayerAnswer, playing id: String) {guard !ended, playing?.id == id, let film = answer.playing, film.id == id else { return }self.answer = answerlet 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 staticfunc 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).privatefunc closeFloating() { #if COTTON_DEVPlayClock.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.staticlet prepareNextAt: Double = 60privatelet core: any CottonCallingprivatelet say: (String) -> Voidprivatelet controller = AVPlayerViewController()privatelet player = AVPlayer()privatevar ticking: Any?privatevar watchers: [NSObjectProtocol] = []privatevar status: NSKeyValueObservation?/// The first frame on screen (PlayClock).privatevar framed: NSKeyValueObservation?privatevar control: NSKeyValueObservation?/// A film on a TV: what the core answered for the route, and its watch.privatevar routing = FilmRouting()privatevar external: NSKeyValueObservation?privatevar checkTask: Task<Void, Never>?/// The item is being replaced where it stands: no report of the new one's nought.privatevar replaying = false/// What was heard of this play, and where it last reported.privatevar heard: PlayHeard?privatevar reported: Double = 0/// Up on the tap, the core's answer not yet in: the answer that comes is this player's.privatevar opening = false/// The title's picture and a spinner over the picture, until its first frame.privatevar waiting: UIView?privatevar nextCount: UIView?privatevar nextTask: Task<Void, Never>?/// A refused stream asked to be signed again, its answer not yet in.privatevar relinking = falseprivatevar floating = falseprivatevar ended = false/// The film's own subtitles (FilmSubtitles.swift): its cues drawn here while shifted, the timing control.privatelazyvar cues = FilmSubtitleCues(player: player)/// The one button of ours over the picture: Subtitles, Cinemas' own sheet (find, make, give, the tracks).privatevar subtitlesButton: UIView?privatevar subtitlesHide: Task<Void, Never>?/// The choice last told to the core, or read from it: a selection the player makes itself is told once.privatevar toldChoice: PlayerPlaying.Tracks.SubtitleChoice?privatevar choosing = false/// The film's subtitle tracks as the player lists them, once its asset said.privatevar legibleGroup: AVMediaSelectionGroup?/// Each of those tracks' own names (the master's NAME, "French (made on your Mac)"), in the group's order.privatevar legibleNames: [String] = []privateinit(core: any CottonCalling, say: @escaping (String) -> Void) {self.core = coreself.say = saysuper.init() }privatefunc 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")guardawaitopen(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.privatefuncopen(_ answer: PlayerAnswer) async -> Bool {guardlet 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) }returnfalse }PlayClock.mark(asset.url.isFileURL ? "file found on this phone" : "stream address in hand")guard !ended else { returnfalse }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 = assetvar then: [FilmRouting.Act] = []iflet ask = routing.opening(onTV: Self.onAirPlay || player.isExternalPlaybackActive) {let route = await routed(ask, at: film.resumeAt, paused: false)guard !ended else { returnfalse }let first = routing.first(route)iflet url = first.from { from = AVURLAsset(url: url) }// Kept from the TV before the item is there to hand it.let tv = first.acts.filter { ifcase .allowTV = $0 { true } else { false } } perform(tv) then = first.acts.filter { !tv.contains($0) } } #if COTTON_DEVifProcessInfo.processInfo.arguments.contains("-play-no-wait") { player.automaticallyWaitsToMinimizeStalling = false } #endif load(from)PlayClock.mark("item made")iflet 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) { _ inTask { @MainActor inPlayClock.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 { [weakself] inawaitself?.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)returntrue }/// What the core named: the kept bundle, the kept whole file, or the/// address it signed.privatefunc asset(_ film: PlayerPlaying) async -> AVURLAsset? {iflet bundle = FilmBundle.url(film.bundle.flatMap { Data(base64Encoded: $0) }) { return AVURLAsset(url: bundle) }iflet key = film.file, let file = awaitCoreAttachmentStore(core: core).localURL(for: key) { return AVURLAsset(url: file) } #if COTTON_DEVreturn film.stream.flatMap(URL.init(string:)).map { AVURLAsset(url: FilmThrottle.route($0)) } #elsereturn 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.privatefunc load(_ asset: AVURLAsset) {let item = AVPlayerItem(asset: asset) player.replaceCurrentItem(with: item) follow(item) artwork = nil shown()guardlet poster = playing?.cover else { return }Task { [weakself, core] inguardlet artwork = awaitSelf.artwork(poster, core: core), letself, self.player.currentItem === item else { return }self.artwork = artworkself.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.privatefunc choose(_ asset: AVURLAsset, _ tracks: PlayerPlaying.Tracks?) async {guardlet item = player.currentItem, let tracks else { return }iflet legible = try? await asset.loadMediaSelectionGroup(for: .legible) {var names: [String] = []for option in legible.options { names.append(awaitSelf.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 = truelet 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 == .leaveswitch pick {case .off: item.select(nil, in: legible)case .option(let index): item.select(legible.options[index], in: legible)case .leave: break } choosing = false }iflet 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).privatestaticfunc name(of option: AVMediaSelectionOption) async -> String {iflet 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.privatefunc 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 = .darkSelf.top()?.present(controller, animated: true)PlayClock.mark("player presented")iflet 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 { [weakself] intry? awaitTask.sleep(for: FilmSlow.after)guardletself, !Task.isCancelled, !self.ended, self.waiting != nilelse { return }PlayClock.note("no picture after \(FilmSlow.after): said slow")self.slow.on() } framed = controller.observe(\.isReadyForDisplay, options: [.initial, .new]) { [weakself] observed, _ inguard observed.isReadyForDisplay else { return }Task { @MainActor in #if COTTON_DEViflet 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") } #endifPlayClock.mark("first frame", last: true)self?.slowWatch?.cancel()self?.slow.off()self?.failures = 0guardlet 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).privatefunc selectionChanged(_ item: AVPlayerItem) {guard !choosing, !ended, let group = legibleGroup else { return }let chosen: PlayerPlaying.Tracks.SubtitleChoiceiflet 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 = chosenlet said: RecordValueswitch 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.staticvar subtitlesSheet: (@MainActor (PlayerPlaying) -> UIViewController?)?privatefunc offerSubtitles() {guard subtitlesButton == nil, let film = playing, Self.subtitlesSheet != nilelse { return }let host = UIHostingController(rootView: FilmSubtitlesButton(label: ShellLines.line("cinemas", "home.act_subtitles")) { [weakself] inself?.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.viewlet tap = UITapGestureRecognizer(target: self, action: #selector(tapped)) tap.cancelsTouchesInView = false tap.delegate = FilmTapsAlongside.shared controller.view.addGestureRecognizer(tap) showSubtitlesButton() } @objc privatefunc tapped() { showSubtitlesButton() }privatefunc showSubtitlesButton() {guardlet button = subtitlesButton else { return } subtitlesHide?.cancel() UIView.animate(withDuration: 0.2) { button.alpha = 1 } subtitlesHide = Task { [weakself] intry? awaitTask.sleep(for: .seconds(4))guard !Task.isCancelled else { return } UIView.animate(withDuration: 0.3) { self?.subtitlesButton?.alpha = 0 } } }privatefunc openSubtitles(_ film: PlayerPlaying) {guardlet 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.staticlet 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.staticlet playerTopRow: CGFloat = 56// MARK: Watching it playprivatefunc follow(_ item: AVPlayerItem) {if ticking == nil { ticking = player.addPeriodicTimeObserver(forInterval: CMTime(seconds: 1, preferredTimescale: 600), queue: .main) { [weakself] now inMainActor.assumeIsolated { self?.tick(now.seconds) } } }if control == nil { control = player.observe(\.timeControlStatus) { [weakself] observed, _ inlet status = observed.timeControlStatuslet stalled = status == .waitingToPlayAtSpecifiedRate && observed.reasonForWaitingToPlay != .noItemToPlayTask { @MainActor inif status == .paused { self?.paused() }self?.stalled(stalled, playing: status == .playing) } } }if external == nil { external = player.observe(\.isExternalPlaybackActive, options: [.initial, .new]) { [weakself] observed, _ inlet active = observed.isExternalPlaybackActiveTask { @MainActor inif active { self?.externalBegan() } else { self?.routeChanged() } } } } status = item.observe(\.status) { [weakself] observed, _ inif observed.status == .readyToPlay { Task { @MainActor inPlayClock.mark("item ready to play") } }guard observed.status == .failed else { return }Task { @MainActor inself?.failed(observed) } } watchers.forEach(NotificationCenter.default.removeObserver) watchers = [NotificationCenter.default.addObserver(forName: AVPlayerItem.newErrorLogEntryNotification, object: item, queue: .main) { [weakself] _ inMainActor.assumeIsolated { self?.logged(item) } },NotificationCenter.default.addObserver(forName: AVPlayerItem.didPlayToEndTimeNotification, object: item, queue: .main) { [weakself] _ inMainActor.assumeIsolated { self?.finished() } },NotificationCenter.default.addObserver(forName: AVPlayerItem.timeJumpedNotification, object: item, queue: .main) { [weakself] _ inMainActor.assumeIsolated {guardletselfelse { 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) { [weakself] _ inMainActor.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) { [weakself] _ inMainActor.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) { [weakself] _ inMainActor.assumeIsolated {guardletself, !self.floating, !self.player.isExternalPlaybackActive else { return }self.player.pause() } }, ] }privatefunc tick(_ seconds: Double) {guardlet 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.idSelf.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.privatefunc stalled(_ waiting: Bool, playing: Bool) {guard waiting else {if waiting == false, waitingSince != nil { waitingSince = nil }ifself.waiting == nil { slowWatch?.cancel(); slow.off() }return }guardself.waiting == nil, waitingSince == nilelse { return } waitingSince = .now slowWatch?.cancel() slowWatch = Task { [weakself] intry? awaitTask.sleep(for: FilmSlow.after)guardletself, !Task.isCancelled, !self.ended, self.waitingSince != nilelse { return }PlayClock.note("waiting on the film for \(FilmSlow.after): said slow")self.slow.on() } }privatevar waitingSince: ContinuousClock.Instant?privatefunc paused() {guard !ended, !replaying else { return } report(at: player.currentTime().seconds) }privatefunc length() -> Double? {let known = player.currentItem?.duration.secondsreturn known.flatMap { $0.isFinite && $0 > 0 ? $0 : nil } }/// Where it stands, told to the core, which writes the resume point and/// the watch row.privatefunc report(at seconds: Double) {guardlet standing = heard?.standing(at: seconds, duration: length(), device: UIDevice.current.model) else { return } reported = secondslet id = playing?.idTask { [core] inguardlet 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.privatefunc 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.privatefunc finished() {guardlet report = heard?.report(ended: "finished", at: player.currentTime().seconds, duration: length(), device: UIDevice.current.model) else { return }Task {guardlet answer = try? await core.call(CottonMethod.shellPlayer, ["listened": report], as: PlayerAnswer.self), !self.ended else { return }self.answer = answerguardlet next = answer.following.first, let film = answer.playing, film.nextAfter > 0else { 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.privatefunc countNext(_ next: PlayerFollowing, seconds: Int) { nextTask?.cancel() nextCount?.removeFromSuperview()let count = FilmNextCount(started: Date(), seconds: seconds, next: { [weakself] inself?.playNext() }, stay: { [weakself] inself?.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 { [weakself] intry? awaitTask.sleep(for: .seconds(seconds))guard !Task.isCancelled else { return }self?.playNext() } }privatefunc stay() { nextTask?.cancel() nextTask = nil nextCount?.removeFromSuperview() nextCount = nil }/// The next episode: the core moves on, and it plays in the same player.privatefunc playNext() { stay()Task {do {let answer = tryawait core.call(CottonMethod.shellPlayer, ["op": RecordValue.text("next")], as: PlayerAnswer.self)iflet refusal = answer.refusal { say(refusal) }guard answer.playing?.kind == "film", awaitopen(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.privatefunc logged(_ item: AVPlayerItem) {guard item.errorLog()?.events.last?.errorStatusCode == 403else { return } relink() }privatefunc failed(_ item: AVPlayerItem) {// On a TV, a film that fails plays through the phone: never an error.iflet ask = routing.failed() { return route(ask) }let refused = item.errorLog()?.events.contains { $0.errorStatusCode == 403 } ?? falselet last = item.errorLog()?.events.lastLog.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.privatefunc retry() {let at = player.currentTime()let tries = failuresTask { [weakself] intry? awaitTask.sleep(for: FilmSlow.wait(tries))guardletself, !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))awaitself.player.seek(to: at, toleranceBefore: .zero, toleranceAfter: .zero)self.player.play() } else {self.relink() } } }privatefunc relink() {guard !relinking, !ended, playing?.stream != nilelse { return } relinking = truelet at = player.currentTime()let wasPlaying = player.timeControlStatus != .pausedTask {defer { relinking = false }do {let answer = tryawait 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 += 1return retry() }iflet refusal = answer.refusal { return say(refusal) }guardlet 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 += 1return 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.privatestaticvar onAirPlay: Bool { AVAudioSession.sharedInstance().currentRoute.outputs.contains { $0.portType == .airPlay } }/// Apple's player began playing to a TV: the core says how.privatefunc 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.privatefunc routeChanged() {guard !ended, !Self.onAirPlay, !player.isExternalPlaybackActive else { return } checkTask?.cancel()let (ask, acts) = routing.cameBack() perform(acts)iflet ask { route(ask) } }/// Stop on TV: the core hears the film came back to the phone, whatever the sound's route still says.fileprivatefunc leftTV() {guard !ended else { return } checkTask?.cancel()let (ask, acts) = routing.cameBack() perform(acts.filter { ifcase .allowTV = $0 { false } else { true } })iflet 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.privatefunc route(_ to: String) {let id = playing?.idlet at = player.currentTime().secondslet paused = player.timeControlStatus == .pausedTask {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.privatefunc 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) }privatefunc perform(_ acts: [FilmRouting.Act]) {for act in acts {switch act {case .play(let url): replay(AVURLAsset(url: url))case .playHere:guardlet film = playing else { continue }Task { iflet here = await asset(film), !ended { replay(here) } }case .allowTV(let allowed): player.allowsExternalPlayback = allowed player.usesExternalPlaybackWhileExternalScreenIsActive = falsecase .check(let after): checkTask?.cancel() checkTask = Task { [weakself] intry? awaitTask.sleep(for: .seconds(after))guard !Task.isCancelled, letself, !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.privatefunc 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 = falseif 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 inguard !context.isCancelled else { return }MainActor.assumeIsolated { [weakself] inguardletself, !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 = nillet at = player.currentTime().seconds player.pause()var request: [String: RecordValue] = clearing ? ["op": .text("clear")] : [:]iflet 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?()iflet 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) } } elseif controller.presentingViewController != nil, !controller.isBeingDismissed { controller.dismiss(animated: true) }ifSelf.current === self { Self.current = nil } }// MARK: Helpersstaticfunc metadata(title: String?, artwork: Data?) -> [AVMetadataItem] {var items: [AVMetadataItem] = []iflet title, !title.isEmpty {let said = AVMutableMetadataItem() said.identifier = .commonIdentifierTitle said.value = title as NSString said.extendedLanguageTag = "und" items.append(said) }iflet artwork {let picture = AVMutableMetadataItem() picture.identifier = .commonIdentifierArtwork picture.value = artwork as NSData picture.dataType = kCMMetadataBaseDataType_JPEG asString picture.extendedLanguageTag = "und" items.append(picture) }return items }/// The poster as JPEG, for the lock screen.staticfunc 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) }guardlet answer else { returnnil }let pixels = artworkPixelsreturnawaitTask.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.staticfunc keyWindow() -> UIWindow? { UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene } .flatMap(\.windows).first(where: \.isKeyWindow) }staticfunc top() -> UIViewController? {var top = keyWindow()?.rootViewControllerwhilelet presented = top?.presentedViewController, !presented.isBeingDismissed { top = presented }return top }}/// The player's own taps go on while a tap shows the Subtitles button.privatefinalclassFilmTapsAlongside: NSObject, UIGestureRecognizerDelegate {staticlet 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.privatefinalclassFilmRestore: @unchecked Sendable {privatelet handler: (Bool) -> Voidinit(_ 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.structFilmNextCount: View {let started: Date/// The core's count (`next_after_s`).let seconds: Intlet next: @MainActor () -> Voidlet stay: @MainActor () -> Void @Environment(\.accessibilityReduceMotion) privatevar reduceMotion @Environment(\.dynamicTypeSize) privatevar typeSizevar body: someView {TimelineView(.periodic(from: started, by: 1)) { context inlet 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.structFilmWaiting: View {let cover: UIImage?var body: someView { ZStack {Color.blackiflet 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.structFilmSubtitlesButton: View {let label: Stringletopen: () -> Voidvar body: someView {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") }}enumFilmNextCountKnobs {/// The count's room: the plate and its two buttons.staticlet 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.extensionFilmPlayback {structOnTV: Equatable, Sendable {let table: Stringlet id: Stringlet title: Stringlet caption: String?/// The art's media key: a film's poster, an episode's still.let cover: String?let at: Doublelet length: Doublelet paused: Bool }/// The film playing on a TV now; nil when nothing plays on one.staticvar onTV: OnTV? {guardlet playback = current, !playback.ended, let film = playback.playing, playback.player.isExternalPlaybackActive || (onAirPlay && playback.player.allowsExternalPlayback) else { returnnil }let at = playback.player.currentTime().secondsreturnOnTV(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) }staticfunc pauseOrPlay() {guardlet player = current?.player else { return }if player.timeControlStatus == .paused { player.play() } else { player.pause() } }staticfunc skip(by seconds: Double) {guardlet player = current?.player else { return }let to = max(0, player.currentTime().seconds + seconds) player.seek(to: CMTime(seconds: to, preferredTimescale: 600)) }staticfunc seek(to seconds: Double) {guardlet 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).staticfunc leaveTV(watchHere: Bool) {guardlet 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 = falseif watchHere { show() playback.player.play() } }/// A track the remote offers: subtitles or sound, by the stream's own names.structTrackChoice: Equatable, Sendable, Identifiable {let id: Intlet name: Stringlet chosen: Bool }/// The stream's subtitle tracks (`.legible`) or sound tracks (`.audible`), the chosen one ticked.staticfunc tracks(_ kind: AVMediaCharacteristic) async -> [TrackChoice] {guardlet 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.staticfunc choose(_ index: Int?, _ kind: AVMediaCharacteristic) async {guardlet 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.staticfunc show() {guardlet playback = current, playback.controller.presentingViewController == nilelse { 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 <step>`, and, in a Dev build, to/// `Library/Caches/play-clock.log` so a walk can read the table back.@MainActorenumPlayClock {privatestaticvar began: ContinuousClock.Instant?privatestaticvar steps: [(String, Int)] = []staticfunc tap() { began = .now steps = [] mark("tap") }/// A line outside any tap's timing (a page's prepare), written as the steps are.staticfunc note(_ what: String) { write("play-clock: \(what)") }staticfunc mark(_ step: String, last: Bool = false) {guardlet 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 } }privatestaticfunc write(_ line: String) {Log.write(line) #if COTTON_DEViflet caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first {let file = caches.appendingPathComponent("play-clock.log")let text = line + "\n"iflet 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.enumFilmNetwork { nonisolated(unsafe) privatestaticlet 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).staticfunc watch() { _ = monitor }staticvar 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.staticvar constrained: Bool { monitor.currentPath.isConstrained }/// Whether the phone has a network at all.staticvar currentStatus: NWPath.Status { monitor.currentPath.status }}