feat: photon denoise base caching and preview optimizations

This commit is contained in:
zhoubinjia committed 2026-11-02 19:00:37 +08:00
1 parent 3fb230d051
commit 1c7a519fd8
14 files changed
+193 -204

No files matched your search

@@ -138,8 +138,6 @@ object GalleryManager {
private const val VIDEO_FILE = "video.mp4"
private const val DNG_FILE = "original.dng"
private const val AI_DENOISE_FILE = "ai_denoise.jpg"
private const val PHOTON_DENOISE_FILE = "photon_denoise.jpg"
private const val PHOTON_DENOISE_KEY_FILE = "photon_denoise.key"
private const val THUMBNAIL_FILE = "thumbnail.jpg"
private const val BOKEH_FILE = "bokeh.jpg"
private const val DETAIL_HDR_FILE = "detail_hdr.jpg"
@@ -602,12 +600,9 @@ object GalleryManager {
return File(getPhotoDir(context, photoId), AI_DENOISE_FILE)
}
fun getPhotonDenoiseFile(context: Context, photoId: String): File {
return File(getPhotoDir(context, photoId), PHOTON_DENOISE_FILE)
}
fun getPhotonDenoiseKeyFile(context: Context, photoId: String): File {
return File(getPhotoDir(context, photoId), PHOTON_DENOISE_KEY_FILE)
/** Photon 降噪基底条目所在目录(PhotoProcessor.updatePhotonDenoiseBase 管理条目)。 */
fun getPhotonDenoiseDir(context: Context, photoId: String): File {
return getPhotoDir(context, photoId)
}
fun getDepthFile(context: Context, photoId: String): File {
@@ -1422,8 +1417,6 @@ object GalleryManager {
metadata
}
val bitmapSharpeningValue = if (isRawPhoto) 0f else sharpeningValue
val bitmapNoiseReductionValue = if (isRawPhoto) 0f else noiseReductionValue
val bitmapChromaNoiseReductionValue = if (isRawPhoto) 0f else chromaNoiseReductionValue
var gainmapResult: GainmapResult? = preparedGainmapResult
if (preparedGainmapResult == null) {
val gainmapElapsed = measureTimeMillis {
@@ -1452,8 +1445,6 @@ object GalleryManager {
input = exportInputBitmap,
metadata = bitmapPostMetadata,
sharpening = bitmapSharpeningValue,
noiseReduction = bitmapNoiseReductionValue,
chromaNoiseReduction = bitmapChromaNoiseReductionValue,
useComputationalAperture = !bitmapComputationalBokehApplied,
)
} ?: photoProcessor.process(
@@ -2136,8 +2127,6 @@ object GalleryManager {
processedSdr = checkNotNull(bokehBitmap),
metadata = metadata,
sharpening = sharpeningValue,
noiseReduction = noiseReductionValue,
chromaNoiseReduction = chromaNoiseReductionValue,
)
val preparedGainmapResult = preparedUltraHdrSource?.let { source ->
gainmapProducer.build(source, HdrGainmapStrength.coerce(metadata.hdrEffectStrength))
@@ -5302,8 +5291,6 @@ object GalleryManager {
input = originalBitmap,
metadata = thumbnailMetadata,
sharpening = 0f,
noiseReduction = 0f,
chromaNoiseReduction = 0f,
useComputationalAperture = false
)
@@ -46,10 +46,13 @@ import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import java.io.File
import java.util.zip.CRC32
import kotlin.math.abs
import kotlin.math.roundToInt
private const val RAW_HDR_REFERENCE_ASPECT_TOLERANCE = 0.0015f
private const val PHOTON_DENOISE_PREFIX = "photon_denoise_"
private const val PHOTON_DENOISE_MAX_ENTRIES = 2
/**
* 照片处理器
@@ -66,6 +69,7 @@ class PhotoProcessor(
) {
private val colorCorrectionPipelineResolver = ColorCorrectionPipelineResolver(lutManager)
private val photonDenoiseBaseMutex = Mutex()
private val photonDenoiseSourceCrc = java.util.concurrent.ConcurrentHashMap<String, Long>()
data class HdrFrameOutput(
val bitmap: Bitmap,
@@ -90,8 +94,11 @@ class PhotoProcessor(
/**
* 非 RAW 照片的降噪基底(对应 RAW 烘焙进 original.jpg 的降噪):对 [source] 全分辨率跑一次
* Photon 降噪并持久化为 photon_denoise.jpg,预览/导出直接加载基底并以 0 强度走 LUT。
* key 绑定源文件与强度;两个强度都为 0 时删除基底。返回基底文件是否发生了变化。
* Photon 降噪并持久化,预览/导出直接加载基底并以 0 强度走 LUT。
*
* 每个条目以源文件内容与强度为 key,最多保留 [PHOTON_DENOISE_MAX_ENTRIES] 个、按最近使用淘汰:
* 已保存的强度与编辑中(未保存)的强度各占一个条目,互不覆盖。真正开始重建前调用 [onBuild]。
* 两个强度都为 0 时无需基底,返回 false;否则返回是否新建了条目。
*/
suspend fun updatePhotonDenoiseBase(
context: Context,
@@ -99,23 +106,16 @@ class PhotoProcessor(
source: File,
noiseReduction: Float,
chromaNoiseReduction: Float,
onBuild: () -> Unit = {},
): Boolean {
val luma = DenoiseStrength.clamp(noiseReduction)
val chroma = DenoiseStrength.clamp(chromaNoiseReduction)
val baseFile = GalleryManager.getPhotonDenoiseFile(context, photoId)
val keyFile = GalleryManager.getPhotonDenoiseKeyFile(context, photoId)
val key = "${photonDenoiseSourceKey(source)}|$luma|$chroma"
if (luma <= 0f && chroma <= 0f) return false
val dir = GalleryManager.getPhotonDenoiseDir(context, photoId)
photonDenoiseBaseMutex.withLock {
if (luma <= 0f && chroma <= 0f) {
return withContext(Dispatchers.IO) {
val existed = baseFile.exists()
keyFile.delete()
baseFile.delete()
existed
}
}
if (withContext(Dispatchers.IO) { readPhotonDenoiseKey(baseFile, keyFile) == key }) return false
withContext(Dispatchers.IO) { keyFile.delete() }
val key = withContext(Dispatchers.IO) { photonDenoiseKey(source, luma, chroma) }
if (withContext(Dispatchers.IO) { findPhotonDenoiseEntry(dir, key)?.touch() } != null) return false
onBuild()
val input = GalleryManager.loadBitmap(context, Uri.fromFile(source)) ?: return false
val denoised = try {
lutImageProcessor.applyBitmapDenoise(input, luma, chroma)
@@ -126,14 +126,19 @@ class PhotoProcessor(
input.recycle()
if (denoised === input) return false
val written = withContext(Dispatchers.IO) {
val tmp = File(baseFile.parentFile, "${baseFile.name}.tmp")
val entry = PhotonDenoiseEntry.of(dir, key)
val tmp = File(dir, "${entry.image.name}.tmp")
try {
tmp.outputStream().use { denoised.compress(Bitmap.CompressFormat.JPEG, 95, it) }
} finally {
denoised.recycle()
}
(tmp.renameTo(baseFile) || run { tmp.delete(); false }).also {
if (it) keyFile.writeText(key)
entry.keyFile.delete()
(tmp.renameTo(entry.image) || run { tmp.delete(); false }).also {
if (it) {
entry.keyFile.writeText(key)
prunePhotonDenoiseEntries(dir)
}
}
}
if (written) PLog.d("PhotoProcessor", "Photon denoise base rebuilt: $photoId luma=$luma chroma=$chroma")
@@ -142,46 +147,80 @@ class PhotoProcessor(
}
/**
* 加载 [source] 的降噪基底,不可用时返回 null(调用方按原路径处理)。给出强度时缺失或过期的
* 基底会先重建;强度为 null(编辑预览)只读取已有基底,和 RAW 一样在松手时才由
* [updatePhotonDenoiseBase] 按新强度生成,拖动过程中保持旧结果。
* 加载 [source] 在给定强度下的降噪基底,没有时返回 null(不降噪)。只读取:基底只在
* 编辑页降噪滑块松手时由 [updatePhotonDenoiseBase] 生成,其他入口从不跑降噪。
*/
suspend fun loadPhotonDenoiseBase(
context: Context,
photoId: String,
source: File,
noiseReduction: Float?,
chromaNoiseReduction: Float?,
noiseReduction: Float,
chromaNoiseReduction: Float,
maxEdge: Int? = null,
): Bitmap? {
if (noiseReduction != null && chromaNoiseReduction != null) {
if (DenoiseStrength.clamp(noiseReduction) <= 0f && DenoiseStrength.clamp(chromaNoiseReduction) <= 0f) {
return null
}
updatePhotonDenoiseBase(context, photoId, source, noiseReduction, chromaNoiseReduction)
}
val baseFile = GalleryManager.getPhotonDenoiseFile(context, photoId)
val keyFile = GalleryManager.getPhotonDenoiseKeyFile(context, photoId)
val luma = DenoiseStrength.clamp(noiseReduction)
val chroma = DenoiseStrength.clamp(chromaNoiseReduction)
if (luma <= 0f && chroma <= 0f) return null
val dir = GalleryManager.getPhotonDenoiseDir(context, photoId)
return photonDenoiseBaseMutex.withLock {
withContext(Dispatchers.IO) {
val key = readPhotonDenoiseKey(baseFile, keyFile) ?: return@withContext null
val expected = if (noiseReduction != null && chromaNoiseReduction != null) {
"${photonDenoiseSourceKey(source)}|${DenoiseStrength.clamp(noiseReduction)}|" +
"${DenoiseStrength.clamp(chromaNoiseReduction)}"
} else {
null
findPhotonDenoiseEntry(dir, photonDenoiseKey(source, luma, chroma))?.touch()?.let {
GalleryManager.loadBitmap(context, Uri.fromFile(it.image), maxEdge)
}
val matches = expected?.let { key == it } ?: key.startsWith("${photonDenoiseSourceKey(source)}|")
if (matches) GalleryManager.loadBitmap(context, Uri.fromFile(baseFile), maxEdge) else null
}
}
}
private fun photonDenoiseSourceKey(source: File) =
"v1|${source.name}|${source.lastModified()}|${source.length()}"
private class PhotonDenoiseEntry(val image: File, val keyFile: File) {
fun touch() = apply { image.setLastModified(System.currentTimeMillis()) }
private fun readPhotonDenoiseKey(baseFile: File, keyFile: File): String? =
if (baseFile.exists() && keyFile.exists()) keyFile.readText() else null
companion object {
fun of(dir: File, key: String): PhotonDenoiseEntry {
val stem = "$PHOTON_DENOISE_PREFIX${Integer.toHexString(key.hashCode())}"
return PhotonDenoiseEntry(File(dir, "$stem.jpg"), File(dir, "$stem.key"))
}
}
}
private fun findPhotonDenoiseEntry(dir: File, key: String): PhotonDenoiseEntry? =
PhotonDenoiseEntry.of(dir, key).takeIf {
it.image.exists() && it.keyFile.exists() && it.keyFile.readText() == key
}
private fun prunePhotonDenoiseEntries(dir: File) {
val files = dir.listFiles { file -> file.name.startsWith(PHOTON_DENOISE_PREFIX) } ?: return
val stems = files.groupBy { it.nameWithoutExtension }
stems.entries
.sortedByDescending { (_, group) -> group.firstOrNull { it.extension == "jpg" }?.lastModified() ?: 0L }
.drop(PHOTON_DENOISE_MAX_ENTRIES)
.forEach { (_, group) -> group.forEach(File::delete) }
// 旧版单槽基底
File(dir, "photon_denoise.jpg").delete()
File(dir, "photon_denoise.key").delete()
}
/**
* 源文件以内容 CRC32 标识(按路径、修改时间、大小缓存):bokeh.jpg 等派生文件会被原样重写,
* 只看修改时间会让内容未变的基底失效。
*/
private fun photonDenoiseKey(source: File, luma: Float, chroma: Float): String {
val stamp = "${source.absolutePath}|${source.lastModified()}|${source.length()}"
val crc = photonDenoiseSourceCrc[stamp] ?: CRC32().run {
source.inputStream().use { input ->
val buffer = ByteArray(1 shl 16)
while (true) {
val read = input.read(buffer)
if (read < 0) break
update(buffer, 0, read)
}
}
value
}.also {
if (photonDenoiseSourceCrc.size > 64) photonDenoiseSourceCrc.clear()
photonDenoiseSourceCrc[stamp] = it
}
return "v2|${source.name}|${source.length()}|$crc|$luma|$chroma"
}
private fun resolveNoiseReduction(metadata: MediaMetadata, fallback: Float): Float {
return metadata.noiseReduction ?: (if (metadata.isImported) 0f else fallback)
@@ -244,10 +283,7 @@ class PhotoProcessor(
val bitmap = BitmapFactory.decodeFile(aiFile.absolutePath)
if (bitmap != null) {
val finalSharpening = metadata.sharpening ?: (if (metadata.isImported) 0f else sharpening)
val finalNoiseReduction = metadata.noiseReduction ?: (if (metadata.isImported) 0f else noiseReduction)
val finalChromaNoiseReduction =
metadata.chromaNoiseReduction ?: (if (metadata.isImported) 0f else chromaNoiseReduction)
var lutLuminanceGainBitmap: Bitmap? = null
val sdrBitmap = processBitmap(
context = context,
@@ -255,8 +291,6 @@ class PhotoProcessor(
input = bitmap,
metadata = metadata,
sharpening = finalSharpening,
noiseReduction = finalNoiseReduction,
chromaNoiseReduction = finalChromaNoiseReduction,
useComputationalAperture = true,
applyFrameWatermark = false,
onLutLuminanceGainMap = { lutLuminanceGainBitmap = it },
@@ -289,24 +323,18 @@ class PhotoProcessor(
}
val fallbackBitmap = if (metadata.hasAiDenoisedBase) {
val aiFile = GalleryManager.getAiDenoiseFile(context, photoId)
if (aiFile.exists()) BitmapFactory.decodeFile(aiFile.absolutePath) else null
val fallbackFile = if (metadata.hasAiDenoisedBase) {
GalleryManager.getAiDenoiseFile(context, photoId).takeIf { it.exists() }
} else {
GalleryManager.loadOriginalBitmap(context, photoId)
GalleryManager.getOriginalImageFile(context, photoId)
}
if (fallbackBitmap != null) {
val sdrBitmap = processBitmap(
context = context,
photoId = photoId,
input = fallbackBitmap,
metadata = metadata,
sharpening = sharpening,
noiseReduction = noiseReduction,
chromaNoiseReduction = chromaNoiseReduction,
useComputationalAperture = true,
applyFrameWatermark = false
)
val sdrBitmap = fallbackFile?.let { file ->
processBitmapSource(context, photoId, file, metadata, sharpening, applyFrameWatermark = false) {
if (metadata.hasAiDenoisedBase) BitmapFactory.decodeFile(file.absolutePath)
else GalleryManager.loadOriginalBitmap(context, photoId)
}
}
if (sdrBitmap != null) {
return GainmapSourceSet(
sdrBase = sdrBitmap,
hdrReference = null,
@@ -330,8 +358,6 @@ class PhotoProcessor(
processedSdr: Bitmap,
metadata: MediaMetadata,
sharpening: Float = 0f,
noiseReduction: Float = 0f,
chromaNoiseReduction: Float = 0f,
): GainmapSourceSet? {
if (!metadata.manualHdrEffectEnabled) return null
@@ -341,8 +367,6 @@ class PhotoProcessor(
input = processedSdr,
metadata = metadata,
sharpening = sharpening,
noiseReduction = noiseReduction,
chromaNoiseReduction = chromaNoiseReduction,
useComputationalAperture = false,
applyFrameWatermark = false,
)
@@ -616,8 +640,9 @@ class PhotoProcessor(
if (metadata.hasAiDenoisedBase) {
val aiFile = GalleryManager.getAiDenoiseFile(context, photoId)
if (aiFile.exists()) {
return processBitmapSource(context, photoId, aiFile, metadata, sharpening, noiseReduction,
chromaNoiseReduction) { GalleryManager.loadBitmap(context, Uri.fromFile(aiFile)) }
return processBitmapSource(context, photoId, aiFile, metadata, sharpening) {
GalleryManager.loadBitmap(context, Uri.fromFile(aiFile))
}
}
return null
}
@@ -635,15 +660,17 @@ class PhotoProcessor(
)
} else {
val originalFile = GalleryManager.getOriginalImageFile(context, photoId) ?: return null
return processBitmapSource(context, photoId, originalFile, metadata, sharpening, noiseReduction,
chromaNoiseReduction) { GalleryManager.loadOriginalBitmap(context, photoId) }
return processBitmapSource(context, photoId, originalFile, metadata, sharpening) {
GalleryManager.loadOriginalBitmap(context, photoId)
}
}
}
/**
* [processBitmap] of a non-RAW source file through its Photon denoise base when one applies.
* With a computational aperture the bokeh pass would persist the denoised pixels into
* bokeh.jpg, which is denoised again on its own base, so that case keeps the in-LUT denoise.
* [processBitmap] of a non-RAW source file (original or AI base): the Photon denoise base of the
* saved strengths replaces it when one exists, otherwise the photo renders without denoise.
* With a computational aperture the preview's base is that of bokeh.jpg, so the export uses it
* as is instead of re-running the bokeh pass on the undenoised source.
*/
private suspend fun processBitmapSource(
context: Context,
@@ -651,30 +678,27 @@ class PhotoProcessor(
source: File,
metadata: MediaMetadata,
sharpening: Float,
noiseReduction: Float,
chromaNoiseReduction: Float,
applyFrameWatermark: Boolean = true,
loadSource: () -> Bitmap?,
): Bitmap? {
val base = if ((metadata.computationalAperture ?: 0f) <= 0f) {
loadPhotonDenoiseBase(
context = context,
photoId = photoId,
source = source,
noiseReduction = resolveNoiseReduction(metadata, noiseReduction),
chromaNoiseReduction = resolveChromaNoiseReduction(metadata, chromaNoiseReduction),
)
} else {
null
}
if (base != null) {
return processBitmap(
context, photoId, base,
metadata.copy(noiseReduction = 0f, chromaNoiseReduction = 0f),
sharpening, 0f, 0f, true
)
}
val bitmap = loadSource() ?: return null
return processBitmap(context, photoId, bitmap, metadata, sharpening, noiseReduction, chromaNoiseReduction, true)
val bokehFile = GalleryManager.getBokehFile(context, photoId)
val bokehBaked = (metadata.computationalAperture ?: 0f) > 0f && bokehFile.exists()
val base = loadPhotonDenoiseBase(
context = context,
photoId = photoId,
source = if (bokehBaked) bokehFile else source,
noiseReduction = resolveNoiseReduction(metadata, 0f),
chromaNoiseReduction = resolveChromaNoiseReduction(metadata, 0f),
)
return processBitmap(
context = context,
photoId = photoId,
input = base ?: loadSource() ?: return null,
metadata = metadata,
sharpening = sharpening,
useComputationalAperture = base == null || !bokehBaked,
applyFrameWatermark = applyFrameWatermark,
)
}
private suspend fun processDngForUltraHdr(
@@ -859,9 +883,10 @@ class PhotoProcessor(
* @param input 输入 Bitmap
* @param metadata 照片元数据(包含编辑配置和拍摄信息)
* @param sharpening 锐化强度
* @param noiseReduction 降噪强度
* @param chromaNoiseReduction 减少杂色强度
* @return 处理后的 Bitmap
*
* 不做降噪:非 RAW 照片的降噪只来自滑块松手时生成的降噪基底([loadPhotonDenoiseBase]),
* 由调用方作为 [input] 传入;RAW 的降噪在 RAW 开发中完成。
*/
suspend fun processBitmap(
context: Context,
@@ -869,17 +894,12 @@ class PhotoProcessor(
input: Bitmap,
metadata: MediaMetadata,
sharpening: Float = 0f,
noiseReduction: Float = 0f,
chromaNoiseReduction: Float = 0f,
useComputationalAperture: Boolean = false,
applyFrameWatermark: Boolean = true,
onLutLuminanceGainMap: ((Bitmap?) -> Unit)? = null,
lutLuminanceGainDownsample: Int = 1,
): Bitmap = withContext(Dispatchers.IO) {
var result = input
val finalNoiseReduction = metadata.noiseReduction ?: (if (metadata.isImported) 0f else noiseReduction)
val finalChromaNoiseReduction =
metadata.chromaNoiseReduction ?: (if (metadata.isImported) 0f else chromaNoiseReduction)
val colorCorrection = resolveColorCorrection(metadata)
@@ -900,8 +920,8 @@ class PhotoProcessor(
result,
colorCorrection.baselineLayer,
colorCorrection.creativeLayer,
finalNoiseReduction,
finalChromaNoiseReduction,
noiseReductionValue = 0f,
chromaNoiseReductionValue = 0f,
luminanceGainDownsample = lutLuminanceGainDownsample,
)
result = lutStackResult.bitmap
@@ -911,8 +931,8 @@ class PhotoProcessor(
result,
colorCorrection.baselineLayer,
colorCorrection.creativeLayer,
finalNoiseReduction,
finalChromaNoiseReduction
noiseReductionValue = 0f,
chromaNoiseReductionValue = 0f
)
}
@@ -87,7 +87,7 @@ class LutImageProcessor(context: Context? = null) {
private var bitmapDenoisePassthroughProgram = 0
private var computeCapabilitiesChecked = false
private var computeCapabilitiesSupported = false
private val bitmapPhotonDenoiser = PhotonMultiScaleDenoiser(PhotonMultiScaleDenoiser.UI_SLICE_PIXELS)
private val bitmapPhotonDenoiser = PhotonMultiScaleDenoiser()
private var lutSharpenProgram = 0
private var lutLuminanceGainProgram = 0
@@ -30,8 +30,6 @@ class PhotoTransformation(
input,
metadata.copy(sharpening = 0f, noiseReduction = 0f, chromaNoiseReduction = 0f),
0f,
0f,
0f
)
}
}
@@ -35,9 +35,7 @@ internal object PhotonDenoiseShaders {
layout(local_size_x = $LOCAL, local_size_y = $LOCAL) in;
// Work-group origin of a sliced dispatch (PhotonMultiScaleDenoiser.sliceBudgetPixels).
uniform ivec2 uGroupOffset;
ivec2 groupId() { return ivec2(gl_WorkGroupID.xy) + uGroupOffset; }
ivec2 groupId() { return ivec2(gl_WorkGroupID.xy); }
ivec2 globalId() { return groupId() * $LOCAL + ivec2(gl_LocalInvocationID.xy); }
const float LUMA_TAPS[7] = float[7](
@@ -18,14 +18,8 @@ import java.nio.ByteOrder
* the LSC gains restored. Only the Gaussian levels and two adjacent denoised levels are held
* (§10.2). A [PassSink] receives every pass output for parity checks; it adds a parity dispatch
* per level that emits the fused pass's band, base, noise and pilot tiles.
*
* [sliceBudgetPixels] > 0 splits every Analyze/Synthesize dispatch into row slices of about that
* many pixels with a GPU checkpoint after each. Callers that hand over a whole image in one call
* (the Bitmap edit path) need it: a full-image dispatch chain cannot be preempted on many GPUs,
* so the compositor starves (black, frozen screen) or the driver watchdog resets the GPU. The
* tiled RAW pipelines already checkpoint between tiles and keep whole-level dispatches.
*/
internal class PhotonMultiScaleDenoiser(private val sliceBudgetPixels: Int = 0) {
internal class PhotonMultiScaleDenoiser {
/** Receives pass outputs while their textures are alive (debug parity, §12.4). */
fun interface PassSink {
fun onPass(name: String, textureId: Int, width: Int, height: Int, float32: Boolean)
@@ -377,33 +371,15 @@ internal class PhotonMultiScaleDenoiser(private val sliceBudgetPixels: Int = 0)
/**
* One whole-level dispatch. As in GlesMgcRawSpatialStacker, the UI renderer is kept responsive
* by the low-priority EGL context and a flush + yield between levels, never by fence waits
* inside a level: those drain the GPU and leave it idle until this thread wakes up. With a
* [sliceBudgetPixels] the level is dispatched in row slices instead, each followed by a
* checkpoint, trading that idle time for bounded GPU occupancy.
* inside a level: those drain the GPU and leave it idle until this thread wakes up.
*/
private fun dispatch(program: Int, size: IntArray) {
val groupsX = GlesComputeWorkGroup.imageGroupCount(size[0])
val groupsY = GlesComputeWorkGroup.imageGroupCount(size[1])
val offset = location(program, "uGroupOffset")
val sliceRows = if (sliceBudgetPixels > 0) {
maxOf(1, sliceBudgetPixels / (groupsX * GlesComputeWorkGroup.IMAGE_TILE_SIZE * GlesComputeWorkGroup.IMAGE_TILE_SIZE))
} else {
groupsY
}
var row = 0
while (row < groupsY) {
val rows = minOf(sliceRows, groupsY - row)
GLES31.glUniform2i(offset, 0, row)
GLES31.glDispatchCompute(groupsX, rows, 1)
row += rows
if (row < groupsY) GlesGpuScheduler.waitForGpuCheckpoint(TAG, "slice")
}
GLES31.glUniform2i(offset, 0, 0)
GLES31.glDispatchCompute(GlesComputeWorkGroup.imageGroupCount(size[0]),
GlesComputeWorkGroup.imageGroupCount(size[1]), 1)
GLES31.glMemoryBarrier(
GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT or
GLES31.GL_FRAMEBUFFER_BARRIER_BIT,
)
if (sliceRows < groupsY) GlesGpuScheduler.waitForGpuCheckpoint(TAG, "level")
}
private fun bindImage(unit: Int, texture: Int, format: Int) {
@@ -424,16 +400,12 @@ internal class PhotonMultiScaleDenoiser(private val sliceBudgetPixels: Int = 0)
private fun uniform3f(program: Int, name: String, v: FloatArray) =
GLES31.glUniform3f(location(program, name), v[0], v[1], v[2])
companion object {
/** [sliceBudgetPixels] for whole-image callers: about 1 MP of work per GPU submission. */
const val UI_SLICE_PIXELS = 1 shl 20
private const val TAG = "PhotonMultiScaleDenoiser"
private const val UNIT_INPUT = 0
private const val UNIT_LSC = 1
private const val UNIT_FINE = 2
private const val UNIT_NOISY_COARSE = 3
private const val UNIT_DENOISED_COARSE = 4
private const val UNIT_MERGE = 5
private companion object {
const val UNIT_INPUT = 0
const val UNIT_LSC = 1
const val UNIT_FINE = 2
const val UNIT_NOISY_COARSE = 3
const val UNIT_DENOISED_COARSE = 4
const val UNIT_MERGE = 5
}
}
@@ -300,6 +300,7 @@ fun GalleryEditScreen(
val editComputationalAperture by viewModel.editComputationalAperture.collectAsState()
val editBokehStyle by viewModel.editBokehStyle.collectAsState()
val isBokehProcessing by viewModel.isBokehProcessing.collectAsState()
val isPhotonDenoising by viewModel.isPhotonDenoising.collectAsState()
val editFocusX by viewModel.editFocusPointX.collectAsState()
val editFocusY by viewModel.editFocusPointY.collectAsState()
@@ -546,12 +547,6 @@ fun GalleryEditScreen(
cropPreviewBitmap = null
}
// 进入编辑或底图(虚化 / AI 降噪)变化后,按当前强度补齐 JPG 降噪基底;无变化时不会刷新。
LaunchedEffect(editSourcePhoto?.id, refreshKey, isRaw) {
val photo = editSourcePhoto ?: return@LaunchedEffect
if (!isRaw) viewModel.refreshPhotonDenoiseBase(photo)
}
LaunchedEffect(editSourcePhoto?.id, refreshKey) {
val photo = editSourcePhoto ?: return@LaunchedEffect
if (photo.isVideo) return@LaunchedEffect
@@ -1135,9 +1130,9 @@ fun GalleryEditScreen(
)
}
// 虚化处理中提示
// 虚化 / 降噪基底处理中提示
AnimatedVisibility(
visible = isBokehProcessing && !currentPhoto.isVideo,
visible = (isBokehProcessing || isPhotonDenoising) && !currentPhoto.isVideo,
enter = fadeIn(),
exit = fadeOut(),
modifier = Modifier
@@ -1157,7 +1152,10 @@ fun GalleryEditScreen(
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = stringResource(R.string.gallery_bokeh_processing),
text = stringResource(
if (isBokehProcessing) R.string.gallery_bokeh_processing
else R.string.gallery_denoise_processing
),
color = Color.White,
fontSize = 13.sp
)
@@ -421,6 +421,9 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
private set
var editNoiseReduction = MutableStateFlow(0f)
private set
/** 编辑中 JPG 降噪基底对应的强度:进入编辑时取已保存的值,之后由松手确认,编辑预览只读取这一组。 */
private val photonDenoiseEditStrengths = java.util.concurrent.ConcurrentHashMap<String, Pair<Float, Float>>()
var editChromaNoiseReduction = MutableStateFlow(0f)
private set
var editRawExposureCompensation = MutableStateFlow(0f)
@@ -1500,6 +1503,9 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
editSharpening.value = m.sharpening ?: 0f
editNoiseReduction.value = DenoiseStrength.clamp(m.noiseReduction)
editChromaNoiseReduction.value = DenoiseStrength.clamp(m.chromaNoiseReduction)
photo?.let {
photonDenoiseEditStrengths[it.id] = editNoiseReduction.value to editChromaNoiseReduction.value
}
editRawExposureCompensation.value = m.rawExposureCompensation ?: 0f
editRawAutoExposure.value = RawAdaptiveExposureMode.resolve(
usePhotonHdr = m.rawToneMappingParameters.usePhotonHdr,
@@ -3392,25 +3398,31 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
}
private var photonDenoiseBaseJob: Job? = null
private val _isPhotonDenoising = MutableStateFlow(false)
val isPhotonDenoising = _isPhotonDenoising.asStateFlow()
/**
* 按当前编辑强度生成非 RAW 照片的降噪基底(松手、进入编辑、源图变化时调用),
* 基底有变化时刷新预览。RAW 照片的降噪在 RAW 开发中烘焙,不走这里。
* 按当前编辑强度生成非 RAW 照片的降噪基底,并确认为编辑预览使用的强度。JPG 降噪的唯一
* 入口:只在编辑页降噪滑块松手时调用。RAW 照片的降噪在 RAW 开发中烘焙,不走这里。
*/
fun refreshPhotonDenoiseBase(photo: MediaData) {
if (photo.isVideo || isRawInGallery(photo.id)) return
val noiseReduction = editNoiseReduction.value
val chromaNoiseReduction = editChromaNoiseReduction.value
photonDenoiseBaseJob?.cancel()
photonDenoiseBaseJob = viewModelScope.launch(Dispatchers.IO) {
// 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 changed = contentRepository.photoProcessor.updatePhotonDenoiseBase(
val built = contentRepository.photoProcessor.updatePhotonDenoiseBase(
context, photo.id, source, noiseReduction, chromaNoiseReduction,
onBuild = { _isPhotonDenoising.value = true },
)
if (changed) {
val strengths = noiseReduction to chromaNoiseReduction
val strengthsChanged = photonDenoiseEditStrengths.put(photo.id, strengths) != strengths
if (built || strengthsChanged) {
invalidatePreviewCache(photo.id)
photoRefreshKeys[photo.id] = System.currentTimeMillis()
}
@@ -3418,8 +3430,12 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
throw e
} catch (e: Exception) {
PLog.e(TAG, "Failed to build Photon denoise base", e)
} finally {
if (photonDenoiseBaseJob === coroutineContext[Job]) _isPhotonDenoising.value = false
}
}
photonDenoiseBaseJob = job
job.start()
}
fun invalidatePreviewCache(photoId: String) {
@@ -3597,18 +3613,19 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
val canLoadExternalUri = isSystemExternal || sourceBackedUri != null
val externalUri = sourceBackedUri ?: photo.uri
val preserveExternalHdr = isSystemExternal && showOrigin && !useGlobalEdit
val skipPreviewDenoise = maxEdge < FULL_QUALITY_PREVIEW_MAX_EDGE
// 非 RAW 照片的降噪基底(同 RAW 烘焙的降噪):编辑中只读取松手时生成的基底,拖动时保持旧结果,
// 不在预览渲染里跑降噪;编辑之外按元数据强度惰性生成。
val photonDenoiseBase = if (bitmap == null && !showOrigin && !isRawPhoto &&
(useGlobalEdit || !skipPreviewDenoise)
) {
photonDenoiseSource(context, photo.id, finalMetadata)?.let { source ->
// 非 RAW 照片的降噪只来自降噪基底(编辑页滑块松手时生成,同 RAW 烘焙的降噪),预览只读取、
// 从不跑降噪;没有匹配的基底就不降噪。
val photonDenoiseBase = if (bitmap == null && !showOrigin && !isRawPhoto) {
// 编辑中按最后一次松手(或进入编辑)时确认的强度读取,拖动中的滑块值不参与。
val strengths = if (useGlobalEdit) photonDenoiseEditStrengths[photo.id] else finalNR to finalCNR
val source = photonDenoiseSource(context, photo.id, finalMetadata)
if (strengths != null && source != null) {
contentRepository.photoProcessor.loadPhotonDenoiseBase(
context, photo.id, source,
finalNR.takeUnless { useGlobalEdit }, finalCNR.takeUnless { useGlobalEdit }, maxEdge,
context, photo.id, source, strengths.first, strengths.second, maxEdge,
)
} else {
null
}
} else {
null
@@ -3644,24 +3661,17 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
currentBitmap
} else {
val applyBitmapSharpening = !isRawPhoto
val applyBitmapDenoise = !isRawPhoto && !skipPreviewDenoise && !useGlobalEdit && photonDenoiseBase == null
val previewMetadata = if (!applyBitmapSharpening || !applyBitmapDenoise) {
finalMetadata.copy(
sharpening = if (applyBitmapSharpening) finalMetadata.sharpening else 0f,
noiseReduction = 0f,
chromaNoiseReduction = 0f
)
} else {
val previewMetadata = if (applyBitmapSharpening) {
finalMetadata
} else {
finalMetadata.copy(sharpening = 0f)
}
val previewSharpening = if (applyBitmapSharpening) finalS else 0f
val previewNoiseReduction = if (applyBitmapDenoise) finalNR else 0f
val previewChromaNoiseReduction = if (applyBitmapDenoise) finalCNR else 0f
// 预览生成
val result = contentRepository.photoProcessor.processBitmap(
context, photo.id, currentBitmap, previewMetadata,
previewSharpening, previewNoiseReduction, previewChromaNoiseReduction,
previewSharpening,
false
)
// 只在全分辨率路径下更新亮度估计(结果更准确)
@@ -1089,6 +1089,7 @@
<string name="gallery_large_aperture_blur_description">使用目前已安裝的相容深度模型估計畫面深度,模擬大光圈的淺景深、背景虛化和柔和散景光斑。輕點畫面可改變對焦位置;光圈值越小,虛化越強。首次使用時可下載預設模型,或匯入其他相容的 TFLite 模型。</string>
<string name="gallery_bokeh_style_title">光斑風格</string>
<string name="gallery_bokeh_processing">虛化處理中…</string>
<string name="gallery_denoise_processing">降噪處理中…</string>
<string name="gallery_bokeh_style_default">旋焦</string>
<string name="gallery_bokeh_style_natural">自然</string>
<string name="gallery_bokeh_style_bubble">泡泡</string>
+1
View File
@@ -1472,4 +1472,5 @@
<string name="gallery_ai_criterion_aesthetic_technical">Esthétique et technique</string>
<string name="gallery_ai_scale_note">Inspiré des principes récurrents des recommandations des jurés LensCulture ; il s\'agit d\'une critique IA indépendante, et non d\'une note officielle LensCulture.</string>
<string name="gallery_bokeh_processing">Application du bokeh…</string>
<string name="gallery_denoise_processing">Réduction du bruit en cours…</string>
</resources>
+1
View File
@@ -940,6 +940,7 @@
<string name="gallery_large_aperture_blur_description">対応深度モデルでシーン深度を推定し、浅い被写界深度、背景ボケ、柔らかな玉ボケをシミュレートします。画像をタップして合焦点を変更できます。F値が小さいほどボケは強くなります。初回使用時に既定モデルをダウンロードするか、別の対応TFLiteモデルを読み込んでください。</string>
<string name="gallery_bokeh_style_title">ボケ味</string>
<string name="gallery_bokeh_processing">ボケ処理中…</string>
<string name="gallery_denoise_processing">ノイズ低減を処理中…</string>
<string name="gallery_bokeh_style_default">ぐるぐるボケ</string>
<string name="gallery_bokeh_style_natural">ナチュラル</string>
<string name="gallery_bokeh_style_bubble">バブルボケ</string>
@@ -1110,6 +1110,7 @@
<string name="gallery_large_aperture_blur_description">使用当前已安装的兼容深度模型估计画面深度,模拟大光圈的浅景深、背景虚化和柔和散景光斑。轻点画面可改变对焦位置;光圈值越小,虚化越强。首次使用时可下载默认模型,或导入其他兼容的 TFLite 模型。</string>
<string name="gallery_bokeh_style_title">光斑风格</string>
<string name="gallery_bokeh_processing">虚化处理中…</string>
<string name="gallery_denoise_processing">降噪处理中…</string>
<string name="gallery_bokeh_style_default">旋焦</string>
<string name="gallery_bokeh_style_natural">自然</string>
<string name="gallery_bokeh_style_bubble">泡泡</string>
@@ -1089,6 +1089,7 @@
<string name="gallery_large_aperture_blur_description">使用目前已安裝的相容深度模型估計畫面深度,模擬大光圈的淺景深、背景虛化和柔和散景光斑。輕點畫面可改變對焦位置;光圈值越小,虛化越強。首次使用時可下載預設模型,或匯入其他相容的 TFLite 模型。</string>
<string name="gallery_bokeh_style_title">光斑風格</string>
<string name="gallery_bokeh_processing">虛化處理中…</string>
<string name="gallery_denoise_processing">降噪處理中…</string>
<string name="gallery_bokeh_style_default">旋焦</string>
<string name="gallery_bokeh_style_natural">自然</string>
<string name="gallery_bokeh_style_bubble">泡泡</string>
+1
View File
@@ -1122,6 +1122,7 @@
<string name="gallery_large_aperture_blur_description">Uses the installed compatible depth model to estimate scene depth and simulate a shallow depth of field, background blur, and soft bokeh highlights. Tap the image to change the focus point. Lower f-numbers produce stronger blur. Download the default model or import another compatible TFLite model on first use.</string>
<string name="gallery_bokeh_style_title">Bokeh style</string>
<string name="gallery_bokeh_processing">Applying bokeh…</string>
<string name="gallery_denoise_processing">Applying noise reduction…</string>
<string name="gallery_bokeh_style_default">Swirl</string>
<string name="gallery_bokeh_style_natural">Natural</string>
<string name="gallery_bokeh_style_bubble">Bubble</string>