Cotton code
228 lines · 10.5 KB · SwiftRaw
// THE PICTURE A FILM WEARS, PICKED FROM THE FILM (18// Nov 2026). The player's "more" choices are the core's (`shell.player`'s// `more`); this draws them and takes the frame.//// - THE FRAME IS THE ONE TAPPED. An `AVPlayerItemVideoOutput` added to the item//   playing hands over nothing until the next key frame, seconds later and a//   different picture. So a second, silent player that no screen shows opens//   the film from the same door and seeks exactly to the moment tapped; what//   plays is never touched.// - ON THE PHONE it reads the film's tallest rung, the full picture.// - ON A TV the film is never pulled back to the phone, and the silent player//   reads the lowest rung of at least 720p.// - HDR comes out SDR: the output asks for BT.709, so the system tone-maps the//   picture rather than handing over a washed-out one.//// The frame is written as a JPEG at the film's full picture size, nothing// cropped, and handed to the core, which seals and keeps it (`use_frame`).import CottonKitimport Foundationimport SwiftUI#if os(iOS)import AVFoundationimport CoreImageimport UIKit#endif/// The choices a player offers of the core's list: subtitle timing only for a/// film that carries subtitle tracks, which only the player can see.enum FilmMoreChoices {    static func offered(_ more: PlayerPlaying.More?, carriesSubtitles: Bool) -> [PlayerPlaying.More.Choice] {        (more?.choices ?? []).filter { $0.needs != "subtitles" || carriesSubtitles }    }}/// The rung of an HLS master a frame is taken from.enum FilmRungs {    /// The shortest picture a poster is taken from.    static let tallEnough = 720    private struct Rung {        let uri: String        let height: Int        let bandwidth: Int        let sdr: Bool    }    /// The tallest rung's address, the full picture: an SDR rung before an    /// HDR one of the same height; nil when the master lists no rung with a size.    static func tallest(master: String) -> String? {        read(master).max { ($0.height, $0.sdr ? 1 : 0, $0.bandwidth) < ($1.height, $1.sdr ? 1 : 0, $1.bandwidth) }?.uri    }    /// The address of the rung to take a frame from on a TV: an SDR rung    /// before an HDR one, then the lowest of at least 720p; the tallest when    /// none is that tall; nil when the master lists no rung with a size.    static func pick(master: String) -> String? {        let rungs = read(master)        let tall = rungs.filter { $0.height >= tallEnough }        if tall.isEmpty { return rungs.max { ($0.height, $0.bandwidth) < ($1.height, $1.bandwidth) }?.uri }        return tall.min { ($0.sdr ? 0 : 1, $0.height, $0.bandwidth) < ($1.sdr ? 0 : 1, $1.height, $1.bandwidth) }?.uri    }    private static func read(_ master: String) -> [Rung] {        var rungs: [Rung] = []        var pending: String?        for raw in master.split(whereSeparator: \.isNewline) {            let line = raw.trimmingCharacters(in: .whitespaces)            if line.hasPrefix("#EXT-X-STREAM-INF:") {                pending = line            } else if !line.isEmpty, !line.hasPrefix("#"), let said = pending {                pending = nil                guard let size = attribute("RESOLUTION", in: said)?.lowercased().split(separator: "x"), size.count == 2, let height = Int(size[1]) else { continue }                let bandwidth = attribute("BANDWIDTH", in: said).flatMap { Int($0) } ?? 0                let range = attribute("VIDEO-RANGE", in: said)?.uppercased() ?? "SDR"                rungs.append(Rung(uri: line, height: height, bandwidth: bandwidth, sdr: range == "SDR"))            }        }        return rungs    }    /// One attribute of a tag, its quotes off; a quoted value may hold commas.    private static func attribute(_ name: String, in tag: String) -> String? {        guard let found = tag.range(of: "(?<=[:,])\(name)=(\"[^\"]*\"|[^,]*)", options: .regularExpression) else { return nil }        return tag[found].dropFirst(name.count + 1).trimmingCharacters(in: CharacterSet(charactersIn: "\""))    }}/// The "more" menu over the picture, in the Subtitle timing panel's look: the/// core's title and its choices.struct FilmMoreMenu: View {    let title: String    let closeLabel: String    let choices: [PlayerPlaying.More.Choice]    let choose: @MainActor (PlayerPlaying.More.Choice) -> Void    let close: @MainActor () -> Void    var body: some View {        VStack(spacing: 14) {            HStack {                Text(title).font(.headline)                Spacer()                Button(action: close) { Image(systemName: "xmark.circle.fill").font(.title2) }                    .accessibilityLabel(closeLabel)                    .accessibilityIdentifier("film-more-close")            }            VStack(spacing: 8) {                ForEach(choices, id: \.id) { choice in                    Button { choose(choice) } label: { Text(choice.label).frame(maxWidth: .infinity) }                        .accessibilityIdentifier("film-more-\(choice.id)")                }            }            .buttonStyle(.bordered)        }        .padding(18)        .foregroundStyle(.white)        .tint(.white)        .background(.ultraThinMaterial.opacity(0.9), in: RoundedRectangle(cornerRadius: 16))        .environment(\.colorScheme, .dark)        .frame(maxWidth: 360)        .accessibilityElement(children: .contain)        .accessibilityIdentifier("film-more")    }}#if os(iOS)/// A pixel buffer carried to the work that writes it; nothing else holds it.private struct FilmFrameBuffer: @unchecked Sendable {    let pixels: CVPixelBuffer}/// Taking one frame of a film and writing it out.enum FilmFrame {    /// How long the silent player is given to open the film and find the frame.    static let wait: Duration = .seconds(20)    /// Which rung the frame is read from: the full picture on the phone, the    /// lowest of at least 720p while the film plays on a TV.    enum Rung { case full, tallEnough }    /// BT.709 at eight bits: an HDR picture is tone-mapped to SDR on its way here.    static var outputSettings: [String: Any] {        [            kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA,            AVVideoAllowWideColorKey: false,            AVVideoColorPropertiesKey: [                AVVideoColorPrimariesKey: AVVideoColorPrimaries_ITU_R_709_2,                AVVideoTransferFunctionKey: AVVideoTransferFunction_ITU_R_709_2,                AVVideoYCbCrMatrixKey: AVVideoYCbCrMatrix_ITU_R_709_2,            ],        ]    }    /// The frame exactly `seconds` into the film at `source`, from a silent,    /// paused player no screen shows: what plays is not touched.    @MainActor    static func take(from source: URL, at seconds: Double, rung wanted: Rung) async -> CVPixelBuffer? {        guard let url = await rung(of: source, wanted) else { return nil }        let item = AVPlayerItem(asset: AVURLAsset(url: url))        let output = AVPlayerItemVideoOutput(outputSettings: outputSettings)        item.add(output)        let silent = AVPlayer(playerItem: item)        silent.isMuted = true        silent.allowsExternalPlayback = false        silent.preventsDisplaySleepDuringVideoPlayback = false        defer {            silent.pause()            silent.replaceCurrentItem(with: nil)        }        let clock = ContinuousClock()        let deadline = clock.now.advanced(by: wait)        while item.status == .unknown, clock.now < deadline { try? await Task.sleep(for: .milliseconds(50)) }        guard item.status == .readyToPlay else { return nil }        guard await silent.seek(to: CMTime(seconds: seconds, preferredTimescale: 600), toleranceBefore: .zero, toleranceAfter: .zero) else { return nil }        return await pull(output, from: item, within: clock.now.duration(to: deadline))    }    /// Where a frame is read from: the chosen rung of a master, else the file itself.    private static func rung(of source: URL, _ wanted: Rung) async -> URL? {        guard !source.isFileURL, source.pathExtension.lowercased() == "m3u8" else { return source }        guard let (body, answer) = try? await URLSession.shared.data(from: source),              (answer as? HTTPURLResponse)?.statusCode == 200,              let master = String(data: body, encoding: .utf8) else { return nil }        guard let uri = wanted == .full ? FilmRungs.tallest(master: master) : FilmRungs.pick(master: master) else { return source }        return URL(string: uri, relativeTo: source)?.absoluteURL    }    @MainActor    private static func pull(_ output: AVPlayerItemVideoOutput, from item: AVPlayerItem, within: Duration) async -> CVPixelBuffer? {        let clock = ContinuousClock()        let deadline = clock.now.advanced(by: within)        while clock.now < deadline {            let now = item.currentTime()            if output.hasNewPixelBuffer(forItemTime: now), let pixels = output.copyPixelBuffer(forItemTime: now, itemTimeForDisplay: nil) { return pixels }            try? await Task.sleep(for: .milliseconds(30))        }        return nil    }    /// The frame as a JPEG file in the temporary folder, written off the main actor.    @MainActor    static func written(_ pixels: CVPixelBuffer) async -> URL? {        let held = FilmFrameBuffer(pixels: pixels)        return await Task.detached(priority: .userInitiated) { () -> URL? in            guard let data = jpeg(held.pixels) else { return nil }            let file = FileManager.default.temporaryDirectory.appendingPathComponent("film-frame-\(UUID().uuidString).jpg")            return (try? data.write(to: file)) == nil ? nil : file        }.value    }    /// The whole picture as a JPEG in sRGB, its pixels made square where the    /// film's are not, so it is never squeezed.    static func jpeg(_ pixels: CVPixelBuffer) -> Data? {        var image = CIImage(cvPixelBuffer: pixels)        if let aspect = CVBufferCopyAttachment(pixels, kCVImageBufferPixelAspectRatioKey, nil) as? [String: Any],           let across = (aspect[kCVImageBufferPixelAspectRatioHorizontalSpacingKey as String] as? NSNumber)?.doubleValue,           let down = (aspect[kCVImageBufferPixelAspectRatioVerticalSpacingKey as String] as? NSNumber)?.doubleValue,           across > 0, down > 0, across != down {            image = image.transformed(by: CGAffineTransform(scaleX: across / down, y: 1))        }        guard let space = CGColorSpace(name: CGColorSpace.sRGB) else { return nil }        let quality = CIImageRepresentationOption(rawValue: kCGImageDestinationLossyCompressionQuality as String)        return CIContext().jpegRepresentation(of: image, colorSpace: space, options: [quality: 0.9])    }}#endif