feat: SCUNet AI denoiser with dynamic model download
This commit is contained in:
1 parent
e878262aa4
commit
2d9e08128d
17 files changed
+736
-688
No files matched your search
+3
-1
@@ -21,4 +21,6 @@ __pycache__
|
||||
.codex-tmp
|
||||
.tmp
|
||||
/research/*
|
||||
/scripts/lut_training/runs
|
||||
/scripts/lut_training/runs
|
||||
/scripts/nafnet_denoise_tflite/out
|
||||
/scripts/scunet_denoise_tflite/out
|
||||
Binary file not shown.
+69
-143
@@ -3878,172 +3878,98 @@ 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) {
|
||||
|
||||
Java_com_hinnka_mycamera_ml_AiDenoiser_readTileNative(
|
||||
JNIEnv *env, jobject, jobject bitmap, jint x, jint y, jint size,
|
||||
jfloatArray outArray) {
|
||||
if (size <= 0 || env->GetArrayLength(outArray) != size * size * 3) {
|
||||
LOGE("AI denoise readTile: invalid tile buffer");
|
||||
return;
|
||||
}
|
||||
AndroidBitmapInfo info;
|
||||
void *pixels = nullptr;
|
||||
if (AndroidBitmap_getInfo(env, bitmap, &info) < 0 ||
|
||||
info.format != ANDROID_BITMAP_FORMAT_RGBA_8888 ||
|
||||
AndroidBitmap_lockPixels(env, bitmap, &pixels) < 0) {
|
||||
LOGE("DnCNN preprocess: failed to lock bitmap");
|
||||
LOGE("AI denoise readTile: failed to lock RGBA_8888 bitmap");
|
||||
return;
|
||||
}
|
||||
|
||||
auto *out = static_cast<float *>(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<int>(info.stride / 4);
|
||||
const auto *src = static_cast<const uint32_t *>(pixels);
|
||||
const bool rgb = isRgb == JNI_TRUE;
|
||||
const bool nchw = channelsFirst == JNI_TRUE;
|
||||
const int pixelCount = w * h;
|
||||
|
||||
auto *out = static_cast<float *>(env->GetPrimitiveArrayCritical(outArray, nullptr));
|
||||
if (out != nullptr) {
|
||||
const int width = static_cast<int>(info.width);
|
||||
const int height = static_cast<int>(info.height);
|
||||
const int stride = static_cast<int>(info.stride / 4);
|
||||
const auto *src = static_cast<const uint32_t *>(pixels);
|
||||
constexpr float kInv255 = 1.0f / 255.0f;
|
||||
#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<int>(x + px), 0,
|
||||
static_cast<int>(info.width) - 1);
|
||||
const int sy = std::clamp(static_cast<int>(y + py), 0,
|
||||
static_cast<int>(info.height) - 1);
|
||||
const uint32_t pixel = src[sy * stride + sx];
|
||||
const float r = static_cast<float>((pixel >> 0) & 0xFF) / 255.0f;
|
||||
const float g = static_cast<float>((pixel >> 8) & 0xFF) / 255.0f;
|
||||
const float b = static_cast<float>((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;
|
||||
for (int ty = 0; ty < size; ++ty) {
|
||||
const int sy = std::clamp(y + ty, 0, height - 1);
|
||||
const uint32_t *row = src + sy * stride;
|
||||
float *o = out + ty * size * 3;
|
||||
for (int tx = 0; tx < size; ++tx) {
|
||||
const uint32_t pixel = row[std::clamp(x + tx, 0, width - 1)];
|
||||
o[tx * 3 + 0] = static_cast<float>(pixel & 0xFF) * kInv255;
|
||||
o[tx * 3 + 1] = static_cast<float>((pixel >> 8) & 0xFF) * kInv255;
|
||||
o[tx * 3 + 2] = static_cast<float>((pixel >> 16) & 0xFF) * kInv255;
|
||||
}
|
||||
}
|
||||
env->ReleasePrimitiveArrayCritical(outArray, out, 0);
|
||||
}
|
||||
|
||||
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");
|
||||
Java_com_hinnka_mycamera_ml_AiDenoiser_writeTileNative(
|
||||
JNIEnv *env, jobject, jfloatArray tileArray, jobject dstBitmap, jint x,
|
||||
jint y, jint size, jint blendLeftEnd, jint blendTopEnd) {
|
||||
if (size <= 0 || env->GetArrayLength(tileArray) != size * size * 3) {
|
||||
LOGE("AI denoise writeTile: invalid tile buffer");
|
||||
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");
|
||||
AndroidBitmapInfo info;
|
||||
void *pixels = nullptr;
|
||||
if (AndroidBitmap_getInfo(env, dstBitmap, &info) < 0 ||
|
||||
info.format != ANDROID_BITMAP_FORMAT_RGBA_8888 ||
|
||||
AndroidBitmap_lockPixels(env, dstBitmap, &pixels) < 0) {
|
||||
LOGE("AI denoise writeTile: failed to lock destination bitmap");
|
||||
return;
|
||||
}
|
||||
|
||||
auto *in = static_cast<float *>(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<int>(srcInfo.stride / 4);
|
||||
const int dstStride = static_cast<int>(dstInfo.stride / 4);
|
||||
const auto *src = static_cast<const uint32_t *>(srcPixels);
|
||||
auto *dst = static_cast<uint32_t *>(dstPixels);
|
||||
const bool rgb = isRgb == JNI_TRUE;
|
||||
const bool nchw = channelsFirst == JNI_TRUE;
|
||||
const float blend = std::clamp(static_cast<float>(strength), 0.0f, 1.0f);
|
||||
const float invBlend = 1.0f - blend;
|
||||
const int patchPixelCount = patchW * patchH;
|
||||
|
||||
const auto *tile = static_cast<const float *>(env->GetPrimitiveArrayCritical(tileArray, nullptr));
|
||||
if (tile != nullptr) {
|
||||
const int x1 = std::min(x + size, static_cast<int>(info.width));
|
||||
const int y1 = std::min(y + size, static_cast<int>(info.height));
|
||||
const int stride = static_cast<int>(info.stride / 4);
|
||||
auto *dst = static_cast<uint32_t *>(pixels);
|
||||
// Weight of this tile over existing content: smoothstep across the band shared with the
|
||||
// tile to the left / above, 1 elsewhere.
|
||||
auto ramp = [](int p, int start, int end) {
|
||||
if (p >= end) return 1.0f;
|
||||
const float t = (static_cast<float>(p - start) + 0.5f) / static_cast<float>(end - start);
|
||||
return t * t * (3.0f - 2.0f * t);
|
||||
};
|
||||
#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<int>(srcX + px), 0,
|
||||
static_cast<int>(srcInfo.width) - 1);
|
||||
const int srcPy = std::clamp(static_cast<int>(srcY + py), 0,
|
||||
static_cast<int>(srcInfo.height) - 1);
|
||||
const int dstPx = static_cast<int>(dstX + px);
|
||||
const int dstPy = static_cast<int>(dstY + py);
|
||||
if (dstPx < 0 || dstPy < 0 || dstPx >= static_cast<int>(dstInfo.width) ||
|
||||
dstPy >= static_cast<int>(dstInfo.height)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const int patchPx = std::clamp(static_cast<int>(patchX + px), 0,
|
||||
static_cast<int>(patchW) - 1);
|
||||
const int patchPy = std::clamp(static_cast<int>(patchY + py), 0,
|
||||
static_cast<int>(patchH) - 1);
|
||||
const int patchBase = patchPy * patchW + patchPx;
|
||||
const uint32_t pixel = src[srcPy * srcStride + srcPx];
|
||||
const float origR = static_cast<float>((pixel >> 0) & 0xFF);
|
||||
const float origG = static_cast<float>((pixel >> 8) & 0xFF);
|
||||
const float origB = static_cast<float>((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;
|
||||
for (int py = y; py < y1; ++py) {
|
||||
const float wy = ramp(py, y, blendTopEnd);
|
||||
const float *trow = tile + (py - y) * size * 3;
|
||||
uint32_t *drow = dst + py * stride;
|
||||
for (int px = x; px < x1; ++px) {
|
||||
const float w = wy * ramp(px, x, blendLeftEnd);
|
||||
const float *t = trow + (px - x) * 3;
|
||||
const uint32_t d = drow[px];
|
||||
uint32_t packed = 0xFF000000u;
|
||||
for (int c = 0; c < 3; ++c) {
|
||||
float v = std::clamp(t[c], 0.0f, 1.0f) * 255.0f;
|
||||
if (w < 1.0f) {
|
||||
const float prev = static_cast<float>((d >> (8 * c)) & 0xFF);
|
||||
v = prev + (v - prev) * w;
|
||||
}
|
||||
const auto q = static_cast<uint32_t>(std::clamp(v + 0.5f, 0.0f, 255.0f));
|
||||
packed |= q << (8 * c);
|
||||
}
|
||||
|
||||
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);
|
||||
drow[px] = packed;
|
||||
}
|
||||
|
||||
const auto resR = static_cast<uint32_t>(std::clamp(r, 0.0f, 255.0f));
|
||||
const auto resG = static_cast<uint32_t>(std::clamp(g, 0.0f, 255.0f));
|
||||
const auto resB = static_cast<uint32_t>(std::clamp(b, 0.0f, 255.0f));
|
||||
dst[dstPy * dstStride + dstPx] =
|
||||
0xFF000000u | (resB << 16) | (resG << 8) | resR;
|
||||
}
|
||||
env->ReleasePrimitiveArrayCritical(tileArray, const_cast<float *>(tile), JNI_ABORT);
|
||||
}
|
||||
|
||||
AndroidBitmap_unlockPixels(env, srcBitmap);
|
||||
AndroidBitmap_unlockPixels(env, dstBitmap);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
package com.hinnka.mycamera.ml
|
||||
|
||||
import android.content.Context
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.CoroutineStart
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import org.tensorflow.lite.Interpreter
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.io.FileOutputStream
|
||||
import java.io.IOException
|
||||
import java.nio.file.AtomicMoveNotSupportedException
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.StandardCopyOption
|
||||
import java.security.MessageDigest
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
sealed interface AiDenoiseModelState {
|
||||
data object Missing : AiDenoiseModelState
|
||||
|
||||
data class Downloading(
|
||||
val progress: Float?,
|
||||
val isInstalling: Boolean
|
||||
) : AiDenoiseModelState
|
||||
|
||||
data object Ready : AiDenoiseModelState
|
||||
|
||||
data object Failed : AiDenoiseModelState
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns the AI denoise model (SCUNet color σ=25, see docs/scunet-tflite.md).
|
||||
*
|
||||
* The model is downloaded from a commit-pinned Hugging Face URL, verified by exact size,
|
||||
* SHA-256 and tensor contract, and installed atomically into app-private storage.
|
||||
*/
|
||||
object AiDenoiseModelManager {
|
||||
private const val TAG = "AiDenoiseModelManager"
|
||||
private const val MODEL_DIRECTORY = "ml_models/scunet_color_25"
|
||||
private const val MODEL_FILE_NAME = "scunet_color_25.tflite"
|
||||
private const val MODEL_PART_FILE_NAME = "scunet_color_25.tflite.part"
|
||||
private const val EXPECTED_MODEL_SIZE_BYTES = 47_200_352L
|
||||
const val MODEL_SHA256 = "8d060b8e58d3224ab14ee2af72c737af30cc3dd68790f26aca20f364734dd10c"
|
||||
|
||||
const val MODEL_DOWNLOAD_URL =
|
||||
"https://huggingface.co/Binjia/scunet-color-25-litert/resolve/" +
|
||||
"9454c201ad03a74bbcbb7005232072f01a3b233c/scunet_color_25.tflite"
|
||||
|
||||
/** Model directories of earlier AI denoise models, removed on first use. */
|
||||
private val LEGACY_MODEL_DIRECTORIES = listOf("ml_models/nafnet_sidd_w32", "ml_models/scunet_color_real_psnr")
|
||||
|
||||
private val lock = Any()
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
private val client = OkHttpClient.Builder()
|
||||
.connectTimeout(30, TimeUnit.SECONDS)
|
||||
.readTimeout(5, TimeUnit.MINUTES)
|
||||
.build()
|
||||
private val _state = MutableStateFlow<AiDenoiseModelState>(AiDenoiseModelState.Missing)
|
||||
private var initialized = false
|
||||
private var operationJob: Job? = null
|
||||
|
||||
fun observe(context: Context): StateFlow<AiDenoiseModelState> {
|
||||
initialize(context.applicationContext)
|
||||
return _state.asStateFlow()
|
||||
}
|
||||
|
||||
fun isInstalled(context: Context): Boolean = installedModelFileOrNull(context) != null
|
||||
|
||||
/** The installed model; its SHA-256 was verified at install time and equals [MODEL_SHA256]. */
|
||||
fun installedModelFileOrNull(context: Context): File? {
|
||||
return modelFile(context.applicationContext).takeIf { it.isFile && it.length() == EXPECTED_MODEL_SIZE_BYTES }
|
||||
}
|
||||
|
||||
fun download(context: Context) {
|
||||
val appContext = context.applicationContext
|
||||
initialize(appContext)
|
||||
synchronized(lock) {
|
||||
if (installedModelFileOrNull(appContext) != null) {
|
||||
_state.value = AiDenoiseModelState.Ready
|
||||
return
|
||||
}
|
||||
if (operationJob?.isActive == true) return
|
||||
|
||||
_state.value = AiDenoiseModelState.Downloading(progress = 0f, isInstalling = false)
|
||||
val newJob = scope.launch(start = CoroutineStart.LAZY) {
|
||||
try {
|
||||
downloadAndInstall(appContext)
|
||||
_state.value = AiDenoiseModelState.Ready
|
||||
} catch (e: Exception) {
|
||||
PLog.w(TAG, "Failed to download or install the AI denoise model", e)
|
||||
_state.value = AiDenoiseModelState.Failed
|
||||
}
|
||||
}
|
||||
operationJob = newJob
|
||||
newJob.invokeOnCompletion {
|
||||
synchronized(lock) {
|
||||
if (operationJob === newJob) operationJob = null
|
||||
}
|
||||
}
|
||||
newJob.start()
|
||||
}
|
||||
}
|
||||
|
||||
private fun initialize(context: Context) {
|
||||
synchronized(lock) {
|
||||
if (initialized) return
|
||||
removeLegacyModels(context)
|
||||
_state.value = if (installedModelFileOrNull(context) != null) {
|
||||
AiDenoiseModelState.Ready
|
||||
} else {
|
||||
AiDenoiseModelState.Missing
|
||||
}
|
||||
initialized = true
|
||||
}
|
||||
}
|
||||
|
||||
private fun removeLegacyModels(context: Context) {
|
||||
for (path in LEGACY_MODEL_DIRECTORIES) {
|
||||
val directory = File(context.filesDir, path)
|
||||
if (directory.exists() && !directory.deleteRecursively()) {
|
||||
PLog.w(TAG, "Cannot remove legacy model directory: ${directory.absolutePath}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun downloadAndInstall(context: Context) {
|
||||
val directory = File(context.filesDir, MODEL_DIRECTORY)
|
||||
if (!directory.isDirectory && !directory.mkdirs()) {
|
||||
throw IOException("Cannot create model directory: ${directory.absolutePath}")
|
||||
}
|
||||
val partFile = File(directory, MODEL_PART_FILE_NAME)
|
||||
if (partFile.exists() && !partFile.delete()) {
|
||||
throw IOException("Cannot remove stale temporary file: ${partFile.absolutePath}")
|
||||
}
|
||||
try {
|
||||
downloadTo(partFile)
|
||||
_state.value = AiDenoiseModelState.Downloading(progress = 1f, isInstalling = true)
|
||||
validate(partFile)
|
||||
installAtomically(partFile, modelFile(context))
|
||||
PLog.d(TAG, "AI denoise model installed: ${modelFile(context).absolutePath}")
|
||||
} finally {
|
||||
if (partFile.exists() && !partFile.delete()) {
|
||||
PLog.w(TAG, "Cannot remove temporary file: ${partFile.absolutePath}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun downloadTo(target: File) {
|
||||
val request = Request.Builder().url(MODEL_DOWNLOAD_URL).get().build()
|
||||
client.newCall(request).execute().use { response ->
|
||||
if (!response.isSuccessful) {
|
||||
throw IOException("Model download failed with HTTP ${response.code}")
|
||||
}
|
||||
val body = response.body ?: throw IOException("Model download response has no body")
|
||||
var downloaded = 0L
|
||||
var lastPublished = 0L
|
||||
body.byteStream().use { input ->
|
||||
FileOutputStream(target).use { output ->
|
||||
val buffer = ByteArray(BUFFER_SIZE)
|
||||
while (true) {
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
downloaded += read
|
||||
if (downloaded > EXPECTED_MODEL_SIZE_BYTES) {
|
||||
throw IOException("Model download exceeds the expected size")
|
||||
}
|
||||
output.write(buffer, 0, read)
|
||||
if (downloaded - lastPublished >= PROGRESS_UPDATE_BYTES) {
|
||||
publishProgress(downloaded)
|
||||
lastPublished = downloaded
|
||||
}
|
||||
}
|
||||
output.fd.sync()
|
||||
}
|
||||
}
|
||||
publishProgress(downloaded)
|
||||
if (downloaded != EXPECTED_MODEL_SIZE_BYTES) {
|
||||
throw IOException("Incomplete model: downloaded=$downloaded expected=$EXPECTED_MODEL_SIZE_BYTES")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun publishProgress(downloaded: Long) {
|
||||
_state.value = AiDenoiseModelState.Downloading(
|
||||
progress = (downloaded.toDouble() / EXPECTED_MODEL_SIZE_BYTES).toFloat().coerceIn(0f, 1f),
|
||||
isInstalling = false
|
||||
)
|
||||
}
|
||||
|
||||
private fun validate(file: File) {
|
||||
if (file.length() != EXPECTED_MODEL_SIZE_BYTES) {
|
||||
throw IOException("Unexpected model size: ${file.length()}")
|
||||
}
|
||||
if (sha256(file) != MODEL_SHA256) {
|
||||
throw IOException("Model checksum mismatch")
|
||||
}
|
||||
Interpreter(file, Interpreter.Options().setUseXNNPACK(false)).use(AiDenoiser::checkContract)
|
||||
}
|
||||
|
||||
private fun installAtomically(source: File, destination: File) {
|
||||
try {
|
||||
Files.move(
|
||||
source.toPath(), destination.toPath(),
|
||||
StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING
|
||||
)
|
||||
} catch (_: AtomicMoveNotSupportedException) {
|
||||
Files.move(source.toPath(), destination.toPath(), StandardCopyOption.REPLACE_EXISTING)
|
||||
}
|
||||
}
|
||||
|
||||
private fun sha256(file: File): String {
|
||||
val digest = MessageDigest.getInstance("SHA-256")
|
||||
FileInputStream(file).use { input ->
|
||||
val buffer = ByteArray(BUFFER_SIZE)
|
||||
while (true) {
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
digest.update(buffer, 0, read)
|
||||
}
|
||||
}
|
||||
return digest.digest().joinToString("") { (it.toInt() and 0xFF).toString(16).padStart(2, '0') }
|
||||
}
|
||||
|
||||
private fun modelFile(context: Context): File = File(File(context.filesDir, MODEL_DIRECTORY), MODEL_FILE_NAME)
|
||||
|
||||
private const val BUFFER_SIZE = 64 * 1024
|
||||
private const val PROGRESS_UPDATE_BYTES = 256 * 1024L
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package com.hinnka.mycamera.ml
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.os.SystemClock
|
||||
import com.google.ai.edge.litert.CompiledModel
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import org.tensorflow.lite.DataType
|
||||
import org.tensorflow.lite.Interpreter
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import java.io.FileInputStream
|
||||
import java.nio.channels.FileChannel
|
||||
|
||||
/**
|
||||
* AI denoise with SCUNet (color σ=25 weights; conversion in docs/scunet-tflite.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.
|
||||
*
|
||||
* [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
|
||||
|
||||
/** Minimum overlap between neighbouring tiles; blended with smoothstep weights. */
|
||||
private const val OVERLAP = 32
|
||||
|
||||
init {
|
||||
System.loadLibrary("my-native-lib")
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the denoised image as a new ARGB_8888 bitmap. Throws on model or backend failure.
|
||||
*/
|
||||
fun denoise(
|
||||
context: Context,
|
||||
input: Bitmap,
|
||||
onProgress: (Float) -> Unit,
|
||||
): Bitmap {
|
||||
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)
|
||||
}
|
||||
} finally {
|
||||
if (source !== input) source.recycle()
|
||||
}
|
||||
}
|
||||
|
||||
private fun runTiles(backend: Backend, source: Bitmap, onProgress: (Float) -> Unit): Bitmap {
|
||||
val width = source.width
|
||||
val height = source.height
|
||||
val xs = tileOrigins(width)
|
||||
val ys = tileOrigins(height)
|
||||
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 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"
|
||||
)
|
||||
return result
|
||||
}
|
||||
|
||||
/** Tile origins along one axis: stride TILE - OVERLAP, last tile aligned to the far edge. */
|
||||
private fun tileOrigins(length: Int): IntArray {
|
||||
if (length <= TILE) return intArrayOf(0)
|
||||
val origins = ArrayList<Int>()
|
||||
var p = 0
|
||||
while (true) {
|
||||
origins += p
|
||||
if (p + TILE >= length) break
|
||||
p = minOf(p + TILE - OVERLAP, length - TILE)
|
||||
}
|
||||
return origins.toIntArray()
|
||||
}
|
||||
|
||||
private fun createBackend(context: Context): Backend {
|
||||
val file = AiDenoiseModelManager.installedModelFileOrNull(context)
|
||||
?: throw IllegalStateException("AI denoise model is not installed")
|
||||
val modelBuffer = FileInputStream(file).channel.use { it.map(FileChannel.MapMode.READ_ONLY, 0, it.size()) }
|
||||
Interpreter(modelBuffer, Interpreter.Options().setUseXNNPACK(false)).use(::checkContract)
|
||||
try {
|
||||
val cache = MlDelegateCacheFactory.create(
|
||||
context = context,
|
||||
tag = TAG,
|
||||
cacheName = "scunet_color_25_fp16",
|
||||
modelAssetName = file.name,
|
||||
modelSizeBytes = file.length().toInt(),
|
||||
modelFingerprint = AiDenoiseModelManager.MODEL_SHA256,
|
||||
)
|
||||
// FP16 is safe: LayerNorm is pre-scaled so its variance stays within FP16 range.
|
||||
val gpu = LiteRtGpuModel.fromFile(
|
||||
file = file,
|
||||
cache = cache,
|
||||
precision = CompiledModel.GpuOptions.Precision.FP16,
|
||||
inputElementCount = TILE_ELEMENTS,
|
||||
outputElementCount = TILE_ELEMENTS,
|
||||
)
|
||||
PLog.d(TAG, "Using LiteRT GPU (FP16)")
|
||||
return GpuBackend(gpu)
|
||||
} catch (e: Exception) {
|
||||
PLog.w(TAG, "LiteRT GPU unavailable, falling back to CPU", e)
|
||||
}
|
||||
val cpu = Interpreter(modelBuffer, Interpreter.Options().setNumThreads(CPU_THREADS).setUseXNNPACK(true))
|
||||
PLog.d(TAG, "Using CPU (XNNPACK, $CPU_THREADS threads)")
|
||||
return CpuBackend(cpu)
|
||||
}
|
||||
|
||||
/** Model contract check, shared with [AiDenoiseModelManager] at install time. */
|
||||
internal fun checkContract(interpreter: Interpreter) {
|
||||
val expected = intArrayOf(1, TILE, TILE, CHANNELS)
|
||||
check(interpreter.inputTensorCount == 1 && interpreter.outputTensorCount == 1) {
|
||||
"AI denoise model must have one input and one output"
|
||||
}
|
||||
val input = interpreter.getInputTensor(0)
|
||||
val output = interpreter.getOutputTensor(0)
|
||||
check(input.shape().contentEquals(expected) && output.shape().contentEquals(expected)) {
|
||||
"Unexpected AI denoise tensor shapes: input=${input.shape().contentToString()} " +
|
||||
"output=${output.shape().contentToString()}"
|
||||
}
|
||||
check(input.dataType() == DataType.FLOAT32 && output.dataType() == DataType.FLOAT32) {
|
||||
"Unexpected AI denoise tensor types: input=${input.dataType()} output=${output.dataType()}"
|
||||
}
|
||||
}
|
||||
|
||||
private const val CPU_THREADS = 4
|
||||
|
||||
private interface Backend : AutoCloseable {
|
||||
val name: String
|
||||
fun run(input: FloatArray): FloatArray
|
||||
}
|
||||
|
||||
private class GpuBackend(private val model: LiteRtGpuModel) : Backend {
|
||||
override val name = "GPU"
|
||||
override fun run(input: FloatArray): FloatArray = model.run(input)
|
||||
override fun close() = model.close()
|
||||
}
|
||||
|
||||
private class CpuBackend(private val interpreter: Interpreter) : Backend {
|
||||
override val name = "CPU"
|
||||
private val inputBuffer = ByteBuffer.allocateDirect(TILE_ELEMENTS * Float.SIZE_BYTES).order(ByteOrder.nativeOrder())
|
||||
private val outputBuffer = ByteBuffer.allocateDirect(TILE_ELEMENTS * Float.SIZE_BYTES).order(ByteOrder.nativeOrder())
|
||||
|
||||
override fun run(input: FloatArray): FloatArray {
|
||||
inputBuffer.rewind()
|
||||
inputBuffer.asFloatBuffer().put(input)
|
||||
outputBuffer.rewind()
|
||||
interpreter.run(inputBuffer, outputBuffer)
|
||||
val output = FloatArray(TILE_ELEMENTS)
|
||||
outputBuffer.rewind()
|
||||
outputBuffer.asFloatBuffer().get(output)
|
||||
return output
|
||||
}
|
||||
|
||||
override fun close() = interpreter.close()
|
||||
}
|
||||
|
||||
/** Fills [out] (NHWC RGB, size x size) from [bitmap] at (x, y), replicating edge pixels. */
|
||||
private external fun readTileNative(bitmap: Bitmap, x: Int, y: Int, size: Int, out: FloatArray)
|
||||
|
||||
/**
|
||||
* Writes the tile at (x, y) into [dst] (clipped to the image), blended over the existing
|
||||
* [dst] content with weight smoothstep across [x, blendLeftEnd) times smoothstep across
|
||||
* [y, blendTopEnd).
|
||||
*/
|
||||
private external fun writeTileNative(
|
||||
tile: FloatArray,
|
||||
dst: Bitmap,
|
||||
x: Int,
|
||||
y: Int,
|
||||
size: Int,
|
||||
blendLeftEnd: Int,
|
||||
blendTopEnd: Int,
|
||||
)
|
||||
}
|
||||
@@ -1,470 +0,0 @@
|
||||
package com.hinnka.mycamera.ml
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.os.SystemClock
|
||||
import com.hinnka.mycamera.utils.LargeDirectBuffer
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import com.hinnka.mycamera.utils.StartupTrace
|
||||
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 com.google.ai.edge.litert.CompiledModel
|
||||
import com.google.ai.edge.litert.support.common.FileUtil
|
||||
import com.google.ai.edge.litert.support.tensorbuffer.TensorBuffer
|
||||
import org.tensorflow.lite.Interpreter
|
||||
import java.nio.ByteBuffer
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import java.util.concurrent.atomic.AtomicLong
|
||||
|
||||
class DnCNNDenoiseEstimator(
|
||||
context: Context,
|
||||
private val modelAssetName: String = MODEL_DNCNN,
|
||||
) {
|
||||
private var interpreter: Interpreter? = null
|
||||
private val extraCpuInterpreters = mutableListOf<Interpreter>()
|
||||
private var gpuModel: LiteRtGpuModel? = 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 var isRgbModel = false
|
||||
private var outputShape = intArrayOf(1, 256, 256, 1)
|
||||
private var outputDataType = org.tensorflow.lite.DataType.FLOAT32
|
||||
private val interpreterMutex = Mutex()
|
||||
|
||||
init {
|
||||
try {
|
||||
val modelFile = StartupTrace.measure("DnCNNDenoiseEstimator.loadMappedFile") {
|
||||
FileUtil.loadMappedFile(context, modelAssetName)
|
||||
}
|
||||
// Tensor dimensions are read from the plain interpreter: the compiled model
|
||||
// exposes buffer sizes but not shapes.
|
||||
Interpreter(modelFile, Interpreter.Options().setUseXNNPACK(false)).use(::updateTensorDimensions)
|
||||
val elementCount = inputWidth * inputHeight * if (isRgbModel) 3 else 1
|
||||
|
||||
val delegateCache = MlDelegateCacheFactory.create(
|
||||
context = context,
|
||||
tag = TAG,
|
||||
cacheName = "dncnn_denoise_litert",
|
||||
modelAssetName = modelAssetName,
|
||||
modelSizeBytes = modelFile.capacity()
|
||||
)
|
||||
|
||||
try {
|
||||
gpuModel = StartupTrace.measure("DnCNNDenoiseEstimator.CompiledModel(GPU)") {
|
||||
LiteRtGpuModel.fromAsset(
|
||||
context = context,
|
||||
assetName = modelAssetName,
|
||||
cache = delegateCache,
|
||||
precision = CompiledModel.GpuOptions.Precision.DEFAULT,
|
||||
inputElementCount = elementCount,
|
||||
outputElementCount = outputWidth * outputHeight * if (isRgbModel) 3 else 1,
|
||||
)
|
||||
}
|
||||
isInitialized = true
|
||||
activeBackend = "GPU"
|
||||
PLog.d(TAG, "Using LiteRT GPU for DnCNN Denoise: $modelAssetName")
|
||||
} catch (e: Exception) {
|
||||
PLog.w(TAG, "Failed to initialize LiteRT GPU, falling back to CPU", e)
|
||||
}
|
||||
|
||||
// Fallback to CPU
|
||||
if (!isInitialized) {
|
||||
configureCpuParallelism()
|
||||
val cpuOptions = createCpuOptions(cpuThreadsPerInterpreter)
|
||||
interpreter = StartupTrace.measure("DnCNNDenoiseEstimator.Interpreter(CPU)") {
|
||||
Interpreter(modelFile, cpuOptions)
|
||||
}
|
||||
isInitialized = true
|
||||
activeBackend = "CPU"
|
||||
PLog.d(
|
||||
TAG,
|
||||
"Using CPU for DnCNN Denoise: $modelAssetName workers=$cpuWorkerCount threadsPerInterpreter=$cpuThreadsPerInterpreter xnnpack=true"
|
||||
)
|
||||
}
|
||||
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Error initializing DnCNNDenoiseEstimator: $modelAssetName", e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun configureCpuParallelism() {
|
||||
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()
|
||||
this.outputShape = outputShape
|
||||
outputDataType = interpreter.getOutputTensor(0).dataType()
|
||||
isRgbModel = inputShape.last() == 3 || (inputShape.size == 4 && inputShape[1] == 3)
|
||||
|
||||
// typically [1, 1, H, W] or [1, H, W, 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]
|
||||
} else if (inputChannelsFirst) {
|
||||
inputHeight = inputShape[2]
|
||||
inputWidth = inputShape[3]
|
||||
} else if (inputShape.size == 4 && inputShape[3] == 3) {
|
||||
inputHeight = inputShape[1]
|
||||
inputWidth = inputShape[2]
|
||||
} else {
|
||||
PLog.w(TAG, "Unexpected input shape: ${inputShape.contentToString()}")
|
||||
}
|
||||
|
||||
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"} 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 or RGB image.
|
||||
* [strength] (0.0 to 1.0) controls the blending with the original image.
|
||||
*/
|
||||
suspend fun denoise(inputBitmap: Bitmap, strength: Float = 1.0f): Bitmap? {
|
||||
if (!isInitialized) {
|
||||
PLog.e(TAG, "DnCNNDenoiseEstimator is not initialized")
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
val isRgb = isRgbModel
|
||||
val channels = if (isRgb) 3 else 1
|
||||
val buffer = LargeDirectBuffer.allocate(
|
||||
inputWidth.toLong() * inputHeight.toLong() * channels.toLong() * 4L,
|
||||
"DnCNN denoise input"
|
||||
) ?: return null
|
||||
try {
|
||||
|
||||
preprocessNative(inputBitmap, 0, 0, inputWidth, inputHeight, buffer, isRgb, inputChannelsFirst)
|
||||
|
||||
val outputBuffer = TensorBuffer.createFixedSize(outputShape, outputDataType)
|
||||
|
||||
StartupTrace.measure("DnCNNDenoiseEstimator.run") {
|
||||
interpreterMutex.withLock {
|
||||
runInference(buffer, outputBuffer.buffer)
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
} finally {
|
||||
LargeDirectBuffer.free(buffer)
|
||||
}
|
||||
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Error during DnCNN denoise", e)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Denoises the full image by splitting it into patches, processing them separately,
|
||||
* and stitching them back together. This preserves the original resolution.
|
||||
*/
|
||||
suspend fun denoisePatchwise(
|
||||
inputBitmap: Bitmap,
|
||||
strength: Float = 1.0f,
|
||||
onProgress: ((Float) -> Unit)? = null
|
||||
): Bitmap? = coroutineScope {
|
||||
if (!isInitialized) {
|
||||
PLog.e(TAG, "DnCNNDenoiseEstimator is not initialized")
|
||||
return@coroutineScope null
|
||||
}
|
||||
|
||||
val width = inputBitmap.width
|
||||
val height = inputBitmap.height
|
||||
val resultBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
|
||||
|
||||
val overlap = 4
|
||||
val strideX = inputWidth - 2 * overlap
|
||||
val strideY = inputHeight - 2 * overlap
|
||||
|
||||
val totalSteps = ((height + strideY - 1) / strideY) * ((width + strideX - 1) / strideX)
|
||||
var completedSteps = 0
|
||||
|
||||
val isRgb = isRgbModel
|
||||
val channels = if (isRgb) 3 else 1
|
||||
var preprocessMs = 0L
|
||||
var inferenceMs = 0L
|
||||
var postprocessMs = 0L
|
||||
val totalStartMs = SystemClock.elapsedRealtime()
|
||||
val patchTasks = mutableListOf<DenoisePatchTask>()
|
||||
|
||||
for (dstY in 0 until height step strideY) {
|
||||
for (dstX in 0 until width step strideX) {
|
||||
val validW = Math.min(width - dstX, strideX)
|
||||
val validH = Math.min(height - dstY, strideY)
|
||||
|
||||
val cx = dstX + validW / 2
|
||||
val cy = dstY + validH / 2
|
||||
|
||||
var startX = cx - inputWidth / 2
|
||||
var startY = cy - inputHeight / 2
|
||||
|
||||
// clamp to image bounds
|
||||
if (startX < 0) startX = 0
|
||||
if (startY < 0) startY = 0
|
||||
if (startX + inputWidth > width) startX = (width - inputWidth).coerceAtLeast(0)
|
||||
if (startY + inputHeight > height) startY = (height - inputHeight).coerceAtLeast(0)
|
||||
|
||||
patchTasks += DenoisePatchTask(
|
||||
startX = startX,
|
||||
startY = startY,
|
||||
dstX = dstX,
|
||||
dstY = dstY,
|
||||
validW = validW,
|
||||
validH = validH
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
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 = LargeDirectBuffer.allocate(
|
||||
inputWidth.toLong() * inputHeight.toLong() * channels.toLong() * 4L,
|
||||
"DnCNN worker input"
|
||||
) ?: throw OutOfMemoryError("Failed to allocate DnCNN worker input buffer")
|
||||
val outBuffer = TensorBuffer.createFixedSize(outputShape, outputDataType)
|
||||
try {
|
||||
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)
|
||||
}
|
||||
} finally {
|
||||
LargeDirectBuffer.free(buffer)
|
||||
}
|
||||
}
|
||||
}.awaitAll()
|
||||
|
||||
completedSteps = completedPatches.get()
|
||||
preprocessMs = preprocessTotalMs.get()
|
||||
inferenceMs = inferenceTotalMs.get()
|
||||
postprocessMs = postprocessTotalMs.get()
|
||||
} else {
|
||||
val buffer = LargeDirectBuffer.allocate(
|
||||
inputWidth.toLong() * inputHeight.toLong() * channels.toLong() * 4L,
|
||||
"DnCNN patch input"
|
||||
) ?: return@coroutineScope null
|
||||
val outBuffer = TensorBuffer.createFixedSize(outputShape, outputDataType)
|
||||
|
||||
try {
|
||||
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.run") {
|
||||
interpreterMutex.withLock {
|
||||
runInference(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)
|
||||
}
|
||||
} finally {
|
||||
LargeDirectBuffer.free(buffer)
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
/** Runs one patch on the active backend; both buffers hold FLOAT32 tensors. */
|
||||
private fun runInference(input: ByteBuffer, output: ByteBuffer) {
|
||||
input.rewind()
|
||||
output.rewind()
|
||||
val gpu = gpuModel
|
||||
if (gpu != null) {
|
||||
val inputValues = FloatArray(input.capacity() / Float.SIZE_BYTES)
|
||||
input.asFloatBuffer().get(inputValues)
|
||||
output.asFloatBuffer().put(gpu.run(inputValues))
|
||||
} else {
|
||||
interpreter?.run(input, output)
|
||||
}
|
||||
}
|
||||
|
||||
fun close() {
|
||||
interpreter?.close()
|
||||
interpreter = null
|
||||
gpuModel?.close()
|
||||
gpuModel = 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
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.hinnka.mycamera.ui.components
|
||||
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.hinnka.mycamera.R
|
||||
import com.hinnka.mycamera.ml.AiDenoiseModelState
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/** Asks to download the AI denoise model; the caller continues once [state] becomes Ready. */
|
||||
@Composable
|
||||
fun AiDenoiseModelDownloadDialog(
|
||||
state: AiDenoiseModelState,
|
||||
onDownload: () -> Unit,
|
||||
onDismiss: () -> Unit
|
||||
) {
|
||||
val downloading = state as? AiDenoiseModelState.Downloading
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = {
|
||||
Text(
|
||||
text = stringResource(R.string.ai_denoise_model_title),
|
||||
style = MaterialTheme.typography.titleLarge
|
||||
)
|
||||
},
|
||||
text = {
|
||||
Column {
|
||||
Text(
|
||||
text = stringResource(
|
||||
if (state == AiDenoiseModelState.Failed) R.string.ai_denoise_model_failed
|
||||
else R.string.ai_denoise_model_description
|
||||
),
|
||||
style = MaterialTheme.typography.bodyMedium
|
||||
)
|
||||
if (downloading != null) {
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
val progress = downloading.progress
|
||||
if (progress != null && !downloading.isInstalling) {
|
||||
LinearProgressIndicator(progress = { progress }, modifier = Modifier.fillMaxWidth())
|
||||
} else {
|
||||
LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
|
||||
}
|
||||
Spacer(modifier = Modifier.height(8.dp))
|
||||
Text(
|
||||
text = if (downloading.isInstalling) {
|
||||
stringResource(R.string.ai_denoise_model_installing)
|
||||
} else {
|
||||
stringResource(
|
||||
R.string.ai_denoise_model_downloading,
|
||||
((progress ?: 0f) * 100f).roundToInt()
|
||||
)
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
when (state) {
|
||||
AiDenoiseModelState.Missing -> TextButton(onClick = onDownload) {
|
||||
Text(stringResource(R.string.ai_denoise_model_download))
|
||||
}
|
||||
AiDenoiseModelState.Failed -> TextButton(onClick = onDownload) {
|
||||
Text(stringResource(R.string.ai_denoise_model_retry))
|
||||
}
|
||||
is AiDenoiseModelState.Downloading, AiDenoiseModelState.Ready -> Unit
|
||||
}
|
||||
},
|
||||
dismissButton = {
|
||||
TextButton(onClick = onDismiss) {
|
||||
Text(stringResource(if (downloading != null) R.string.close else R.string.cancel))
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
@@ -72,6 +72,8 @@ import com.hinnka.mycamera.model.RecipeParam
|
||||
import com.hinnka.mycamera.model.toEffectParams
|
||||
import com.hinnka.mycamera.ml.DepthModelDownloadState
|
||||
import com.hinnka.mycamera.ml.DepthModelManager
|
||||
import com.hinnka.mycamera.ml.AiDenoiseModelManager
|
||||
import com.hinnka.mycamera.ml.AiDenoiseModelState
|
||||
import com.hinnka.mycamera.raw.SpectralFilmSelection
|
||||
import com.hinnka.mycamera.raw.SpectralFilmTuning
|
||||
import com.hinnka.mycamera.raw.DngEmbeddedProfile
|
||||
@@ -313,7 +315,7 @@ fun GalleryEditScreen(
|
||||
val editStraightenDegrees by viewModel.editStraightenDegrees.collectAsState()
|
||||
val editMirrorHorizontal by viewModel.editMirrorHorizontal.collectAsState()
|
||||
|
||||
val editAiDenoiseStrength by viewModel.editAiDenoiseStrength.collectAsState()
|
||||
val editAiDenoiseEnabled by viewModel.editAiDenoiseEnabled.collectAsState()
|
||||
|
||||
val isRaw = editSourcePhoto?.let { viewModel.isRaw(it.id) } ?: false
|
||||
val refreshKey = editSourcePhoto?.id?.let { viewModel.photoRefreshKeys[it] } ?: 0L
|
||||
@@ -611,6 +613,28 @@ fun GalleryEditScreen(
|
||||
}
|
||||
val currentEditSourcePhoto = editSourcePhoto ?: currentPhoto
|
||||
val currentEditMetadata = currentEditSourcePhoto.metadata ?: viewModel.currentMediaMetadata
|
||||
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.
|
||||
var pendingAiDenoise by remember { mutableStateOf(false) }
|
||||
val showAiDenoiseFailure = {
|
||||
Toast.makeText(context, context.getString(R.string.ai_denoise_failed), Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
val startAiDenoise = {
|
||||
viewModel.applyAiDenoise(photo = currentEditSourcePhoto) { success ->
|
||||
if (!success) {
|
||||
viewModel.setAiDenoiseEnabled(false)
|
||||
showAiDenoiseFailure()
|
||||
}
|
||||
}
|
||||
}
|
||||
LaunchedEffect(aiDenoiseModelState, pendingAiDenoise) {
|
||||
if (aiDenoiseModelState is AiDenoiseModelState.Ready && pendingAiDenoise) {
|
||||
pendingAiDenoise = false
|
||||
startAiDenoise()
|
||||
}
|
||||
}
|
||||
val isImportedRaw = currentEditMetadata?.isImported == true && isRaw
|
||||
|
||||
val previewSourceWidth = previewBitmap?.width?.takeIf { it > 0 }
|
||||
@@ -1714,47 +1738,32 @@ fun GalleryEditScreen(
|
||||
EDIT_TAB_DETAIL -> {
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
if (!currentPhoto.isVideo) {
|
||||
val isDnCNNDenoising by viewModel.isAiDenoising.collectAsState()
|
||||
val dnCNNProgress by viewModel.aiDenoiseProgress.collectAsState()
|
||||
val isAiDenoising by viewModel.isAiDenoising.collectAsState()
|
||||
val aiDenoiseProgress by viewModel.aiDenoiseProgress.collectAsState()
|
||||
|
||||
SliderSettingItem(
|
||||
SwitchSettingItem(
|
||||
title = stringResource(R.string.ai_denoise_title),
|
||||
description = if (isDnCNNDenoising) stringResource(
|
||||
description = if (isAiDenoising) stringResource(
|
||||
R.string.ai_denoise_processing,
|
||||
dnCNNProgress * 100
|
||||
aiDenoiseProgress * 100
|
||||
) else stringResource(R.string.ai_denoise_description),
|
||||
value = editAiDenoiseStrength,
|
||||
valueRange = 0f..1f,
|
||||
onValueChange = { viewModel.setAiDenoiseStrength(it) },
|
||||
onValueChangeFinished = {
|
||||
if (isDnCNNDenoising) return@SliderSettingItem
|
||||
if (editAiDenoiseStrength > 0.01f) {
|
||||
viewModel.applyDnCNNDenoise(
|
||||
photo = currentEditSourcePhoto,
|
||||
strength = editAiDenoiseStrength,
|
||||
onComplete = { success ->
|
||||
if (!success) {
|
||||
Toast.makeText(
|
||||
context,
|
||||
context.getString(R.string.ai_denoise_failed),
|
||||
Toast.LENGTH_SHORT
|
||||
).show()
|
||||
}
|
||||
}
|
||||
)
|
||||
checked = editAiDenoiseEnabled,
|
||||
onCheckedChange = { enabled ->
|
||||
if (isAiDenoising) return@SwitchSettingItem
|
||||
viewModel.setAiDenoiseEnabled(enabled)
|
||||
if (enabled) {
|
||||
if (AiDenoiseModelManager.isInstalled(context)) {
|
||||
startAiDenoise()
|
||||
} else {
|
||||
pendingAiDenoise = true
|
||||
}
|
||||
} else {
|
||||
viewModel.resetDnCNNDenoise(
|
||||
photo = currentEditSourcePhoto,
|
||||
onComplete = { success ->
|
||||
if (!success) {
|
||||
Toast.makeText(
|
||||
context,
|
||||
context.getString(R.string.ai_denoise_failed),
|
||||
Toast.LENGTH_SHORT
|
||||
).show()
|
||||
}
|
||||
viewModel.resetAiDenoise(photo = currentEditSourcePhoto) { success ->
|
||||
if (!success) {
|
||||
viewModel.setAiDenoiseEnabled(true)
|
||||
showAiDenoiseFailure()
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -2105,6 +2114,17 @@ fun GalleryEditScreen(
|
||||
)
|
||||
}
|
||||
|
||||
if (pendingAiDenoise) {
|
||||
AiDenoiseModelDownloadDialog(
|
||||
state = aiDenoiseModelState,
|
||||
onDownload = { AiDenoiseModelManager.download(context) },
|
||||
onDismiss = {
|
||||
pendingAiDenoise = false
|
||||
viewModel.setAiDenoiseEnabled(false)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
if (showDepthModelDownloadDialog) {
|
||||
DepthModelDownloadDialog(
|
||||
state = depthModelState,
|
||||
|
||||
@@ -501,8 +501,8 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
var editMirrorHorizontal = MutableStateFlow(false)
|
||||
private set
|
||||
|
||||
private val _editAiDenoiseStrength = MutableStateFlow(1.0f)
|
||||
val editAiDenoiseStrength = _editAiDenoiseStrength.asStateFlow()
|
||||
private val _editAiDenoiseEnabled = MutableStateFlow(false)
|
||||
val editAiDenoiseEnabled = _editAiDenoiseEnabled.asStateFlow()
|
||||
|
||||
private val _isAiDenoising = MutableStateFlow(false)
|
||||
val isAiDenoising = _isAiDenoising.asStateFlow()
|
||||
@@ -632,11 +632,11 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
job.start()
|
||||
}
|
||||
|
||||
fun setAiDenoiseStrength(value: Float) {
|
||||
_editAiDenoiseStrength.value = value
|
||||
fun setAiDenoiseEnabled(enabled: Boolean) {
|
||||
_editAiDenoiseEnabled.value = enabled
|
||||
}
|
||||
|
||||
fun applyDnCNNDenoise(photo: MediaData, strength: Float = 1.0f, onComplete: (Boolean) -> Unit) {
|
||||
fun applyAiDenoise(photo: MediaData, onComplete: (Boolean) -> Unit) {
|
||||
if (_isAiDenoising.value) return
|
||||
_isAiDenoising.value = true
|
||||
_aiDenoiseProgress.value = 0f
|
||||
@@ -644,41 +644,22 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
viewModelScope.launch(Dispatchers.IO) {
|
||||
val context = getApplication<Application>()
|
||||
try {
|
||||
var bitmap = GalleryManager.loadOriginalBitmap(context, photo.id) ?: GalleryManager.loadBitmap(context, photo.uri)
|
||||
val bitmap = GalleryManager.loadOriginalBitmap(context, photo.id) ?: GalleryManager.loadBitmap(context, photo.uri)
|
||||
if (bitmap == null) {
|
||||
_isAiDenoising.value = false
|
||||
withContext(Dispatchers.Main) { onComplete(false) }
|
||||
return@launch
|
||||
}
|
||||
|
||||
if (!isRawInGallery(photo.id)) {
|
||||
// 非 RAW 照片,先进行一次色度降噪
|
||||
val lutProcessor = com.hinnka.mycamera.lut.LutImageProcessor(context)
|
||||
val chromaDenoised = lutProcessor.applyChromaDenoise(
|
||||
bitmap,
|
||||
strength = 0.8f,
|
||||
sensorIso = (photo.metadata ?: GalleryManager.loadMetadata(context, photo.id))?.iso,
|
||||
)
|
||||
lutProcessor.release()
|
||||
if (chromaDenoised !== bitmap) {
|
||||
bitmap.recycle()
|
||||
bitmap = chromaDenoised
|
||||
|
||||
// Runs on this IO thread without suspending: the GPU model is thread-bound.
|
||||
val denoised = try {
|
||||
com.hinnka.mycamera.ml.AiDenoiser.denoise(context, bitmap) { p ->
|
||||
_aiDenoiseProgress.value = p
|
||||
}
|
||||
} finally {
|
||||
bitmap.recycle()
|
||||
}
|
||||
|
||||
val estimator = com.hinnka.mycamera.ml.DnCNNDenoiseEstimator(context)
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
val file = GalleryManager.getAiDenoiseFile(context, photo.id)
|
||||
file.parentFile?.mkdirs()
|
||||
FileOutputStream(file).use { outputStream ->
|
||||
@@ -706,7 +687,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
val updatedMetadata = GalleryManager.updateMetadata(context, photo.id) { current ->
|
||||
current.copy(
|
||||
hasAiDenoisedBase = true,
|
||||
aiDenoiseStrength = strength
|
||||
aiDenoiseStrength = 1.0f
|
||||
)
|
||||
} ?: run {
|
||||
_isAiDenoising.value = false
|
||||
@@ -746,14 +727,14 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
_isAiDenoising.value = false
|
||||
withContext(Dispatchers.Main) { onComplete(true) }
|
||||
} catch (e: Exception) {
|
||||
PLog.e(TAG, "Failed to apply DnCNN denoise", e)
|
||||
PLog.e(TAG, "Failed to apply AI denoise", e)
|
||||
_isAiDenoising.value = false
|
||||
withContext(Dispatchers.Main) { onComplete(false) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun resetDnCNNDenoise(photo: MediaData, onComplete: (Boolean) -> Unit = {}) {
|
||||
fun resetAiDenoise(photo: MediaData, onComplete: (Boolean) -> Unit = {}) {
|
||||
if (_isAiDenoising.value) return
|
||||
_isAiDenoising.value = true
|
||||
|
||||
@@ -1525,7 +1506,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
editStraightenDegrees.value =
|
||||
PostEditGeometry.normalizeStraightenDegrees(m.postStraightenDegrees)
|
||||
editMirrorHorizontal.value = m.postMirrorHorizontal
|
||||
_editAiDenoiseStrength.value = if (m.hasAiDenoisedBase) m.aiDenoiseStrength ?: 1.0f else 0.0f
|
||||
_editAiDenoiseEnabled.value = m.hasAiDenoisedBase
|
||||
restoreCropEditState(photo, m)
|
||||
|
||||
// 加载 LUT 配置
|
||||
@@ -1540,7 +1521,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application)
|
||||
editRotationDegrees.value = 0
|
||||
editStraightenDegrees.value = 0f
|
||||
editMirrorHorizontal.value = false
|
||||
_editAiDenoiseStrength.value = 0.0f
|
||||
_editAiDenoiseEnabled.value = false
|
||||
restoreCropEditState(photo, null)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1441,4 +1441,11 @@
|
||||
<string name="fotufilm_value_minutes">%1$s 分鐘</string>
|
||||
<string name="fotufilm_value_years">%1$s 年</string>
|
||||
<!-- /Fotufilm controls -->
|
||||
<string name="ai_denoise_model_title">AI 降噪模型</string>
|
||||
<string name="ai_denoise_model_description">AI 降噪需要 SCUNet 降噪模型(約 47 MB),是否現在下載?模型僅儲存在應用程式私有目錄中。</string>
|
||||
<string name="ai_denoise_model_downloading">正在下載模型… %1$d%%</string>
|
||||
<string name="ai_denoise_model_installing">正在驗證並安裝模型…</string>
|
||||
<string name="ai_denoise_model_failed">模型下載或驗證失敗,請檢查網路後重試。</string>
|
||||
<string name="ai_denoise_model_download">下載</string>
|
||||
<string name="ai_denoise_model_retry">重試</string>
|
||||
</resources>
|
||||
@@ -1479,4 +1479,11 @@
|
||||
<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>
|
||||
<string name="ai_denoise_model_title">Modèle de débruitage IA</string>
|
||||
<string name="ai_denoise_model_description">Le débruitage IA nécessite le modèle SCUNet (environ 47 Mo). Le télécharger maintenant ? Il est stocké de façon privée par l\'application.</string>
|
||||
<string name="ai_denoise_model_downloading">Téléchargement du modèle… %1$d%%</string>
|
||||
<string name="ai_denoise_model_installing">Vérification et installation du modèle…</string>
|
||||
<string name="ai_denoise_model_failed">Le modèle n\'a pas pu être téléchargé ou vérifié. Vérifiez votre connexion et réessayez.</string>
|
||||
<string name="ai_denoise_model_download">Télécharger</string>
|
||||
<string name="ai_denoise_model_retry">Réessayer</string>
|
||||
</resources>
|
||||
@@ -1318,4 +1318,11 @@
|
||||
<string name="fotufilm_value_minutes">%1$s 分</string>
|
||||
<string name="fotufilm_value_years">%1$s 年</string>
|
||||
<!-- /Fotufilm controls -->
|
||||
<string name="ai_denoise_model_title">AI ノイズ除去モデル</string>
|
||||
<string name="ai_denoise_model_description">AI ノイズ除去には SCUNet ノイズ除去モデル(約 47 MB)が必要です。今すぐダウンロードしますか?モデルはアプリ専用の領域に保存されます。</string>
|
||||
<string name="ai_denoise_model_downloading">モデルをダウンロード中… %1$d%%</string>
|
||||
<string name="ai_denoise_model_installing">モデルを検証してインストール中…</string>
|
||||
<string name="ai_denoise_model_failed">モデルのダウンロードまたは検証に失敗しました。接続を確認して再試行してください。</string>
|
||||
<string name="ai_denoise_model_download">ダウンロード</string>
|
||||
<string name="ai_denoise_model_retry">再試行</string>
|
||||
</resources>
|
||||
@@ -1114,4 +1114,11 @@
|
||||
<string name="fotufilm_value_years">%1$s ปี</string>
|
||||
<!-- /Fotufilm controls -->
|
||||
<string name="save_as_preset">บันทึกเป็นพรีเซ็ต</string>
|
||||
<string name="ai_denoise_model_title">โมเดลลดสัญญาณรบกวน AI</string>
|
||||
<string name="ai_denoise_model_description">การลดสัญญาณรบกวนด้วย AI ต้องใช้โมเดล SCUNet (ประมาณ 47 MB) ดาวน์โหลดตอนนี้หรือไม่? โมเดลจะถูกเก็บไว้เป็นส่วนตัวในแอป</string>
|
||||
<string name="ai_denoise_model_downloading">กำลังดาวน์โหลดโมเดล… %1$d%%</string>
|
||||
<string name="ai_denoise_model_installing">กำลังตรวจสอบและติดตั้งโมเดล…</string>
|
||||
<string name="ai_denoise_model_failed">ไม่สามารถดาวน์โหลดหรือตรวจสอบโมเดลได้ โปรดตรวจสอบการเชื่อมต่อแล้วลองอีกครั้ง</string>
|
||||
<string name="ai_denoise_model_download">ดาวน์โหลด</string>
|
||||
<string name="ai_denoise_model_retry">ลองอีกครั้ง</string>
|
||||
</resources>
|
||||
@@ -1497,4 +1497,11 @@
|
||||
<string name="fotufilm_value_minutes">%1$s 分钟</string>
|
||||
<string name="fotufilm_value_years">%1$s 年</string>
|
||||
<!-- /Fotufilm controls -->
|
||||
<string name="ai_denoise_model_title">AI 降噪模型</string>
|
||||
<string name="ai_denoise_model_description">AI 降噪需要 SCUNet 降噪模型(约 47 MB),是否现在下载?模型仅保存在应用私有目录中。</string>
|
||||
<string name="ai_denoise_model_downloading">正在下载模型… %1$d%%</string>
|
||||
<string name="ai_denoise_model_installing">正在校验并安装模型…</string>
|
||||
<string name="ai_denoise_model_failed">模型下载或校验失败,请检查网络后重试。</string>
|
||||
<string name="ai_denoise_model_download">下载</string>
|
||||
<string name="ai_denoise_model_retry">重试</string>
|
||||
</resources>
|
||||
@@ -1435,4 +1435,11 @@
|
||||
<string name="fotufilm_value_minutes">%1$s 分鐘</string>
|
||||
<string name="fotufilm_value_years">%1$s 年</string>
|
||||
<!-- /Fotufilm controls -->
|
||||
<string name="ai_denoise_model_title">AI 降噪模型</string>
|
||||
<string name="ai_denoise_model_description">AI 降噪需要 SCUNet 降噪模型(約 47 MB),是否現在下載?模型僅儲存在應用程式私有目錄中。</string>
|
||||
<string name="ai_denoise_model_downloading">正在下載模型… %1$d%%</string>
|
||||
<string name="ai_denoise_model_installing">正在驗證並安裝模型…</string>
|
||||
<string name="ai_denoise_model_failed">模型下載或驗證失敗,請檢查網絡後重試。</string>
|
||||
<string name="ai_denoise_model_download">下載</string>
|
||||
<string name="ai_denoise_model_retry">重試</string>
|
||||
</resources>
|
||||
@@ -1441,4 +1441,11 @@
|
||||
<string name="fotufilm_value_minutes">%1$s 分鐘</string>
|
||||
<string name="fotufilm_value_years">%1$s 年</string>
|
||||
<!-- /Fotufilm controls -->
|
||||
<string name="ai_denoise_model_title">AI 降噪模型</string>
|
||||
<string name="ai_denoise_model_description">AI 降噪需要 SCUNet 降噪模型(約 47 MB),是否現在下載?模型僅儲存在應用程式私有目錄中。</string>
|
||||
<string name="ai_denoise_model_downloading">正在下載模型… %1$d%%</string>
|
||||
<string name="ai_denoise_model_installing">正在驗證並安裝模型…</string>
|
||||
<string name="ai_denoise_model_failed">模型下載或驗證失敗,請檢查網路後重試。</string>
|
||||
<string name="ai_denoise_model_download">下載</string>
|
||||
<string name="ai_denoise_model_retry">重試</string>
|
||||
</resources>
|
||||
@@ -1521,4 +1521,11 @@
|
||||
<string name="fotufilm_value_minutes">%1$s min</string>
|
||||
<string name="fotufilm_value_years">%1$s yr</string>
|
||||
<!-- /Fotufilm controls -->
|
||||
<string name="ai_denoise_model_title">AI Denoise Model</string>
|
||||
<string name="ai_denoise_model_description">AI denoise needs the SCUNet denoise model (about 47 MB). Download it now? It is stored privately by the app.</string>
|
||||
<string name="ai_denoise_model_downloading">Downloading model… %1$d%%</string>
|
||||
<string name="ai_denoise_model_installing">Verifying and installing model…</string>
|
||||
<string name="ai_denoise_model_failed">The model could not be downloaded or verified. Check your connection and try again.</string>
|
||||
<string name="ai_denoise_model_download">Download</string>
|
||||
<string name="ai_denoise_model_retry">Retry</string>
|
||||
</resources>
|
||||
Reference in new issue
Block a user