Cotton code
191 lines · 11.3 KB · SwiftRaw
import AVFoundationimport CoreImageimport Foundationimport XCTest@testable import CottonUI/// The picture a film wears, picked from the film (FilmFrames.swift): the/// core's choices, the rung a frame is read from, and the frame itself, taken/// from invented clips written here.@MainActorfinal class FilmFramesTests: XCTestCase {    private func more(_ json: String) throws -> PlayerPlaying.More {        try JSONDecoder().decode(PlayerPlaying.More.self, from: Data(json.utf8))    }    private let answered = """    {"title": "More", "choices": [      {"id": "subtitle_timing", "label": "Subtitle timing", "needs": "subtitles"},      {"id": "use_frame", "label": "Use this frame as the poster", "failed": "This frame could not be kept just now."},      {"id": "original_picture", "label": "Back to the original picture"}    ]}    """    /// RULE (film-poster-pick, 18 Nov 2026): the menu draws the core's choices in the core's order, leaving out subtitle timing for a film that carries no subtitle tracks.    func testTheMenuOffersTheCoresChoices() throws {        let said = try more(answered)        XCTAssertEqual(FilmMoreChoices.offered(said, carriesSubtitles: true).map(\.id), ["subtitle_timing", "use_frame", "original_picture"])        XCTAssertEqual(FilmMoreChoices.offered(said, carriesSubtitles: false).map(\.id), ["use_frame", "original_picture"])        XCTAssertEqual(said.choices[1].failed, "This frame could not be kept just now.")        XCTAssertEqual(FilmMoreChoices.offered(nil, carriesSubtitles: true), [])    }    /// RULE (film-poster-pick, 18 Nov 2026): on a TV a frame is read from the lowest rung of at least 720p, an SDR rung before an HDR one, and from the tallest when none is that tall.    func testAFrameIsReadFromTheLowestRungOfAtLeast720p() {        let master = """        #EXTM3U        #EXT-X-I-FRAME-STREAM-INF:BANDWIDTH=90000,RESOLUTION=1920x1080,URI="iframe.m3u8"        #EXT-X-STREAM-INF:BANDWIDTH=800000,AVERAGE-BANDWIDTH=700000,RESOLUTION=854x480,CODECS="avc1.64001f,mp4a.40.2"        480/index.m3u8        #EXT-X-STREAM-INF:BANDWIDTH=6000000,RESOLUTION=1920x1080,CODECS="avc1.640028,mp4a.40.2"        1080/index.m3u8        #EXT-X-STREAM-INF:BANDWIDTH=3000000,RESOLUTION=1280x720,CODECS="avc1.64001f,mp4a.40.2"        720/index.m3u8        """        XCTAssertEqual(FilmRungs.pick(master: master), "720/index.m3u8")        let hdr = """        #EXTM3U        #EXT-X-STREAM-INF:BANDWIDTH=3000000,RESOLUTION=1280x720,VIDEO-RANGE=PQ        hdr720.m3u8        #EXT-X-STREAM-INF:BANDWIDTH=6000000,RESOLUTION=1920x1080,VIDEO-RANGE=SDR        sdr1080.m3u8        """        XCTAssertEqual(FilmRungs.pick(master: hdr), "sdr1080.m3u8")        let short = "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1,RESOLUTION=640x360\nlow.m3u8\n#EXT-X-STREAM-INF:BANDWIDTH=2,RESOLUTION=854x480\nmid.m3u8\n"        XCTAssertEqual(FilmRungs.pick(master: short), "mid.m3u8")        XCTAssertNil(FilmRungs.pick(master: "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1\nnosize.m3u8\n"))    }    // MARK: The frame itself    private static let size = (width: 640, height: 360)    /// An invented clip: a red second, then a blue one.    private func clip(codec: AVVideoCodecType = .h264, colour: [String: Any]? = nil, format: OSType = kCVPixelFormatType_32BGRA,                      fill: (CVPixelBuffer, Bool) -> Void) async throws -> URL {        let url = FileManager.default.temporaryDirectory.appendingPathComponent("film-frame-test-\(UUID().uuidString).mov")        addTeardownBlock { try? FileManager.default.removeItem(at: url) }        let writer = try AVAssetWriter(outputURL: url, fileType: .mov)        var settings: [String: Any] = [AVVideoCodecKey: codec, AVVideoWidthKey: Self.size.width, AVVideoHeightKey: Self.size.height]        if let colour { settings[AVVideoColorPropertiesKey] = colour }        guard writer.canApply(outputSettings: settings, forMediaType: .video) else { throw XCTSkip("this simulator cannot write \(codec.rawValue)") }        let input = AVAssetWriterInput(mediaType: .video, outputSettings: settings)        input.expectsMediaDataInRealTime = false        let adaptor = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: input, sourcePixelBufferAttributes: [            kCVPixelBufferPixelFormatTypeKey as String: format, kCVPixelBufferWidthKey as String: Self.size.width,            kCVPixelBufferHeightKey as String: Self.size.height, kCVPixelBufferIOSurfacePropertiesKey as String: [String: Any](),        ])        writer.add(input)        guard writer.startWriting() else { throw XCTSkip("this simulator cannot write the clip: \(String(describing: writer.error))") }        writer.startSession(atSourceTime: .zero)        for index in 0..<20 {            while !input.isReadyForMoreMediaData { try await Task.sleep(for: .milliseconds(5)) }            let pool = try XCTUnwrap(adaptor.pixelBufferPool)            var made: CVPixelBuffer?            CVPixelBufferPoolCreatePixelBuffer(nil, pool, &made)            let pixels = try XCTUnwrap(made)            fill(pixels, index < 10)            guard adaptor.append(pixels, withPresentationTime: CMTime(value: CMTimeValue(index), timescale: 10)) else {                throw XCTSkip("this simulator cannot encode the clip: \(String(describing: writer.error))")            }        }        input.markAsFinished()        await writer.finishWriting()        guard writer.status == .completed else { throw XCTSkip("this simulator did not finish the clip: \(String(describing: writer.error))") }        return url    }    private func redThenBlue() async throws -> URL {        try await clip { pixels, first in            CVPixelBufferLockBaseAddress(pixels, [])            defer { CVPixelBufferUnlockBaseAddress(pixels, []) }            let base = CVPixelBufferGetBaseAddress(pixels)!.assumingMemoryBound(to: UInt8.self)            let row = CVPixelBufferGetBytesPerRow(pixels)            for y in 0..<Self.size.height {                for x in 0..<Self.size.width {                    let at = y * row + x * 4                    (base[at], base[at + 1], base[at + 2], base[at + 3]) = first ? (0, 0, 255, 255) : (255, 0, 0, 255)                }            }        }    }    /// The picture's middle pixel, as red, green and blue.    private func middle(_ jpeg: Data) throws -> (red: Int, green: Int, blue: Int, width: Int, height: Int) {        let image = try XCTUnwrap(CIImage(data: jpeg))        var pixel = [UInt8](repeating: 0, count: 4)        let box = CGRect(x: image.extent.midX, y: image.extent.midY, width: 1, height: 1)        CIContext().render(image, toBitmap: &pixel, rowBytes: 4, bounds: box, format: .RGBA8, colorSpace: CGColorSpace(name: CGColorSpace.sRGB))        return (Int(pixel[0]), Int(pixel[1]), Int(pixel[2]), Int(image.extent.width), Int(image.extent.height))    }    #if os(iOS)    /// RULE (film-poster-pick, 18 Nov 2026): the frame is the one asked for, between key frames, whole and at the film's full picture size.    func testTheFrameIsTheOneAskedForAtFullSize() async throws {        let pixels = await FilmFrame.take(from: try await redThenBlue(), at: 1.5, rung: .full)        let frame = try middle(try XCTUnwrap(FilmFrame.jpeg(try XCTUnwrap(pixels))))        XCTAssertEqual(frame.width, Self.size.width)        XCTAssertEqual(frame.height, Self.size.height)        XCTAssertGreaterThan(frame.blue, 180, "the second half is blue: \(frame)")        XCTAssertLessThan(frame.red, 80, "\(frame)")    }    #endif    /// RULE (film-poster-pick, 18 Nov 2026): the phone reads the full picture's rung.    func testThePhoneReadsTheTallestRung() {        let master = "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=3,RESOLUTION=1280x720\n720.m3u8\n#EXT-X-STREAM-INF:BANDWIDTH=9,RESOLUTION=3840x2160,VIDEO-RANGE=PQ\nhdr.m3u8\n#EXT-X-STREAM-INF:BANDWIDTH=8,RESOLUTION=3840x2160,VIDEO-RANGE=SDR\nsdr.m3u8\n"        XCTAssertEqual(FilmRungs.tallest(master: master), "sdr.m3u8")    }    #if os(iOS)    /// RULE (film-poster-pick, 18 Nov 2026): on a TV the frame comes from a second, silent player at the place asked, and the file is written whole as a JPEG.    func testAFrameFromASilentPlayerIsAtThePlaceAsked() async throws {        let url = try await redThenBlue()        let red = await FilmFrame.take(from: url, at: 0.5, rung: .tallEnough)        let first = try middle(try XCTUnwrap(FilmFrame.jpeg(try XCTUnwrap(red))))        XCTAssertGreaterThan(first.red, 180, "\(first)")        let blue = await FilmFrame.take(from: url, at: 1.5, rung: .tallEnough)        let written = await FilmFrame.written(try XCTUnwrap(blue))        let file = try XCTUnwrap(written)        defer { try? FileManager.default.removeItem(at: file) }        XCTAssertEqual(file.pathExtension, "jpg")        let second = try middle(try Data(contentsOf: file))        XCTAssertGreaterThan(second.blue, 180, "\(second)")    }    /// RULE (film-poster-pick, 18 Nov 2026): an HDR film's frame comes out SDR: BT.709, and a mid grey of the film stays a mid grey rather than a washed-out one.    func testAnHDRFilmsFrameComesOutSDR() async throws {        let hlg: [String: Any] = [            AVVideoColorPrimariesKey: AVVideoColorPrimaries_ITU_R_2020,            AVVideoTransferFunctionKey: AVVideoTransferFunction_ITU_R_2100_HLG,            AVVideoYCbCrMatrixKey: AVVideoYCbCrMatrix_ITU_R_2020,        ]        let url = try await clip(codec: .hevc, colour: hlg, format: kCVPixelFormatType_420YpCbCr10BiPlanarVideoRange) { pixels, _ in            CVBufferSetAttachment(pixels, kCVImageBufferColorPrimariesKey, kCVImageBufferColorPrimaries_ITU_R_2020, .shouldPropagate)            CVBufferSetAttachment(pixels, kCVImageBufferTransferFunctionKey, kCVImageBufferTransferFunction_ITU_R_2100_HLG, .shouldPropagate)            CVBufferSetAttachment(pixels, kCVImageBufferYCbCrMatrixKey, kCVImageBufferYCbCrMatrix_ITU_R_2020, .shouldPropagate)            CVPixelBufferLockBaseAddress(pixels, [])            defer { CVPixelBufferUnlockBaseAddress(pixels, []) }            // HLG's reference grey: 38% of the signal, no colour.            let luma = CVPixelBufferGetBaseAddressOfPlane(pixels, 0)!.assumingMemoryBound(to: UInt16.self)            let lumaRow = CVPixelBufferGetBytesPerRowOfPlane(pixels, 0) / 2            let grey = UInt16(64 + 0.38 * 876) << 6            for y in 0..<CVPixelBufferGetHeightOfPlane(pixels, 0) {                for x in 0..<CVPixelBufferGetWidthOfPlane(pixels, 0) { luma[y * lumaRow + x] = grey }            }            let chroma = CVPixelBufferGetBaseAddressOfPlane(pixels, 1)!.assumingMemoryBound(to: UInt16.self)            let chromaRow = CVPixelBufferGetBytesPerRowOfPlane(pixels, 1) / 2            for y in 0..<CVPixelBufferGetHeightOfPlane(pixels, 1) {                for x in 0..<(CVPixelBufferGetWidthOfPlane(pixels, 1) * 2) { chroma[y * chromaRow + x] = 512 << 6 }            }        }        let pixels = await FilmFrame.take(from: url, at: 0.5, rung: .full)        let frame = try XCTUnwrap(pixels)        XCTAssertEqual(CVBufferCopyAttachment(frame, kCVImageBufferTransferFunctionKey, nil) as? String, kCVImageBufferTransferFunction_ITU_R_709_2 as String)        let seen = try middle(try XCTUnwrap(FilmFrame.jpeg(frame)))        XCTAssertLessThan(abs(seen.red - seen.blue), 16, "no colour cast: \(seen)")        XCTAssertTrue((70...190).contains(seen.green), "a mid grey stays a mid grey: \(seen)")    }    #endif}