// The tiers, made on the phone at the moment of capture. // // ## Why this is Swift and not Rust // // The Rust workspace has no image decoder at all — no `image`, no `libheif`, // no `webp`, no `blurhash` — and HEIC is the majority format in a real // library. ImageIO and AVFoundation are already on the phone, they decode // everything the camera writes, and they are hardware-accelerated. So every // rendition is encoded HERE and handed to the crate as a PATH, which is the // same rule `capture.media` has always kept: bytes never cross that boundary // (`crates/cotton-ffi/src/phone/media.rs`). The one exception is the blur, and // it is a ≤ 1,024 byte string because it is a replicated COLUMN. // // ## The four tiers, and what each is for // // | Tier | What it is | Where it goes | // |---|---|---| // | blur | 24 px JPEG, base64, ≤ 1,024 B | `cotton_photos.preview` — a row column, so it travels in the ordinary fold | // | thumb | 256 px longest edge, JPEG q 0.55, ≤ 20 KB | an object, and what every grid tile draws | // | display | 1600 px longest edge, JPEG q 0.8 | an object, and only when the original is over two megapixels | // | poster | a film's still frame, JPEG | an object under the film's own `poster_key` | // // A film costs ONE decode: the still is cut first, and the thumbnail, the // display rendition and the blur are all derived from the still rather than // from the film. // // ## Nothing here ever throws // // A capture is the photograph. A tier is a convenience that a backlog worker // on the Mac can make later, or that can stay missing for ever for a format // ImageIO cannot decode — in which case the tile draws a glyph, honestly. So // every failure here is an ABSENT tier and a line in the log, never an error // that reaches the caller: `capture.media` must land whatever ImageIO thought // of the file. The crate agrees from the other side — it refuses a tier path // that is not there, and the way to say "I could not make this one" is to send // nothing. // // The constants below are the same numbers the Mac's backlog worker uses, and // they are spelled in both places rather than shared by path, because the two // producers are in different modules on different platforms and a guard that // reads another lane's file by path goes quiet rather than red when that file // moves (AGENTS.md). import AVFoundation import CoreGraphics import Foundation import ImageIO import UniformTypeIdentifiers /// The renditions a capture made, as paths plus the one string that is a /// column. /// /// Every field is optional and every `nil` is a real state: a picture at or /// under two megapixels has no `displayPath` because the original IS its own /// display tier, only a film has a `posterPath`, and a file nothing could /// decode has all four empty and is captured anyway. public struct MediaTiers: Sendable, Equatable { /// The 256 px grid thumbnail. public var thumbPath: String? /// The 1600 px rendition a detail view opens. public var displayPath: String? /// A film's still frame. public var posterPath: String? /// The 24 px blur, base64. public var preview: String? public init( thumbPath: String? = nil, displayPath: String? = nil, posterPath: String? = nil, preview: String? = nil ) { self.thumbPath = thumbPath self.displayPath = displayPath self.posterPath = posterPath self.preview = preview } /// Nothing could be made. The capture still happens. public static let none = MediaTiers() /// `true` when there is nothing at all to hand the crate. public var isEmpty: Bool { thumbPath == nil && displayPath == nil && posterPath == nil && preview == nil } } extension MediaTiers { // ── The numbers ───────────────────────────────────────────────────────── /// The thumbnail's longest edge, in pixels. /// /// 256 and not the screen's width, and the arithmetic is the reason: a /// 1170 px JPEG is 150–250 KB, so fifty thousand of them is 8–12 GB. At /// 256 px a thumbnail is 10–14 KB and the same library is about 600 MB — /// which is what a phone can actually hold for every picture the person /// owns, which is the whole point of the tier. public static let thumbMaxEdge: CGFloat = 256 /// The thumbnail's JPEG quality. public static let thumbQuality: CGFloat = 0.55 /// The ceiling a thumbnail may not pass, in bytes. /// /// Enforced by re-encoding at a lower quality rather than by refusing: a /// tile that is a little softer is better than a tile that is not there. public static let thumbMaxBytes = 20 * 1_024 /// The display rendition's longest edge, in pixels. public static let displayMaxEdge: CGFloat = 1_600 /// The display rendition's JPEG quality. public static let displayQuality: CGFloat = 0.8 /// Above this many pixels an original earns a display rendition; at or /// below it, the original IS the display tier and a second copy would be /// pure cost. public static let displayThresholdPixels = 2_000_000 /// The blur's longest edge, in pixels. public static let blurMaxEdge: CGFloat = 24 /// The blur's JPEG quality — low, because it is drawn blurred anyway and /// every byte of it is carried by every device for ever. public static let blurQuality: CGFloat = 0.4 /// The ceiling on the blur, in bytes of BASE64 — the encoded string, since /// that is what the column stores. /// /// **1,536, and the number is a measurement rather than a preference.** A /// baseline JPEG's Huffman and quantization tables come to about 700 bytes /// before a pixel is encoded, so the smallest 24 px JPEG ImageIO will write /// — a flat colour at quality 0.1 — is 1,036 bytes of base64, and per-pixel /// noise at the same quality is 1,260. The kilobyte the design asked for is /// not reachable in this format at all; 1,536 clears the worst case, and an /// ordinary picture lands at 1,040–1,150. /// /// The crate refuses anything over this before a byte moves /// (`PREVIEW_MAX_BASE64_BYTES`, `phone/media.rs`), so a producer that went /// over would cost the person the photograph. This side never sends one. public static let previewMaxBase64Bytes = 1_536 /// Where in a film the still is cut from. /// /// `min(0.1s, duration/2)` — the first tenth of a second for anything of /// ordinary length, and the midpoint of a clip shorter than two tenths, so /// a very short film cannot ask for a frame past its own end. public static let stillAtSeconds = 0.1 // ── Where they are written ────────────────────────────────────────────── /// A fresh directory for one capture's renditions. /// /// The caller OWNS it and hands it to [`discard(_:)`] when the capture has /// answered — by which point the crate has copied every tier into the /// content-addressed store, exactly as it copies the original. Nothing here /// is ever referenced in place. /// /// A per-capture directory rather than one shared folder so two captures in /// flight at once cannot collide, and so cleaning up after one cannot take /// the other's files with it. public static func scratchDirectory() -> URL { let directory = FileManager.default.temporaryDirectory .appendingPathComponent("cotton-tiers-\(UUID().uuidString)") do { try FileManager.default.createDirectory( at: directory, withIntermediateDirectories: true ) } catch { // Logged rather than thrown: with no directory every rendition // simply fails to write and the capture lands without them, which // is the behaviour this whole file is built around. Log.warn("mediaTiers: no scratch directory: \(error)") } return directory } /// Throw the renditions away once the crate has copied them. public static func discard(_ directory: URL) { try? FileManager.default.removeItem(at: directory) } // ── Making them ───────────────────────────────────────────────────────── /// The renditions for one captured file, made OFF the main actor. /// /// The caller is a share-sheet drain or a picker, both of which are driving /// a screen; a 4 MB HEIC decode on the main actor is a visible stall. The /// work is handed to a detached task at `.utility`, which is also what says /// this is not urgent: the capture is what matters and it is already /// queued behind this only because the paths have to exist before the /// crate is told about them. /// /// `directory` is where the files are written — the caller's own temp /// directory, which it owns and cleans up. The crate COPIES them into the /// content-addressed store, so nothing here is referenced in place. public static func make(for url: URL, film: Bool, in directory: URL) async -> MediaTiers { if film { // THE STILL FIRST, and everything else from the still: a film costs // one decode, not four, and AVFoundation is the only thing here // that can open it at all. guard let poster = await still(from: url, in: directory) else { return .none } var tiers = await Task.detached(priority: .utility) { renditions(ofPicture: poster, in: directory) }.value tiers.posterPath = poster.path(percentEncoded: false) return tiers } return await Task.detached(priority: .utility) { renditions(ofPicture: url, in: directory) }.value } /// The three ImageIO renditions of one picture — the whole act, synchronous /// and pure, so a test can drive it against a generated image. /// /// SYNCHRONOUS on purpose: there is no await in it, so there is nothing for /// a test to race, and the one caller that must not block a screen is the /// one that wraps it in a detached task above. public static func renditions(ofPicture url: URL, in directory: URL) -> MediaTiers { guard let source = CGImageSourceCreateWithURL(url as CFURL, nil), CGImageSourceGetCount(source) > 0 else { // A format ImageIO cannot read rests rather than failing. The // capture still lands; the tile draws a glyph until something else // makes a rendition, and that may be never. Log.warn("mediaTiers: ImageIO could not open \(url.lastPathComponent)") return .none } // THESE ARE TEMP FILE NAMES, NOT KEYS, and they deliberately do not // look like keys. The rendition suffixes are spelled ONCE, in // `cotton_core::media::keys`, and this app never builds one of those // keys at all (`ThumbFetchSweepTests`): the crate derives it from the // ORIGINAL's digest, which is a number this side has not computed and // has no business computing. let stem = UUID().uuidString var tiers = MediaTiers() // THE THUMBNAIL, which every grid tile draws. if let thumb = scaled(source, toMaxEdge: thumbMaxEdge) { tiers.thumbPath = write( thumb, to: directory.appendingPathComponent("\(stem)-thumb.jpg"), quality: thumbQuality, underBytes: thumbMaxBytes )?.path(percentEncoded: false) } // THE DISPLAY RENDITION, and only when the original earns one. if pixels(of: source) > displayThresholdPixels, let display = scaled(source, toMaxEdge: displayMaxEdge) { tiers.displayPath = write( display, to: directory.appendingPathComponent("\(stem)-display.jpg"), quality: displayQuality, underBytes: nil )?.path(percentEncoded: false) } // THE BLUR, which is a column and therefore a string. tiers.preview = blur(source) return tiers } /// A film's first frame, as a JPEG on disk. /// /// `appliesPreferredTrackTransform` is not optional: a clip shot in /// portrait carries its rotation in the track's transform, and without this /// every poster of every portrait film is on its side. public static func still(from url: URL, in directory: URL) async -> URL? { let asset = AVURLAsset(url: url) let generator = AVAssetImageGenerator(asset: asset) generator.appliesPreferredTrackTransform = true // The frame at exactly the time asked for, not the nearest keyframe: // on a short clip the nearest keyframe can be the last one, which is // usually a fade to black. generator.requestedTimeToleranceBefore = .zero generator.requestedTimeToleranceAfter = .zero do { let duration = try await asset.load(.duration).seconds let at = duration.isFinite && duration > 0 ? min(stillAtSeconds, duration / 2) : stillAtSeconds let (frame, _) = try await generator.image( at: CMTime(seconds: at, preferredTimescale: 600) ) let destination = directory.appendingPathComponent("\(UUID().uuidString)-still.jpg") return write(frame, to: destination, quality: displayQuality, underBytes: nil) } catch { Log.warn("mediaTiers: no still from \(url.lastPathComponent): \(error)") return nil } } // ── The ImageIO pieces ────────────────────────────────────────────────── /// How many pixels the original has, straight off the file's metadata — /// no decode. static func pixels(of source: CGImageSource) -> Int { guard let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any], let width = properties[kCGImagePropertyPixelWidth] as? Int, let height = properties[kCGImagePropertyPixelHeight] as? Int else { // Unknown is not "small": a file whose dimensions ImageIO will not // state gets a display rendition, because the cost of one it did // not need is a copy and the cost of missing one is a detail view // that opens the whole original. return .max } return width * height } /// The picture at a bounded longest edge. /// /// `CreateThumbnailFromImageAlways` because a HEIC's embedded thumbnail is /// whatever the camera felt like and is often 320 px of something else; /// `WithTransform` because the EXIF orientation has to be baked in — the /// renditions are handed to a renderer that will not read EXIF. static func scaled(_ source: CGImageSource, toMaxEdge edge: CGFloat) -> CGImage? { CGImageSourceCreateThumbnailAtIndex( source, 0, [ kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceThumbnailMaxPixelSize: edge, ] as CFDictionary ) } /// JPEG bytes at one quality, in memory. static func jpeg(_ image: CGImage, quality: CGFloat) -> Data? { let data = NSMutableData() guard let destination = CGImageDestinationCreateWithData( data as CFMutableData, UTType.jpeg.identifier as CFString, 1, nil ) else { return nil } CGImageDestinationAddImage( destination, image, [kCGImageDestinationLossyCompressionQuality: quality] as CFDictionary ) guard CGImageDestinationFinalize(destination) else { return nil } return data as Data } /// JPEG bytes at a quality low enough to fit under a ceiling. /// /// Softer rather than absent: the thumbnail's 20 KB is a budget over a /// whole library, and a single busy picture that will not fit at q 0.55 /// is worth re-encoding rather than losing. Four steps, then the smallest /// one whatever it weighs — a tile a little over budget is still a tile. static func jpeg(_ image: CGImage, quality: CGFloat, underBytes ceiling: Int?) -> Data? { guard var best = jpeg(image, quality: quality) else { return nil } guard let ceiling, best.count > ceiling else { return best } for step in [0.4, 0.3, 0.2, 0.1] as [CGFloat] { guard let smaller = jpeg(image, quality: step) else { break } best = smaller if smaller.count <= ceiling { break } } return best } /// Encode and write, answering where it landed — or `nil`, having said so. static func write( _ image: CGImage, to destination: URL, quality: CGFloat, underBytes ceiling: Int? ) -> URL? { guard let data = jpeg(image, quality: quality, underBytes: ceiling) else { Log.warn("mediaTiers: could not encode \(destination.lastPathComponent)") return nil } do { try data.write(to: destination, options: .atomic) return destination } catch { Log.warn("mediaTiers: could not write \(destination.lastPathComponent): \(error)") return nil } } /// The picture redrawn into a plain device-RGB bitmap, carrying no colour /// profile and no alpha. /// /// **This is what keeps a film's blur under the cap.** A still cut out of a /// video carries the track's colour space — Rec. 709 on anything a phone /// shoots — and `CGImageDestination` embeds that profile in the JPEG it /// writes. At 24 px the profile is a large fraction of the whole file, and /// a film's blur went over the ceiling on the profile alone while the same /// picture out of the camera roll fitted. Redrawing costs one 24 × 24 /// bitmap and makes the two paths produce the same shape of file. /// /// Only the BLUR needs it: a 20 KB thumbnail has room for a profile, and a /// display rendition should keep the colours it was shot in. static func flattened(_ image: CGImage) -> CGImage? { guard let context = CGContext( data: nil, width: image.width, height: image.height, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue ) else { return nil } context.draw( image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height) ) return context.makeImage() } /// The 24 px blur, base64, or `nil` rather than anything over the cap. /// /// **Never returns a string the crate would refuse.** The cap is on the /// ENCODED length because that is what the column stores, and a preview /// over it would be refused by `capture.media` before a byte moved — which /// would cost the person the photograph to save the blur. So this checks /// what it is about to send, and sends nothing when it cannot fit. static func blur(_ source: CGImageSource) -> String? { guard let small = scaled(source, toMaxEdge: blurMaxEdge) else { return nil } let flat = flattened(small) ?? small for quality in [blurQuality, 0.3, 0.2, 0.1] as [CGFloat] { guard let data = jpeg(flat, quality: quality) else { return nil } let encoded = data.base64EncodedString() if encoded.utf8.count <= previewMaxBase64Bytes { return encoded } } Log.warn("mediaTiers: no blur fits under \(previewMaxBase64Bytes) bytes of base64") return nil } }