// What this process has already decoded, so a lazy view rebuilt on a scroll // does not decode it again. // // Every tile used to re-read `read.mediaPath` and re-decode through ImageIO // whenever SwiftUI recreated it — which, in a `LazyVGrid`, is every time it // scrolls back into view. A 256 px JPEG decodes in a millisecond, but a grid // scrolled up and down decodes the same forty squares over and over, and a // person's page rebuilds its prints on every navigation. The map snapshots // already had an `NSCache`; pictures did not. // // **Keyed by the OBJECT KEY and the longest pixel side, and every entry // CARRIES THE RUNG it was decoded from.** A key is content-addressed (the // digest is in it), so a picture under one key never changes and there is // nothing to invalidate; the side is in the key because the same picture // decoded for a 120 pt tile and a full-width hero are two different bitmaps. // The rung is on the entry because the SAME key at the SAME size can be // answered by three files — `read.mediaPath` walks thumbnail, display, // original — and an entry that did not say which would hand a hero the 256 px // thumbnail it cached on a second phone for the rest of the process, after // the original had arrived beside it. A caller that wants the top rung reads // the rung off the hit and asks again if it is lower; `keep` never downgrades. // // **Bounded by COST, in bytes of decoded bitmap.** `NSCache` evicts under // memory pressure on its own; the cost limit is the ceiling it keeps under // before pressure ever arrives. A blur is a 24 px square and is cached by its // base64 string — the same string decodes to the same bitmap every time, and // `PhotosBlur.image` was called on every body evaluation. import CottonKit import Foundation #if canImport(UIKit) import UIKit #endif /// Which file `read.mediaPath` answered — the three rungs of the ladder, in /// order, spelled as the crate spells them. public enum MediaRung: String, Comparable, Sendable { case thumb case display case original private var height: Int { switch self { case .thumb: return 0 case .display: return 1 case .original: return 2 } } public static func < (lhs: MediaRung, rhs: MediaRung) -> Bool { lhs.height < rhs.height } /// The rung a `read.mediaPath` answer names — the ONE reader of the /// answer's `tier` word. A present answer always names one, so an answer /// that does not is not a picture this can draw. A renderer never SAYS a /// tier (`ThumbFetchSweepTests` holds the two that may); reading which one /// came back is this. public init?(answered answer: JSONValue) { self.init(rawValue: answer.text("tier") ?? "") } } /// One decoded picture and the rung it came from. public final class CachedPicture: @unchecked Sendable { public let image: UIImage public let rung: MediaRung public init(image: UIImage, rung: MediaRung) { self.image = image self.rung = rung } } /// The ONE decoded-picture cache for both lanes' loaders. public final class MediaImageCache: @unchecked Sendable { public static let shared = MediaImageCache(costLimit: MediaImageCache.defaultCostLimit) /// Sixty-four mebibytes of decoded bitmaps: about six hundred 256 px /// tiles, or a dozen full-width heroes. Small enough that jetsam never has /// a reason to look at it. public static let defaultCostLimit = 64 * 1024 * 1024 private let pictures = NSCache() private let blurs = NSCache() public init(costLimit: Int) { pictures.totalCostLimit = costLimit // Blurs are tiny and there is one per row: a whole library's worth // is a few megabytes, so their limit is a count rather than a cost. blurs.countLimit = 4_096 } /// The name one decode is filed under. public static func name(key: String, maxPixel: Int) -> String { "\(key)@\(max(1, maxPixel))" } /// What a decoded picture costs — its bitmap, four bytes a pixel. public static func cost(of image: UIImage) -> Int { guard let cg = image.cgImage else { return 0 } return cg.bytesPerRow * cg.height } public func picture(key: String, maxPixel: Int) -> CachedPicture? { pictures.object(forKey: MediaImageCache.name(key: key, maxPixel: maxPixel) as NSString) } /// File a decode under its key, size and rung. **Never a downgrade**: an /// entry already holding a higher rung stays — a grid re-decoding the /// thumbnail must not replace the original the hero just kept. public func keep(_ image: UIImage, rung: MediaRung, key: String, maxPixel: Int) { let name = MediaImageCache.name(key: key, maxPixel: maxPixel) as NSString if let held = pictures.object(forKey: name), held.rung > rung { return } pictures.setObject( CachedPicture(image: image, rung: rung), forKey: name, cost: MediaImageCache.cost(of: image) ) } public func blur(base64: String) -> UIImage? { blurs.object(forKey: base64 as NSString) } public func keepBlur(_ image: UIImage, base64: String) { blurs.setObject(image, forKey: base64 as NSString) } /// Everything, for a test that wants a cold cache. public func removeAll() { pictures.removeAllObjects() blurs.removeAllObjects() } }