Cotton code
193 lines · 8.1 KB · SwiftRaw
// 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`).import CottonKitimport Foundationimport SwiftUI#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.enum FilmSubtitlePick: Equatable {    case off    case 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.    struct Offered: Equatable {        let language: String?        let name: String    }    static func 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 : .leave        case .track(let language, let name)?:            if let exact = offered.firstIndex(where: { $0.name == name && primary($0.language) == primary(language) }) { return .option(exact) }            if let same = offered.firstIndex(where: { primary($0.language) == primary(language) }) { return .option(same) }        case nil:            break        }        guard tracks.subtitles else { return allowsOff ? .off : .leave }        guard let 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).struct FilmCueTimeline: Equatable {    struct Change: Equatable {        let at: Double        let lines: [String]    }    private(set) var changes: [Change] = []    /// A change heard: kept in time order, one per moment (the later word wins).    mutating func 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.    mutating func forget(before now: Double, offset: Double) {        guard let showing = changes.lastIndex(where: { $0.at + offset <= now }), showing > 0 else { return }        changes.removeFirst(showing)    }    /// A seek: what was heard belongs to another place.    mutating func clear() { changes = [] }}#if os(iOS)/// The film's cues, drawn here while its timing is shifted; Apple's own/// drawing otherwise.@MainActorfinal class FilmSubtitleCues: NSObject, AVPlayerItemLegibleOutputPushDelegate {    /// How far ahead the player hands cues over: as far as the timing goes.    static let ahead: TimeInterval = 30    private weak var player: AVPlayer?    private var output: AVPlayerItemLegibleOutput?    private weak var item: AVPlayerItem?    private var timeline = FilmCueTimeline()    private var offset: Double = 0    private var ticking: Any?    private let label = UILabel()    init(player: AVPlayer) {        self.player = player        super.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) {        if let 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 = output        self.item = item        timeline.clear()        if ticking == nil, let player {            ticking = player.addPeriodicTimeObserver(forInterval: CMTime(value: 1, timescale: 10), queue: .main) { [weak self] now in                MainActor.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 != 0        if offset == 0 { label.isHidden = true }        if let 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() {        if let ticking { player?.removeTimeObserver(ticking) }        ticking = nil        label.removeFromSuperview()    }    private func 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.seconds        MainActor.assumeIsolated { timeline.heard(at: at, lines: lines) }    }}#endif