Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
420 changes: 321 additions & 99 deletions app/src/main/cpp/waifu2x_jni.cpp

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@ import com.kmworks.kmreader.ui.reader.UpscalePrecision
* thumbnails and plain page loads keep the default decoder. Flow:
*
* 1. decode bounds only
* 2. [UpscaleDecision]: not worth it → plain sampled decode of the source
* 3. [EnhancementCache] hit → return the cached enhanced bitmap
* 2. [EnhancementCache] hit → return the cached enhanced bitmap (before the trigger, so a layout
* change cannot hide a page that was already upscaled)
* 3. [UpscaleDecision]: not worth it → plain sampled decode of the source
* 4. miss, but another denoise variant of the page is cached → return that one immediately and
* regenerate the requested variant in the background (a denoise switch must not re-run the book)
* 5. full-res decode → [ImageEnhancer] queue (priority from the request) → write cache
Expand All @@ -50,6 +51,8 @@ class EnhancementDecoder private constructor(
private val context: Context,
private val cache: EnhancementCache,
private val enhancer: ImageEnhancer,
/** The page is cropped into its cell (a split spread half) rather than fitted; see the decision. */
private val cover: Boolean,
) : Decoder {

override suspend fun decode(): DecodeResult? {
Expand All @@ -59,15 +62,36 @@ class EnhancementDecoder private constructor(
return null
}

val cacheKey = EnhancementCache.cacheKey(pageUrl, config.denoise, config.precision)

if (priority == ImageEnhancer.PRIORITY_PRELOAD && enhancer.isSlow) {
// Background precompute cannot keep up on this device. Do not even decode the full
// source, or every settle would still allocate a multi-megapixel bitmap for nothing.
return decodeSampled(srcWidth, srcHeight, PRELOAD_DECODE_TARGET, PRELOAD_DECODE_TARGET)
}

// Cache before the trigger: the trigger asks whether the layout would enlarge this page, and
// the answer changes with the layout (a fitted cell vs the cropped half of a split spread,
// a rotation, a different neighbour slot) while an enhanced page is better than the source
// in all of them. Looking the cache up first is what makes a split/no-split toggle, and
// flipping the threshold back, land on the run that already exists instead of silently
// going back to the blurred source. It is also the guard against re-running a page whose
// enhancement is already on disk.
cache.read(cacheKey)?.let {
info("cache hit (${it.width}x${it.height}): $pageUrl")
return DecodeResult(it.asImage(), false)
}

val (targetWidth, targetHeight) = resolveTargetSize()
val upscale = UpscaleDecision.shouldUpscale(
srcWidth, srcHeight, targetWidth, targetHeight, config,
maxTextureWidth = textureLimits.first,
maxTextureHeight = textureLimits.second,
cover = cover,
)
info(
"decision: src=${srcWidth}x$srcHeight target=${targetWidth}x$targetHeight " +
"mode=${config.mode} threshold=${config.autoTriggerScale} -> upscale=$upscale",
"mode=${config.mode} threshold=${config.autoTriggerScale} cover=$cover -> upscale=$upscale",
)
if (!upscale) {
// Preload requests only warm the disk source cache: decoding the full page here would
Expand All @@ -80,18 +104,6 @@ class EnhancementDecoder private constructor(
}
}

if (priority == ImageEnhancer.PRIORITY_PRELOAD && enhancer.isSlow) {
// Background precompute cannot keep up on this device. Do not even decode the full
// source, or every settle would still allocate a multi-megapixel bitmap for nothing.
return decodeSampled(srcWidth, srcHeight, PRELOAD_DECODE_TARGET, PRELOAD_DECODE_TARGET)
}

val cacheKey = EnhancementCache.cacheKey(pageUrl, config.denoise, config.precision)
cache.read(cacheKey)?.let {
info("cache hit (${it.width}x${it.height}): $pageUrl")
return DecodeResult(it.asImage(), false)
}

// Stale-while-revalidate: the exact denoise variant is missing (the level was just changed, or
// the bundled model was bumped), but another level of the same page is usually still on disk.
// Serve it instead of paying a full native re-run for the whole book on the critical path, and
Expand Down Expand Up @@ -267,9 +279,10 @@ class EnhancementDecoder private constructor(
precision = enumExtra(extras[KEY_PRECISION], UpscalePrecision.Auto),
)
val priority = extras[KEY_PRIORITY] ?: ImageEnhancer.PRIORITY_VISIBLE
Log.i(TAG, "marked for upscaling: $pageUrl (mode=${config.mode}, denoise=${config.denoise}, priority=$priority)")
AppLog.i(APP_TAG, "marked for upscaling (mode=${config.mode}, denoise=${config.denoise}, priority=$priority)")
return EnhancementDecoder(result.source, pageUrl, config, priority, options, context, cache, enhancer)
val cover = extras[KEY_COVER] == true
Log.i(TAG, "marked for upscaling: $pageUrl (mode=${config.mode}, denoise=${config.denoise}, priority=$priority, cover=$cover)")
AppLog.i(APP_TAG, "marked for upscaling (mode=${config.mode}, denoise=${config.denoise}, priority=$priority, cover=$cover)")
return EnhancementDecoder(result.source, pageUrl, config, priority, options, context, cache, enhancer, cover)
}
}

Expand All @@ -290,16 +303,25 @@ class EnhancementDecoder private constructor(
private val KEY_AUTO_SCALE = Extras.Key(default = UpscaleConfig.DEFAULT_AUTO_TRIGGER_SCALE)
private val KEY_PRECISION = Extras.Key(default = UpscalePrecision.Auto.name)
private val KEY_PRIORITY = Extras.Key(default = ImageEnhancer.PRIORITY_VISIBLE)
private val KEY_COVER = Extras.Key(default = false)

private inline fun <reified T : Enum<T>> enumExtra(name: String?, fallback: T): T =
if (name == null) fallback else enumValues<T>().firstOrNull { it.name == name } ?: fallback

/** Marks [builder] as an upscaling page request and records the config for the decoder. */
/**
* Marks [builder] as an upscaling page request and records the config for the decoder.
*
* [cover] tells the decision that the page is painted with `ContentScale.Crop` (one half of
* a split spread), where the cell is half the page's aspect and the page is enlarged until
* it covers the cell: the painted scale is then the larger of the two ratios, not the
* smaller one.
*/
fun applyTo(
builder: ImageRequest.Builder,
config: UpscaleConfig,
pageUrl: String,
priority: Int,
cover: Boolean = false,
) {
builder.extras.set(KEY_ENABLED, true)
builder.extras.set(KEY_PAGE_URL, pageUrl)
Expand All @@ -308,6 +330,7 @@ class EnhancementDecoder private constructor(
builder.extras.set(KEY_AUTO_SCALE, config.autoTriggerScale)
builder.extras.set(KEY_PRECISION, config.precision.name)
builder.extras.set(KEY_PRIORITY, priority)
builder.extras.set(KEY_COVER, cover)
}
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.kmworks.kmreader.core.image.upscale

import com.kmworks.kmreader.ui.reader.UpscaleMode
import kotlin.math.max
import kotlin.math.min

/**
Expand All @@ -14,6 +15,8 @@ object UpscaleDecision {
* @param srcWidth/srcHeight decoded source dimensions
* @param screenWidth/screenHeight display target size in px
* @param maxTextureWidth/maxTextureHeight device texture limits (0 = unknown, skips the guard)
* @param cover true when the page is painted with `ContentScale.Crop` (one half of a split
* spread) instead of fitted inside the cell; see [displayScale]
*/
fun shouldUpscale(
srcWidth: Int,
Expand All @@ -23,18 +26,62 @@ object UpscaleDecision {
config: UpscaleConfig,
maxTextureWidth: Int = 0,
maxTextureHeight: Int = 0,
cover: Boolean = false,
): Boolean {
if (srcWidth <= 0 || srcHeight <= 0 || screenWidth <= 0 || screenHeight <= 0) return false

return when (config.mode) {
UpscaleMode.Off -> false
UpscaleMode.Auto ->
fitsTexture(srcWidth, srcHeight, maxTextureWidth, maxTextureHeight) &&
min(screenWidth.toFloat() / srcWidth, screenHeight.toFloat() / srcHeight) >
fitsEngineBudget(srcWidth, srcHeight) &&
fitsTexture(srcWidth, srcHeight, maxTextureWidth, maxTextureHeight) &&
displayScale(srcWidth, srcHeight, screenWidth, screenHeight, cover) >
config.autoTriggerScale
}
}

/**
* Screen pixels the page gets per source pixel.
*
* A fitted cell keeps the *smaller* of the two ratios: the page is scaled down until both axes
* fit, so the tighter axis decides. A cropped cell keeps the *larger* one: the page is scaled up
* until it covers the cell and the overflow is clipped away.
*
* The cropped case exists because a wide page is displayed as two half cells (ContentScale.Crop
* in `ReaderScreen.PageImage`, matching the iOS cropImageForSplitMode). Each cell is also exactly
* half the spread's aspect, so its width is half of what the page is painted at: passing it
* through min() reported exactly half the painted scale, and a 1760x1300 spread enlarged to
* ~1.8x in a 1600x2364 cell read as 0.9x and was never upscaled — while the same page without
* the split qualified. Splitting a book therefore silently switched upscaling off for every
* spread in it.
*/
private fun displayScale(
srcWidth: Int,
srcHeight: Int,
screenWidth: Int,
screenHeight: Int,
cover: Boolean,
): Float {
val widthRatio = screenWidth.toFloat() / srcWidth
val heightRatio = screenHeight.toFloat() / srcHeight
return if (cover) max(widthRatio, heightRatio) else min(widthRatio, heightRatio)
}

/**
* A page the engine cannot hold is not "not worth it" but "impossible": queueing it would
* allocate the 2x bitmap, be refused natively and count as a failed run towards the enhancer's
* circuit breaker — three webtoon strips in a row and the whole book loses enhancement. The
* budget is the engine's own ([Waifu2xBridge.MAX_OUTPUT_WIDTH] and friends), so the decision
* and the refusal can never disagree.
*/
private fun fitsEngineBudget(srcWidth: Int, srcHeight: Int): Boolean {
val outWidth = srcWidth * Waifu2xBridge.SCALE
val outHeight = srcHeight * Waifu2xBridge.SCALE
return outWidth <= Waifu2xBridge.MAX_OUTPUT_WIDTH &&
outHeight <= Waifu2xBridge.MAX_OUTPUT_HEIGHT &&
outWidth.toLong() * outHeight <= Waifu2xBridge.MAX_OUTPUT_PIXELS
}

/**
* A 2x output that cannot fit a texture would be downscaled on draw, destroying the gain.
* With only Auto left this is a safety net rather than a routine skip: a source small enough
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,21 @@ object Waifu2xBridge {

const val SCALE = 2

/**
* Output budget of the native engine, mirrored by `waifu2x_jni.cpp`
* (`kMaxPageOutput*`) and applied by [UpscaleDecision] before a page is queued.
*
* The width cap is one fused pass: that path holds the source page and its 2x result in VRAM
* at once. The height cap is larger because a tall page (webtoon strip) is processed as stacked
* bands, so what bounds it is the output bitmap instead — hence the pixel budget, which keeps
* the allocation around 80 MB of ARGB. Applying the same numbers in the decision matters: a
* page the engine would refuse must not reach the queue, where its null result counts as a
* failed run and feeds the enhancer's circuit breaker.
*/
const val MAX_OUTPUT_WIDTH = 4096
const val MAX_OUTPUT_HEIGHT = 16384
const val MAX_OUTPUT_PIXELS = 20_000_000L

private const val TAG = "Waifu2xBridge"
private const val MODEL_ASSET_DIR = "upscale-models/waifu2x-upconv7"

Expand Down Expand Up @@ -122,6 +137,20 @@ object Waifu2xBridge {
} else {
input.copy(Bitmap.Config.ARGB_8888, false)
} ?: return@withLock null
// Checked before the output bitmap exists: a refused page used to allocate its 2x bitmap
// first (65 MB for a webtoon strip) and only then be turned down by the engine.
val outWidth = argb.width * SCALE
val outHeight = argb.height * SCALE
if (outWidth > MAX_OUTPUT_WIDTH || outHeight > MAX_OUTPUT_HEIGHT ||
outWidth.toLong() * outHeight > MAX_OUTPUT_PIXELS
) {
Log.w(TAG, "refusing ${argb.width}x${argb.height}: 2x is ${outWidth}x$outHeight, outside the engine budget")
AppLog.w(
EnhancementDecoder.APP_TAG,
"upscale refused, 2x of ${argb.width}x${argb.height} = ${outWidth}x$outHeight is outside the engine budget",
)
return@withLock null
}
val output = try {
Bitmap.createBitmap(argb.width * SCALE, argb.height * SCALE, Bitmap.Config.ARGB_8888)
} catch (e: OutOfMemoryError) {
Expand Down
28 changes: 24 additions & 4 deletions app/src/main/java/com/kmworks/kmreader/ui/reader/ReaderScreen.kt
Original file line number Diff line number Diff line change
Expand Up @@ -1136,6 +1136,7 @@ fun ReaderScreen(
} else {
ImageEnhancer.PRIORITY_ADJACENT
},
cellVisible = index == pagerState.currentPage,
)
}
}
Expand Down Expand Up @@ -1174,6 +1175,7 @@ fun ReaderScreen(
pageUrl = viewModel::pageImageUrl,
firstHalfOnLeft = firstHalfOnLeft,
enhancementPriority = priority,
cellVisible = isActive,
)
}
}
Expand Down Expand Up @@ -1221,6 +1223,7 @@ fun ReaderScreen(
} else {
ImageEnhancer.PRIORITY_ADJACENT
},
cellVisible = index == pagerState.currentPage,
)
}
}
Expand Down Expand Up @@ -1808,6 +1811,9 @@ private fun ViewerPage(
/** waifu2x queue level for this cell's pages (plan §7). A pre-composed neighbour passes
* [ImageEnhancer.PRIORITY_ADJACENT] so the page being read always keeps the queue. */
enhancementPriority: Int = ImageEnhancer.PRIORITY_VISIBLE,
/** True when this cell is the page on screen; null where the host has no such notion (a
* plain composable call site), which keeps the badge rule conservative. */
cellVisible: Boolean? = null,
) {
Box(
modifier = Modifier.fillMaxSize(),
Expand Down Expand Up @@ -1863,6 +1869,7 @@ private fun ViewerPage(
half = if (item.secondHalf) 1 else 0,
firstHalfOnLeft = firstHalfOnLeft,
enhancementPriority = enhancementPriority,
cellVisible = cellVisible,
)

// The end pages own no pages and are rendered by the caller
Expand Down Expand Up @@ -1892,6 +1899,8 @@ private fun PageImage(
alignment: Alignment = Alignment.Center,
/** waifu2x queue level; see [ViewerPage]. */
enhancementPriority: Int = ImageEnhancer.PRIORITY_VISIBLE,
/** True when this cell is the page on screen; null where the host has no such notion. */
cellVisible: Boolean? = null,
) {
// The box is sized from the decoded page once it is available, like iOS (which fits by the loaded
// UIImage size): the server page.width/height is only the pre-load guess, so missing or stale
Expand Down Expand Up @@ -1973,7 +1982,7 @@ private fun PageImage(
} else {
null
}
val request = remember(context, url, crop, upscaleConfig, enhancementReady) {
val request = remember(context, url, crop, upscaleConfig, enhancementReady, half) {
url?.let {
ImageRequest.Builder(context).data(it).apply {
if (crop != BorderCropMode.Disabled) {
Expand All @@ -1991,6 +2000,9 @@ private fun PageImage(
// for it again, so the demotion only ever applies while the page is a
// preload.
priority = enhancementPriority,
// A split half is a crop: the page is enlarged until it covers the cell, so
// the trigger has to compare against the painted scale (see UpscaleDecision).
cover = half != null,
)
// Coil's default compose equality compares memoryCacheKeyExtras but NOT typed
// extras. The ready flag and the upscale config must therefore live here, or a
Expand Down Expand Up @@ -2090,15 +2102,23 @@ private fun PageImage(
}
}
// Mirrors the iOS in-page waifu2x badge: a split page is one enhancement but two
// cells, so only its first cell owns the badge. It pulses while the page is queued or
// running and fades out when the enhanced bitmap is ready.
// cells, so the two halves must not both show a badge (it would read as two runs).
// The badge belongs to the half that is actually on screen instead of the first half
// by definition: turning to the second half while the first has slid away used to
// leave the page waiting with no indicator at all. Where the host cannot say which
// cell is visible, the old rule (first half owns it) stays.
val badgeAlignment = when {
half == null -> Alignment.TopEnd
halfAnchorLeft -> Alignment.TopStart
else -> Alignment.TopEnd
}
val badgeVisible = enhancementProcessing && when {
half == null -> true
cellVisible == null -> half == 0
else -> cellVisible
}
UpscaleProcessingBadge(
visible = enhancementProcessing && (half == null || half == 0),
visible = badgeVisible,
modifier = Modifier
.align(badgeAlignment)
.padding(10.dp),
Expand Down
Loading