feat: half-resolution scunet-color-real-psnr AI denoise with RAISR upscale

This commit is contained in:
zhoubinjia committed 2026-11-10 14:29:10 +08:00
1 parent 833f6ce242
commit 2640bade33
6 files changed
+304 -100

No files matched your search

+1
View File
@@ -25,3 +25,4 @@ __pycache__
/scripts/nafnet_denoise_tflite/out
/scripts/scunet_denoise_tflite/out
/scripts/colorfm_tflite/out
/scripts/ffdnet_denoise_tflite/out
@@ -284,7 +284,10 @@ class PhotoProcessor(
if (source != null && metadata.hasAiDenoisedBase) {
val aiFile = GalleryManager.getAiDenoiseFile(context, photoId)
if (aiFile.exists()) {
val bitmap = BitmapFactory.decodeFile(aiFile.absolutePath)
// Luma noise reduction after AI denoise, as in [processBitmapSource].
val bitmap = loadPhotonDenoiseBase(
context, photoId, aiFile, resolveNoiseReduction(metadata, 0f), 0f, metadata.iso
) ?: BitmapFactory.decodeFile(aiFile.absolutePath)
if (bitmap != null) {
val finalSharpening = metadata.sharpening ?: (if (metadata.isImported) 0f else sharpening)
@@ -690,7 +693,8 @@ class PhotoProcessor(
photoId = photoId,
source = if (bokehBaked) bokehFile else source,
noiseReduction = resolveNoiseReduction(metadata, 0f),
chromaNoiseReduction = resolveChromaNoiseReduction(metadata, 0f),
// With an AI denoised base, color noise was reduced before AI denoise; only luma remains.
chromaNoiseReduction = if (metadata.hasAiDenoisedBase) 0f else resolveChromaNoiseReduction(metadata, 0f),
sensorIso = metadata.iso,
)
return processBitmap(
@@ -776,6 +780,94 @@ class PhotoProcessor(
)
}
/** RAW development of [dngPath] to the base image (before bokeh, LUTs, geometry and frame). */
private suspend fun developDng(
context: Context,
dngPath: String,
metadata: MediaMetadata,
sharpening: Float,
noiseReduction: Float,
chromaNoiseReduction: Float,
onRawMetadata: ((RawMetadata) -> Unit)? = null,
): Bitmap? {
val cropRegion = metadata.cropRegion
return RawDemosaicProcessor.getInstance().process(
context,
dngPath,
resolveRawAspectRatio(metadata),
cropRegion,
metadata.rotation,
metadata.exposureBias ?: 0f,
rawExposureCompensation = metadata.rawExposureCompensation ?: 0f,
rawHighlightsAdjustment = metadata.rawHighlightsAdjustment ?: 0f,
rawShadowsAdjustment = metadata.rawShadowsAdjustment ?: 0f,
rawBlackPointCorrection = metadata.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = metadata.rawWhitePointCorrection ?: 0f,
applyLensShadingCorrection = resolveRawLensShadingCorrectionEnabled(metadata),
mgcTuningSnr = RawMgcTuningSnr.read(metadata.customProperties),
rawBlackLevelMode = metadata.rawBlackLevelMode,
rawCustomBlackLevel = metadata.rawCustomBlackLevel,
rawWhiteLevelMode = metadata.rawWhiteLevelMode,
rawCustomWhiteLevel = metadata.rawCustomWhiteLevel,
sharpeningValue = sharpening,
denoiseValue = noiseReduction,
chromaDenoiseValue = chromaNoiseReduction,
rawDcpId = metadata.rawDcpId,
rawEmbeddedDngProfileId = metadata.rawEmbeddedDngProfileId,
rawNoiseProfileId = resolveRawNoiseProfileId(metadata),
rawHncsProfileId = metadata.rawHncsProfileId,
rawHncsRenderIntent = metadata.rawHncsRenderIntent,
rawHncsFilmCurveMode = metadata.rawHncsFilmCurveMode,
rawRenderingEngine = metadata.rawRenderingEngine,
rawToneMappingParameters = metadata.rawToneMappingParameters,
rawCfaCorrectionMode = metadata.rawCfaCorrectionMode,
rawBlackBorderCrop = metadata.rawBlackBorderCrop,
rawOutputScale = RawOutputScaling.read(metadata.customProperties),
rawOutputUpscaleMode = metadata.rawOutputUpscaleMode,
rawPhysicalOutputSize = RawDigitalZoomResampling.readPhysicalSize(metadata.customProperties),
spectralFilmStock = metadata.spectralFilmStock,
spectralFilmPrint = metadata.spectralFilmPrint,
spectralFilmTuning = SpectralFilmTuning(
cDensityGain = metadata.spectralFilmCDensityGain,
mDensityGain = metadata.spectralFilmMDensityGain,
yDensityGain = metadata.spectralFilmYDensityGain
),
fotufilmDocument = FotufilmDocumentStorage.decode(metadata.fotufilmDocument, "photo metadata"),
onMetadata = onRawMetadata
)
}
/**
* The input of AI denoise for [photoId]: the base image with only color noise reduction
* ([chromaNoiseReduction]) applied, no luma noise reduction and no sharpening. FFDNet is trained
* on white noise and keeps large color blotches as image content, so they are removed first.
* RAW photos are developed with the current RAW settings; other photos use the original image
* ([loadFallback] when the photo has no original file).
*/
suspend fun renderAiDenoiseInput(
context: Context,
photoId: String,
metadata: MediaMetadata,
chromaNoiseReduction: Float,
loadFallback: () -> Bitmap?,
): Bitmap? = withContext(Dispatchers.IO) {
val chroma = DenoiseStrength.clamp(chromaNoiseReduction)
val dngFile = GalleryManager.getDngFile(context, photoId)
if (dngFile.exists()) {
return@withContext developDng(context, dngFile.absolutePath, metadata, 0f, 0f, chroma)
}
val original = GalleryManager.loadOriginalBitmap(context, photoId) ?: loadFallback() ?: return@withContext null
if (chroma <= 0f) return@withContext original
val denoised = try {
lutImageProcessor.applyBitmapDenoise(original, 0f, chroma, metadata.iso)
} catch (e: Throwable) {
original.recycle()
throw e
}
if (denoised !== original) original.recycle()
denoised
}
/**
* @param dngPath dng 文件路径
* @param metadata 照片元数据(包含编辑配置和拍摄信息)
@@ -804,51 +896,9 @@ class PhotoProcessor(
// 1. 应用 LUT
val colorCorrection = resolveColorCorrection(metadata)
val cropRegion = metadata.cropRegion
val bitmap = RawDemosaicProcessor.getInstance().process(
context,
dngPath,
resolveRawAspectRatio(metadata),
cropRegion,
metadata.rotation,
metadata.exposureBias ?: 0f,
rawExposureCompensation = metadata.rawExposureCompensation ?: 0f,
rawHighlightsAdjustment = metadata.rawHighlightsAdjustment ?: 0f,
rawShadowsAdjustment = metadata.rawShadowsAdjustment ?: 0f,
rawBlackPointCorrection = metadata.rawBlackPointCorrection ?: 0f,
rawWhitePointCorrection = metadata.rawWhitePointCorrection ?: 0f,
applyLensShadingCorrection = resolveRawLensShadingCorrectionEnabled(metadata),
mgcTuningSnr = RawMgcTuningSnr.read(metadata.customProperties),
rawBlackLevelMode = metadata.rawBlackLevelMode,
rawCustomBlackLevel = metadata.rawCustomBlackLevel,
rawWhiteLevelMode = metadata.rawWhiteLevelMode,
rawCustomWhiteLevel = metadata.rawCustomWhiteLevel,
sharpeningValue = finalSharpening,
denoiseValue = finalNoiseReduction,
chromaDenoiseValue = finalChromaNoiseReduction,
rawDcpId = metadata.rawDcpId,
rawEmbeddedDngProfileId = metadata.rawEmbeddedDngProfileId,
rawNoiseProfileId = resolveRawNoiseProfileId(metadata),
rawHncsProfileId = metadata.rawHncsProfileId,
rawHncsRenderIntent = metadata.rawHncsRenderIntent,
rawHncsFilmCurveMode = metadata.rawHncsFilmCurveMode,
rawRenderingEngine = metadata.rawRenderingEngine,
rawToneMappingParameters = metadata.rawToneMappingParameters,
rawCfaCorrectionMode = metadata.rawCfaCorrectionMode,
rawBlackBorderCrop = metadata.rawBlackBorderCrop,
rawOutputScale = RawOutputScaling.read(metadata.customProperties),
rawOutputUpscaleMode = metadata.rawOutputUpscaleMode,
rawPhysicalOutputSize = RawDigitalZoomResampling.readPhysicalSize(metadata.customProperties),
spectralFilmStock = metadata.spectralFilmStock,
spectralFilmPrint = metadata.spectralFilmPrint,
spectralFilmTuning = SpectralFilmTuning(
cDensityGain = metadata.spectralFilmCDensityGain,
mDensityGain = metadata.spectralFilmMDensityGain,
yDensityGain = metadata.spectralFilmYDensityGain
),
fotufilmDocument = FotufilmDocumentStorage.decode(metadata.fotufilmDocument, "photo metadata"),
onMetadata = onRawMetadata
val bitmap = developDng(
context, dngPath, metadata, finalSharpening, finalNoiseReduction, finalChromaNoiseReduction, onRawMetadata
)
result = bitmap?.let {
@@ -1,13 +1,18 @@
package com.hinnka.mycamera.ml
/** The AI denoise model: SCUNet color σ=25 (see docs/scunet-tflite.md). */
/** The AI denoise model: SCUNet real_psnr, run at half resolution (see [AiDenoiser]). */
object AiDenoiseModelManager : HfModelInstaller(
tag = "AiDenoiseModelManager",
directory = "ml_models/scunet_color_25",
fileName = "scunet_color_25.tflite",
directory = "ml_models/scunet_color_real_psnr",
fileName = "scunet_color_real_psnr.tflite",
expectedSizeBytes = 47_200_352L,
sha256 = "8d060b8e58d3224ab14ee2af72c737af30cc3dd68790f26aca20f364734dd10c",
path = "/Binjia/scunet-color-25-litert/resolve/9454c201ad03a74bbcbb7005232072f01a3b233c/scunet_color_25.tflite",
legacyDirectories = listOf("ml_models/nafnet_sidd_w32", "ml_models/scunet_color_real_psnr"),
sha256 = "a0def81002254ee05676bd4a4708dea27c4276d264e22bb3f4dc70b44fcd45df",
path = "/Binjia/scunet-color-real-psnr-litert/resolve/647a03f52d333d2bd06126d1182a027ee9cd6624/scunet_color_real_psnr.tflite",
legacyDirectories = listOf(
"ml_models/nafnet_sidd_w32",
"ml_models/scunet_color_25",
"ml_models/ffdnet_color_s20",
"ml_models/ffdnet_color",
),
checkContract = AiDenoiser::checkContract,
)
@@ -2,8 +2,12 @@ package com.hinnka.mycamera.ml
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.os.SystemClock
import com.google.ai.edge.litert.CompiledModel
import com.hinnka.mycamera.raw.MgcRaisrUpscale
import com.hinnka.mycamera.utils.PLog
import org.tensorflow.lite.DataType
import org.tensorflow.lite.Interpreter
@@ -13,30 +17,41 @@ import java.io.FileInputStream
import java.nio.channels.FileChannel
/**
* AI denoise with SCUNet (color σ=25 weights; conversion in docs/scunet-tflite.md).
* AI denoise with SCUNet real_psnr at half resolution (see docs/scunet-tflite.md and
* docs/ai-denoise-half-resolution.md).
*
* Model contract: float32 NHWC [1, 256, 256, 3] RGB in [0, 1] -> same shape. The tile size is
* part of the model (the shifted-window attention mask is built for 256 x 256), so the image
* is always processed in overlapping 256 x 256 tiles.
* 1. The image is box-downsampled 2x (an exact 2x2 average, which also halves the noise; odd
* sizes are padded by repeating the last row / column).
* 2. SCUNet real_psnr (trained on real camera noise) denoises the half-resolution image in
* overlapping 256 x 256 tiles. Model contract: float32 NHWC [1, 256, 256, 3] RGB in [0, 1]
* -> same shape; the tile size is part of the model (shifted-window attention mask).
* 3. MGC V25 RAISR ([MgcRaisrUpscale], resample rate 2) restores full resolution; on real high
* ISO photos it is closer to a full-resolution pass than bicubic or Lanczos-3 and restores
* edge acuity.
*
* [denoise] creates, uses and closes the backend on the calling thread: the LiteRT GPU model
* is bound to the thread that created it.
* About a quarter of the compute of full-resolution SCUNet. [denoise] creates, uses and closes the
* backend on the calling thread: the LiteRT GPU model is bound to the thread that created it.
*/
object AiDenoiser {
private const val TAG = "AiDenoiser"
private const val TILE = 256
private const val CHANNELS = 3
private const val TILE_ELEMENTS = TILE * TILE * CHANNELS
private const val SCALE = 2
/** Minimum overlap between neighbouring tiles; blended with smoothstep weights. */
private const val OVERLAP = 32
/** Share of the progress bar taken by the model; RAISR and the blend take the rest. */
private const val MODEL_PROGRESS = 0.9f
init {
System.loadLibrary("my-native-lib")
}
/**
* Returns the denoised image as a new ARGB_8888 bitmap. Throws on model or backend failure.
* Returns the denoised image as a new ARGB_8888 bitmap in the input's size and color space.
* Throws on model, backend or upscale failure.
*/
fun denoise(
context: Context,
@@ -46,14 +61,95 @@ object AiDenoiser {
val source = if (input.config == Bitmap.Config.ARGB_8888) input else input.copy(Bitmap.Config.ARGB_8888, false)
?: error("Failed to convert ${input.config} bitmap to ARGB_8888")
try {
return createBackend(context).use { backend ->
runTiles(backend, source, onProgress)
val startMs = SystemClock.elapsedRealtime()
val low = boxDownsample(source)
val denoisedLow = try {
createBackend(context).use { backend ->
runTiles(backend, low) { onProgress(it * MODEL_PROGRESS) }
}
} finally {
low.recycle()
}
val modelMs = SystemClock.elapsedRealtime() - startMs
val upscaled = try {
MgcRaisrUpscale().upscale(denoisedLow, SCALE.toFloat())
?: error("RAISR upscale failed for ${denoisedLow.width}x${denoisedLow.height}")
} finally {
denoisedLow.recycle()
}
val result = cropToInput(source, upscaled)
onProgress(1f)
PLog.d(
TAG,
"AI denoise finished: image=${source.width}x${source.height} " +
"model=${modelMs}ms total=${SystemClock.elapsedRealtime() - startMs}ms"
)
return result
} finally {
if (source !== input) source.recycle()
}
}
/**
* Exact 2x2 box average: a bilinear 1/2 draw samples each output pixel at the shared corner
* of its 2x2 source block. Odd sizes are first padded by repeating the last row / column.
*/
private fun boxDownsample(source: Bitmap): Bitmap {
val evenWidth = (source.width + 1) / 2 * 2
val evenHeight = (source.height + 1) / 2 * 2
val even = if (evenWidth == source.width && evenHeight == source.height) {
source
} else {
createLike(source, evenWidth, evenHeight).also { padded ->
val canvas = Canvas(padded)
canvas.drawBitmap(source, 0f, 0f, null)
val w = source.width
val h = source.height
if (evenWidth != w) canvas.drawBitmap(source, Rect(w - 1, 0, w, h), Rect(w, 0, w + 1, h), null)
if (evenHeight != h) canvas.drawBitmap(source, Rect(0, h - 1, w, h), Rect(0, h, w, h + 1), null)
if (evenWidth != w && evenHeight != h) {
canvas.drawBitmap(source, Rect(w - 1, h - 1, w, h), Rect(w, h, w + 1, h + 1), null)
}
}
}
try {
return createLike(source, evenWidth / SCALE, evenHeight / SCALE).also { low ->
Canvas(low).drawBitmap(
even, null, Rect(0, 0, low.width, low.height), Paint(Paint.FILTER_BITMAP_FLAG)
)
}
} finally {
if (even !== source) even.recycle()
}
}
/**
* ARGB_8888 bitmap in [like]'s color space. Every intermediate shares it so that Canvas draws
* never convert colors; the model and RAISR work on the raw pixel values.
*/
private fun createLike(like: Bitmap, width: Int, height: Int): Bitmap {
val colorSpace = like.colorSpace
return if (colorSpace != null) {
Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888, true, colorSpace)
} else {
Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
}
}
/**
* [upscaled] holds raw values in [input]'s color space (every step works on raw pixels):
* relabel it without converting, then crop the padding of odd sizes. Consumes [upscaled].
*/
private fun cropToInput(input: Bitmap, upscaled: Bitmap): Bitmap {
input.colorSpace?.let(upscaled::setColorSpace)
if (upscaled.width == input.width && upscaled.height == input.height) return upscaled
return try {
Bitmap.createBitmap(upscaled, 0, 0, input.width, input.height)
} finally {
upscaled.recycle()
}
}
private fun runTiles(backend: Backend, source: Bitmap, onProgress: (Float) -> Unit): Bitmap {
val width = source.width
val height = source.height
@@ -62,38 +158,23 @@ object AiDenoiser {
val total = xs.size * ys.size
val result = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val tileInput = FloatArray(TILE_ELEMENTS)
var readMs = 0L
var inferenceMs = 0L
var writeMs = 0L
val startMs = SystemClock.elapsedRealtime()
var done = 0
for ((row, y) in ys.withIndex()) {
// Rows above blend over [y, previous tile bottom); the first row has no blend band.
val blendTopEnd = if (row == 0) y else minOf(ys[row - 1] + TILE, height)
for ((col, x) in xs.withIndex()) {
val blendLeftEnd = if (col == 0) x else minOf(xs[col - 1] + TILE, width)
var t = SystemClock.elapsedRealtime()
readTileNative(source, x, y, TILE, tileInput)
readMs += SystemClock.elapsedRealtime() - t
t = SystemClock.elapsedRealtime()
val t = SystemClock.elapsedRealtime()
val tileOutput = backend.run(tileInput)
inferenceMs += SystemClock.elapsedRealtime() - t
t = SystemClock.elapsedRealtime()
writeTileNative(tileOutput, result, x, y, TILE, blendLeftEnd, blendTopEnd)
writeMs += SystemClock.elapsedRealtime() - t
done++
onProgress(done.toFloat() / total)
}
}
PLog.d(
TAG,
"AI denoise finished: backend=${backend.name} image=${width}x$height tiles=$total " +
"total=${SystemClock.elapsedRealtime() - startMs}ms read=${readMs}ms " +
"inference=${inferenceMs}ms write=${writeMs}ms"
)
PLog.d(TAG, "AI denoise model: backend=${backend.name} half=${width}x$height tiles=$total inference=${inferenceMs}ms")
return result
}
@@ -119,7 +200,7 @@ object AiDenoiser {
val cache = MlDelegateCacheFactory.create(
context = context,
tag = TAG,
cacheName = "scunet_color_25_fp16",
cacheName = "scunet_color_real_psnr_fp16",
modelAssetName = file.name,
modelSizeBytes = file.length().toInt(),
modelFingerprint = AiDenoiseModelManager.sha256,
@@ -631,7 +631,7 @@ fun GalleryEditScreen(
val aiDenoiseModelState by remember(context.applicationContext) {
AiDenoiseModelManager.observe(context)
}.collectAsState()
// AI denoise was switched on while its model is missing; applied once the model is installed.
// AI denoise was requested while its model is missing; applied once the model is installed.
var pendingAiDenoise by remember { mutableStateOf(false) }
val showAiDenoiseFailure = {
Toast.makeText(context, context.getString(R.string.ai_denoise_failed), Toast.LENGTH_SHORT).show()
@@ -639,7 +639,7 @@ fun GalleryEditScreen(
val startAiDenoise = {
viewModel.applyAiDenoise(photo = currentEditSourcePhoto) { success ->
if (!success) {
viewModel.setAiDenoiseEnabled(false)
viewModel.revertAiDenoiseEnabled()
showAiDenoiseFailure()
}
}
@@ -1788,7 +1788,7 @@ fun GalleryEditScreen(
} else {
viewModel.resetAiDenoise(photo = currentEditSourcePhoto) { success ->
if (!success) {
viewModel.setAiDenoiseEnabled(true)
viewModel.revertAiDenoiseEnabled()
showAiDenoiseFailure()
}
}
@@ -1848,7 +1848,16 @@ fun GalleryEditScreen(
resetValue = 0f,
onValueChange = { viewModel.setNoiseReduction(it) },
onValueChangeFinished = {
if (isRaw) {
if (viewModel.hasAppliedAiDenoise()) {
// Luma noise reduction runs on the AI output.
if (isRaw) {
viewModel.persistCurrentRawEditMetadata(currentEditSourcePhoto) { success ->
if (success) viewModel.refreshPhotonDenoiseBase(currentEditSourcePhoto)
}
} else {
viewModel.refreshPhotonDenoiseBase(currentEditSourcePhoto)
}
} else if (isRaw) {
viewModel.persistCurrentRawEditMetadata(currentEditSourcePhoto) { success ->
if (success) requestRawPreviewRefresh()
}
@@ -1864,7 +1873,16 @@ fun GalleryEditScreen(
resetValue = 0f,
onValueChange = { viewModel.setChromaNoiseReduction(it) },
onValueChangeFinished = {
if (isRaw) {
if (viewModel.hasAppliedAiDenoise()) {
// Color noise is reduced before AI denoise: run AI denoise again.
if (isRaw) {
viewModel.persistCurrentRawEditMetadata(currentEditSourcePhoto) { success ->
if (success) startAiDenoise()
}
} else {
startAiDenoise()
}
} else if (isRaw) {
viewModel.persistCurrentRawEditMetadata(currentEditSourcePhoto) { success ->
if (success) requestRawPreviewRefresh()
}
@@ -2192,7 +2210,7 @@ fun GalleryEditScreen(
onDownload = { AiDenoiseModelManager.download(context, aiDenoiseModelSource) },
onDismiss = {
pendingAiDenoise = false
viewModel.setAiDenoiseEnabled(false)
viewModel.revertAiDenoiseEnabled()
}
)
}
@@ -2750,3 +2768,4 @@ private fun AiColorMatchRow(
}
}
}
@@ -508,6 +508,9 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
private val _editAiDenoiseEnabled = MutableStateFlow(false)
val editAiDenoiseEnabled = _editAiDenoiseEnabled.asStateFlow()
/** Whether the photo being edited has a saved AI denoised base. */
private var aiDenoiseApplied = false
private val _isAiDenoising = MutableStateFlow(false)
val isAiDenoising = _isAiDenoising.asStateFlow()
@@ -640,6 +643,11 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
_editAiDenoiseEnabled.value = enabled
}
/** Puts the switch back to whether a denoised base is saved (after a cancel or failure). */
fun revertAiDenoiseEnabled() {
_editAiDenoiseEnabled.value = aiDenoiseApplied
}
fun applyAiDenoise(photo: MediaData, onComplete: (Boolean) -> Unit) {
if (_isAiDenoising.value) return
_isAiDenoising.value = true
@@ -648,7 +656,13 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
viewModelScope.launch(Dispatchers.IO) {
val context = getApplication<Application>()
try {
val bitmap = GalleryManager.loadOriginalBitmap(context, photo.id) ?: GalleryManager.loadBitmap(context, photo.uri)
// Color noise is reduced before AI denoise (FFDNet keeps large color blotches);
// luma noise reduction, if any, runs on the AI output (see buildPhotonDenoiseBase).
val inputMetadata = GalleryManager.loadMetadata(context, photo.id)
?: currentMediaMetadata ?: photo.metadata ?: MediaMetadata()
val bitmap = contentRepository.photoProcessor.renderAiDenoiseInput(
context, photo.id, inputMetadata, editChromaNoiseReduction.value
) { GalleryManager.loadBitmap(context, photo.uri) }
if (bitmap == null) {
_isAiDenoising.value = false
withContext(Dispatchers.Main) { onComplete(false) }
@@ -708,6 +722,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
_latestPhoto.value = _latestPhoto.value?.copy(metadata = updatedMetadata)
}
buildPhotonDenoiseBase(context, photo.id, updatedMetadata)
photoRefreshKeys[photo.id] = System.currentTimeMillis()
invalidatePreviewCache(photo.id)
@@ -729,6 +744,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
)
_isAiDenoising.value = false
aiDenoiseApplied = true
withContext(Dispatchers.Main) { onComplete(true) }
} catch (e: Exception) {
PLog.e(TAG, "Failed to apply AI denoise", e)
@@ -765,6 +781,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
GalleryManager.getBokehFile(context, photo.id).takeIf { it.exists() }?.delete()
}
if (!isRawInGallery(photo.id)) buildPhotonDenoiseBase(context, photo.id, updatedMetadata)
GalleryManager.deleteDetailHdrFile(context, photo.id)
if (updatedMetadata.manualHdrEffectEnabled) {
GalleryManager.queueDetailHdrCacheBuild(
@@ -785,6 +802,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
invalidatePreviewCache(photo.id)
photoRefreshKeys[photo.id] = System.currentTimeMillis()
_isAiDenoising.value = false
aiDenoiseApplied = false
withContext(Dispatchers.Main) { onComplete(true) }
} catch (e: Exception) {
PLog.e(TAG, "Failed to reset AI denoise", e)
@@ -1510,7 +1528,8 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
editStraightenDegrees.value =
PostEditGeometry.normalizeStraightenDegrees(m.postStraightenDegrees)
editMirrorHorizontal.value = m.postMirrorHorizontal
_editAiDenoiseEnabled.value = m.hasAiDenoisedBase
aiDenoiseApplied = m.hasAiDenoisedBase
_editAiDenoiseEnabled.value = aiDenoiseApplied
restoreCropEditState(photo, m)
// 加载 LUT 配置
@@ -1525,6 +1544,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
editRotationDegrees.value = 0
editStraightenDegrees.value = 0f
editMirrorHorizontal.value = false
aiDenoiseApplied = false
_editAiDenoiseEnabled.value = false
restoreCropEditState(photo, null)
}
@@ -3502,23 +3522,19 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
* 入口:只在编辑页降噪滑块松手时调用。RAW 照片的降噪在 RAW 开发中烘焙,不走这里。
*/
fun refreshPhotonDenoiseBase(photo: MediaData) {
if (photo.isVideo || isRawInGallery(photo.id)) return
val noiseReduction = editNoiseReduction.value
val chromaNoiseReduction = editChromaNoiseReduction.value
if (photo.isVideo) return
val metadataNow = currentMediaMetadata ?: photo.metadata ?: MediaMetadata()
// RAW denoise is baked in RAW development, except on an AI denoised base (a bitmap).
if (isRawInGallery(photo.id) && !metadataNow.hasAiDenoisedBase) return
photonDenoiseBaseJob?.cancel()
// LAZY 启动保证 photonDenoiseBaseJob 已赋值,被新任务取消的旧任务不会清掉新任务的处理中状态
val job = viewModelScope.launch(Dispatchers.IO, start = CoroutineStart.LAZY) {
val context = getApplication<Application>()
try {
val metadata = currentMediaMetadata ?: photo.metadata ?: MediaMetadata()
val source = photonDenoiseSource(context, photo.id, metadata) ?: return@launch
val built = contentRepository.photoProcessor.updatePhotonDenoiseBase(
context, photo.id, source, noiseReduction, chromaNoiseReduction,
sensorIso = metadata.iso,
onBuild = { _isPhotonDenoising.value = true },
)
val strengths = noiseReduction to chromaNoiseReduction
val strengthsChanged = photonDenoiseEditStrengths.put(photo.id, strengths) != strengths
val (built, strengthsChanged) = buildPhotonDenoiseBase(
context, photo.id, metadata, onBuild = { _isPhotonDenoising.value = true }
) ?: return@launch
if (built || strengthsChanged) {
invalidatePreviewCache(photo.id)
photoRefreshKeys[photo.id] = System.currentTimeMillis()
@@ -3535,6 +3551,34 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
job.start()
}
/**
* Builds the Photon denoise base of [photoId]'s current base image at the edit strengths and
* records those strengths for the edit preview. With an AI denoised base only luma noise
* reduction runs here: color noise was reduced before AI denoise. Returns (built, strengths
* changed), or null when there is no source.
*/
private suspend fun buildPhotonDenoiseBase(
context: Context,
photoId: String,
metadata: MediaMetadata,
onBuild: () -> Unit = {},
): Pair<Boolean, Boolean>? {
val noiseReduction = editNoiseReduction.value
val chromaNoiseReduction = editChromaNoiseReduction.value
val source = photonDenoiseSource(context, photoId, metadata) ?: return null
val built = contentRepository.photoProcessor.updatePhotonDenoiseBase(
context, photoId, source, noiseReduction,
if (metadata.hasAiDenoisedBase) 0f else chromaNoiseReduction,
sensorIso = metadata.iso,
onBuild = onBuild,
)
val strengths = noiseReduction to chromaNoiseReduction
return built to (photonDenoiseEditStrengths.put(photoId, strengths) != strengths)
}
/** True when the photo being edited has an AI denoised base. */
fun hasAppliedAiDenoise(): Boolean = aiDenoiseApplied
fun invalidatePreviewCache(photoId: String) {
val snapshot = previewBitmapCache.snapshot()
snapshot.keys.filter { it.startsWith("${photoId}_") }.forEach {
@@ -3713,13 +3757,17 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
// 非 RAW 照片的降噪只来自降噪基底(编辑页滑块松手时生成,同 RAW 烘焙的降噪),预览只读取、
// 从不跑降噪;没有匹配的基底就不降噪。
val photonDenoiseBase = if (bitmap == null && !showOrigin && !isRawPhoto) {
val photonDenoiseBase = if (
bitmap == null && !showOrigin && (!isRawPhoto || finalMetadata.hasAiDenoisedBase)
) {
// 编辑中按最后一次松手(或进入编辑)时确认的强度读取,拖动中的滑块值不参与。
val strengths = if (useGlobalEdit) photonDenoiseEditStrengths[photo.id] else finalNR to finalCNR
val source = photonDenoiseSource(context, photo.id, finalMetadata)
if (strengths != null && source != null) {
// AI 降噪底图的色噪已在 AI 之前处理,这里只做亮度降噪。
contentRepository.photoProcessor.loadPhotonDenoiseBase(
context, photo.id, source, strengths.first, strengths.second,
context, photo.id, source, strengths.first,
if (finalMetadata.hasAiDenoisedBase) 0f else strengths.second,
sensorIso = finalMetadata.iso,
maxEdge = maxEdge,
)