// The tiers a capture makes, proved against a GENERATED picture. // // Every fixture here is synthetic — a gradient with noise drawn into a // CGContext, and a two-frame film written by AVAssetWriter // ([nothing-real-ever-goes-in-cotton-s-public-tree]). Nothing in this tree is // ever a real photograph, and these cases would be worthless if it were: the // point is the SIZES and the ORDER, not what the picture is of. // // The other half of this is `writes_tests.rs` in `cotton-ffi`, which owns where // the renditions GO. This file owns whether they can be made at all. import AVFoundation import CoreGraphics import Foundation import ImageIO import UniformTypeIdentifiers import XCTest @testable import CottonKit final class MediaTiersTests: XCTestCase { // ── The fixtures ──────────────────────────────────────────────────────── private func temporaryRoot() throws -> URL { let root = URL(fileURLWithPath: NSTemporaryDirectory()) .appendingPathComponent("cotton-media-tiers-\(UUID().uuidString)") try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) addTeardownBlock { try? FileManager.default.removeItem(at: root) } return root } /// A picture of nothing, at a size the test names. /// /// Deliberately BUSY — a gradient plus per-cell noise — because a flat /// colour compresses to almost nothing and would make every size assertion /// below pass for the wrong reason. private func aPicture(_ width: Int, _ height: Int, in directory: URL) throws -> URL { let space = CGColorSpaceCreateDeviceRGB() guard let context = CGContext( data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: space, bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue ) else { throw XCTSkip("this machine has no RGB bitmap context") } var generator = SystemRandomNumberGenerator() let cell = 4 for y in stride(from: 0, to: height, by: cell) { for x in stride(from: 0, to: width, by: cell) { context.setFillColor( red: CGFloat(x) / CGFloat(width), green: CGFloat(y) / CGFloat(height), blue: CGFloat(UInt8.random(in: 0...255, using: &generator)) / 255, alpha: 1 ) context.fill(CGRect(x: x, y: y, width: cell, height: cell)) } } guard let image = context.makeImage() else { throw XCTSkip("this machine could not make a CGImage") } let url = directory.appendingPathComponent("\(UUID().uuidString).png") guard let destination = CGImageDestinationCreateWithURL( url as CFURL, UTType.png.identifier as CFString, 1, nil ) else { throw XCTSkip("this machine has no PNG encoder") } CGImageDestinationAddImage(destination, image, nil) XCTAssertTrue(CGImageDestinationFinalize(destination), "the fixture was not written") return url } /// Two frames of a film, written by AVAssetWriter. private func aFilm(in directory: URL) async throws -> URL { let url = directory.appendingPathComponent("\(UUID().uuidString).mov") let writer = try AVAssetWriter(outputURL: url, fileType: .mov) let input = AVAssetWriterInput( mediaType: .video, outputSettings: [ AVVideoCodecKey: AVVideoCodecType.h264, AVVideoWidthKey: 160, AVVideoHeightKey: 120, ] ) input.expectsMediaDataInRealTime = false let adaptor = AVAssetWriterInputPixelBufferAdaptor( assetWriterInput: input, sourcePixelBufferAttributes: [ kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32ARGB ] ) writer.add(input) XCTAssertTrue(writer.startWriting(), "\(String(describing: writer.error))") writer.startSession(atSourceTime: .zero) for frame in 0..<4 { var buffer: CVPixelBuffer? guard let pool = adaptor.pixelBufferPool, CVPixelBufferPoolCreatePixelBuffer(nil, pool, &buffer) == kCVReturnSuccess, let buffer else { throw XCTSkip("this machine has no pixel buffer pool") } CVPixelBufferLockBaseAddress(buffer, []) if let base = CVPixelBufferGetBaseAddress(buffer) { memset(base, Int32(40 + frame * 50), CVPixelBufferGetDataSize(buffer)) } CVPixelBufferUnlockBaseAddress(buffer, []) while !input.isReadyForMoreMediaData { try await Task.sleep(nanoseconds: 1_000_000) } XCTAssertTrue( adaptor.append( buffer, withPresentationTime: CMTime(value: CMTimeValue(frame), timescale: 10) ) ) } input.markAsFinished() await writer.finishWriting() XCTAssertEqual(writer.status, .completed, "\(String(describing: writer.error))") return url } // ── a_thumb_is_at_most_twenty_kilobytes ───────────────────────────────── // ── a_blur_is_at_most_a_kilobyte_of_base64 ────────────────────────────── // ── a_small_original_gets_no_display_rendition ────────────────────────── // ── a_film_gets_a_still_first ─────────────────────────────────────────── // ── a_capture_still_lands_when_the_tiers_cannot_be_made ───────────────── func testACaptureStillLandsWhenTheTiersCannotBeMade() async throws { let root = try temporaryRoot() let notAPicture = root.appendingPathComponent("broken.heic") try Data("this is not a picture".utf8).write(to: notAPicture) let tiers = await MediaTiers.make(for: notAPicture, film: false, in: root) XCTAssertTrue(tiers.isEmpty, "something was made out of bytes ImageIO cannot read") // AND THE CAPTURE GOES ANYWAY, carrying NOTHING rather than a path to a // file that was never written. The crate refuses a named path that is // not there — deliberately, because a caller that sent one believes it // did something — so the only honest way to say "I could not make this // one" is to send no key at all. let request = CaptureMediaRequest( path: notAPicture.path(percentEncoded: false), mime: "image/heic", kind: .photo, filename: "broken.heic", tiers: tiers ) let encoded = try JSONEncoder().encode(request) let json = try XCTUnwrap( JSONSerialization.jsonObject(with: encoded) as? [String: Any] ) XCTAssertEqual(json["path"] as? String, notAPicture.path(percentEncoded: false)) XCTAssertEqual(json["kind"] as? String, "photo") for tier in ["thumbPath", "displayPath", "posterPath", "preview"] { XCTAssertNil(json[tier], "`\(tier)` was sent for a capture that made no renditions") } } }