Decode thumbnails at display size from DownloadedImageCache.

This commit is contained in:
Brent Simmons committed 2026-10-26 21:12:21 -07:00
1 parent 6831d31fc9
commit f7daad126b
5 files changed
+106 -164

No files matched your search

@@ -45,8 +45,7 @@ extension Notification.Name {
/// URLs that recently failed to download are skipped, so a dead or rejected image
/// falls through to the next source.
///
/// Images come from `ImageDownloader.thumbnails` in small mode and
/// `ImageDownloader.largeThumbnails` in large mode, and are decoded off the main thread.
/// Images are decoded at display size from `DownloadedImageCache`’s copy, off the main thread.
@MainActor public final class ArticleThumbnailFinder {
public enum Mode: Sendable {
@@ -64,18 +63,17 @@ extension Notification.Name {
private var articleIDsWithNoHTMLThumbnail = Set<String>()
private var articleIDsBeingDiscovered = Set<String>()
private let imageCache = NSCache<NSString, RSImage>() // See cacheKey
private var cacheKeysBeingDecoded = Set<String>()
private var isObservingLargeThumbnails = false
private var cacheKeysInProgress = Set<String>()
/// Decoded bitmaps: about 1 MB each in small mode, 2–5 MB in large mode.
private static let imageCacheByteLimit = 128 * 1024 * 1024
nonisolated private static let bytesPerPixel = 4
/// Sized for aspect-fill cropping into a small square.
private static let smallThumbnailMaxPixelSize = 512
init(metadataDatabase: ImageMetadataDatabase) {
self.metadataDatabase = metadataDatabase
self.imageCache.totalCostLimit = Self.imageCacheByteLimit
observeImageDownloader(ImageDownloader.thumbnails)
// Not flushed on appDidGoToBackground, which would make thumbnails flash on resume.
NotificationCenter.default.addObserver(self, selector: #selector(handleLowMemory(_:)), name: .lowMemory, object: nil)
}
@@ -90,10 +88,7 @@ extension Notification.Name {
return image
}
let kind = ActivityKind.downloadThumbnail(imageURL: url)
if let data = imageDownloader(for: mode).image(for: url, activityOwner: .thumbnailDownloader, activityKind: kind, activityDetail: article.title) {
decodeAndCacheImage(data, url: url, mode: mode)
}
findImage(url, mode: mode, activityDetail: article.title)
return nil
}
@@ -141,24 +136,6 @@ extension Notification.Name {
// MARK: - Notifications
@objc func handleImageDidBecomeAvailable(_ notification: Notification) {
guard let url = notification.userInfo?["url"] as? String else {
return
}
let mode: Mode = notification.object as AnyObject === ImageDownloader.thumbnails ? .small : .large
guard imageCache.object(forKey: Self.cacheKey(url, mode)) == nil, let data = imageDownloader(for: mode).image(for: url) else {
return
}
decodeAndCacheImage(data, url: url, mode: mode)
}
@objc func handleImageDownloadDidFail(_ notification: Notification) {
guard let url = notification.userInfo?["url"] as? String else {
return
}
NotificationCenter.default.post(name: .articleThumbnailDownloadDidFail, object: self, userInfo: [Self.urlKey: url])
}
@objc func handleLowMemory(_ notification: Notification) {
imageCache.removeAllObjects()
}
@@ -188,57 +165,42 @@ private extension ArticleThumbnailFinder {
"\(mode) \(url)" as NSString
}
/// The large-thumbnail downloader isn’t created or observed until large mode is used.
func imageDownloader(for mode: Mode) -> ImageDownloader {
static func maxPixelSize(_ mode: Mode) -> Int {
switch mode {
case .small:
return ImageDownloader.thumbnails
smallThumbnailMaxPixelSize
case .large:
if !isObservingLargeThumbnails {
isObservingLargeThumbnails = true
observeImageDownloader(ImageDownloader.largeThumbnails)
}
return ImageDownloader.largeThumbnails
DownloadedImageCache.maxPixelSize
}
}
func observeImageDownloader(_ imageDownloader: ImageDownloader) {
NotificationCenter.default.addObserver(self, selector: #selector(handleImageDidBecomeAvailable(_:)), name: .imageDidBecomeAvailable, object: imageDownloader)
NotificationCenter.default.addObserver(self, selector: #selector(handleImageDownloadDidFail(_:)), name: .imageDownloadDidFail, object: imageDownloader)
}
func decodeAndCacheImage(_ data: Data, url: String, mode: Mode) {
func findImage(_ url: String, mode: Mode, activityDetail: String?) {
let cacheKey = Self.cacheKey(url, mode)
guard !cacheKeysBeingDecoded.contains(cacheKey as String) else {
guard !cacheKeysInProgress.contains(cacheKey as String) else {
return
}
cacheKeysBeingDecoded.insert(cacheKey as String)
cacheKeysInProgress.insert(cacheKey as String)
Task {
let decodedImage = await Self.decodedImage(data)
cacheKeysBeingDecoded.remove(cacheKey as String)
guard let decodedImage else {
return
defer {
cacheKeysInProgress.remove(cacheKey as String)
}
do throws(ImageDownloadError) {
let data = try await DownloadedImageCache.shared.imageData(for: url, usesDownloadLimiter: true, activityOwner: .thumbnailDownloader, activityKind: .downloadThumbnail(imageURL: url), activityDetail: activityDetail)
let decodedImage = try await Self.decodedImage(data, maxPixelSize: Self.maxPixelSize(mode))
imageCache.setObject(decodedImage.image, forKey: cacheKey, cost: decodedImage.byteCount)
NotificationCenter.default.post(name: .articleThumbnailDidBecomeAvailable, object: self, userInfo: [Self.urlKey: url])
} catch {
if error.rejectedPixelSize != nil {
metadataDatabase.recordInsignificantDimensions(url: url)
}
if !error.isTransient {
NotificationCenter.default.post(name: .articleThumbnailDownloadDidFail, object: self, userInfo: [Self.urlKey: url])
}
}
imageCache.setObject(decodedImage.image, forKey: cacheKey, cost: decodedImage.byteCount)
NotificationCenter.default.post(name: .articleThumbnailDidBecomeAvailable, object: self, userInfo: [Self.urlKey: url])
}
}
/// Decodes now, so drawing the image in the timeline doesn’t decode it on the main thread.
@concurrent static func decodedImage(_ data: Data) async -> (image: RSImage, byteCount: Int)? {
let options = [kCGImageSourceShouldCacheImmediately: true] as CFDictionary
guard let imageSource = CGImageSourceCreateWithData(data as CFData, nil), let cgImage = CGImageSourceCreateImageAtIndex(imageSource, 0, options) else {
return nil
}
let byteCount = cgImage.width * cgImage.height * bytesPerPixel
#if os(macOS)
return (image: NSImage(cgImage: cgImage, size: .zero), byteCount: byteCount)
#else
return (image: UIImage(cgImage: cgImage), byteCount: byteCount)
#endif
}
func providedThumbnailURL(for article: Article, mode: Mode) -> String? {
let thumbnailURL = Self.normalizedURLString(article.rawThumbnailLink)
let imageURL = Self.normalizedURLString(article.rawImageLink)
@@ -314,3 +276,36 @@ private extension ArticleThumbnailFinder {
return URL.encodeSpacesIfNeeded(link)?.absoluteString ?? link
}
}
// MARK: - Decoding
extension ArticleThumbnailFinder {
/// Decodes now, at display size and in EXIF orientation, so drawing the image in the timeline
/// doesn’t decode it on the main thread. Throws when the image is unreadable, too small, or too narrow.
@concurrent static func decodedImage(_ data: Data, maxPixelSize: Int) async throws(ImageDownloadError) -> (image: RSImage, byteCount: Int) {
guard let pixelSize = RSImage.largestFramePixelSize(data) else {
throw ImageDownloadError(statusCode: nil, decodingFailed: true, isTransient: false)
}
guard SignificantImageFilter.hasSignificantDimensions(width: pixelSize.width, height: pixelSize.height) else {
throw ImageDownloadError(statusCode: nil, decodingFailed: false, isTransient: false, rejectedPixelSize: pixelSize)
}
let options: [CFString: Any] = [
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceThumbnailMaxPixelSize: maxPixelSize,
kCGImageSourceShouldCacheImmediately: true
]
guard let imageSource = CGImageSourceCreateWithData(data as CFData, nil), let cgImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options as CFDictionary) else {
throw ImageDownloadError(statusCode: nil, decodingFailed: true, isTransient: false)
}
let byteCount = cgImage.bytesPerRow * cgImage.height
#if os(macOS)
return (image: NSImage(cgImage: cgImage, size: .zero), byteCount: byteCount)
#else
return (image: UIImage(cgImage: cgImage), byteCount: byteCount)
#endif
}
}
@@ -11,10 +11,11 @@ import RSCore
import RSWeb
import ActivityLog
/// Downloads each image URL once and keeps one copy on disk, shared by every `ImageDownloader`.
/// Downloads each image URL once and keeps one copy on disk, shared by icons and thumbnails.
///
/// The copy is scaled down to `maxPixelSize`, the largest size anything displays,
/// or kept as is when it’s already smaller. Each `ImageDownloader` makes its own size from it.
/// or kept as is when it’s already smaller. `ImageDownloader` and `ArticleThumbnailFinder`
/// make their own sizes from it.
/// Requests for a URL that’s already being read or downloaded share that work.
@MainActor final class DownloadedImageCache {
@@ -9,7 +9,6 @@
import Foundation
import os
import RSCore
import RSParser
import ActivityLog
extension Notification.Name {
@@ -49,41 +48,18 @@ extension ImageDownloadError: LocalizedError {
}
}
/// Makes images at one size from `DownloadedImageCache`’s copy, and caches them in memory.
/// Makes feed icons, favicons, and avatars from `DownloadedImageCache`’s copy, and caches them in memory.
/// The public API is the same whether the copy is on disk or has to be downloaded.
@MainActor public final class ImageDownloader {
/// Feed icons, favicons, and avatars.
public static let shared = ImageDownloader(configuration: Configuration(maxPixelSize: RSImage.maxIconPixelSize, format: .png, memoryCacheByteLimit: 0, requiresSignificantDimensions: false, usesDownloadLimiter: false))
/// Timeline thumbnails, sized for aspect-fill cropping into a small square.
public static let thumbnails = ImageDownloader(configuration: Configuration(maxPixelSize: thumbnailMaxPixelSize, format: .jpeg(compressionQuality: thumbnailCompressionQuality), memoryCacheByteLimit: thumbnailMemoryCacheByteLimit, requiresSignificantDimensions: true, usesDownloadLimiter: true))
/// Timeline thumbnails, sized to span the timeline’s width.
public static let largeThumbnails = ImageDownloader(configuration: Configuration(maxPixelSize: DownloadedImageCache.maxPixelSize, format: .jpeg(compressionQuality: thumbnailCompressionQuality), memoryCacheByteLimit: thumbnailMemoryCacheByteLimit, requiresSignificantDimensions: true, usesDownloadLimiter: true))
struct Configuration: Sendable {
let maxPixelSize: Int
let format: ScaledImageFormat
let memoryCacheByteLimit: Int // 0 means no limit
let requiresSignificantDimensions: Bool // Checked against the stored image’s pixel dimensions
let usesDownloadLimiter: Bool
}
private static let thumbnailMaxPixelSize = 512
private static let thumbnailCompressionQuality = 0.8
private static let thumbnailMemoryCacheByteLimit = 32 * 1024 * 1024
public static let shared = ImageDownloader()
nonisolated static private let logger = Logger(subsystem: Logger.nnwSubsystem, category: "ImageDownloader")
private let configuration: Configuration
private let imageCache = NSCache<NSString, NSData>() // url: image
private var urlsInProgress = Set<String>()
init(configuration: Configuration) {
self.configuration = configuration
self.imageCache.totalCostLimit = configuration.memoryCacheByteLimit
private init() {
NotificationCenter.default.addObserver(self, selector: #selector(handleAppDidGoToBackground(_:)), name: .appDidGoToBackground, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleLowMemory(_:)), name: .lowMemory, object: nil)
}
@@ -113,10 +89,6 @@ extension ImageDownloadError: LocalizedError {
Self.logger.debug("Skipping recently-failed URL: \(url)")
return nil
}
if configuration.requiresSignificantDimensions && ImageMetadataDatabase.shared.recentlyLackedSignificantDimensions(url: url) {
Self.logger.debug("Skipping thumbnail URL with insignificant dimensions: \(url)")
return nil
}
Task { @MainActor in
await findImage(url, activityOwner: activityOwner, activityKind: activityKind, activityDetail: activityDetail)
@@ -138,13 +110,10 @@ private extension ImageDownloader {
}
do {
let storedData = try await DownloadedImageCache.shared.imageData(for: url, usesDownloadLimiter: configuration.usesDownloadLimiter, activityOwner: activityOwner, activityKind: activityKind, activityDetail: activityDetail)
let data = try await Self.scaledImageData(storedData, configuration: configuration)
let storedData = try await DownloadedImageCache.shared.imageData(for: url, usesDownloadLimiter: false, activityOwner: activityOwner, activityKind: activityKind, activityDetail: activityDetail)
let data = await Self.scaledImageData(storedData, maxPixelSize: RSImage.maxIconPixelSize)
cacheImage(url, data)
} catch {
if error.rejectedPixelSize != nil {
ImageMetadataDatabase.shared.recordInsignificantDimensions(url: url)
}
if !error.isTransient {
NotificationCenter.default.post(name: .imageDownloadDidFail, object: self, userInfo: ["url": url])
}
@@ -156,23 +125,8 @@ private extension ImageDownloader {
imageCache.setObject(image as NSData, forKey: url as NSString, cost: image.count)
NotificationCenter.default.post(name: .imageDidBecomeAvailable, object: self, userInfo: ["url": url])
}
}
// MARK: - Image Processing
extension ImageDownloader {
/// Resizes off the main thread. Throws when `requiresSignificantDimensions` and the image is
/// unreadable, too small, or too narrow.
@concurrent static func scaledImageData(_ data: Data, configuration: Configuration) async throws(ImageDownloadError) -> Data {
if configuration.requiresSignificantDimensions {
guard let pixelSize = RSImage.largestFramePixelSize(data) else {
throw ImageDownloadError(statusCode: nil, decodingFailed: true, isTransient: false)
}
guard SignificantImageFilter.hasSignificantDimensions(width: pixelSize.width, height: pixelSize.height) else {
throw ImageDownloadError(statusCode: nil, decodingFailed: false, isTransient: false, rejectedPixelSize: pixelSize)
}
}
return RSImage.scaledImageData(data, maxPixelSize: configuration.maxPixelSize, format: configuration.format) ?? data
@concurrent static func scaledImageData(_ data: Data, maxPixelSize: Int) async -> Data {
RSImage.scaledImageData(data, maxPixelSize: maxPixelSize) ?? data
}
}
@@ -7,6 +7,9 @@
import Foundation
import Testing
import CoreGraphics
import ImageIO
import UniformTypeIdentifiers
import Articles
@testable import Images
@@ -66,6 +69,23 @@ private typealias ArticleAttachment = Articles.Attachment
#expect(records.first { $0.articleID == "1" }?.thumbnailURL == "https://example.com/uploads/photo.jpg")
#expect(records.first { $0.articleID == "2" }?.thumbnailURL == nil)
}
@Test func thumbnailTooSmallIsRejected() async throws {
let smallImageData = try #require(jpegData(width: 48, height: 48))
await #expect {
_ = try await ArticleThumbnailFinder.decodedImage(smallImageData, maxPixelSize: 512)
} throws: { error in
(error as? ImageDownloadError)?.rejectedPixelSize?.width == 48
}
}
@Test func thumbnailIsDecodedInEXIFOrientation() async throws {
let rotatedImageData = try #require(jpegData(width: 400, height: 200, orientation: .right))
let decodedImage = try await ArticleThumbnailFinder.decodedImage(rotatedImageData, maxPixelSize: 512)
#expect(decodedImage.image.size == CGSize(width: 200, height: 400))
}
}
// MARK: - Helpers
@@ -74,3 +94,20 @@ private func makeArticle(articleID: String = "1", contentHTML: String? = nil, im
let status = ArticleStatus(articleID: articleID, read: false, starred: false, dateArrived: Date())
return Article(accountID: "account", articleID: articleID, feedID: "feed", uniqueID: articleID, title: nil, contentHTML: contentHTML, contentText: nil, markdown: nil, url: "https://example.com/posts/\(articleID)", externalURL: nil, summary: nil, imageURL: imageURL, thumbnailURL: thumbnailURL, datePublished: nil, dateModified: nil, authors: nil, attachments: attachments, status: status)
}
private func jpegData(width: Int, height: Int, orientation: CGImagePropertyOrientation = .up) -> Data? {
guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else {
return nil
}
context.setFillColor(red: 0.2, green: 0.4, blue: 0.6, alpha: 1)
context.fill(CGRect(x: 0, y: 0, width: width, height: height))
guard let cgImage = context.makeImage(), let mutableData = CFDataCreateMutable(nil, 0), let destination = CGImageDestinationCreateWithData(mutableData, UTType.jpeg.identifier as CFString, 1, nil) else {
return nil
}
let properties = [kCGImagePropertyOrientation: orientation.rawValue] as CFDictionary
CGImageDestinationAddImage(destination, cgImage, properties)
guard CGImageDestinationFinalize(destination) else {
return nil
}
return mutableData as Data
}
@@ -1,45 +0,0 @@
//
// ImageDownloaderTests.swift
// ImagesTests
//
// Created by Brent Simmons on 10/25/26.
//
import Foundation
import Testing
import CoreGraphics
import ImageIO
import UniformTypeIdentifiers
@testable import Images
@Suite struct ImageDownloaderTests {
@Test func thumbnailTooSmallIsRejected() async throws {
let configuration = ImageDownloader.Configuration(maxPixelSize: 512, format: .jpeg(compressionQuality: 0.8), memoryCacheByteLimit: 0, requiresSignificantDimensions: true, usesDownloadLimiter: false)
let smallImageData = try #require(pngData(width: 48, height: 48))
await #expect {
_ = try await ImageDownloader.scaledImageData(smallImageData, configuration: configuration)
} throws: { error in
(error as? ImageDownloadError)?.rejectedPixelSize?.width == 48
}
}
}
// MARK: - Helpers
private func pngData(width: Int, height: Int) -> Data? {
guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else {
return nil
}
context.setFillColor(red: 0.2, green: 0.4, blue: 0.6, alpha: 1)
context.fill(CGRect(x: 0, y: 0, width: width, height: height))
guard let cgImage = context.makeImage(), let mutableData = CFDataCreateMutable(nil, 0), let destination = CGImageDestinationCreateWithData(mutableData, UTType.png.identifier as CFString, 1, nil) else {
return nil
}
CGImageDestinationAddImage(destination, cgImage, nil)
guard CGImageDestinationFinalize(destination) else {
return nil
}
return mutableData as Data
}