// A FILM'S OWN SUBTITLES IN APPLE'S PLAYER (17 Nov// 2026: "every film in Cotton Cinemas can have subtitles … user experience// first"). The film's HLS master names each subtitle track as a rendition and// Apple's player lists them in its own subtitle menu; three things are added// here, every rule and word the core's (`shell.player` `tracks`)://// - THE CHOICE IS THE FILM'S. The track the owner picks in the player's menu// (or Off) is told to the core (`subtitles { choice }`), which keeps it on// the film's row; the next play, on any device, opens with it// (`FilmSubtitlePick`), over the cinema's language setting.// - THE TIMING IS THE FILM'S. Subtitle timing in the player's "more" menu// (FilmFrames.swift) opens the core's control: Earlier and Later move a tenth of a second (`subtitle_timing// { step }`), Reset puts them back in time; the core keeps the value on the// row and says where it stands.// - THE PLAYER ONLY SHIFTS THE CUES. In time, Apple's player draws the// subtitles itself. Shifted, its drawing is held back// (`AVPlayerItemLegibleOutput.suppressesPlayerRendering`) and the same cues,// delivered ahead of time, are drawn here at their time plus the offset// (`FilmCueTimeline`).importCottonKitimportFoundationimportSwiftUI#if os(iOS)import AVFoundationimport AVKitimport UIKit#endif/// Which of a film's subtitle tracks plays: the film's own choice first,/// then the cinema's setting (a language, the phone's when none is named),/// then none.enumFilmSubtitlePick: Equatable {case offcase option(Int)/// Nothing to say: the player keeps its own selection.case leave/// One subtitle track as the player lists it: its language tag and its name.structOffered: Equatable {let language: String?let name: String }staticfunc pick(_ offered: [Offered], tracks: PlayerPlaying.Tracks, phone: String?, allowsOff: Bool) -> FilmSubtitlePick {func primary(_ tag: String?) -> String? { tag?.lowercased().split(whereSeparator: { $0 == "-" || $0 == "_" }).first.map(String.init) }switch tracks.choice {case .off?:return allowsOff ? .off : .leavecase .track(let language, let name)?:iflet exact = offered.firstIndex(where: { $0.name == name && primary($0.language) == primary(language) }) { return .option(exact) }iflet same = offered.firstIndex(where: { primary($0.language) == primary(language) }) { return .option(same) }casenil:break }guard tracks.subtitles else { return allowsOff ? .off : .leave }guardlet language = primary(tracks.subtitleLanguage ?? phone) else { return .leave }// A track in the language, its forced-only one aside; a made one only when none other is.let inLanguage = offered.indices.filter { primary(offered[$0].language) == language }return inLanguage.first.map(FilmSubtitlePick.option) ?? .leave }}/// The cues the player hands over ahead of their time, drawn at their time/// plus the film's offset. Each change is a moment and what shows from it on/// (nothing, when a cue ends).structFilmCueTimeline: Equatable {structChange: Equatable {let at: Doublelet lines: [String] }private(set) var changes: [Change] = []/// A change heard: kept in time order, one per moment (the later word wins).mutatingfunc heard(at: Double, lines: [String]) { changes.removeAll { abs($0.at - at) < 0.001 }let index = changes.firstIndex { $0.at > at } ?? changes.count changes.insert(Change(at: at, lines: lines), at: index) }/// What shows at `now` with the cues `offset` seconds later (negative: earlier).func showing(at now: Double, offset: Double) -> [String] { changes.last { $0.at + offset <= now }?.lines ?? [] }/// What is long past forgotten, keeping the change that shows now.mutatingfunc forget(before now: Double, offset: Double) {guardlet showing = changes.lastIndex(where: { $0.at + offset <= now }), showing > 0else { return } changes.removeFirst(showing) }/// A seek: what was heard belongs to another place.mutatingfunc clear() { changes = [] }}#if os(iOS)/// The film's cues, drawn here while its timing is shifted; Apple's own/// drawing otherwise.@MainActorfinalclassFilmSubtitleCues: NSObject, AVPlayerItemLegibleOutputPushDelegate {/// How far ahead the player hands cues over: as far as the timing goes.staticlet ahead: TimeInterval = 30privateweakvar player: AVPlayer?privatevar output: AVPlayerItemLegibleOutput?privateweakvar item: AVPlayerItem?privatevar timeline = FilmCueTimeline()privatevar offset: Double = 0privatevar ticking: Any?privatelet label = UILabel()init(player: AVPlayer) {self.player = playersuper.init() label.numberOfLines = 0 label.textAlignment = .center label.textColor = .white label.font = UIFont.preferredFont(forTextStyle: .title3) label.adjustsFontForContentSizeCategory = true label.backgroundColor = UIColor.black.withAlphaComponent(0.55) label.layer.cornerRadius = 6 label.layer.masksToBounds = true label.isHidden = true label.accessibilityIdentifier = "film-subtitle-shifted" }/// The cue drawer laid over the picture, under the player's controls.func place(in overlay: UIView) {guard label.superview !== overlay else { return } label.translatesAutoresizingMaskIntoConstraints = false overlay.addSubview(label) NSLayoutConstraint.activate([ label.centerXAnchor.constraint(equalTo: overlay.centerXAnchor), label.bottomAnchor.constraint(equalTo: overlay.safeAreaLayoutGuide.bottomAnchor, constant: -48), label.widthAnchor.constraint(lessThanOrEqualTo: overlay.widthAnchor, multiplier: 0.86), ]) }/// A new item: the cues are read from it.func follow(_ item: AVPlayerItem) {iflet output, let old = self.item, old.outputs.contains(output) { old.remove(output) }let output = AVPlayerItemLegibleOutput() output.advanceIntervalForDelegateInvocation = Self.ahead output.setDelegate(self, queue: .main) output.suppressesPlayerRendering = offset != 0 item.add(output)self.output = outputself.item = item timeline.clear()if ticking == nil, let player { ticking = player.addPeriodicTimeObserver(forInterval: CMTime(value: 1, timescale: 10), queue: .main) { [weakself] now inMainActor.assumeIsolated { self?.draw(at: now.seconds) } } } }/// The film's timing, milliseconds: in time Apple's player draws; shifted, this does.func shift(_ milliseconds: Int) { offset = Double(milliseconds) / 1000 output?.suppressesPlayerRendering = offset != 0if offset == 0 { label.isHidden = true }iflet now = player?.currentTime().seconds { draw(at: now) } }/// A seek: the player hands the cues of the new place over again.func jumped() { timeline.clear() }func stop() {iflet ticking { player?.removeTimeObserver(ticking) } ticking = nil label.removeFromSuperview() }privatefunc draw(at now: Double) {guard offset != 0, now.isFinite else { return }let lines = timeline.showing(at: now, offset: offset) label.text = lines.isEmpty ? nil : " \(lines.joined(separator: "\n")) " label.isHidden = lines.isEmpty timeline.forget(before: now, offset: offset) } nonisolated func legibleOutput(_ output: AVPlayerItemLegibleOutput, didOutputAttributedStrings strings: [NSAttributedString], nativeSampleBuffers nativeSamples: [Any], forItemTime itemTime: CMTime) {let lines = strings.map(\.string).map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty }let at = itemTime.secondsMainActor.assumeIsolated { timeline.heard(at: at, lines: lines) } }}#endif