From e6613115bb61e61aefe65e95c5defe906547df07 Mon Sep 17 00:00:00 2001 From: ZHENG YUNKAI <769440615@> Date: Sun, 29 Nov 2026 03:50:22 +0800 Subject: [PATCH 1/3] fix(reader): reduce long-strip scroll jank in continuous scroll Fixes several compounding bottlenecks on the webtoon/long-strip reading hot path: - ReaderStripTileLayer: drop levelsOfDetailBias (2 -> 0). Long strips render at fitWidth and are never zoomed, so the magnification LOD tiers only force the highest-LOD tile on first display and keep extra magnified bitmaps resident for no benefit. - ReaderStripTileLayer.draw: draw the full image once and let Core Graphics clip to the tile's dirty region instead of allocating a fresh bitmap via CGImage.cropping(to:) on every draw callback. - ReaderImageCache: continuous scroll now keeps a neighbour decode running even while a foreground page is decoding (new allowConcurrentDuringForegroundLoad flag) and preloads with maximumConcurrent 2, so the pipeline no longer stalls during a fast scroll. - ContinuousScrollReader: widen retainsDecodedImage from <= 3 to <= 5 so scrolling back up does not re-decode recently rendered pages. Adds docs/reader-strip-scroll-performance-review-2026-11-29.md with the full audit and remaining lower-priority follow-ups. --- ...ip-scroll-performance-review-2026-11-29.md | 290 ++++++++++++++++++ mreader/ReaderStripTiles.swift | 22 +- mreader/ReaderView.swift | 32 +- 3 files changed, 326 insertions(+), 18 deletions(-) create mode 100644 docs/reader-strip-scroll-performance-review-2026-11-29.md diff --git a/docs/reader-strip-scroll-performance-review-2026-11-29.md b/docs/reader-strip-scroll-performance-review-2026-11-29.md new file mode 100644 index 00000000..f6c5f304 --- /dev/null +++ b/docs/reader-strip-scroll-performance-review-2026-11-29.md @@ -0,0 +1,290 @@ +# 条漫阅读卡顿:代码层性能审核报告 + +日期:2026-11-29 +范围:`mreader/ReaderView.swift`、`mreader/ReaderStripTiles.swift`、`mreader/ReaderMemoryBudget.swift`、`mreader/ReaderPrefetchPolicy.swift`、`mreader/SharedPageTaskPool.swift` +基线:`main` @ `52262a4` + +--- + +## 结论速览 + +| # | 现象 | 主根因 | 证据 | 优先级 | +|---|------|--------|------|--------| +| 1 | 条漫首屏与滚动时主线程掉帧 | `ReaderStripTileLayer` 设 `levelsOfDetailBias = 2`,为"永不缩放"的条漫维护多级放大图,首帧即绘制最高 LOD | `ReaderStripTiles.swift:38-41` | **P0** | +| 2 | 每个 tile 都额外分配一块中间位图 | `draw(in:)` 里对每个 tile 调 `CGImage.cropping(to:)`,滚动时高频分配/释放位图 | `ReaderStripTiles.swift:62-68` | **P0** | +| 3 | 滚动时持续出现加载圈 | 连续滚动预载并发被硬限为 1,且存在前台消费时直接暂停预载,预载追不上滚动 | `ReaderView.swift:3011`、`ReaderView.swift:1150-1157` | **P0** | +| 4 | 回看上一页时白屏/重复解码 | `retainsDecodedImage` 阈值 `<= 3`,已渲染页滚动出 3 页外即被置空 | `ReaderView.swift:3870`、`ReaderView.swift:6265-6277` | P1 | +| 5 | 内存峰值高、NSCache 频繁逐出 | 条漫无几何时预载直接上 8192px,单页位图可达百 MB 级,多条同时持有 | `ReaderView.swift:3008-3009` | P1 | +| 6 | 滚动回调遍历全量页框 | 每次 `contentOffset` KVO 后 `visiblePageIndex` 遍历整个 frames 字典 | `ReaderView.swift:3551-3573` | P2 | + +--- + +## 条漫渲染链路概览 + +条漫(长条图 / webtoon)进入阅读器后,由 `InitialReadingPresetDetector` 判定为 `continuousScroll + fitWidth`(`ReaderView.swift:440-444`),走以下链路: + +``` +ReaderView (body) + └─ ContinuousScrollReader ReaderView.swift:3805 + └─ ScrollView + LazyVStack ReaderView.swift:3839-3840 + └─ LocalImageView ReaderView.swift:5741 + └─ fittedImage(.fitWidth) + └─ ReaderStripTiles (CATiledLayer) ReaderView.swift:6324-6326 +``` + +- 解码:`decodeReaderImage`(`ReaderView.swift:1284`)用 `CGImageSourceCreateThumbnailAtIndex` 一次性解出整张位图。 +- 分片渲染:`ReaderStripTileLayer`(`ReaderStripTiles.swift:33`)继承 `CATiledLayer`,声称"避免一张巨大纹理",但**解码出的 `UIImage` 本身仍是整张位图**,tile 只在合成(compositing)层分片。 +- 页框跟踪:`ScrollViewAccessor` 用 KVO 观察 `contentOffset`(`ReaderView.swift:3637`),`PageFramePreferenceKey` 上报每页 frame,`ReaderVisiblePageDetector` 据此判定当前页。 + +下面逐条展开六个问题。 + +--- + +## 问题 1(P0):`levelsOfDetailBias = 2` 让条漫维护无用多级 LOD + +### 已验证的事实 + +`ReaderStripTiles.swift:36-41`: + +```swift +override init() { + super.init() + tileSize = CGSize(width: 512, height: 512) + levelsOfDetail = 1 + levelsOfDetailBias = 2 +} +``` + +`CATiledLayer` 的语义: + +- `levelsOfDetail` 是**缩小方向的额外层级数**(LOD 从 1 递减),用于在图层被缩小显示时取更小尺寸的缓存 tile 以省内存。 +- `levelsOfDetailBias` 是**放大方向的额外层级数**(LOD 从 1 递增),用于在图层被放大(scale > 1)时预取更高清的 tile。 + +`levelsOfDetailBias = 2` 意味着系统会为这条条漫**额外维护 2 级放大图**(等效 LOD 从 1 升到 4)。带来的后果: + +1. 首帧渲染时,因为 bias 让图层"预放大两档",会**立即请求最高 LOD 的 tile**,主线程在首屏就做一次完整高清重采样,而不是渐进式先糊后清。 +2. 内存里要为同一张条漫同时保留多级 tile 位图,内存峰值翻倍。 +3. 滚动时每进入一个 tile,都要为多级 LOD 重绘。 + +而条漫在 `fitWidth` 模式下**永远铺满屏宽、从不缩放**(`LocalImageView` 的缩放手势在连续滚动模式下被 `ReaderGestureGate.allowsSingleFingerPan` 关闭,`ReaderView.swift:236-238`)。因此放大方向的 LOD 完全用不上。 + +### 建议 + +```swift +tileSize = CGSize(width: 512, height: 512) +levelsOfDetail = 1 +levelsOfDetailBias = 0 // 条漫 fitWidth 从不缩放,去掉放大方向的多级 LOD +``` + +这一行改动是本次修复中**单点收益最大**的一项。 + +--- + +## 问题 2(P0):`draw(in:)` 对每个 tile 分配中间裁剪位图 + +### 已验证的事实 + +`ReaderStripTiles.swift:54-70`: + +```swift +override func draw(in context: CGContext) { + guard let state = snapshotLock.withLock({ snapshot }), ... else { return } + let region = context.boundingBoxOfClipPath.intersection(...) + ... + let pixels = CGRect(...).integral.intersection(...) + guard let tile = state.image.cropping(to: pixels) else { return } + let target = CGRect(...) + context.saveGState() + context.translateBy(x: target.minX, y: target.maxY) + context.scaleBy(x: 1, y: -1) + context.interpolationQuality = .medium + context.draw(tile, in: CGRect(origin: .zero, size: target.size)) + context.restoreGState() +} +``` + +`CGImage.cropping(to:)` 会**分配一块全新的位图**。条漫被切成 512×512 的 tile,一条 8192px 高的条漫约产生 16 个纵向 tile,滚动过程中每次 `draw(in:)` 被回调都至少 `cropping` 一次 —— 这是**高频的位图分配/释放**,在滚动热路径上直接造成内存抖动与掉帧。 + +此外,裁剪出的 `tile` 只是中间产物,最终仍要 `context.draw` 把它缩放到 target。CoreGraphics 本身支持"从大图取子区域直接绘制",无需手动裁剪。 + +### 建议 + +用 `context.draw(_:in:)` 配合 `context.clip`,让 CoreGraphics 自己在绘制时裁到 clip 区域,省掉中间位图: + +```swift +override func draw(in context: CGContext) { + guard let state = snapshotLock.withLock({ snapshot }), ... else { return } + let region = context.boundingBoxOfClipPath.intersection( + CGRect(origin: .zero, size: state.size)) + guard !region.isNull, region.width > 0, region.height > 0 else { return } + let sx = CGFloat(state.image.width) / state.size.width + let sy = CGFloat(state.image.height) / state.size.height + // 整图按 clip 区域直接绘制,避免为每个 tile 额外 cropping 一块位图。 + let fullRect = CGRect(x: 0, y: 0, width: state.size.width, height: state.size.height) + context.saveGState() + context.clip(to: region) + context.translateBy(x: 0, y: state.size.height) + context.scaleBy(x: 1, y: -1) + context.interpolationQuality = .medium + context.draw(state.image, in: fullRect) + context.restoreGState() +} +``` + +--- + +## 问题 3(P0):连续滚动预载并发被压到 1,且前台消费时直接停预载 + +### 已验证的事实 + +`ReaderView.swift:3003-3014`,条漫预载参数: + +```swift +ReaderImageCache.shared.preload( + urls, + maxPixelSize: isContinuous ? ReaderImageCache.fitWidthMaxPixelSize : ..., + maximumConcurrent: isContinuous ? 1 : 2, + ... +) +``` + +`ReaderView.swift:1150-1157`,`drainPreloadQueue` 里的"前台消费暂停": + +```swift +while activePreloadCount < maximumConcurrentPreloads, !preloadQueue.isEmpty { + if hasAnyForegroundConsumers, activePreloadCount >= 1 { + return // 只要有前台页在解码,就不再启动任何预载 + } + ... +} +``` + +同时,解码全局限流只有 2 个许可(`ReaderView.swift:804-805`): + +```swift +private let readerForegroundImageLoadLimiter = ReaderAsyncPermitPool(maximumConcurrentPermits: 3) +private let readerImageDecodeLimiter = ReaderAsyncPermitPool(maximumConcurrentPermits: 2) +``` + +对条漫(连续滚动)这个场景: + +- 用户快速下滑时,一屏要连续经过多页长图;`maximumConcurrent = 1` 意味着同一时刻只有 1 页在预载解码。 +- 而一旦当前页正在解码(`hasAnyForegroundConsumers == true`),`drainPreloadQueue` 会**完全停止**启动新的预载(`activePreloadCount >= 1` 即 return)。 +- 结果:预载永远追不上滚动速度,前端页解完码才轮到下一页 → 用户持续看到加载圈,这是"看条漫卡顿"最直接的可感知来源。 + +对分页阅读(paged)来说"前台消费时停预载"是合理的——避免预载抢占当前页的解码许可。但条漫是**流式阅读**,用户几乎总在滚动,这条保护反而成了瓶颈。 + +### 建议 + +1. 把连续滚动的预载并发放宽: + +```swift +maximumConcurrent: isContinuous ? 2 : 2, +``` + +2. 给条漫预载一个"前台消费豁免",让它在流式阅读时保持预载不中断。在 `ReaderImageCache` 中为连续滚动引入一个 `allowPreloadDuringForegroundLoad` 标志,`drainPreloadQueue` 据此决定是否套用"前台消费暂停"逻辑。保守起见可保留一个上限(例如前台解码进行中最多再并行 1 个预载),在"流畅"与"不抢占当前页"之间取平衡。 + +--- + +## 问题 4(P1):`retainsDecodedImage` 阈值 `<= 3` 导致回看重复解码 + +### 已验证的事实 + +`ReaderView.swift:3870`: + +```swift +retainsDecodedImage: abs(page.index - currentPageIndex) <= 3, +``` + +`ReaderView.swift:6265-6277`,`performImageLoadTask` 开头: + +```swift +guard retainsDecodedImage else { + cancelLiveTranslationForPage() + ... + uiImage = nil + loadedPageURL = nil + isLoadingImage = false + return +} +``` + +`currentPageIndex` 由 `updateCurrentPageFromVisibleFrames` 在滚动时高频更新(`ReaderView.swift:4088`)。当页面滚出当前页 3 页之外,**已经解码并渲染好的页会被立即置空**;滚回去时 `LocalImageView` 要重新走一遍 `loadImage`(即便 `ReaderImageCache` 命中内存缓存,也要重新做 `uiImage` 赋值、OCR/翻译状态重建、`fittedImage` 重算)。 + +`LazyVStack` 本身只在滚动到可视区才实例化视图,二者叠加:往下滚快、往上回看时,上一页会先白屏/加载圈再恢复。这个阈值对分页阅读无感,但对连续滚动是明显的回看抖动源。 + +### 建议 + +把阈值放宽(例如 `<= 5`),或改为"按可视距离"而非"按 index 差值"判定。更稳妥的方案是让 `retainsDecodedImage` 与 `LazyVStack` 的懒加载窗口对齐,保持可见区 ±5 页内都保留解码图。 + +--- + +## 问题 5(P1):条漫无几何时预载直接上 8192px,单页位图可达百 MB + +### 已验证的事实 + +`ReaderView.swift:3008-3009`: + +```swift +maxPixelSize: isContinuous + ? ReaderImageCache.fitWidthMaxPixelSize // = 8192 + : ReaderImageCache.fitScreenMaxPixelSize, // = 4096 +``` + +`ReaderFitWidthDecodePolicy.tiers = [4096, 6144, 8192]`,`maximumPixelSize = 8192`(`ReaderView.swift:244-245`)。 + +`decodeReaderImage` 用 `CGImageSourceCreateThumbnailAtIndex` 一次性解出整张位图(`ReaderView.swift:1313`),`cacheCost` 按 `bytesPerRow × height` 计(`ReaderView.swift:1266-1271`)。8192px 高的一条长图,RGBA 位图可达 **8192 × 8192 × 4 ≈ 256MB 量级**(视实际宽高比)。 + +虽然 `ReaderMemoryBudget` 给 8GB 机型配了 896MB 解码缓存(`ReaderMemoryBudget.swift:25`),但条漫连续滚动时是**同时持有可见页 + 预载页多条**,叠加问题 3 的低并发,容易触顶触发 NSCache 逐出 → 正在显示的页被逐出 → 重新解码 → 卡顿。 + +`ReaderFitWidthDecodePolicy.maxPixelSize`(`ReaderView.swift:248-277`)本身已有"按屏幕宽度 × scale 精算"的逻辑,但预载路径在**无几何信息时直接跳到 8192 兜底**,绕开了精算。 + +### 建议 + +- 预载路径尽量先取 `neighbouringAspectRatio`(已有 `inferredAspectRatios` 机制,`ReaderView.swift:2989-3002`),仅在确实无法推断时才回退 8192。 +- 对条漫,解码上限可以按"最长边"更精确地绑定到 `viewportWidth × displayScale` 的实际需求,避免无谓产出 8192 高位的巨型位图。 + +--- + +## 问题 6(P2):滚动回调每次遍历全量页框 + +### 已验证的事实 + +`ReaderVisiblePageDetector.visiblePageIndex`(`ReaderView.swift:3552-3573`)每次都对 `frames` 字典做 `compactMap` 全量遍历: + +```swift +let candidates = frames.compactMap { index, frame -> ... in + let intersection = frame.intersection(viewport) + ... +} +``` + +`frames` 由 `PageFramePreferenceKey` 累积(`ReaderView.swift:3576-3582`),随滚动不断增长;`onScroll` 的 KVO(`ReaderView.swift:3637`)每次 `contentOffset` 变化都触发(虽后续有 0.04s debounce,`ReaderView.swift:3910`)。页面越多,单次判定越慢。这条相对次要,但与问题 1/2/3 叠加会放大抖动。 + +### 建议 + +- 在 `frames` 里只保留"与 viewport 相交"的候选子集,或维护一个按 `minY` 排序的有序结构做二分定位,避免全量 `compactMap`。 +- 或者:把 `visiblePageIndex` 的调用频率进一步压低(增大 debounce),用"最后一帧已知页 ± 若干页"缩小遍历范围。 + +--- + +## 修复计划与风险 + +| 优先级 | 改动 | 文件 | 风险 | +|--------|------|------|------| +| P0 | `levelsOfDetailBias` 2 → 0 | `ReaderStripTiles.swift` | 极低(仅去掉无用 LOD) | +| P0 | `draw(in:)` 去掉 `cropping` 中间位图 | `ReaderStripTiles.swift` | 低(需回归验证 tile 画面正确性) | +| P0 | 连续滚动预载并发 1 → 2 + 前台消费豁免 | `ReaderView.swift` | 中(需验证不抢占当前页解码、内存峰值可控) | +| P1 | `retainsDecodedImage` 阈值放宽 | `ReaderView.swift` | 低(内存略增) | +| P1 | 条漫预载尺寸精算替代 8192 兜底 | `ReaderView.swift` | 中(依赖几何推断准确性) | +| P2 | 可见页判定遍历优化 | `ReaderView.swift` | 中(逻辑改动较大,建议单独 PR) | + +**验证手段**:修复后建议用 Instruments 的 Core Animation(掉帧检测)+ Allocations(内存峰值/位图分配)在真机条漫场景下对比修复前后;`mreaderTests` 中 `ReaderVisiblePageDetector` 已有单测,可补充 `ReaderStripTileLayer` 的裁剪/绘制正确性测试。 + +--- + +## 附:本轮其他代码质量观察(非性能) + +- `ReaderView.swift` 8553 行单文件过大,`LocalImageView` 含 100+ 个 `@State`,body 依赖链极长;已有提交 `1f2cc48`("Decompose LocalImageView to unblock Swift type checking")证明 SwiftUI 类型检查开销真实存在,建议后续继续拆分。 +- `ReaderStripTileLayer` 用 `nonisolated + @unchecked Sendable + NSLock` 手动加锁(`ReaderStripTiles.swift:33-35`),注释正确但属易错点;`CATiledLayer` 的 `draw(in:)` 本就在后台线程回调且图层本身线程安全,锁可能过度防御,可评估是否可简化。 +- `decodeReaderImage` 使用 `kCGImageSourceShouldCacheImmediately: true`(`ReaderView.swift:1309`)强制立即解码,对后台 `.utility` 优先级的预载任务也会抢占内存,建议预载路径关闭立即缓存。 diff --git a/mreader/ReaderStripTiles.swift b/mreader/ReaderStripTiles.swift index 6a5ec4c1..20f84348 100644 --- a/mreader/ReaderStripTiles.swift +++ b/mreader/ReaderStripTiles.swift @@ -37,7 +37,11 @@ nonisolated final class ReaderStripTileLayer: CATiledLayer, @unchecked Sendable super.init() tileSize = CGSize(width: 512, height: 512) levelsOfDetail = 1 - levelsOfDetailBias = 2 + // Long strips render at fitWidth and are never zoomed (single-finger pan is + // handed to the outer UIScrollView in continuous scroll), so a magnification + // LOD bias is pure overhead: it forces the highest-LOD tile on first display + // and keeps extra magnified tiers resident. Keep a single magnification LOD. + levelsOfDetailBias = 0 } override init(layer: Any) { super.init(layer: layer) } required init?(coder: NSCoder) { super.init(coder: coder) } @@ -55,17 +59,17 @@ nonisolated final class ReaderStripTileLayer: CATiledLayer, @unchecked Sendable guard let state = snapshotLock.withLock({ snapshot }), state.size.width > 0, state.size.height > 0 else { return } let region = context.boundingBoxOfClipPath.intersection(CGRect(origin: .zero, size: state.size)) guard !region.isNull, region.width > 0, region.height > 0 else { return } - let sx = CGFloat(state.image.width) / state.size.width - let sy = CGFloat(state.image.height) / state.size.height - let pixels = CGRect(x: region.minX * sx, y: region.minY * sy, width: region.width * sx, height: region.height * sy) - .integral.intersection(CGRect(x: 0, y: 0, width: state.image.width, height: state.image.height)) - guard let tile = state.image.cropping(to: pixels) else { return } - let target = CGRect(x: pixels.minX / sx, y: pixels.minY / sy, width: pixels.width / sx, height: pixels.height / sy) + // Draw the full image once and let Core Graphics clip to the tile's dirty + // region. A per-tile `CGImage.cropping(to:)` allocates a fresh bitmap on every + // draw callback; a long strip yields many vertical tiles, so that allocation + // churn lands directly on the scroll hot path. + let fullRect = CGRect(origin: .zero, size: state.size) context.saveGState() - context.translateBy(x: target.minX, y: target.maxY) + context.clip(to: region) + context.translateBy(x: 0, y: state.size.height) context.scaleBy(x: 1, y: -1) context.interpolationQuality = .medium - context.draw(tile, in: CGRect(origin: .zero, size: target.size)) + context.draw(state.image, in: fullRect) context.restoreGState() } } diff --git a/mreader/ReaderView.swift b/mreader/ReaderView.swift index 3e0c10ee..b1fd8a9d 100644 --- a/mreader/ReaderView.swift +++ b/mreader/ReaderView.swift @@ -822,6 +822,11 @@ private final class ReaderImageCache { let adaptiveFitWidthSizing: Bool let inferredAspectRatios: [URL: CGFloat] let unknownAdaptiveMaxPixelSize: CGFloat? + /// Continuous scroll is streaming reading: the user is nearly always moving, so + /// pausing neighbour preload while the visible page decodes starves the pipeline + /// and shows loading spinners during a fast scroll. When true, preload keeps one + /// neighbour decode running even while a foreground page is being decoded. + let allowConcurrentDuringForegroundLoad: Bool } private let cache = NSCache() @@ -834,6 +839,8 @@ private final class ReaderImageCache { private var maximumConcurrentPreloads = 2 private var preloadKeys: Set = [] private var desiredPreloadKeys: Set = [] + /// 最近一次 preload 请求是否允许"前台页解码时仍并行预载"(连续滚动专用)。 + private var allowConcurrentPreloadDuringForegroundLoad = false /// A Set cannot represent two LocalImageViews joining the same decode. Track consumers /// individually so one cancelled waiter never drops protection for another active waiter. private var foregroundConsumers: [String: Set] = [:] @@ -1069,7 +1076,8 @@ private final class ReaderImageCache { delay: TimeInterval = 0.25, adaptiveFitWidthSizing: Bool = false, inferredAspectRatios: [URL: CGFloat] = [:], - unknownAdaptiveMaxPixelSize: CGFloat? = nil + unknownAdaptiveMaxPixelSize: CGFloat? = nil, + allowConcurrentDuringForegroundLoad: Bool = false ) { var seenURLs = Set() let uniqueURLs = urls.filter { seenURLs.insert($0).inserted } @@ -1079,7 +1087,8 @@ private final class ReaderImageCache { maximumConcurrent: maximumConcurrent, adaptiveFitWidthSizing: adaptiveFitWidthSizing, inferredAspectRatios: inferredAspectRatios, - unknownAdaptiveMaxPixelSize: unknownAdaptiveMaxPixelSize + unknownAdaptiveMaxPixelSize: unknownAdaptiveMaxPixelSize, + allowConcurrentDuringForegroundLoad: allowConcurrentDuringForegroundLoad ) // Leading-edge debounce: while the timer is pending, page changes replace only the @@ -1140,6 +1149,7 @@ private final class ReaderImageCache { preloadQueue = candidates maximumConcurrentPreloads = max(1, request.maximumConcurrent) + allowConcurrentPreloadDuringForegroundLoad = request.allowConcurrentDuringForegroundLoad let queuedBytes = candidates.reduce(0) { $0 + $1.cost } MReaderLog.reader.debug( "decoded image preload budget=\(self.preloadBudgetBytes, privacy: .public) queuedBytes=\(queuedBytes, privacy: .public) queued=\(candidates.count, privacy: .public)" @@ -1148,11 +1158,14 @@ private final class ReaderImageCache { } private func drainPreloadQueue() { - // Continuous scroll uses one preload at a time. When foreground consumers exist, - // still allow one neighbour decode so the pipeline keeps moving, but never start - // a second preload that could occupy both ImageIO permits and block the visible page. + // Paged readers stop starting new preloads while a foreground page is decoding so + // neighbour work never occupies both ImageIO permits and blocks the visible page. + // Continuous scroll is streaming reading: keeping a neighbour decode alive there + // prevents the pipeline from stalling and showing spinners during a fast scroll. while activePreloadCount < maximumConcurrentPreloads, !preloadQueue.isEmpty { - if hasAnyForegroundConsumers, activePreloadCount >= 1 { + if hasAnyForegroundConsumers, + !allowConcurrentPreloadDuringForegroundLoad, + activePreloadCount >= 1 { return } let candidate = preloadQueue[0] @@ -3008,7 +3021,7 @@ struct ReaderView: View { maxPixelSize: isContinuous ? ReaderImageCache.fitWidthMaxPixelSize : ReaderImageCache.fitScreenMaxPixelSize, - maximumConcurrent: isContinuous ? 1 : 2, + maximumConcurrent: 2, delay: isContinuous ? ReaderPrefetchPolicy.continuousDecodedImagePreloadDelay : ReaderPrefetchPolicy.pagedDecodedImagePreloadDelay, @@ -3016,7 +3029,8 @@ struct ReaderView: View { inferredAspectRatios: inferredAspectRatios, unknownAdaptiveMaxPixelSize: isContinuous ? ReaderFitWidthDecodePolicy.maximumPixelSize - : nil + : nil, + allowConcurrentDuringForegroundLoad: isContinuous ) mangaVisionPreanalysisTask?.cancel() @@ -3867,7 +3881,7 @@ struct ContinuousScrollReader: View { ), imageLoadDelay: 0, showsLoadingIndicator: page.index == currentPageIndex, - retainsDecodedImage: abs(page.index - currentPageIndex) <= 3, + retainsDecodedImage: abs(page.index - currentPageIndex) <= 5, isPageTapGestureEnabled: !areControlsVisible, isSingleFingerPanEnabled: ReaderGestureGate.allowsSingleFingerPan(readingMode: readingMode), onTranslationStateChange: onTranslationStateChange, From e1790dd824b061ed36c8b19941495bbafe2c4971 Mon Sep 17 00:00:00 2001 From: ZHENG YUNKAI <769440615@> Date: Sun, 29 Nov 2026 08:56:35 +0800 Subject: [PATCH 2/3] Keep strip preloads reusable and scroll position current --- ...ip-scroll-performance-review-2026-11-29.md | 16 ++ mreader/ComicManager.swift | 7 +- mreader/ReaderStripTiles.swift | 23 +- mreader/ReaderView.swift | 230 +++++++++--------- mreader/RemotePageLoader.swift | 15 +- mreaderTests/ReaderStateMutationTests.swift | 37 +++ mreaderUITests/mreaderUITests.swift | 5 + 7 files changed, 187 insertions(+), 146 deletions(-) diff --git a/docs/reader-strip-scroll-performance-review-2026-11-29.md b/docs/reader-strip-scroll-performance-review-2026-11-29.md index f6c5f304..ddc117fd 100644 --- a/docs/reader-strip-scroll-performance-review-2026-11-29.md +++ b/docs/reader-strip-scroll-performance-review-2026-11-29.md @@ -6,6 +6,22 @@ --- +## PR #112 复核记录 + +下文保留 DeepSeek Pro 针对 `52262a4` 的原始判断。复核后采用了以下处理。 + +| 原建议 | 代码核对与处理 | +| --- | --- | +| 1、2 · 取消放大层级、改画整图 | 条漫仍挂有双指缩放手势,最高 5×。保留放大层级与原有子图绘制。上调 LOD 会让图层支持相应放大倍率,首帧实际请求哪些 tile 需要运行时观测。子图保留对原图的引用,不能据此推导每次都会复制像素。[Apple · CATiledLayer](https://developer.apple.com/documentation/quartzcore/catiledlayer/levelsofdetailbias) · [Apple · CGImage 裁剪](https://developer.apple.com/documentation/coregraphics/cgimage/cropping%28to%3A%29) | +| 3 · 增加预载并发 | 空闲时最多启动两项预载。有前台请求时最多准入一项邻页预载,已进入 ImageIO 的任务自然完成。候选排队后若已有足够清晰的缓存或在途任务,则复用它。一次预载窗口内每页只解析一次源文件标识,减少主线程反复查询压缩包或 PDF 文件属性。 | +| 4 · 扩大保留窗口 | 保留当前页前后各三页的视图持图范围。放开到五页也会让更多视图具备主动加载图片的资格。超出范围后仍可命中按字节预算管理的图片缓存。 | +| 5 · 降低未知页面的解码上限 | 现有实现已优先采用本页尺寸、其次采用邻页比例,均缺失时保留 8192 上限。修正了缩略图解码后把小图尺寸写回页面几何的问题,预载估算和占位高度使用应用旋转方向后的原始像素尺寸。 | +| 6 · 优化可见页判断 | 页框来自本次布局,字典随布局替换。现在始终保留最新页框,由已有定时回调合并计算,停止滚动时也能取到最后一次布局。回滑进入超长首页的中下段时,结合实际页框和滚动距离识别首页,进度与预载可以及时跟上。筛选可见页使用惰性遍历,滚动期间复用空闲计时器。 | + +**绘制对照。** 在 macOS 的 Core Graphics 位图上下文中,把解码图绘到 512 × 512 像素的区域。预热后交替测两种画法,每轮 96 块,取五轮中位数。1024 × 8192、328 × 8192 两组放大绘制以及双倍显示宽度的一组,耗时差异均低于 1%。1536 × 6144 缩到 1170 像素宽时,裁子图为 3.88 毫秒/块,绘整图并裁切为 5.23 毫秒/块。该实验只覆盖 Mac 上的绘制调用,iPhone 上的合成、掉帧和常驻内存需要单独测量。 + +--- + ## 结论速览 | # | 现象 | 主根因 | 证据 | 优先级 | diff --git a/mreader/ComicManager.swift b/mreader/ComicManager.swift index e0a92e3e..1f66d7ff 100644 --- a/mreader/ComicManager.swift +++ b/mreader/ComicManager.swift @@ -1435,11 +1435,8 @@ class ComicManager { guard accumulated.count + chunk.count <= 1_024 * 1_024 else { throw ProbeStop.prefixLimit } accumulated.append(chunk) CGImageSourceUpdateData(source, accumulated as CFData, false) - if let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any], - let width = properties[kCGImagePropertyPixelWidth] as? CGFloat, - let height = properties[kCGImagePropertyPixelHeight] as? CGFloat, - width > 0, height > 0 { - throw ProbeStop.found(CGSize(width: width, height: height)) + if let size = readerOrientedPixelSize(of: source) { + throw ProbeStop.found(size) } } } catch ProbeStop.found(let size) { return size } diff --git a/mreader/ReaderStripTiles.swift b/mreader/ReaderStripTiles.swift index 20f84348..bbdb6f8b 100644 --- a/mreader/ReaderStripTiles.swift +++ b/mreader/ReaderStripTiles.swift @@ -37,11 +37,8 @@ nonisolated final class ReaderStripTileLayer: CATiledLayer, @unchecked Sendable super.init() tileSize = CGSize(width: 512, height: 512) levelsOfDetail = 1 - // Long strips render at fitWidth and are never zoomed (single-finger pan is - // handed to the outer UIScrollView in continuous scroll), so a magnification - // LOD bias is pure overhead: it forces the highest-LOD tile on first display - // and keeps extra magnified tiers resident. Keep a single magnification LOD. - levelsOfDetailBias = 0 + // Fit-width pages still support pinch zoom. + levelsOfDetailBias = 2 } override init(layer: Any) { super.init(layer: layer) } required init?(coder: NSCoder) { super.init(coder: coder) } @@ -59,17 +56,17 @@ nonisolated final class ReaderStripTileLayer: CATiledLayer, @unchecked Sendable guard let state = snapshotLock.withLock({ snapshot }), state.size.width > 0, state.size.height > 0 else { return } let region = context.boundingBoxOfClipPath.intersection(CGRect(origin: .zero, size: state.size)) guard !region.isNull, region.width > 0, region.height > 0 else { return } - // Draw the full image once and let Core Graphics clip to the tile's dirty - // region. A per-tile `CGImage.cropping(to:)` allocates a fresh bitmap on every - // draw callback; a long strip yields many vertical tiles, so that allocation - // churn lands directly on the scroll hot path. - let fullRect = CGRect(origin: .zero, size: state.size) + let sx = CGFloat(state.image.width) / state.size.width + let sy = CGFloat(state.image.height) / state.size.height + let pixels = CGRect(x: region.minX * sx, y: region.minY * sy, width: region.width * sx, height: region.height * sy) + .integral.intersection(CGRect(x: 0, y: 0, width: state.image.width, height: state.image.height)) + guard let tile = state.image.cropping(to: pixels) else { return } + let target = CGRect(x: pixels.minX / sx, y: pixels.minY / sy, width: pixels.width / sx, height: pixels.height / sy) context.saveGState() - context.clip(to: region) - context.translateBy(x: 0, y: state.size.height) + context.translateBy(x: target.minX, y: target.maxY) context.scaleBy(x: 1, y: -1) context.interpolationQuality = .medium - context.draw(state.image, in: fullRect) + context.draw(tile, in: CGRect(origin: .zero, size: target.size)) context.restoreGState() } } diff --git a/mreader/ReaderView.swift b/mreader/ReaderView.swift index b1fd8a9d..c447e746 100644 --- a/mreader/ReaderView.swift +++ b/mreader/ReaderView.swift @@ -331,6 +331,13 @@ nonisolated enum ReaderContinuousScrollPolicy { return true } + static func isStaleFirstPageFrame(_ frame: CGRect, offsetFromTop: CGFloat, viewportHeight: CGFloat) -> Bool { + // At the end of a tall first strip, the viewport can be many screens from + // the top. Its first row should still start at approximately -offsetFromTop. + let tolerance = max(viewportHeight * 0.42, 140) + return offsetFromTop > tolerance && abs(frame.minY + offsetFromTop) > tolerance + } + /// targetFrame 是目标页在 scroll coordinate-space 中的实时 frame。 /// 只基于当前 contentOffset + 目标页实时 frame 做页内恢复,不再累计 0.. String { + "\(cacheIdentity)#px=\(Int(maxPixelSize))" + } } static let shared = ReaderImageSourceMetadataStore() @@ -810,7 +821,8 @@ private final class ReaderImageCache { private struct PreloadCandidate { let url: URL - let key: String + let source: ReaderImageSourceMetadataStore.Entry + var key: String { source.cacheKey(maxPixelSize: maxPixelSize) } let cost: Int let maxPixelSize: CGFloat } @@ -822,11 +834,6 @@ private final class ReaderImageCache { let adaptiveFitWidthSizing: Bool let inferredAspectRatios: [URL: CGFloat] let unknownAdaptiveMaxPixelSize: CGFloat? - /// Continuous scroll is streaming reading: the user is nearly always moving, so - /// pausing neighbour preload while the visible page decodes starves the pipeline - /// and shows loading spinners during a fast scroll. When true, preload keeps one - /// neighbour decode running even while a foreground page is being decoded. - let allowConcurrentDuringForegroundLoad: Bool } private let cache = NSCache() @@ -839,8 +846,6 @@ private final class ReaderImageCache { private var maximumConcurrentPreloads = 2 private var preloadKeys: Set = [] private var desiredPreloadKeys: Set = [] - /// 最近一次 preload 请求是否允许"前台页解码时仍并行预载"(连续滚动专用)。 - private var allowConcurrentPreloadDuringForegroundLoad = false /// A Set cannot represent two LocalImageViews joining the same decode. Track consumers /// individually so one cancelled waiter never drops protection for another active waiter. private var foregroundConsumers: [String: Set] = [:] @@ -914,8 +919,12 @@ private final class ReaderImageCache { } func cachedImage(for url: URL, maxPixelSize: CGFloat = 4096) -> UIImage? { + cachedImage(for: ReaderImageSourceMetadataStore.shared.entry(for: url), maxPixelSize: maxPixelSize) + } + + private func cachedImage(for source: ReaderImageSourceMetadataStore.Entry, maxPixelSize: CGFloat) -> UIImage? { for tier in resolutionTiers where tier >= maxPixelSize { - if let image = cache.object(forKey: cacheKey(for: url, maxPixelSize: tier) as NSString) { + if let image = cache.object(forKey: source.cacheKey(maxPixelSize: tier) as NSString) { return image } } @@ -923,9 +932,11 @@ private final class ReaderImageCache { } /// 返回 ≥ 请求分辨率且在途的 task 对应 cacheKey(项11:让低分辨率请求 join 高分辨率在途任务)。 - private func inFlightKeySatisfying(url: URL, maxPixelSize: CGFloat) -> String? { - for tier in resolutionTiers where tier >= maxPixelSize { - let key = cacheKey(for: url, maxPixelSize: tier) + private func inFlightKeySatisfying(source: ReaderImageSourceMetadataStore.Entry, maxPixelSize: CGFloat) -> String? { + let requestedKey = source.cacheKey(maxPixelSize: maxPixelSize) + if inFlightLoads[requestedKey]?.canJoin == true { return requestedKey } + for tier in resolutionTiers where tier > maxPixelSize { + let key = source.cacheKey(maxPixelSize: tier) if inFlightLoads[key]?.canJoin == true { return key } @@ -1019,23 +1030,19 @@ private final class ReaderImageCache { func loadImage(for url: URL, maxPixelSize: CGFloat = 4096) async -> UIImage? { // 跨分辨率复用:已有更高分辨率缓存(如 8192)时,低分辨率请求(如 4096)直接复用(项11) - if let cached = cachedImage(for: url, maxPixelSize: maxPixelSize) { + let source = ReaderImageSourceMetadataStore.shared.entry(for: url) + if let cached = cachedImage(for: source, maxPixelSize: maxPixelSize) { return cached } let epoch = generation - let key = cacheKey(for: url, maxPixelSize: maxPixelSize) - if let existingTask = inFlightLoads[key], existingTask.canJoin { - let image = await awaitForegroundTask(existingTask, key: key, epoch: epoch) - return epoch == generation && !Task.isCancelled ? image : nil - } - // 加入更高分辨率的在途解码任务,避免同时双解码 - if let higherKey = inFlightKeySatisfying(url: url, maxPixelSize: maxPixelSize), - let existingTask = inFlightLoads[higherKey], existingTask.canJoin { - let image = await awaitForegroundTask(existingTask, key: higherKey, epoch: epoch) + if let existingKey = inFlightKeySatisfying(source: source, maxPixelSize: maxPixelSize), + let entry = inFlightLoads[existingKey] { + let image = await awaitForegroundTask(entry, key: existingKey, epoch: epoch) return epoch == generation && !Task.isCancelled ? image : nil } - let estimatedCost = estimatedDecodedCost(for: url, maxPixelSize: maxPixelSize) + let key = source.cacheKey(maxPixelSize: maxPixelSize) + let estimatedCost = estimatedDecodedCost(for: url, source: source, maxPixelSize: maxPixelSize) applyDynamicMemoryLimit() let task = Task.detached(priority: .userInitiated) { await loadForegroundReaderImage(from: url, maxPixelSize: maxPixelSize) @@ -1053,7 +1060,6 @@ private final class ReaderImageCache { inFlightLoads[key] = nil preloadKeys.remove(key) } - drainPreloadQueue() } // clearMemoryCache() may have advanced generation and a new Reader may already own @@ -1066,6 +1072,7 @@ private final class ReaderImageCache { // an immediate duplicate decode on the next page update. cache.setObject(image, forKey: key as NSString, cost: image.cacheCost) } + drainPreloadQueue() return Task.isCancelled ? nil : image } @@ -1076,8 +1083,7 @@ private final class ReaderImageCache { delay: TimeInterval = 0.25, adaptiveFitWidthSizing: Bool = false, inferredAspectRatios: [URL: CGFloat] = [:], - unknownAdaptiveMaxPixelSize: CGFloat? = nil, - allowConcurrentDuringForegroundLoad: Bool = false + unknownAdaptiveMaxPixelSize: CGFloat? = nil ) { var seenURLs = Set() let uniqueURLs = urls.filter { seenURLs.insert($0).inserted } @@ -1087,8 +1093,7 @@ private final class ReaderImageCache { maximumConcurrent: maximumConcurrent, adaptiveFitWidthSizing: adaptiveFitWidthSizing, inferredAspectRatios: inferredAspectRatios, - unknownAdaptiveMaxPixelSize: unknownAdaptiveMaxPixelSize, - allowConcurrentDuringForegroundLoad: allowConcurrentDuringForegroundLoad + unknownAdaptiveMaxPixelSize: unknownAdaptiveMaxPixelSize ) // Leading-edge debounce: while the timer is pending, page changes replace only the @@ -1123,54 +1128,46 @@ private final class ReaderImageCache { unknownMaxPixelSize: request.unknownAdaptiveMaxPixelSize ) } - let desiredKeys = Set(request.urls.map { - cacheKey(for: $0, maxPixelSize: requestedSize(for: $0)) + // Resolving an archive/PDF revision can stat its file. Share one snapshot + // across all resolution-tier lookups for this page in the same window. + let candidates = request.urls.map { url in + let source = ReaderImageSourceMetadataStore.shared.entry(for: url) + let size = requestedSize(for: url) + return PreloadCandidate( + url: url, + source: source, + cost: estimatedDecodedCost(for: url, source: source, maxPixelSize: size), + maxPixelSize: size + ) + } + desiredPreloadKeys = Set(candidates.map { candidate in + inFlightKeySatisfying(source: candidate.source, maxPixelSize: candidate.maxPixelSize) ?? candidate.key }) - desiredPreloadKeys = desiredKeys - for staleKey in preloadKeys.subtracting(desiredKeys) { + for staleKey in preloadKeys.subtracting(desiredPreloadKeys) { guard !hasForegroundConsumer(for: staleKey) else { continue } inFlightLoads[staleKey]?.task.cancel() } - let candidates = request.urls - .map { url in - let requestedMaxPixelSize = requestedSize(for: url) - return PreloadCandidate( - url: url, - key: cacheKey(for: url, maxPixelSize: requestedMaxPixelSize), - cost: estimatedDecodedCost(for: url, maxPixelSize: requestedMaxPixelSize), - maxPixelSize: requestedMaxPixelSize - ) - } - .filter { - cachedImage(for: $0.url, maxPixelSize: $0.maxPixelSize) == nil - && inFlightKeySatisfying(url: $0.url, maxPixelSize: $0.maxPixelSize) == nil - } - - preloadQueue = candidates + preloadQueue = candidates.filter { + cachedImage(for: $0.source, maxPixelSize: $0.maxPixelSize) == nil + && inFlightKeySatisfying(source: $0.source, maxPixelSize: $0.maxPixelSize) == nil + } maximumConcurrentPreloads = max(1, request.maximumConcurrent) - allowConcurrentPreloadDuringForegroundLoad = request.allowConcurrentDuringForegroundLoad - let queuedBytes = candidates.reduce(0) { $0 + $1.cost } + let queuedBytes = preloadQueue.reduce(0) { $0 + $1.cost } MReaderLog.reader.debug( - "decoded image preload budget=\(self.preloadBudgetBytes, privacy: .public) queuedBytes=\(queuedBytes, privacy: .public) queued=\(candidates.count, privacy: .public)" + "decoded image preload budget=\(self.preloadBudgetBytes, privacy: .public) queuedBytes=\(queuedBytes, privacy: .public) queued=\(self.preloadQueue.count, privacy: .public)" ) drainPreloadQueue() } private func drainPreloadQueue() { - // Paged readers stop starting new preloads while a foreground page is decoding so - // neighbour work never occupies both ImageIO permits and blocks the visible page. - // Continuous scroll is streaming reading: keeping a neighbour decode alive there - // prevents the pipeline from stalling and showing spinners during a fast scroll. - while activePreloadCount < maximumConcurrentPreloads, !preloadQueue.isEmpty { - if hasAnyForegroundConsumers, - !allowConcurrentPreloadDuringForegroundLoad, - activePreloadCount >= 1 { - return - } + // Two neighbours may start while idle. With foreground demand, leave the + // second ImageIO permit available when admitting new preloads. + let limit = hasAnyForegroundConsumers ? 1 : maximumConcurrentPreloads + while activePreloadCount < limit, !preloadQueue.isEmpty { let candidate = preloadQueue[0] - guard cache.object(forKey: candidate.key as NSString) == nil, - inFlightLoads[candidate.key]?.canJoin != true else { + guard cachedImage(for: candidate.source, maxPixelSize: candidate.maxPixelSize) == nil, + inFlightKeySatisfying(source: candidate.source, maxPixelSize: candidate.maxPixelSize) == nil else { preloadQueue.removeFirst() continue } @@ -1244,12 +1241,9 @@ private final class ReaderImageCache { shared.clearMemoryCache() } - private func cacheKey(for url: URL, maxPixelSize: CGFloat) -> String { - let metadata = ReaderImageSourceMetadataStore.shared.entry(for: url) - return "\(metadata.cacheIdentity)#px=\(Int(maxPixelSize))" - } - - private func estimatedDecodedCost(for url: URL, maxPixelSize: CGFloat) -> Int { + private func estimatedDecodedCost( + for url: URL, source: ReaderImageSourceMetadataStore.Entry, maxPixelSize: CGFloat + ) -> Int { if let pixelSize = PageGeometryStore.shared.size(for: url), pixelSize.width > 0, pixelSize.height > 0 { @@ -1258,21 +1252,14 @@ private final class ReaderImageCache { } if ComicManager.isLocalPageURL(url) { // 估算阶段不能再次解压 CBZ;优先使用已经登记的几何信息,未知时采用保守预算。 - if let pixelSize = PageGeometryStore.shared.size(for: url), - pixelSize.width > 0, - pixelSize.height > 0 { - let scale = min(1, maxPixelSize / max(pixelSize.width, pixelSize.height)) - return max(1, Int(pixelSize.width * scale * pixelSize.height * scale * 4)) - } return max(12 * 1024 * 1024, Int(maxPixelSize * maxPixelSize * 0.55)) } if RemotePageLoader.isRemotePageURL(url) { return Int(maxPixelSize * maxPixelSize * 0.55) } - let fileSize = ReaderImageSourceMetadataStore.shared.entry(for: url).fileSize // Geometry is registered after the first decode. Before then, avoid synchronous // ImageIO property reads on MainActor and use a conservative compressed-size estimate. - return max(fileSize * 6, 12 * 1024 * 1024) + return max(source.fileSize * 6, 12 * 1024 * 1024) } } @@ -1294,7 +1281,7 @@ nonisolated private func loadForegroundReaderImage(from url: URL, maxPixelSize: return Task.isCancelled ? nil : image } -nonisolated private func decodeReaderImage(from url: URL, maxPixelSize: CGFloat) async -> UIImage? { +nonisolated func decodeReaderImage(from url: URL, maxPixelSize: CGFloat) async -> UIImage? { let remoteData: Data? if RemotePageLoader.isRemotePageURL(url) { remoteData = await RemotePageLoader.imageData(forRemotePageURL: url) @@ -1306,7 +1293,7 @@ nonisolated private func decodeReaderImage(from url: URL, maxPixelSize: CGFloat) await readerImageDecodeLimiter.release() return nil } - let image = autoreleasepool { () -> UIImage? in + let decoded = autoreleasepool { () -> (image: UIImage, sourceSize: CGSize?)? in let source: CGImageSource? if ComicManager.isLocalPageURL(url), let data = ComicManager.imageData(forArchivePageURL: url) { source = CGImageSourceCreateWithData(data as CFData, nil) @@ -1324,7 +1311,7 @@ nonisolated private func decodeReaderImage(from url: URL, maxPixelSize: CGFloat) kCGImageSourceThumbnailMaxPixelSize: maxPixelSize ] if let cgImage = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) { - return UIImage(cgImage: cgImage) + return (UIImage(cgImage: cgImage), readerOrientedPixelSize(of: source)) } return nil } @@ -1333,31 +1320,29 @@ nonisolated private func decodeReaderImage(from url: URL, maxPixelSize: CGFloat) return nil } await readerImageDecodeLimiter.release() - if let image { - let pixelSize = CGSize( - width: image.size.width * image.scale, - height: image.size.height * image.scale - ) - await MainActor.run { PageGeometryStore.shared.setSize(pixelSize, for: url) } + // The geometry store also estimates future decode costs. A 640px progress + // thumbnail must not replace the dimensions of an 8192px source strip. + if let sourceSize = decoded?.sourceSize { + await MainActor.run { PageGeometryStore.shared.setSize(sourceSize, for: url) } } - return image + return decoded?.image } nonisolated private func imagePixelSize(from data: Data) -> CGSize? { guard let source = CGImageSourceCreateWithData(data as CFData, [kCGImageSourceShouldCache: false] as CFDictionary) else { return nil } - return imagePixelSize(from: source) + return readerOrientedPixelSize(of: source) } nonisolated private func imagePixelSize(from url: URL) -> CGSize? { guard let source = CGImageSourceCreateWithURL(url as CFURL, [kCGImageSourceShouldCache: false] as CFDictionary) else { return nil } - return imagePixelSize(from: source) + return readerOrientedPixelSize(of: source) } -nonisolated private func imagePixelSize(from source: CGImageSource) -> CGSize? { +nonisolated func readerOrientedPixelSize(of source: CGImageSource) -> CGSize? { guard let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, [kCGImageSourceShouldCache: false] as CFDictionary) as? [CFString: Any], let width = properties[kCGImagePropertyPixelWidth] as? CGFloat, let height = properties[kCGImagePropertyPixelHeight] as? CGFloat, @@ -1365,6 +1350,10 @@ nonisolated private func imagePixelSize(from source: CGImageSource) -> CGSize? { height > 0 else { return nil } + // Match kCGImageSourceCreateThumbnailWithTransform, including mirrored rotations. + if let orientation = properties[kCGImagePropertyOrientation] as? Int, (5...8).contains(orientation) { + return CGSize(width: height, height: width) + } return CGSize(width: width, height: height) } @@ -3029,8 +3018,7 @@ struct ReaderView: View { inferredAspectRatios: inferredAspectRatios, unknownAdaptiveMaxPixelSize: isContinuous ? ReaderFitWidthDecodePolicy.maximumPixelSize - : nil, - allowConcurrentDuringForegroundLoad: isContinuous + : nil ) mangaVisionPreanalysisTask?.cancel() @@ -3566,7 +3554,7 @@ nonisolated enum ReaderVisiblePageDetector { static func visiblePageIndex(frames: [Int: CGRect], viewport: CGRect) -> Int? { guard !frames.isEmpty, viewport.width > 0, viewport.height > 0 else { return nil } let viewportCenterY = viewport.midY - let candidates = frames.compactMap { index, frame -> (index: Int, visibleArea: CGFloat, centerDistance: CGFloat)? in + let candidates = frames.lazy.compactMap { index, frame -> (index: Int, visibleArea: CGFloat, centerDistance: CGFloat)? in let intersection = frame.intersection(viewport) guard !intersection.isNull, intersection.width > 1, intersection.height > 1 else { return nil } return ( @@ -3761,15 +3749,14 @@ private final class ReaderScrollPageMetricsStore { private final class ReaderScrollRuntimeState { var lastStepTime = Date.distantPast var visiblePageUpdateWorkItem: DispatchWorkItem? - var scrollIdleWorkItem: DispatchWorkItem? + var scrollIdleTimer: DispatchSourceTimer? var lastStableContentOffsetY: CGFloat = 0 - var lastPageFrameCommitDate = Date.distantPast func cancelScheduledWork() { visiblePageUpdateWorkItem?.cancel() visiblePageUpdateWorkItem = nil - scrollIdleWorkItem?.cancel() - scrollIdleWorkItem = nil + scrollIdleTimer?.cancel() + scrollIdleTimer = nil } } @@ -3881,7 +3868,7 @@ struct ContinuousScrollReader: View { ), imageLoadDelay: 0, showsLoadingIndicator: page.index == currentPageIndex, - retainsDecodedImage: abs(page.index - currentPageIndex) <= 5, + retainsDecodedImage: abs(page.index - currentPageIndex) <= 3, isPageTapGestureEnabled: !areControlsVisible, isSingleFingerPanEnabled: ReaderGestureGate.allowsSingleFingerPan(readingMode: readingMode), onTranslationStateChange: onTranslationStateChange, @@ -3921,6 +3908,13 @@ struct ContinuousScrollReader: View { } }, onScroll: { + // A fast reverse flick can reach the top between visibility samples. + // Record that the offset came from the user before deceleration ends. + if let scrollView, + scrollView.isDragging || scrollView.isDecelerating, + scrollView.contentOffset.y <= -scrollView.adjustedContentInset.top + 2 { + runtimeState.lastStableContentOffsetY = scrollView.contentOffset.y + } scheduleVisiblePageUpdate(delay: 0.04) scheduleScrollIdleProgressCommit() } @@ -3941,12 +3935,8 @@ struct ContinuousScrollReader: View { scheduleVisiblePageUpdate(delay: 0.02) } .onPreferenceChange(PageFramePreferenceKey.self) { frames in - let now = Date() - guard pageMetrics.frames != frames else { return } - guard !didRestorePosition || now.timeIntervalSince(runtimeState.lastPageFrameCommitDate) >= 0.08 else { - return - } - runtimeState.lastPageFrameCommitDate = now + // Keep the final layout sample even when a visible-page update is + // already scheduled. The store doesn't invalidate the view. pageMetrics.frames = frames scheduleVisiblePageUpdate(delay: 0.04) } @@ -4108,13 +4098,20 @@ struct ContinuousScrollReader: View { } private func scheduleScrollIdleProgressCommit(delay: TimeInterval = 0.45) { - runtimeState.scrollIdleWorkItem?.cancel() - let workItem = DispatchWorkItem { - runtimeState.scrollIdleWorkItem = nil + let deadline = DispatchTime.now() + delay + if let timer = runtimeState.scrollIdleTimer { + timer.schedule(deadline: deadline) + return + } + let timer = DispatchSource.makeTimerSource(queue: .main) + timer.setEventHandler { + runtimeState.scrollIdleTimer?.cancel() + runtimeState.scrollIdleTimer = nil updateCurrentPageFromVisibleFrames(forceNotifyProgress: true) } - runtimeState.scrollIdleWorkItem = workItem - DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: workItem) + runtimeState.scrollIdleTimer = timer + timer.schedule(deadline: deadline) + timer.activate() } private func updateCurrentPageFromViewport( @@ -4159,10 +4156,12 @@ struct ContinuousScrollReader: View { if visiblePageIndex == 0, currentPageIndex > 0, + let firstFrame = frames[0], let scrollView { - let minOffsetY = -scrollView.adjustedContentInset.top - let isStillBelowTop = scrollView.contentOffset.y > minOffsetY + max(visibleSize.height * 0.42, 140) - if isStillBelowTop { + let offsetFromTop = scrollView.contentOffset.y + scrollView.adjustedContentInset.top + if ReaderContinuousScrollPolicy.isStaleFirstPageFrame( + firstFrame, offsetFromTop: offsetFromTop, viewportHeight: visibleSize.height + ) { MReaderLog.reader.debug( "scroll ignored stale page-zero frame current=\(currentPageIndex, privacy: .public) offsetY=\(Int(scrollView.contentOffset.y), privacy: .public) frames=\(frames.count, privacy: .public)" ) @@ -4211,9 +4210,10 @@ struct ContinuousScrollReader: View { private func placeholderHeight(for url: URL, pageIndex: Int, viewport: CGSize) -> CGFloat { let store = PageGeometryStore.shared let fallbackRatio: CGFloat = 1.35 - let ratio = store.aspectRatio(for: url) - ?? store.neighbouringAspectRatio(forPageIndex: pageIndex, among: pages) - ?? fallbackRatio + if let ratio = store.aspectRatio(for: url), viewport.width > 1 { + return max(1, viewport.width * ratio) + } + let ratio = store.neighbouringAspectRatio(forPageIndex: pageIndex, among: pages) ?? fallbackRatio return max(viewport.height, viewport.width * max(ratio, 0.2)) } diff --git a/mreader/RemotePageLoader.swift b/mreader/RemotePageLoader.swift index 807bf630..79bf38f5 100644 --- a/mreader/RemotePageLoader.swift +++ b/mreader/RemotePageLoader.swift @@ -278,19 +278,8 @@ nonisolated enum RemotePageGeometry { let source = CGImageSourceCreateWithData( data as CFData, [kCGImageSourceShouldCache: false] as CFDictionary - ), - let properties = CGImageSourceCopyPropertiesAtIndex( - source, - 0, - [kCGImageSourceShouldCache: false] as CFDictionary - ) as? [CFString: Any], - let width = properties[kCGImagePropertyPixelWidth] as? CGFloat, - let height = properties[kCGImagePropertyPixelHeight] as? CGFloat, - width > 0, - height > 0 else { - return nil - } - return CGSize(width: width, height: height) + ) else { return nil } + return readerOrientedPixelSize(of: source) } } diff --git a/mreaderTests/ReaderStateMutationTests.swift b/mreaderTests/ReaderStateMutationTests.swift index fcad2c81..c6986240 100644 --- a/mreaderTests/ReaderStateMutationTests.swift +++ b/mreaderTests/ReaderStateMutationTests.swift @@ -1,3 +1,5 @@ +import ImageIO +import UniformTypeIdentifiers import XCTest import UIKit @testable import mreader @@ -60,6 +62,16 @@ final class ReaderStateMutationTests: XCTestCase { ) } + func testReturningToLowerPanelsOfFirstStripAcceptsOnlyCurrentFrame() { + let firstPage = CGRect(x: 0, y: -8_000, width: 390, height: 9_000) + XCTAssertFalse(ReaderContinuousScrollPolicy.isStaleFirstPageFrame( + firstPage, offsetFromTop: 8_000, viewportHeight: 844 + )) + XCTAssertTrue(ReaderContinuousScrollPolicy.isStaleFirstPageFrame( + firstPage.offsetBy(dx: 0, dy: 8_000), offsetFromTop: 8_000, viewportHeight: 844 + )) + } + func testContinuousScrollRestoreUsesTargetFrameRelativeOffset() { let y = ReaderContinuousScrollPolicy.alignedContentOffsetY( currentOffsetY: 10_000, @@ -196,6 +208,31 @@ final class ReaderStateMutationTests: XCTestCase { XCTAssertEqual(size.height, 20, accuracy: 0.001) } + func testThumbnailDecodeKeepsOrientedSourceGeometryForStripBudgetAndLayout() async throws { + let format = UIGraphicsImageRendererFormat() + format.scale = 1 + let renderer = UIGraphicsImageRenderer(size: CGSize(width: 800, height: 100), format: format) + let source = try XCTUnwrap(renderer.image { context in + UIColor.white.setFill() + context.fill(CGRect(x: 0, y: 0, width: 800, height: 100)) + }.cgImage) + let data = NSMutableData() + let destination = try XCTUnwrap(CGImageDestinationCreateWithData(data, UTType.jpeg.identifier as CFString, 1, nil)) + CGImageDestinationAddImage(destination, source, [kCGImagePropertyOrientation: 6] as CFDictionary) + XCTAssertTrue(CGImageDestinationFinalize(destination)) + + let expectedSize = CGSize(width: 100, height: 800) + XCTAssertEqual(RemotePageGeometry.pixelSize(from: data as Data), expectedSize) + let url = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString + ".jpg") + try (data as Data).write(to: url) + defer { try? FileManager.default.removeItem(at: url) } + for tier: CGFloat in [320, 80] { + let image = await decodeReaderImage(from: url, maxPixelSize: tier) + XCTAssertEqual(image?.size, CGSize(width: tier / 8, height: tier)) + XCTAssertEqual(PageGeometryStore.shared.size(for: url), expectedSize) + } + } + func testDoublePageGateRequiresEveryPageToLeaveZoom() { var zoomedPages = Set() XCTAssertTrue(ReaderGestureGate.allowsDoublePageTurn(zoomedPageIndexes: zoomedPages)) diff --git a/mreaderUITests/mreaderUITests.swift b/mreaderUITests/mreaderUITests.swift index a9c45382..237d2098 100644 --- a/mreaderUITests/mreaderUITests.swift +++ b/mreaderUITests/mreaderUITests.swift @@ -237,14 +237,19 @@ final class mreaderUITests: XCTestCase { openReader.tap() let reader = element("mreader.reader.root", in: app) XCTAssertTrue(reader.waitForExistence(timeout: timeout)) + let progress = app.staticTexts["mreader.reader.progress"].firstMatch + XCTAssertTrue(progress.waitForExistence(timeout: timeout)) + let startingPage = progress.label let options = XCTMeasureOptions() options.iterationCount = 1 options.invocationOptions = .manuallyStop measure(metrics: [XCTMemoryMetric(application: app), XCTHitchMetric(application: app)], options: options) { // Exercise page boundaries as well as scrolling inside a single strip. for _ in 0..<25 { reader.swipeUp(velocity: .fast) } + XCTAssertNotEqual(progress.label, startingPage, "Forward swipes should cross at least one strip boundary") for _ in 0..<25 { reader.swipeDown(velocity: .fast) } stopMeasuring() + XCTAssertTrue(progress.wait(for: \.label, toEqual: startingPage, timeout: timeout)) XCTAssertTrue(reader.exists) XCTAssertFalse(app.staticTexts["图片加载失败"].exists) } From 5dac48a5e4368488ebf609a4237077665c86a91c Mon Sep 17 00:00:00 2001 From: ZHENG YUNKAI <769440615@> Date: Sun, 29 Nov 2026 09:20:14 +0800 Subject: [PATCH 3/3] Enable magnified strip tiles only during pinch zoom --- ...rip-scroll-performance-review-2026-11-29.md | 2 +- mreader/ReaderStripTiles.swift | 18 ++++++++++++++---- mreader/ReaderView.swift | 2 +- mreaderTests/ReaderStateMutationTests.swift | 15 +++++++++++++++ 4 files changed, 31 insertions(+), 6 deletions(-) diff --git a/docs/reader-strip-scroll-performance-review-2026-11-29.md b/docs/reader-strip-scroll-performance-review-2026-11-29.md index ddc117fd..438ddc9f 100644 --- a/docs/reader-strip-scroll-performance-review-2026-11-29.md +++ b/docs/reader-strip-scroll-performance-review-2026-11-29.md @@ -12,7 +12,7 @@ | 原建议 | 代码核对与处理 | | --- | --- | -| 1、2 · 取消放大层级、改画整图 | 条漫仍挂有双指缩放手势,最高 5×。保留放大层级与原有子图绘制。上调 LOD 会让图层支持相应放大倍率,首帧实际请求哪些 tile 需要运行时观测。子图保留对原图的引用,不能据此推导每次都会复制像素。[Apple · CATiledLayer](https://developer.apple.com/documentation/quartzcore/catiledlayer/levelsofdetailbias) · [Apple · CGImage 裁剪](https://developer.apple.com/documentation/coregraphics/cgimage/cropping%28to%3A%29) | +| 1、2 · 取消放大层级、改画整图 | 条漫仍挂有双指缩放手势,最高 5×。常规宽度下使用基础层级,仅捏合放大时启用额外层级,恢复原大后关闭。保留原有子图绘制。上调 LOD 会让图层支持相应放大倍率,首帧实际请求哪些 tile 需要运行时观测。子图保留对原图的引用,不能据此推导每次都会复制像素。[Apple · CATiledLayer](https://developer.apple.com/documentation/quartzcore/catiledlayer/levelsofdetailbias) · [Apple · CGImage 裁剪](https://developer.apple.com/documentation/coregraphics/cgimage/cropping%28to%3A%29) | | 3 · 增加预载并发 | 空闲时最多启动两项预载。有前台请求时最多准入一项邻页预载,已进入 ImageIO 的任务自然完成。候选排队后若已有足够清晰的缓存或在途任务,则复用它。一次预载窗口内每页只解析一次源文件标识,减少主线程反复查询压缩包或 PDF 文件属性。 | | 4 · 扩大保留窗口 | 保留当前页前后各三页的视图持图范围。放开到五页也会让更多视图具备主动加载图片的资格。超出范围后仍可命中按字节预算管理的图片缓存。 | | 5 · 降低未知页面的解码上限 | 现有实现已优先采用本页尺寸、其次采用邻页比例,均缺失时保留 8192 上限。修正了缩略图解码后把小图尺寸写回页面几何的问题,预载估算和占位高度使用应用旋转方向后的原始像素尺寸。 | diff --git a/mreader/ReaderStripTiles.swift b/mreader/ReaderStripTiles.swift index bbdb6f8b..91b2f4b9 100644 --- a/mreader/ReaderStripTiles.swift +++ b/mreader/ReaderStripTiles.swift @@ -6,14 +6,25 @@ import UIKit /// compositor tiles are allocated for a long strip, avoiding one giant texture. struct ReaderStripTiles: UIViewRepresentable { let image: CGImage + let isZoomed: Bool + func makeUIView(context: Context) -> ReaderStripTileView { ReaderStripTileView() } - func updateUIView(_ view: ReaderStripTileView, context: Context) { view.setImage(image) } + func updateUIView(_ view: ReaderStripTileView, context: Context) { + view.setImage(image, isZoomed: isZoomed) + } } final class ReaderStripTileView: UIView { override class var layerClass: AnyClass { ReaderStripTileLayer.self } private var image: CGImage? - func setImage(_ image: CGImage) { + func setImage(_ image: CGImage, isZoomed: Bool) { + if let tiledLayer = layer as? ReaderStripTileLayer { + let bias = isZoomed ? 2 : 0 + if tiledLayer.levelsOfDetailBias != bias { + tiledLayer.levelsOfDetailBias = bias + tiledLayer.setNeedsDisplay() + } + } guard self.image !== image else { return } self.image = image updateSnapshot() @@ -37,8 +48,7 @@ nonisolated final class ReaderStripTileLayer: CATiledLayer, @unchecked Sendable super.init() tileSize = CGSize(width: 512, height: 512) levelsOfDetail = 1 - // Fit-width pages still support pinch zoom. - levelsOfDetailBias = 2 + levelsOfDetailBias = 0 } override init(layer: Any) { super.init(layer: layer) } required init?(coder: NSCoder) { super.init(coder: coder) } diff --git a/mreader/ReaderView.swift b/mreader/ReaderView.swift index c447e746..10edcdf6 100644 --- a/mreader/ReaderView.swift +++ b/mreader/ReaderView.swift @@ -6336,7 +6336,7 @@ struct LocalImageView: View { .scaledToFit() case .fitWidth: if let cgImage = image.cgImage, image.size.height / max(image.size.width, 1) >= 3 { - ReaderStripTiles(image: cgImage) + ReaderStripTiles(image: cgImage, isZoomed: isZoomedIn) .frame(width: max(viewportWidth, 1), height: displayHeight(for: image)) } else { Image(uiImage: image) diff --git a/mreaderTests/ReaderStateMutationTests.swift b/mreaderTests/ReaderStateMutationTests.swift index c6986240..fb7b53c1 100644 --- a/mreaderTests/ReaderStateMutationTests.swift +++ b/mreaderTests/ReaderStateMutationTests.swift @@ -23,6 +23,21 @@ final class ReaderStateMutationTests: XCTestCase { XCTAssertTrue(ReaderGestureGate.allowsSingleFingerPan(readingMode: .guidedPanel)) } + func testStripOffersMagnifiedTilesOnlyWhileZoomed() throws { + let size = CGSize(width: 30, height: 120) + let strip = ReaderStripTileView(frame: CGRect(origin: .zero, size: size)) + let layer = try XCTUnwrap(strip.layer as? ReaderStripTileLayer) + let image = try XCTUnwrap(UIGraphicsImageRenderer(size: size).image { context in + context.fill(CGRect(origin: .zero, size: size)) + }.cgImage) + strip.setImage(image, isZoomed: false) + XCTAssertEqual(layer.levelsOfDetailBias, 0) + strip.setImage(image, isZoomed: true) + XCTAssertEqual(layer.levelsOfDetailBias, 2) + strip.setImage(image, isZoomed: false) + XCTAssertEqual(layer.levelsOfDetailBias, 0) + } + func testContinuousScrollRejectsImplausibleRestoreJump() { XCTAssertFalse( ReaderContinuousScrollPolicy.shouldAcceptVisiblePage(