diff --git a/app/src/main/cpp/native-lib.cpp b/app/src/main/cpp/native-lib.cpp index eba9f67d..9b2a44fc 100644 --- a/app/src/main/cpp/native-lib.cpp +++ b/app/src/main/cpp/native-lib.cpp @@ -2481,4 +2481,174 @@ JNIEXPORT void JNICALL Java_com_hinnka_mycamera_raw_DngRawData_freeNativeBuffer( } } +JNIEXPORT void JNICALL +Java_com_hinnka_mycamera_ml_DnCNNDenoiseEstimator_preprocessNative( + JNIEnv *env, jobject, jobject bitmap, jint x, jint y, jint w, jint h, + jobject outBuffer, jboolean isRgb, jboolean channelsFirst) { + + AndroidBitmapInfo info; + void *pixels = nullptr; + if (AndroidBitmap_getInfo(env, bitmap, &info) < 0 || + AndroidBitmap_lockPixels(env, bitmap, &pixels) < 0) { + LOGE("DnCNN preprocess: failed to lock bitmap"); + return; + } + + auto *out = static_cast(env->GetDirectBufferAddress(outBuffer)); + if (!out || w <= 0 || h <= 0 || info.width <= 0 || info.height <= 0) { + AndroidBitmap_unlockPixels(env, bitmap); + return; + } + + const int stride = static_cast(info.stride / 4); + const auto *src = static_cast(pixels); + const bool rgb = isRgb == JNI_TRUE; + const bool nchw = channelsFirst == JNI_TRUE; + const int pixelCount = w * h; + +#pragma omp parallel for num_threads(8) + for (int py = 0; py < h; ++py) { + for (int px = 0; px < w; ++px) { + const int sx = std::clamp(static_cast(x + px), 0, + static_cast(info.width) - 1); + const int sy = std::clamp(static_cast(y + py), 0, + static_cast(info.height) - 1); + const uint32_t pixel = src[sy * stride + sx]; + const float r = static_cast((pixel >> 0) & 0xFF) / 255.0f; + const float g = static_cast((pixel >> 8) & 0xFF) / 255.0f; + const float b = static_cast((pixel >> 16) & 0xFF) / 255.0f; + const int base = py * w + px; + + if (rgb) { + if (nchw) { + out[base] = r; + out[pixelCount + base] = g; + out[pixelCount * 2 + base] = b; + } else { + const int outIdx = base * 3; + out[outIdx] = r; + out[outIdx + 1] = g; + out[outIdx + 2] = b; + } + } else { + out[base] = 0.299f * r + 0.587f * g + 0.114f * b; + } + } + } + + AndroidBitmap_unlockPixels(env, bitmap); +} + +JNIEXPORT void JNICALL +Java_com_hinnka_mycamera_ml_DnCNNDenoiseEstimator_postprocessNative( + JNIEnv *env, jobject, jobject inBuffer, jobject srcBitmap, jobject dstBitmap, + jint patchX, jint patchY, jint srcX, jint srcY, jint dstX, jint dstY, + jint w, jint h, jint patchW, jint patchH, jfloat strength, jboolean isRgb, + jboolean channelsFirst) { + + AndroidBitmapInfo srcInfo, dstInfo; + void *srcPixels = nullptr; + void *dstPixels = nullptr; + if (AndroidBitmap_getInfo(env, srcBitmap, &srcInfo) < 0 || + AndroidBitmap_lockPixels(env, srcBitmap, &srcPixels) < 0) { + LOGE("DnCNN postprocess: failed to lock source bitmap"); + return; + } + if (AndroidBitmap_getInfo(env, dstBitmap, &dstInfo) < 0 || + AndroidBitmap_lockPixels(env, dstBitmap, &dstPixels) < 0) { + AndroidBitmap_unlockPixels(env, srcBitmap); + LOGE("DnCNN postprocess: failed to lock destination bitmap"); + return; + } + + auto *in = static_cast(env->GetDirectBufferAddress(inBuffer)); + if (!in || w <= 0 || h <= 0 || patchW <= 0 || patchH <= 0 || + srcInfo.width <= 0 || srcInfo.height <= 0 || dstInfo.width <= 0 || + dstInfo.height <= 0) { + AndroidBitmap_unlockPixels(env, srcBitmap); + AndroidBitmap_unlockPixels(env, dstBitmap); + return; + } + + const int srcStride = static_cast(srcInfo.stride / 4); + const int dstStride = static_cast(dstInfo.stride / 4); + const auto *src = static_cast(srcPixels); + auto *dst = static_cast(dstPixels); + const bool rgb = isRgb == JNI_TRUE; + const bool nchw = channelsFirst == JNI_TRUE; + const float blend = std::clamp(static_cast(strength), 0.0f, 1.0f); + const float invBlend = 1.0f - blend; + const int patchPixelCount = patchW * patchH; + +#pragma omp parallel for num_threads(8) + for (int py = 0; py < h; ++py) { + for (int px = 0; px < w; ++px) { + const int srcPx = std::clamp(static_cast(srcX + px), 0, + static_cast(srcInfo.width) - 1); + const int srcPy = std::clamp(static_cast(srcY + py), 0, + static_cast(srcInfo.height) - 1); + const int dstPx = static_cast(dstX + px); + const int dstPy = static_cast(dstY + py); + if (dstPx < 0 || dstPy < 0 || dstPx >= static_cast(dstInfo.width) || + dstPy >= static_cast(dstInfo.height)) { + continue; + } + + const int patchPx = std::clamp(static_cast(patchX + px), 0, + static_cast(patchW) - 1); + const int patchPy = std::clamp(static_cast(patchY + py), 0, + static_cast(patchH) - 1); + const int patchBase = patchPy * patchW + patchPx; + const uint32_t pixel = src[srcPy * srcStride + srcPx]; + const float origR = static_cast((pixel >> 0) & 0xFF); + const float origG = static_cast((pixel >> 8) & 0xFF); + const float origB = static_cast((pixel >> 16) & 0xFF); + + float r; + float g; + float b; + if (rgb) { + float denR; + float denG; + float denB; + if (nchw) { + denR = in[patchBase] * 255.0f; + denG = in[patchPixelCount + patchBase] * 255.0f; + denB = in[patchPixelCount * 2 + patchBase] * 255.0f; + } else { + const int inIdx = patchBase * 3; + denR = in[inIdx] * 255.0f; + denG = in[inIdx + 1] * 255.0f; + denB = in[inIdx + 2] * 255.0f; + } + + r = origR * invBlend + denR * blend; + g = origG * invBlend + denG * blend; + b = origB * invBlend + denB * blend; + } else { + const float cb = + -0.1687f * origR - 0.3313f * origG + 0.5f * origB + 128.0f; + const float cr = + 0.5f * origR - 0.4187f * origG - 0.0813f * origB + 128.0f; + const float originalY = 0.299f * origR + 0.587f * origG + 0.114f * origB; + const float denoisedY = in[patchBase] * 255.0f; + const float newY = originalY * invBlend + denoisedY * blend; + + r = newY + 1.402f * (cr - 128.0f); + g = newY - 0.344136f * (cb - 128.0f) - 0.714136f * (cr - 128.0f); + b = newY + 1.772f * (cb - 128.0f); + } + + const auto resR = static_cast(std::clamp(r, 0.0f, 255.0f)); + const auto resG = static_cast(std::clamp(g, 0.0f, 255.0f)); + const auto resB = static_cast(std::clamp(b, 0.0f, 255.0f)); + dst[dstPy * dstStride + dstPx] = + 0xFF000000u | (resB << 16) | (resG << 8) | resR; + } + } + + AndroidBitmap_unlockPixels(env, srcBitmap); + AndroidBitmap_unlockPixels(env, dstBitmap); +} + } // extern "C" diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/MediaMetadata.kt b/app/src/main/java/com/hinnka/mycamera/gallery/MediaMetadata.kt index 62e7a4e5..467f1222 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/MediaMetadata.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/MediaMetadata.kt @@ -98,7 +98,8 @@ data class MediaMetadata( val dynamicRangeProfile: String? = null, val captureMode: String? = null, val multipleExposureFrameCount: Int? = null, - val hasAiDenoisedBase: Boolean = false + val hasAiDenoisedBase: Boolean = false, + val aiDenoiseStrength: Float? = null ) { /** * 将元数据转换为 CaptureInfo,用于写入 EXIF @@ -262,6 +263,7 @@ data class MediaMetadata( put("captureMode", captureMode ?: JSONObject.NULL) put("multipleExposureFrameCount", multipleExposureFrameCount ?: JSONObject.NULL) put("hasAiDenoisedBase", hasAiDenoisedBase) + put("aiDenoiseStrength", aiDenoiseStrength?.toDouble() ?: JSONObject.NULL) }.toString(2) } @@ -432,6 +434,7 @@ data class MediaMetadata( captureMode = if (obj.isNull("captureMode")) null else obj.optString("captureMode"), multipleExposureFrameCount = if (obj.isNull("multipleExposureFrameCount")) null else obj.optInt("multipleExposureFrameCount"), hasAiDenoisedBase = obj.optBoolean("hasAiDenoisedBase", false), + aiDenoiseStrength = if (obj.isNull("aiDenoiseStrength")) null else obj.optDouble("aiDenoiseStrength").toFloat(), ) } catch (e: Exception) { PLog.e(TAG, "Failed to parse JSON", e) diff --git a/app/src/main/java/com/hinnka/mycamera/ml/DnCNNDenoiseEstimator.kt b/app/src/main/java/com/hinnka/mycamera/ml/DnCNNDenoiseEstimator.kt index 42352224..38fbb1f2 100644 --- a/app/src/main/java/com/hinnka/mycamera/ml/DnCNNDenoiseEstimator.kt +++ b/app/src/main/java/com/hinnka/mycamera/ml/DnCNNDenoiseEstimator.kt @@ -2,10 +2,15 @@ package com.hinnka.mycamera.ml import android.content.Context import android.graphics.Bitmap -import android.graphics.Color +import android.os.SystemClock import com.hinnka.mycamera.utils.PLog import com.hinnka.mycamera.utils.StartupTrace -import org.tensorflow.lite.DataType +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.awaitAll +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock import org.tensorflow.lite.Interpreter import org.tensorflow.lite.gpu.CompatibilityList import org.tensorflow.lite.gpu.GpuDelegate @@ -14,20 +19,29 @@ import org.tensorflow.lite.support.common.FileUtil import org.tensorflow.lite.support.tensorbuffer.TensorBuffer import java.nio.ByteBuffer import java.nio.ByteOrder +import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.atomic.AtomicLong class DnCNNDenoiseEstimator( context: Context, - private val modelAssetName: String = MODEL_DNCNN + private val modelAssetName: String = MODEL_DNCNN, + private val backend: Backend = Backend.AUTO ) { private var interpreter: Interpreter? = null + private val extraCpuInterpreters = mutableListOf() private var gpuDelegate: GpuDelegate? = null private var nnApiDelegate: NnApiDelegate? = null private var isInitialized = false + private var activeBackend = "none" + private var cpuWorkerCount = 1 + private var cpuThreadsPerInterpreter = 4 private var inputWidth = 256 private var inputHeight = 256 private var outputWidth = 256 private var outputHeight = 256 private var inputChannelsFirst = false + private var outputChannelsFirst = false + private val interpreterMutex = Mutex() init { try { @@ -35,34 +49,37 @@ class DnCNNDenoiseEstimator( FileUtil.loadMappedFile(context, modelAssetName) } - val gpuOptions = Interpreter.Options() - val compatList = StartupTrace.measure("DnCNNDenoiseEstimator.CompatibilityList()") { - CompatibilityList() - } - gpuDelegate = StartupTrace.measure("DnCNNDenoiseEstimator.GpuDelegate()") { - if (compatList.isDelegateSupportedOnThisDevice) { - val delegateOptions = compatList.bestOptionsForThisDevice - GpuDelegate(delegateOptions) - } else { - GpuDelegate() + if (backend == Backend.AUTO || backend == Backend.GPU) { + val gpuOptions = Interpreter.Options() + val compatList = StartupTrace.measure("DnCNNDenoiseEstimator.CompatibilityList()") { + CompatibilityList() } - } - StartupTrace.measure("DnCNNDenoiseEstimator.gpuOptions.addDelegate") { - gpuOptions.addDelegate(gpuDelegate) - } - try { - interpreter = StartupTrace.measure("DnCNNDenoiseEstimator.Interpreter(GPU)") { - Interpreter(modelFile, gpuOptions) + gpuDelegate = StartupTrace.measure("DnCNNDenoiseEstimator.GpuDelegate()") { + if (compatList.isDelegateSupportedOnThisDevice) { + val delegateOptions = compatList.bestOptionsForThisDevice + GpuDelegate(delegateOptions) + } else { + GpuDelegate() + } + } + StartupTrace.measure("DnCNNDenoiseEstimator.gpuOptions.addDelegate") { + gpuOptions.addDelegate(gpuDelegate) + } + try { + interpreter = StartupTrace.measure("DnCNNDenoiseEstimator.Interpreter(GPU)") { + Interpreter(modelFile, gpuOptions) + } + isInitialized = true + activeBackend = "GPU" + PLog.d(TAG, "Using GPU Delegate for DnCNN Denoise: $modelAssetName") + } catch (e: Exception) { + PLog.w(TAG, "Failed to initialize GPU delegate, falling back to ${if (backend == Backend.AUTO) "NNAPI" else "CPU"}", e) + gpuDelegate?.close() + gpuDelegate = null } - isInitialized = true - PLog.d(TAG, "Using GPU Delegate for DnCNN Denoise: $modelAssetName") - } catch (e: Exception) { - PLog.w(TAG, "Failed to initialize GPU delegate, falling back to CPU", e) - gpuDelegate?.close() - gpuDelegate = null } - if (!isInitialized) { + if (backend == Backend.AUTO && !isInitialized) { val nnApiOptions = Interpreter.Options() nnApiDelegate = StartupTrace.measure("DnCNNDenoiseEstimator.NnApiDelegate()") { NnApiDelegate() @@ -75,9 +92,10 @@ class DnCNNDenoiseEstimator( Interpreter(modelFile, nnApiOptions) } isInitialized = true + activeBackend = "NNAPI" PLog.d(TAG, "Using NNAPI (NPU) for DnCNN Denoise: $modelAssetName") } catch (e: Exception) { - PLog.w(TAG, "Failed to initialize NNAPI delegate, falling back to GPU", e) + PLog.w(TAG, "Failed to initialize NNAPI delegate, falling back to CPU", e) nnApiDelegate?.close() nnApiDelegate = null } @@ -85,13 +103,24 @@ class DnCNNDenoiseEstimator( // Fallback to CPU if (!isInitialized) { - val cpuOptions = Interpreter.Options() - cpuOptions.setNumThreads(4) + configureCpuParallelism() + val cpuOptions = createCpuOptions(cpuThreadsPerInterpreter) interpreter = StartupTrace.measure("DnCNNDenoiseEstimator.Interpreter(CPU)") { Interpreter(modelFile, cpuOptions) } + if (backend == Backend.CPU && cpuWorkerCount > 1) { + repeat(cpuWorkerCount - 1) { index -> + extraCpuInterpreters += StartupTrace.measure("DnCNNDenoiseEstimator.Interpreter(CPU worker ${index + 2})") { + Interpreter(modelFile, createCpuOptions(cpuThreadsPerInterpreter)) + } + } + } isInitialized = true - PLog.d(TAG, "Using CPU for DnCNN Denoise: $modelAssetName") + activeBackend = "CPU" + PLog.d( + TAG, + "Using CPU for DnCNN Denoise: $modelAssetName workers=$cpuWorkerCount threadsPerInterpreter=$cpuThreadsPerInterpreter xnnpack=true" + ) } interpreter?.let { @@ -102,12 +131,31 @@ class DnCNNDenoiseEstimator( } } + private fun configureCpuParallelism() { + val availableProcessors = Runtime.getRuntime().availableProcessors().coerceAtLeast(1) + if (backend == Backend.CPU) { + cpuWorkerCount = availableProcessors.coerceIn(2, 4) + cpuThreadsPerInterpreter = (availableProcessors / cpuWorkerCount).coerceAtLeast(1) + } else { + cpuWorkerCount = 1 + cpuThreadsPerInterpreter = 4 + } + } + + private fun createCpuOptions(numThreads: Int): Interpreter.Options { + return Interpreter.Options().apply { + setNumThreads(numThreads) + setUseXNNPACK(true) + } + } + private fun updateTensorDimensions(interpreter: Interpreter) { val inputShape = interpreter.getInputTensor(0).shape() val outputShape = interpreter.getOutputTensor(0).shape() // typically [1, 1, H, W] or [1, H, W, 1] - inputChannelsFirst = inputShape.size == 4 && inputShape[1] == 1 + inputChannelsFirst = inputShape.size == 4 && (inputShape[1] == 1 || inputShape[1] == 3) + outputChannelsFirst = outputShape.size == 4 && (outputShape[1] == 1 || outputShape[1] == 3) if (inputShape.size == 4 && inputShape[3] == 1) { inputHeight = inputShape[1] inputWidth = inputShape[2] @@ -121,23 +169,61 @@ class DnCNNDenoiseEstimator( PLog.w(TAG, "Unexpected input shape: ${inputShape.contentToString()}") } - val outputDims = outputShape.filter { it > 1 } - if (outputDims.size >= 2) { - outputHeight = outputDims[outputDims.size - 2] - outputWidth = outputDims[outputDims.size - 1] + if (outputShape.size == 4 && outputShape[3] == 1) { + outputHeight = outputShape[1] + outputWidth = outputShape[2] + } else if (outputChannelsFirst) { + outputHeight = outputShape[2] + outputWidth = outputShape[3] + } else { + val outputDims = outputShape.filter { it > 1 } + if (outputDims.size >= 2) { + outputHeight = outputDims[outputDims.size - 2] + outputWidth = outputDims[outputDims.size - 1] + } } PLog.d( TAG, - "DnCNN model ready: asset=$modelAssetName input=${inputWidth}x$inputHeight output=${outputWidth}x$outputHeight inputLayout=${if (inputChannelsFirst) "NCHW" else "NHWC"} inputType=${interpreter.getInputTensor(0).dataType()} outputType=${interpreter.getOutputTensor(0).dataType()} inputShape=${inputShape.contentToString()} outputShape=${outputShape.contentToString()}" + "DnCNN model ready: asset=$modelAssetName input=${inputWidth}x$inputHeight output=${outputWidth}x$outputHeight inputLayout=${if (inputChannelsFirst) "NCHW" else "NHWC"} outputLayout=${if (outputChannelsFirst) "NCHW" else "NHWC"} inputType=${interpreter.getInputTensor(0).dataType()} outputType=${interpreter.getOutputTensor(0).dataType()} inputShape=${inputShape.contentToString()} outputShape=${outputShape.contentToString()}" ) } + private external fun preprocessNative( + bitmap: Bitmap, + x: Int, + y: Int, + w: Int, + h: Int, + outBuffer: ByteBuffer, + isRgb: Boolean, + channelsFirst: Boolean + ) + + private external fun postprocessNative( + inBuffer: ByteBuffer, + srcBitmap: Bitmap, + dstBitmap: Bitmap, + patchX: Int, + patchY: Int, + srcX: Int, + srcY: Int, + dstX: Int, + dstY: Int, + w: Int, + h: Int, + patchW: Int, + patchH: Int, + strength: Float, + isRgb: Boolean, + channelsFirst: Boolean + ) + /** - * Denoises a single-channel (Grayscale) Luma component. - * Expects inputBitmap to be resized or we will resize it internally. + * Denoises a single-channel (Grayscale) Luma component or RGB image. + * [strength] (0.0 to 1.0) controls the blending with the original image. */ - fun denoise(inputBitmap: Bitmap): Bitmap? { + suspend fun denoise(inputBitmap: Bitmap, strength: Float = 1.0f): Bitmap? { if (!isInitialized || interpreter == null) { PLog.e(TAG, "DnCNNDenoiseEstimator is not initialized") return null @@ -146,83 +232,44 @@ class DnCNNDenoiseEstimator( try { val inputTensor = interpreter!!.getInputTensor(0) val outputTensor = interpreter!!.getOutputTensor(0) - val inputDataType = inputTensor.dataType() val outputDataType = outputTensor.dataType() - val resized = if (inputBitmap.width == inputWidth && inputBitmap.height == inputHeight) { - inputBitmap - } else { - Bitmap.createScaledBitmap(inputBitmap, inputWidth, inputHeight, true) - } - - val pixels = IntArray(inputWidth * inputHeight) - resized.getPixels(pixels, 0, inputWidth, 0, 0, inputWidth, inputHeight) - if (resized !== inputBitmap) { - resized.recycle() - } - val isRgb = inputTensor.shape().last() == 3 || (inputChannelsFirst && inputTensor.shape()[1] == 3) val channels = if (isRgb) 3 else 1 val buffer = ByteBuffer.allocateDirect(inputWidth * inputHeight * channels * 4).order(ByteOrder.nativeOrder()) - // Input normalization: typically DnCNN takes [0, 1] range float input. - for (pixel in pixels) { - if (isRgb) { - val r = Color.red(pixel) / 255.0f - val g = Color.green(pixel) / 255.0f - val b = Color.blue(pixel) / 255.0f - buffer.putFloat(r) - buffer.putFloat(g) - buffer.putFloat(b) - } else { - // Convert to grayscale/luma - val r = Color.red(pixel) - val g = Color.green(pixel) - val b = Color.blue(pixel) - val luma = (0.299f * r + 0.587f * g + 0.114f * b) / 255.0f - buffer.putFloat(luma) - } - } - buffer.rewind() + preprocessNative(inputBitmap, 0, 0, inputWidth, inputHeight, buffer, isRgb, inputChannelsFirst) val outputBuffer = TensorBuffer.createFixedSize(outputTensor.shape(), outputDataType) StartupTrace.measure("DnCNNDenoiseEstimator.Interpreter.run") { - interpreter?.run(buffer, outputBuffer.buffer) - } - - val floatArray = outputBuffer.floatArray - val resultBitmap = Bitmap.createBitmap(outputWidth, outputHeight, Bitmap.Config.ARGB_8888) - val resultPixels = IntArray(outputWidth * outputHeight) - - for (i in resultPixels.indices) { - if (isRgb) { - val r = (floatArray[i * 3] * 255.0f).toInt().coerceIn(0, 255) - val g = (floatArray[i * 3 + 1] * 255.0f).toInt().coerceIn(0, 255) - val b = (floatArray[i * 3 + 2] * 255.0f).toInt().coerceIn(0, 255) - resultPixels[i] = Color.rgb(r, g, b) - } else { - val pixel = pixels[i] - val origR = Color.red(pixel).toFloat() - val origG = Color.green(pixel).toFloat() - val origB = Color.blue(pixel).toFloat() - - // Convert original to YCbCr - val cb = -0.1687f * origR - 0.3313f * origG + 0.5f * origB + 128f - val cr = 0.5f * origR - 0.4187f * origG - 0.0813f * origB + 128f - - // Use new denoised Y - val newY = floatArray[i] * 255.0f - - // Convert back to RGB - val r = (newY + 1.402f * (cr - 128f)).toInt().coerceIn(0, 255) - val g = (newY - 0.344136f * (cb - 128f) - 0.714136f * (cr - 128f)).toInt().coerceIn(0, 255) - val b = (newY + 1.772f * (cb - 128f)).toInt().coerceIn(0, 255) - - resultPixels[i] = Color.rgb(r, g, b) + interpreterMutex.withLock { + buffer.rewind() + outputBuffer.buffer.rewind() + interpreter?.run(buffer, outputBuffer.buffer) } } - resultBitmap.setPixels(resultPixels, 0, outputWidth, 0, 0, outputWidth, outputHeight) + + val resultBitmap = Bitmap.createBitmap(outputWidth, outputHeight, Bitmap.Config.ARGB_8888) + postprocessNative( + outputBuffer.buffer, + inputBitmap, + resultBitmap, + 0, + 0, + 0, + 0, + 0, + 0, + outputWidth, + outputHeight, + outputWidth, + outputHeight, + strength, + isRgb, + outputChannelsFirst + ) + return resultBitmap } catch (e: Exception) { @@ -235,24 +282,37 @@ class DnCNNDenoiseEstimator( * Denoises the full image by splitting it into patches, processing them separately, * and stitching them back together. This preserves the original resolution. */ - fun denoisePatchwise(inputBitmap: Bitmap, onProgress: ((Float) -> Unit)? = null): Bitmap? { + suspend fun denoisePatchwise( + inputBitmap: Bitmap, + strength: Float = 1.0f, + onProgress: ((Float) -> Unit)? = null + ): Bitmap? = coroutineScope { if (!isInitialized || interpreter == null) { PLog.e(TAG, "DnCNNDenoiseEstimator is not initialized") - return null + return@coroutineScope null } val width = inputBitmap.width val height = inputBitmap.height val resultBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) - val canvas = android.graphics.Canvas(resultBitmap) - val paint = android.graphics.Paint() - val overlap = 24 + val overlap = 4 val strideX = inputWidth - 2 * overlap val strideY = inputHeight - 2 * overlap val totalSteps = ((height + strideY - 1) / strideY) * ((width + strideX - 1) / strideX) - var currentStep = 0 + var completedSteps = 0 + + val inputTensor = interpreter!!.getInputTensor(0) + val outputTensor = interpreter!!.getOutputTensor(0) + val isRgb = inputTensor.shape().last() == 3 || (inputChannelsFirst && inputTensor.shape()[1] == 3) + val channels = if (isRgb) 3 else 1 + val outputDataType = outputTensor.dataType() + var preprocessMs = 0L + var inferenceMs = 0L + var postprocessMs = 0L + val totalStartMs = SystemClock.elapsedRealtime() + val patchTasks = mutableListOf() for (dstY in 0 until height step strideY) { for (dstX in 0 until width step strideX) { @@ -268,35 +328,123 @@ class DnCNNDenoiseEstimator( // clamp to image bounds if (startX < 0) startX = 0 if (startY < 0) startY = 0 - if (startX + inputWidth > width) startX = Math.max(0, width - inputWidth) - if (startY + inputHeight > height) startY = Math.max(0, height - inputHeight) + if (startX + inputWidth > width) startX = (width - inputWidth).coerceAtLeast(0) + if (startY + inputHeight > height) startY = (height - inputHeight).coerceAtLeast(0) - // Create a patch of exactly inputWidth x inputHeight (with padding if image is smaller) - val patchBitmap = Bitmap.createBitmap(inputWidth, inputHeight, Bitmap.Config.ARGB_8888) - val patchCanvas = android.graphics.Canvas(patchBitmap) - val cropW = Math.min(width - startX, inputWidth) - val cropH = Math.min(height - startY, inputHeight) - - val srcRect = android.graphics.Rect(startX, startY, startX + cropW, startY + cropH) - val dstRect = android.graphics.Rect(0, 0, cropW, cropH) - patchCanvas.drawBitmap(inputBitmap, srcRect, dstRect, null) - - val denoisedPatch = denoise(patchBitmap) - patchBitmap.recycle() - - if (denoisedPatch != null) { - val patchSrcRect = android.graphics.Rect(dstX - startX, dstY - startY, dstX - startX + validW, dstY - startY + validH) - val patchDstRect = android.graphics.Rect(dstX, dstY, dstX + validW, dstY + validH) - canvas.drawBitmap(denoisedPatch, patchSrcRect, patchDstRect, paint) - denoisedPatch.recycle() - } - - currentStep++ - onProgress?.invoke(currentStep.toFloat() / totalSteps) + patchTasks += DenoisePatchTask( + startX = startX, + startY = startY, + dstX = dstX, + dstY = dstY, + validW = validW, + validH = validH + ) } } - return resultBitmap + val cpuInterpreters = if (activeBackend == "CPU" && extraCpuInterpreters.isNotEmpty()) { + listOfNotNull(interpreter) + extraCpuInterpreters + } else { + emptyList() + } + + if (cpuInterpreters.isNotEmpty()) { + val nextPatch = AtomicInteger(0) + val completedPatches = AtomicInteger(0) + val preprocessTotalMs = AtomicLong(0L) + val inferenceTotalMs = AtomicLong(0L) + val postprocessTotalMs = AtomicLong(0L) + val bitmapMutex = Mutex() + + cpuInterpreters.map { workerInterpreter -> + async(Dispatchers.Default) { + val buffer = ByteBuffer.allocateDirect(inputWidth * inputHeight * channels * 4).order(ByteOrder.nativeOrder()) + val outBuffer = TensorBuffer.createFixedSize(outputTensor.shape(), outputDataType) + + while (true) { + val patchIndex = nextPatch.getAndIncrement() + if (patchIndex >= patchTasks.size) break + + val task = patchTasks[patchIndex] + var stageStartMs = SystemClock.elapsedRealtime() + bitmapMutex.withLock { + preprocessNative(inputBitmap, task.startX, task.startY, inputWidth, inputHeight, buffer, isRgb, inputChannelsFirst) + } + preprocessTotalMs.addAndGet(SystemClock.elapsedRealtime() - stageStartMs) + + stageStartMs = SystemClock.elapsedRealtime() + buffer.rewind() + outBuffer.buffer.rewind() + workerInterpreter.run(buffer, outBuffer.buffer) + inferenceTotalMs.addAndGet(SystemClock.elapsedRealtime() - stageStartMs) + + stageStartMs = SystemClock.elapsedRealtime() + bitmapMutex.withLock { + postprocessNative( + outBuffer.buffer, inputBitmap, resultBitmap, + task.dstX - task.startX, task.dstY - task.startY, + task.dstX, task.dstY, + task.dstX, task.dstY, + task.validW, task.validH, + outputWidth, outputHeight, + strength, isRgb, outputChannelsFirst + ) + } + postprocessTotalMs.addAndGet(SystemClock.elapsedRealtime() - stageStartMs) + + val progress = completedPatches.incrementAndGet().toFloat() / totalSteps + onProgress?.invoke(progress) + } + } + }.awaitAll() + + completedSteps = completedPatches.get() + preprocessMs = preprocessTotalMs.get() + inferenceMs = inferenceTotalMs.get() + postprocessMs = postprocessTotalMs.get() + } else { + val buffer = ByteBuffer.allocateDirect(inputWidth * inputHeight * channels * 4).order(ByteOrder.nativeOrder()) + val outBuffer = TensorBuffer.createFixedSize(outputTensor.shape(), outputDataType) + + for (task in patchTasks) { + var stageStartMs = SystemClock.elapsedRealtime() + preprocessNative(inputBitmap, task.startX, task.startY, inputWidth, inputHeight, buffer, isRgb, inputChannelsFirst) + preprocessMs += SystemClock.elapsedRealtime() - stageStartMs + + stageStartMs = SystemClock.elapsedRealtime() + StartupTrace.measure("DnCNNDenoiseEstimator.Interpreter.run") { + interpreterMutex.withLock { + buffer.rewind() + outBuffer.buffer.rewind() + interpreter?.run(buffer, outBuffer.buffer) + } + } + inferenceMs += SystemClock.elapsedRealtime() - stageStartMs + + stageStartMs = SystemClock.elapsedRealtime() + postprocessNative( + outBuffer.buffer, inputBitmap, resultBitmap, + task.dstX - task.startX, task.dstY - task.startY, + task.dstX, task.dstY, + task.dstX, task.dstY, + task.validW, task.validH, + outputWidth, outputHeight, + strength, isRgb, outputChannelsFirst + ) + postprocessMs += SystemClock.elapsedRealtime() - stageStartMs + + completedSteps++ + onProgress?.invoke(completedSteps.toFloat() / totalSteps) + } + } + + val totalMs = SystemClock.elapsedRealtime() - totalStartMs + PLog.d( + TAG, + "DnCNN patchwise finished: backend=$activeBackend image=${width}x${height} patches=$completedSteps patch=${inputWidth}x$inputHeight stride=${strideX}x$strideY total=${totalMs}ms preprocess=${preprocessMs}ms inference=${inferenceMs}ms postprocess=${postprocessMs}ms layout=${if (inputChannelsFirst) "NCHW" else "NHWC"}->${if (outputChannelsFirst) "NCHW" else "NHWC"} rgb=$isRgb" + ) + + return@coroutineScope resultBitmap } fun close() { @@ -306,11 +454,32 @@ class DnCNNDenoiseEstimator( gpuDelegate = null nnApiDelegate?.close() nnApiDelegate = null + extraCpuInterpreters.forEach { it.close() } + extraCpuInterpreters.clear() isInitialized = false } companion object { private const val TAG = "DnCNNDenoiseEstimator" const val MODEL_DNCNN = "dncnn.tflite" + + init { + System.loadLibrary("my-native-lib") + } } + + enum class Backend { + AUTO, + GPU, + CPU + } + + private data class DenoisePatchTask( + val startX: Int, + val startY: Int, + val dstX: Int, + val dstY: Int, + val validW: Int, + val validH: Int + ) } diff --git a/app/src/main/java/com/hinnka/mycamera/ui/gallery/PhotoEditScreen.kt b/app/src/main/java/com/hinnka/mycamera/ui/gallery/PhotoEditScreen.kt index c480f2c0..6bf307c2 100644 --- a/app/src/main/java/com/hinnka/mycamera/ui/gallery/PhotoEditScreen.kt +++ b/app/src/main/java/com/hinnka/mycamera/ui/gallery/PhotoEditScreen.kt @@ -159,6 +159,8 @@ fun PhotoEditScreen( val editCropRect by viewModel.editCropRect.collectAsState() val editCropAspectOption by viewModel.editCropAspectOption.collectAsState() + val editAiDenoiseStrength by viewModel.editAiDenoiseStrength.collectAsState() + val isRaw = currentPhoto?.let { viewModel.isRaw(it.id) } ?: false var showOrigin by remember { mutableStateOf(false) } @@ -747,61 +749,32 @@ fun PhotoEditScreen( } } else if (editTab == 1) { Spacer(modifier = Modifier.height(16.dp)) - var isDnCNNDenoising by remember { mutableStateOf(false) } - var isDnCNNResetting by remember { mutableStateOf(false) } - var dnCNNProgress by remember { mutableFloatStateOf(0f) } - val aiDenoiseMetadataEnabled = - (viewModel.currentMediaMetadata ?: currentPhoto.metadata)?.hasAiDenoisedBase == true - var isAiDenoiseEnabled by remember(currentPhoto.id) { - mutableStateOf(aiDenoiseMetadataEnabled) - } + val isDnCNNDenoising by viewModel.isAiDenoising.collectAsState() + val dnCNNProgress by viewModel.aiDenoiseProgress.collectAsState() - LaunchedEffect( - currentPhoto.id, - aiDenoiseMetadataEnabled, - isDnCNNDenoising, - isDnCNNResetting - ) { - if (!isDnCNNDenoising && !isDnCNNResetting) { - isAiDenoiseEnabled = aiDenoiseMetadataEnabled - } - } - - SwitchSettingItem( + SliderSettingItem( title = stringResource(R.string.ai_denoise_title), description = if (isDnCNNDenoising) stringResource(R.string.ai_denoise_processing, dnCNNProgress * 100) else stringResource(R.string.ai_denoise_description), - checked = isAiDenoiseEnabled || isDnCNNDenoising, - onCheckedChange = { checked -> - if (isDnCNNDenoising || isDnCNNResetting) { - return@SwitchSettingItem - } - if (checked && !isAiDenoiseEnabled) { - isDnCNNDenoising = true - dnCNNProgress = 0f + value = editAiDenoiseStrength, + valueRange = 0f..1f, + onValueChange = { viewModel.setAiDenoiseStrength(it) }, + onValueChangeFinished = { + if (isDnCNNDenoising) return@SliderSettingItem + if (editAiDenoiseStrength > 0.01f) { viewModel.applyDnCNNDenoise( photo = currentPhoto, - onProgress = { p -> dnCNNProgress = p }, + strength = editAiDenoiseStrength, onComplete = { success -> - isDnCNNDenoising = false - if (success) { - isAiDenoiseEnabled = true - Toast.makeText(context, context.getString(R.string.ai_denoise_success), Toast.LENGTH_SHORT).show() - } else { - isAiDenoiseEnabled = false + if (!success) { Toast.makeText(context, context.getString(R.string.ai_denoise_failed), Toast.LENGTH_SHORT).show() } } ) - } else if (!checked && isAiDenoiseEnabled) { - isDnCNNResetting = true + } else { viewModel.resetDnCNNDenoise( photo = currentPhoto, onComplete = { success -> - isDnCNNResetting = false - if (success) { - isAiDenoiseEnabled = false - } else { - isAiDenoiseEnabled = true + if (!success) { Toast.makeText(context, context.getString(R.string.ai_denoise_failed), Toast.LENGTH_SHORT).show() } } @@ -809,14 +782,6 @@ fun PhotoEditScreen( } } ) - if (isDnCNNDenoising) { - LinearProgressIndicator( - progress = { dnCNNProgress }, - modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp), - color = AccentOrange, - trackColor = Color.White.copy(alpha = 0.2f), - ) - } Spacer(modifier = Modifier.height(8.dp)) // 细节处理调整 (锐化, 降噪, 杂色降噪) val aperture = editComputationalAperture diff --git a/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt b/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt index 091618be..c9717d87 100644 --- a/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt +++ b/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt @@ -310,6 +310,15 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) var editCropAspectOption = MutableStateFlow(CropAspectOption.Free) private set + private val _editAiDenoiseStrength = MutableStateFlow(1.0f) + val editAiDenoiseStrength = _editAiDenoiseStrength.asStateFlow() + + private val _isAiDenoising = MutableStateFlow(false) + val isAiDenoising = _isAiDenoising.asStateFlow() + + private val _aiDenoiseProgress = MutableStateFlow(0f) + val aiDenoiseProgress = _aiDenoiseProgress.asStateFlow() + private var bokehJob: Job? = null fun setComputationalAperture(value: Float?) { @@ -383,12 +392,21 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) } } - fun applyDnCNNDenoise(photo: MediaData, onProgress: ((Float) -> Unit)? = null, onComplete: (Boolean) -> Unit) { + fun setAiDenoiseStrength(value: Float) { + _editAiDenoiseStrength.value = value + } + + fun applyDnCNNDenoise(photo: MediaData, strength: Float = 1.0f, onComplete: (Boolean) -> Unit) { + if (_isAiDenoising.value) return + _isAiDenoising.value = true + _aiDenoiseProgress.value = 0f + viewModelScope.launch(Dispatchers.IO) { val context = getApplication() try { var bitmap = GalleryManager.loadOriginalBitmap(context, photo.id) ?: GalleryManager.loadBitmap(context, photo.uri) if (bitmap == null) { + _isAiDenoising.value = false withContext(Dispatchers.Main) { onComplete(false) } return@launch } @@ -405,13 +423,14 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) } val estimator = com.hinnka.mycamera.ml.DnCNNDenoiseEstimator(context) - val denoised = estimator.denoisePatchwise(bitmap) { p -> - onProgress?.invoke(p) + val denoised = estimator.denoisePatchwise(bitmap, strength = strength) { p -> + _aiDenoiseProgress.value = p } estimator.close() bitmap.recycle() if (denoised == null) { + _isAiDenoising.value = false withContext(Dispatchers.Main) { onComplete(false) } return@launch } @@ -440,7 +459,8 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) } } val updatedMetadata = metadata.copy( - hasAiDenoisedBase = true + hasAiDenoisedBase = true, + aiDenoiseStrength = strength ) GalleryManager.saveMetadata(context, photo.id, updatedMetadata) currentMediaMetadata = updatedMetadata @@ -467,22 +487,28 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) chromaNoiseReduction = updatedMetadata.chromaNoiseReduction ?: 0f ) + _isAiDenoising.value = false withContext(Dispatchers.Main) { onComplete(true) } } catch (e: Exception) { PLog.e(TAG, "Failed to apply DnCNN denoise", e) + _isAiDenoising.value = false withContext(Dispatchers.Main) { onComplete(false) } } } } fun resetDnCNNDenoise(photo: MediaData, onComplete: (Boolean) -> Unit = {}) { + if (_isAiDenoising.value) return + _isAiDenoising.value = true + viewModelScope.launch(Dispatchers.IO) { val context = getApplication() try { GalleryManager.getAiDenoiseFile(context, photo.id).takeIf { it.exists() }?.delete() val updatedMetadata = updatePhotoMetadata(photo.id) { - it.copy(hasAiDenoisedBase = false) + it.copy(hasAiDenoisedBase = false, aiDenoiseStrength = 0.0f) } ?: run { + _isAiDenoising.value = false withContext(Dispatchers.Main) { onComplete(false) } return@launch } @@ -511,9 +537,11 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) } invalidatePreviewCache(photo.id) photoRefreshKeys[photo.id] = System.currentTimeMillis() + _isAiDenoising.value = false withContext(Dispatchers.Main) { onComplete(true) } } catch (e: Exception) { - PLog.e(TAG, "Failed to reset DnCNN denoise", e) + PLog.e(TAG, "Failed to reset AI denoise", e) + _isAiDenoising.value = false withContext(Dispatchers.Main) { onComplete(false) } } } @@ -990,6 +1018,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) editRawBlackPointCorrection.value = m.rawBlackPointCorrection ?: 0f editRawWhitePointCorrection.value = m.rawWhitePointCorrection ?: 0f editRawDcpId.value = m.rawDcpId + _editAiDenoiseStrength.value = if (m.hasAiDenoisedBase) m.aiDenoiseStrength ?: 1.0f else 0.0f restoreCropEditState(photo, m) // 加载 LUT 配置 @@ -1000,7 +1029,10 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) } } } - } ?: restoreCropEditState(photo, null) + } ?: run { + _editAiDenoiseStrength.value = 0.0f + restoreCropEditState(photo, null) + } } fun loadThumbnail(photo: MediaData): Bitmap? { diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index a7ac9088..480e5416 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -795,4 +795,5 @@ 正在处理... %1$.1f%% AI 降噪成功 AI 降噪失败 + AI 降噪强度 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 0fc5550c..01abbd22 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -795,4 +795,5 @@ Processing... %1$.1f%% AI Denoise Success AI Denoise Failed + AI Denoise Strength