// 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`).importCottonKitimportFoundationimportSwiftUI#if os(iOS)import AVFoundationimportCoreImageimport 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.enumFilmMoreChoices {staticfunc 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.enumFilmRungs {/// The shortest picture a poster is taken from.staticlet tallEnough = 720privatestructRung {let uri: Stringlet height: Intlet bandwidth: Intlet 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.staticfunc 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.staticfunc 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 }privatestaticfunc 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 } elseif !line.isEmpty, !line.hasPrefix("#"), let said = pending { pending = nilguardlet 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) } ?? 0let 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.privatestaticfunc attribute(_ name: String, in tag: String) -> String? {guardlet found = tag.range(of: "(?<=[:,])\(name)=(\"[^\"]*\"|[^,]*)", options: .regularExpression) else { returnnil }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.structFilmMoreMenu: View {let title: Stringlet closeLabel: Stringlet choices: [PlayerPlaying.More.Choice]let choose: @MainActor (PlayerPlaying.More.Choice) -> Voidlet close: @MainActor () -> Voidvar body: someView { 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 inButton { 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.privatestructFilmFrameBuffer: @unchecked Sendable {let pixels: CVPixelBuffer}/// Taking one frame of a film and writing it out.enumFilmFrame {/// How long the silent player is given to open the film and find the frame.staticlet 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.enumRung { case full, tallEnough }/// BT.709 at eight bits: an HDR picture is tone-mapped to SDR on its way here.staticvar outputSettings: [String: Any] { [ kCVPixelBufferPixelFormatTypeKey asString: 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. @MainActorstaticfunc take(from source: URL, at seconds: Double, rung wanted: Rung) async -> CVPixelBuffer? {guardlet url = await rung(of: source, wanted) else { returnnil }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 = falsedefer { silent.pause() silent.replaceCurrentItem(with: nil) }let clock = ContinuousClock()let deadline = clock.now.advanced(by: wait)while item.status == .unknown, clock.now < deadline { try? awaitTask.sleep(for: .milliseconds(50)) }guard item.status == .readyToPlay else { returnnil }guardawait silent.seek(to: CMTime(seconds: seconds, preferredTimescale: 600), toleranceBefore: .zero, toleranceAfter: .zero) else { returnnil }returnawait 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.privatestaticfunc rung(of source: URL, _ wanted: Rung) async -> URL? {guard !source.isFileURL, source.pathExtension.lowercased() == "m3u8"else { return source }guardlet (body, answer) = try? await URLSession.shared.data(from: source), (answer as? HTTPURLResponse)?.statusCode == 200,let master = String(data: body, encoding: .utf8) else { returnnil }guardlet uri = wanted == .full ? FilmRungs.tallest(master: master) : FilmRungs.pick(master: master) else { return source }return URL(string: uri, relativeTo: source)?.absoluteURL } @MainActorprivatestaticfunc 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? awaitTask.sleep(for: .milliseconds(30)) }returnnil }/// The frame as a JPEG file in the temporary folder, written off the main actor. @MainActorstaticfunc written(_ pixels: CVPixelBuffer) async -> URL? {let held = FilmFrameBuffer(pixels: pixels)returnawaitTask.detached(priority: .userInitiated) { () -> URL? inguardlet data = jpeg(held.pixels) else { returnnil }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.staticfunc jpeg(_ pixels: CVPixelBuffer) -> Data? {var image = CIImage(cvPixelBuffer: pixels)iflet aspect = CVBufferCopyAttachment(pixels, kCVImageBufferPixelAspectRatioKey, nil) as? [String: Any],let across = (aspect[kCVImageBufferPixelAspectRatioHorizontalSpacingKey asString] as? NSNumber)?.doubleValue,let down = (aspect[kCVImageBufferPixelAspectRatioVerticalSpacingKey asString] as? NSNumber)?.doubleValue, across > 0, down > 0, across != down { image = image.transformed(by: CGAffineTransform(scaleX: across / down, y: 1)) }guardlet space = CGColorSpace(name: CGColorSpace.sRGB) else { returnnil }let quality = CIImageRepresentationOption(rawValue: kCGImageDestinationLossyCompressionQuality asString)return CIContext().jpegRepresentation(of: image, colorSpace: space, options: [quality: 0.9]) }}#endif