diff --git a/app/src/main/cpp/CMakeLists.txt b/app/src/main/cpp/CMakeLists.txt index 19dae178..c8b41b09 100644 --- a/app/src/main/cpp/CMakeLists.txt +++ b/app/src/main/cpp/CMakeLists.txt @@ -359,6 +359,7 @@ add_library(my-native-lib SHARED dcp_parser.cpp mgc_denoise_static/mgc_halide_runtime.cpp mgc_denoise_static/mgc_denoise_static.cpp + mgc_denoise_static/mgc_full_resolution_denoise.cpp mgc_denoise_static/mgc_full_resolution_denoise_jni.cpp mgc_denoise_static/mgc_spatial_strength_jni.cpp raw_float_texture_transfer_jni.cpp diff --git a/app/src/main/cpp/mgc_denoise_static/mgc_full_resolution_denoise.cpp b/app/src/main/cpp/mgc_denoise_static/mgc_full_resolution_denoise.cpp new file mode 100644 index 00000000..66b8a042 --- /dev/null +++ b/app/src/main/cpp/mgc_denoise_static/mgc_full_resolution_denoise.cpp @@ -0,0 +1,1612 @@ +#include "mgc_full_resolution_denoise.h" + +#include "mgc_denoise_static.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +constexpr int kWhiteLevel = 16383; +constexpr int kHostWorkers = 4; +constexpr char kLogTag[] = "PLog_MgcFullResolutionDenoise"; + +int HostWorkerCount() { + return kHostWorkers; +} + +void ZeroPlanarBuffers( + int16_t* planar_a, + int16_t* planar_b, + size_t sample_count, + int worker_count) { +#pragma omp parallel num_threads(worker_count) + { + const size_t worker = static_cast(omp_get_thread_num()); + const size_t workers = static_cast(omp_get_num_threads()); + const size_t begin = sample_count * worker / workers; + const size_t end = sample_count * (worker + 1) / workers; + const size_t byte_count = (end - begin) * sizeof(int16_t); + std::memset(planar_a + begin, 0, byte_count); + std::memset(planar_b + begin, 0, byte_count); + } +} + +int LogStageFailure(const char* stage, int result) { + __android_log_print( + ANDROID_LOG_ERROR, + kLogTag, + "MGC full-resolution denoise stage=%s failed result=%d", + stage, + result); + return result; +} + +int RoundUp(int value, int multiple) { + return ((value + multiple - 1) / multiple) * multiple; +} + +float HalfToFloat(uint16_t bits) { + _Float16 half = {}; + static_assert(sizeof(half) == sizeof(bits)); + std::memcpy(&half, &bits, sizeof(bits)); + return static_cast(half); +} + +uint16_t FloatToHalf(float value) { + const _Float16 half = static_cast<_Float16>(value); + uint16_t bits = 0; + std::memcpy(&bits, &half, sizeof(bits)); + return bits; +} + +struct SampledDelta { + int64_t sample_count = 0; + int64_t changed_count = 0; + double absolute_sum = 0.0; + double squared_sum = 0.0; + int maximum = 0; +}; + +std::array MeasurePlanarDelta( + const int16_t* source, + const int16_t* denoised, + int width, + int height, + int stride, + size_t plane_size) { + std::array result = {}; + constexpr int kSampleStep = 8; + for (int y = 0; y < height; y += kSampleStep) { + for (int x = 0; x < width; x += kSampleStep) { + const size_t pixel = static_cast(y) * stride + x; + for (int channel = 0; channel < 3; ++channel) { + const size_t index = + static_cast(channel) * plane_size + pixel; + const int difference = + static_cast(denoised[index]) - + static_cast(source[index]); + const int absolute = std::abs(difference); + SampledDelta& delta = result[channel]; + ++delta.sample_count; + if (difference != 0) ++delta.changed_count; + delta.absolute_sum += static_cast(absolute); + delta.squared_sum += + static_cast(difference) * difference; + delta.maximum = std::max(delta.maximum, absolute); + } + } + } + return result; +} + +void LogDenoiseDiagnostics( + const uint16_t* strength, + size_t strength_count, + const std::array& delta) { + std::array strength_min = { + std::numeric_limits::max(), + std::numeric_limits::max(), + std::numeric_limits::max(), + }; + std::array strength_max = {}; + std::array strength_sum = {}; + for (int channel = 0; channel < 3; ++channel) { + const uint16_t* plane = + strength + static_cast(channel) * strength_count; + for (size_t index = 0; index < strength_count; ++index) { + const uint16_t value = plane[index]; + strength_min[channel] = + std::min(strength_min[channel], value); + strength_max[channel] = + std::max(strength_max[channel], value); + strength_sum[channel] += value; + } + } + const auto mean_strength = [&](int channel) { + return strength_count > 0 + ? strength_sum[channel] / + static_cast(strength_count) + : 0.0; + }; + const auto changed_percent = [&](int channel) { + return delta[channel].sample_count > 0 + ? 100.0 * static_cast(delta[channel].changed_count) / + static_cast(delta[channel].sample_count) + : 0.0; + }; + const auto mean_absolute = [&](int channel) { + return delta[channel].sample_count > 0 + ? delta[channel].absolute_sum / + static_cast(delta[channel].sample_count) + : 0.0; + }; + const auto rms = [&](int channel) { + return delta[channel].sample_count > 0 + ? std::sqrt( + delta[channel].squared_sum / + static_cast(delta[channel].sample_count)) + : 0.0; + }; + __android_log_print( + ANDROID_LOG_INFO, + kLogTag, + "MGC denoise diagnostics strengthQ8=" + "[%u..%u/%.2f,%u..%u/%.2f,%u..%u/%.2f] " + "delta14 Y=%.2f/%.2f/%d/%.1f%% " + "Cb=%.2f/%.2f/%d/%.1f%% " + "Cr=%.2f/%.2f/%d/%.1f%% samples=%lld", + strength_min[0], + strength_max[0], + mean_strength(0), + strength_min[1], + strength_max[1], + mean_strength(1), + strength_min[2], + strength_max[2], + mean_strength(2), + mean_absolute(0), + rms(0), + delta[0].maximum, + changed_percent(0), + mean_absolute(1), + rms(1), + delta[1].maximum, + changed_percent(1), + mean_absolute(2), + rms(2), + delta[2].maximum, + changed_percent(2), + static_cast(delta[0].sample_count)); +} + +void LogMeasureMoireDiagnostics( + const uint16_t* input, + const uint16_t* output, + size_t plane_size) { + std::array input_min = { + std::numeric_limits::max(), + std::numeric_limits::max(), + std::numeric_limits::max(), + }; + std::array input_max = {}; + std::array output_min = input_min; + std::array output_max = {}; + std::array input_sum = {}; + std::array output_sum = {}; + std::array changed = {}; + for (int channel = 0; channel < 3; ++channel) { + const size_t plane_offset = + static_cast(channel) * plane_size; + for (size_t index = 0; index < plane_size; ++index) { + const uint16_t input_value = input[plane_offset + index]; + const uint16_t output_value = output[plane_offset + index]; + input_min[channel] = std::min(input_min[channel], input_value); + input_max[channel] = std::max(input_max[channel], input_value); + output_min[channel] = std::min(output_min[channel], output_value); + output_max[channel] = std::max(output_max[channel], output_value); + input_sum[channel] += input_value; + output_sum[channel] += output_value; + if (input_value != output_value) ++changed[channel]; + } + } + const auto mean = [plane_size](uint64_t sum) { + return plane_size > 0 + ? static_cast(sum) / static_cast(plane_size) + : 0.0; + }; + const auto changed_percent = [plane_size](size_t count) { + return plane_size > 0 + ? 100.0 * static_cast(count) / + static_cast(plane_size) + : 0.0; + }; + __android_log_print( + ANDROID_LOG_INFO, + kLogTag, + "MGC MeasureMoire strengthQ8 " + "in=[%u..%u/%.2f,%u..%u/%.2f,%u..%u/%.2f] " + "out=[%u..%u/%.2f,%u..%u/%.2f,%u..%u/%.2f] " + "changed=[%.1f%%,%.1f%%,%.1f%%]", + input_min[0], + input_max[0], + mean(input_sum[0]), + input_min[1], + input_max[1], + mean(input_sum[1]), + input_min[2], + input_max[2], + mean(input_sum[2]), + output_min[0], + output_max[0], + mean(output_sum[0]), + output_min[1], + output_max[1], + mean(output_sum[1]), + output_min[2], + output_max[2], + mean(output_sum[2]), + changed_percent(changed[0]), + changed_percent(changed[1]), + changed_percent(changed[2])); +} + +void LogPecanInputs( + const float normalized_yuv_read[3], + const float normalized_yuv_shot[3], + const float normalized_yuv_quadratic[3], + const float q14_yuv_read[3], + const float q14_yuv_shot[3], + const float correlation[128], + const float luma_strength[5], + const photon::mgc_denoise::DenoiseNoiseBuffers& noise) { + float correlation_min = std::numeric_limits::max(); + float correlation_max = std::numeric_limits::lowest(); + double correlation_sum = 0.0; + for (int index = 0; index < 128; ++index) { + correlation_min = std::min(correlation_min, correlation[index]); + correlation_max = std::max(correlation_max, correlation[index]); + correlation_sum += correlation[index]; + } + const auto luma_sigma_q14 = [&](float normalized_signal) { + const float variance = + std::max( + normalized_yuv_read[0] + + normalized_yuv_shot[0] * normalized_signal + + normalized_yuv_quadratic[0] * normalized_signal * + normalized_signal, + 0.0f); + return std::sqrt(variance) * + static_cast(kWhiteLevel); + }; + __android_log_print( + ANDROID_LOG_INFO, + kLogTag, + "MGC Pecan inputs " + "normalizedRead=[%.6g,%.6g,%.6g] " + "normalizedShot=[%.6g,%.6g,%.6g] " + "normalizedQuadratic=[%.6g,%.6g,%.6g] " + "q14Read=[%.6g,%.6g,%.6g] q14Shot=[%.6g,%.6g,%.6g] " + "lumaSigmaQ14(18%%/50%%)=[%.3f,%.3f] " + "correlation=%.6g..%.6g/%.6g " + "strength=[%.6g,%.6g,%.6g,%.6g,%.6g] " + "read4x2=[%.6g,%.6g,%.6g,%.6g;%.6g,%.6g,%.6g,%.6g] " + "shot4x2=[%.6g,%.6g,%.6g,%.6g;%.6g,%.6g,%.6g,%.6g] " + "outlier=[%.6g,%.6g,%.6g,%.6g,%.6g] " + "revert=[%.6g,%.6g,%.6g,%.6g,%.6g]", + normalized_yuv_read[0], + normalized_yuv_read[1], + normalized_yuv_read[2], + normalized_yuv_shot[0], + normalized_yuv_shot[1], + normalized_yuv_shot[2], + normalized_yuv_quadratic[0], + normalized_yuv_quadratic[1], + normalized_yuv_quadratic[2], + q14_yuv_read[0], + q14_yuv_read[1], + q14_yuv_read[2], + q14_yuv_shot[0], + q14_yuv_shot[1], + q14_yuv_shot[2], + luma_sigma_q14(0.18f), + luma_sigma_q14(0.5f), + correlation_min, + correlation_max, + correlation_sum / 128.0, + luma_strength[0], + luma_strength[1], + luma_strength[2], + luma_strength[3], + luma_strength[4], + noise.read[0], + noise.read[1], + noise.read[2], + noise.read[3], + noise.read[4], + noise.read[5], + noise.read[6], + noise.read[7], + noise.shot[0], + noise.shot[1], + noise.shot[2], + noise.shot[3], + noise.shot[4], + noise.shot[5], + noise.shot[6], + noise.shot[7], + noise.outlier_distance[0], + noise.outlier_distance[1], + noise.outlier_distance[2], + noise.outlier_distance[3], + noise.outlier_distance[4], + noise.revert_factor[0], + noise.revert_factor[1], + noise.revert_factor[2], + noise.revert_factor[3], + noise.revert_factor[4]); +} + +// BoxDownsampleS16Halide (0x4cc8ac8): every plane is the rounded mean of an f x f +// block, round(sum / f^2) via a rounding arithmetic shift. +void BoxDownsamplePlanes( + const int16_t* input, + int width, + int height, + int log2_factor, + int16_t* output) { + const int factor = 1 << log2_factor; + const int output_width = width >> log2_factor; + const int output_height = height >> log2_factor; + const int shift = 2 * log2_factor; + const int64_t rounding = int64_t{1} << (shift - 1); + const size_t input_plane = static_cast(width) * height; + const size_t output_plane = static_cast(output_width) * output_height; + #pragma omp parallel for collapse(2) schedule(static) + for (int channel = 0; channel < 3; ++channel) { + for (int y = 0; y < output_height; ++y) { + const int16_t* source = input + channel * input_plane; + int16_t* destination = output + channel * output_plane + + static_cast(y) * output_width; + for (int x = 0; x < output_width; ++x) { + int64_t sum = 0; + for (int dy = 0; dy < factor; ++dy) { + const int16_t* row = source + + static_cast(y * factor + dy) * width + x * factor; + for (int dx = 0; dx < factor; ++dx) sum += row[dx]; + } + destination[x] = static_cast((sum + rounding) >> shift); + } + } + } +} + +// GCam ChromaMedianFilter (V25 0x4cfb1b8; AGC 9.6 0x4c8d2a8), bit-exact model of +// ChromaDualFivePointMedianFilterS16Halide (type 1) and +// ChromaDualThreePointMedianFilterS16Halide (type 2), verified by emulation: +// Y is copied; U and V each take two medians whose floor average is blended in +// with one shared Q11 weight driven by how much more saturated the centre is. +enum class ChromaMedianFilterType : int { kNone = 0, kDualFivePoint = 1, kDualThreePoint = 2 }; + +inline int16_t Wrap16(int value) { return static_cast(static_cast(value)); } +// NEON abs on int16: abs(-32768) stays -32768. +inline int16_t Abs16(int16_t value) { return Wrap16(value < 0 ? -static_cast(value) : value); } +inline int16_t AbsDiff16(int16_t a, int16_t m) { return Wrap16(Abs16(a) - Abs16(m)); } + +inline int16_t Median3(int16_t a, int16_t b, int16_t c) { + return std::max(std::min(a, b), std::min(std::max(a, b), c)); +} + +inline int16_t Median5(int16_t a, int16_t b, int16_t c, int16_t d, int16_t e) { + int16_t v[5] = {a, b, c, d, e}; + std::sort(v, v + 5); + return v[2]; +} + +void ChromaMedianFilter( + ChromaMedianFilterType type, + const int16_t* input, + int width, + int height, + int16_t* output) { + const size_t plane = static_cast(width) * height; + std::copy_n(input, plane, output); + const int16_t* u_plane = input + plane; + const int16_t* v_plane = input + 2 * plane; + #pragma omp parallel for schedule(static) + for (int y = 0; y < height; ++y) { + const int ym = std::max(y - 1, 0); + const int yp = std::min(y + 1, height - 1); + for (int x = 0; x < width; ++x) { + const int xm = std::max(x - 1, 0); + const int xp = std::min(x + 1, width - 1); + const auto at = [&](const int16_t* p, int yy, int xx) { + return p[static_cast(yy) * width + xx]; + }; + int16_t median_a[2]; + int16_t median_b[2]; + int16_t centre[2]; + const int16_t* planes[2] = {u_plane, v_plane}; + for (int c = 0; c < 2; ++c) { + const int16_t* p = planes[c]; + centre[c] = at(p, y, x); + if (type == ChromaMedianFilterType::kDualFivePoint) { + median_a[c] = Median5(centre[c], at(p, ym, x), at(p, yp, x), + at(p, y, xm), at(p, y, xp)); + median_b[c] = Median5(centre[c], at(p, ym, xm), at(p, ym, xp), + at(p, yp, xm), at(p, yp, xp)); + } else { + median_a[c] = Median3(at(p, y, xm), centre[c], at(p, y, xp)); + median_b[c] = Median3(at(p, ym, x), centre[c], at(p, yp, x)); + } + } + int16_t average[2]; + for (int c = 0; c < 2; ++c) { + average[c] = static_cast( + (static_cast(median_a[c]) + median_b[c]) >> 1); + } + int16_t excess; + if (type == ChromaMedianFilterType::kDualFivePoint) { + excess = std::max(AbsDiff16(centre[0], average[0]), + AbsDiff16(centre[1], average[1])); + } else { + excess = std::min( + std::max(AbsDiff16(centre[0], median_a[0]), + AbsDiff16(centre[1], median_a[1])), + std::max(AbsDiff16(centre[0], median_b[0]), + AbsDiff16(centre[1], median_b[1]))); + } + const int weight = std::clamp( + std::clamp(static_cast(excess) + 1024, -32768, 32767), 0, 2047); + const size_t index = static_cast(y) * width + x; + for (int c = 0; c < 2; ++c) { + const int16_t d = Wrap16(average[c] - centre[c]); + const int delta = (static_cast(d) * weight + 1024) >> 11; + output[(c + 1) * plane + index] = Wrap16(centre[c] + delta); + } + } + } +} + +// Adds the low-frequency chroma correction back to the full-resolution Cb/Cr +// planes. The renderer derives its chroma from a box-downsampled copy of this +// output (GuidedUpsample takes chroma only from the low-resolution image, as in +// GCam), so storing the correction at full resolution makes that copy carry the +// low-frequency ChromaDenoise result, in the DNG and in every later render. +void AddUpsampledChromaCorrection( + const int16_t* low_input, + const int16_t* low_output, + int low_width, + int low_height, + int log2_factor, + int16_t* full, + int width, + int height) { + const float factor = static_cast(1 << log2_factor); + const size_t full_plane = static_cast(width) * height; + const size_t low_plane = static_cast(low_width) * low_height; + #pragma omp parallel for collapse(2) schedule(static) + for (int channel = 1; channel < 3; ++channel) { + for (int y = 0; y < height; ++y) { + const float low_y = std::clamp( + (static_cast(y) + 0.5f) / factor - 0.5f, + 0.0f, + static_cast(low_height - 1)); + const int y0 = static_cast(low_y); + const int y1 = std::min(y0 + 1, low_height - 1); + const float fy = low_y - static_cast(y0); + const size_t base = channel * low_plane; + int16_t* row = full + channel * full_plane + static_cast(y) * width; + for (int x = 0; x < width; ++x) { + const float low_x = std::clamp( + (static_cast(x) + 0.5f) / factor - 0.5f, + 0.0f, + static_cast(low_width - 1)); + const int x0 = static_cast(low_x); + const int x1 = std::min(x0 + 1, low_width - 1); + const float fx = low_x - static_cast(x0); + const auto delta = [&](int lx, int ly) { + const size_t index = base + static_cast(ly) * low_width + lx; + return static_cast(low_output[index]) - + static_cast(low_input[index]); + }; + const float correction = + (1.0f - fy) * ((1.0f - fx) * delta(x0, y0) + fx * delta(x1, y0)) + + fy * ((1.0f - fx) * delta(x0, y1) + fx * delta(x1, y1)); + const float value = static_cast(row[x]) + correction; + row[x] = static_cast( + std::lrint(std::clamp(value, -32768.0f, 32767.0f))); + } + } + } +} + +} // namespace + +namespace photon::mgc_denoise { + +int RunFullResolutionDenoise(const FullResolutionDenoiseRequest& request) { + const int width = request.width; + const int height = request.height; + const int global_origin_x = request.global_origin_x; + const int global_origin_y = request.global_origin_y; + const int full_width = request.full_width; + const int full_height = request.full_height; + const int cfa_pattern = request.cfa_pattern; + const float* lens_shading = request.lens_shading; + const int lens_width = request.lens_width; + const int lens_height = request.lens_height; + const float denoise_response_offset = request.denoise_response_offset; + const float denoise_response_cosine_offset = request.denoise_response_cosine_offset; + const uint16_t* spatial_strength_q8 = request.spatial_strength_q8; + const int spatial_strength_width = request.spatial_strength_width; + const int spatial_strength_height = request.spatial_strength_height; + const int low_frequency_log2_downsample = request.low_frequency_log2_downsample; + const int chroma_median_filter_type = request.chroma_median_filter_type; + const bool run_luma = request.luma_enabled; + const bool run_chroma = request.chroma_enabled; + const bool run_diagnostics = request.diagnostics_enabled; + const bool bayer_input = request.input_is_bayer; + const bool run_measure_moire = request.measure_moire_enabled; + const bool apply_bayer_lens_shading = request.apply_lens_shading_in_bayer_aot; + if (request.rgba == nullptr || width <= 0 || height <= 0 || + full_width <= 0 || full_height <= 0 || + global_origin_x < 0 || global_origin_y < 0 || + global_origin_x + width > full_width || + global_origin_y + height > full_height || + (bayer_input && (cfa_pattern < 0 || cfa_pattern > 3)) || + (run_measure_moire && + (!run_chroma || cfa_pattern < 0 || cfa_pattern > 3)) || + (apply_bayer_lens_shading && !bayer_input) || + (lens_shading != nullptr && (lens_width <= 0 || lens_height <= 0)) || + (spatial_strength_q8 != nullptr && + (spatial_strength_width <= 0 || spatial_strength_height <= 0)) || + !std::isfinite(denoise_response_offset) || + !std::isfinite(denoise_response_cosine_offset) || + (!run_luma && !run_chroma)) { + return -1; + } + uint16_t* rgba = request.rgba; + + float normalized_rgb_shot[3] = {}; + float normalized_rgb_read[3] = {}; + float normalized_rgb_white_balance[3] = {}; + float prepared_normalized_yuv_read[3] = {}; + float luma_strength[5] = {}; + float luma_outlier[5] = {}; + float luma_revert[5] = {}; + float chroma_strength[5] = {}; + float chroma_outlier[5] = {}; + std::copy_n(request.normalized_rgb_shot, 3, normalized_rgb_shot); + std::copy_n(request.normalized_rgb_read, 3, normalized_rgb_read); + std::copy_n(request.normalized_rgb_white_balance, 3, normalized_rgb_white_balance); + std::copy_n(request.luma_strength, 5, luma_strength); + std::copy_n(request.luma_outlier, 5, luma_outlier); + std::copy_n(request.luma_revert, 5, luma_revert); + std::copy_n(request.chroma_strength, 5, chroma_strength); + std::copy_n(request.chroma_outlier, 5, chroma_outlier); + const bool has_prepared_yuv_noise = request.has_prepared_yuv_noise; + if (has_prepared_yuv_noise && bayer_input) return -1; + std::copy_n(request.prepared_normalized_yuv_read, 3, prepared_normalized_yuv_read); + const float prepared_normalized_luma_shot = request.prepared_normalized_luma_shot; + const float prepared_normalized_luma_quadratic = + request.prepared_normalized_luma_quadratic; + const float prepared_normalized_chroma_shot = request.prepared_normalized_chroma_shot; + const float prepared_normalized_chroma_quadratic = + request.prepared_normalized_chroma_quadratic; + if (has_prepared_yuv_noise && + (!std::isfinite(prepared_normalized_luma_shot) || + prepared_normalized_luma_shot < 0.0f || + !std::isfinite(prepared_normalized_luma_quadratic) || + prepared_normalized_luma_quadratic < 0.0f || + !std::isfinite(prepared_normalized_chroma_shot) || + prepared_normalized_chroma_shot < 0.0f || + !std::isfinite(prepared_normalized_chroma_quadratic) || + prepared_normalized_chroma_quadratic < 0.0f)) { + return -1; + } + for (int channel = 0; channel < 3; ++channel) { + if (!std::isfinite(normalized_rgb_white_balance[channel]) || + normalized_rgb_white_balance[channel] <= 0.0f) { + return -1; + } + if (has_prepared_yuv_noise && + (!std::isfinite(prepared_normalized_yuv_read[channel]) || + prepared_normalized_yuv_read[channel] < 0.0f)) { + return -1; + } + } + + float luma_correlation[128]; + float chroma_correlation[128]; + std::copy_n(request.luma_correlation, 128, luma_correlation); + std::copy_n(request.chroma_correlation, 128, chroma_correlation); + for (int index = 0; index < 128; ++index) { + if (!std::isfinite(luma_correlation[index]) || luma_correlation[index] < 0.0f || + !std::isfinite(chroma_correlation[index]) || chroma_correlation[index] < 0.0f) { + return -1; + } + } + + const int padded_width = RoundUp(width, 128); + const int padded_height = RoundUp(height, 16); + const int strength_width = padded_width / 4; + const int strength_height = padded_height / 4; + const size_t pixel_count = + static_cast(padded_width) * padded_height; + const size_t strength_count = + static_cast(strength_width) * strength_height; + const int host_worker_count = HostWorkerCount(); + + using StageClock = std::chrono::steady_clock; + const auto elapsed_ms = [](StageClock::time_point start) -> int64_t { + return std::chrono::duration_cast( + StageClock::now() - start).count(); + }; + const auto total_start = StageClock::now(); + int64_t allocation_ms = 0; + int64_t input_pack_ms = 0; + int64_t strength_ms = 0; + int64_t demoire_ms = 0; + int64_t rgb_to_yuv_ms = 0; + int64_t chroma_ms = 0; + int64_t pecan_ms = 0; + int64_t diagnostics_ms = 0; + int64_t yuv_to_rgb_ms = 0; + int64_t output_pack_ms = 0; + try { + // Two zero-initialized planar allocations are reused across RGB -> YUV, chroma, + // Pecan luma and YUV -> RGB. The lifted AOT kernels may use untouched output regions as + // deterministic boundary state, so initialization is part of this buffer contract. + const auto allocation_start = StageClock::now(); + const size_t planar_sample_count = pixel_count * 3; + // Array make_unique value-initializes every sample before returning. + // Allocate without initialization so the explicit parallel clear below + // is the only full-buffer zeroing pass. + std::unique_ptr planar_a( + new int16_t[planar_sample_count]); + std::unique_ptr planar_b( + new int16_t[planar_sample_count]); + ZeroPlanarBuffers( + planar_a.get(), + planar_b.get(), + planar_sample_count, + host_worker_count); + allocation_ms = elapsed_ms(allocation_start); + const auto input_pack_start = StageClock::now(); + if (bayer_input) { + // BayerRawToYuv's exact input contract is a 3D U16 buffer whose + // four planes are the spatial positions in each 2x2 Bayer cell. + // Pack into planar_a's first pixel_count samples so this does not + // require another full-resolution allocation. + auto* packed_bayer = + reinterpret_cast(planar_a.get()); + const int packed_width = padded_width / 2; + const int packed_height = padded_height / 2; + const size_t packed_plane_size = + static_cast(packed_width) * packed_height; +#pragma omp parallel for schedule(static) num_threads(host_worker_count) + for (int packed_y = 0; packed_y < packed_height; ++packed_y) { + for (int packed_x = 0; packed_x < packed_width; ++packed_x) { + const size_t packed_index = + static_cast(packed_y) * packed_width + packed_x; + for (int position_y = 0; position_y < 2; ++position_y) { + const int source_y = std::min( + packed_y * 2 + position_y, + height - 1); + for (int position_x = 0; position_x < 2; ++position_x) { + const int source_x = std::min( + packed_x * 2 + position_x, + width - 1); + const int plane = position_y * 2 + position_x; + const uint16_t normalized_u16 = rgba[ + static_cast(source_y) * width + source_x]; + const uint16_t normalized_q14 = + static_cast(std::lround( + static_cast(normalized_u16) * + 16384.0 / 65535.0)); + packed_bayer[ + static_cast(plane) * packed_plane_size + + packed_index] = normalized_q14; + } + } + } + } + } else { + auto* rgb_input = + reinterpret_cast(planar_a.get()); +#pragma omp parallel for schedule(static) num_threads(host_worker_count) + for (int y = 0; y < padded_height; ++y) { + const int source_y = std::min(y, height - 1); + for (int x = 0; x < padded_width; ++x) { + const int source_x = std::min(x, width - 1); + const size_t source_index = + (static_cast(source_y) * width + source_x) * 4; + const size_t destination_index = + static_cast(y) * padded_width + x; + for (int channel = 0; channel < 3; ++channel) { + const float normalized = std::clamp( + std::max( + HalfToFloat(rgba[source_index + channel]), + 0.0f) * + normalized_rgb_white_balance[channel], + 0.0f, + 1.0f); + rgb_input[ + static_cast(channel) * pixel_count + + destination_index] = + static_cast( + std::lround(normalized * kWhiteLevel)); + } + } + } + } + input_pack_ms = elapsed_ms(input_pack_start); + + const auto strength_start = StageClock::now(); + std::vector base_strength(strength_count, 256); + std::vector strength(strength_count * 3, 256); + if (spatial_strength_q8 != nullptr) { + const int expected_full_strength_width = + (full_width + 3) / 4; + const int expected_full_strength_height = + (full_height + 3) / 4; + if (spatial_strength_width != expected_full_strength_width || + spatial_strength_height != expected_full_strength_height) { + return -1; + } + const uint16_t* spatial_strength = spatial_strength_q8; + for (int y = 0; y < strength_height; ++y) { + const int local_pixel_y = std::min(y * 4, height - 1); + const int source_y = std::clamp( + (global_origin_y + local_pixel_y) / 4, + 0, + spatial_strength_height - 1); + for (int x = 0; x < strength_width; ++x) { + const int local_pixel_x = std::min(x * 4, width - 1); + const int source_x = std::clamp( + (global_origin_x + local_pixel_x) / 4, + 0, + spatial_strength_width - 1); + base_strength[ + static_cast(y) * strength_width + x] = + spatial_strength[ + static_cast(source_y) * + spatial_strength_width + + source_x]; + } + } + } else if (spatial_strength_width != 0 || + spatial_strength_height != 0) { + return -1; + } + if (run_diagnostics) { + uint16_t base_strength_min = std::numeric_limits::max(); + uint16_t base_strength_max = 0; + uint64_t base_strength_sum = 0; + for (const uint16_t value : base_strength) { + base_strength_min = std::min(base_strength_min, value); + base_strength_max = std::max(base_strength_max, value); + base_strength_sum += value; + } + __android_log_print( + ANDROID_LOG_INFO, + kLogTag, + "MGC denoise base Spatial strengthQ8=%u..%u/%.3f " + "source=%s logical=%dx%d padded=%dx%d origin=(%d,%d)", + base_strength_min, + base_strength_max, + base_strength.empty() + ? 0.0 + : static_cast(base_strength_sum) / + static_cast(base_strength.size()), + spatial_strength_q8 == nullptr ? "identity" : "spatial-aot", + spatial_strength_width, + spatial_strength_height, + strength_width, + strength_height, + global_origin_x, + global_origin_y); + } + std::vector lens; + if (lens_shading != nullptr && lens_width > 0 && lens_height > 0) { + lens.assign( + lens_shading, + lens_shading + static_cast(lens_width) * lens_height * 4); + const int full_strength_width = RoundUp(full_width, 128) / 4; + const int full_strength_height = RoundUp(full_height, 16) / 4; + const int strength_origin_x = global_origin_x / 4; + const int strength_origin_y = global_origin_y / 4; + const float sample_rate_x = full_strength_width > 1 + ? static_cast(lens_width - 1) / + static_cast(full_strength_width - 1) + : 1.0f; + const float sample_rate_y = full_strength_height > 1 + ? static_cast(lens_height - 1) / + static_cast(full_strength_height - 1) + : 1.0f; + const int strength_result = + photon::mgc_denoise::ComputeStrengthMap( + base_strength.data(), + strength_width, + strength_height, + strength_origin_x, + strength_origin_y, + lens.data(), + lens_width, + lens_height, + sample_rate_x, + sample_rate_y, + strength.data()); + if (strength_result != 0) { + return LogStageFailure("strength_map", strength_result); + } + } else { + if (apply_bayer_lens_shading) return -1; + for (int channel = 0; channel < 3; ++channel) { + std::copy_n( + base_strength.data(), + strength_count, + strength.data() + + static_cast(channel) * strength_count); + } + } + strength_ms = elapsed_ms(strength_start); + + // Exact matrix stored by MGC at libgcastartup.so+0x0d64c24. + constexpr float rgb_to_yuv[9] = { + 0.2125999927520752f, + 0.7152000069618225f, + 0.07219959795475006f, + -0.16245023906230927f, + -0.5464943051338196f, + 0.7089447379112244f, + 0.9999967217445374f, + -0.9083024859428406f, + -0.09169333428144455f, + }; + float scaled_rgb_read[3] = {}; + float scaled_rgb_shot[3] = {}; + float scaled_rgb_quadratic[3] = {}; + float prepared_rgb_read[3] = {}; + float prepared_rgb_shot[3] = {}; + float prepared_rgb_quadratic[3] = {}; + float prepared_luma_correlation[128] = {}; + float prepared_chroma_correlation[128] = {}; + // The input NoiseModel is expressed in normalized, un-white-balanced + // camera RGB: variance(x) = read + shot * x + quadratic * x^2. + // MGC FinishRaw hands the full-resolution denoiser NoiseModel.Scale(2) of + // the white-balanced model: x' = 2 * gain * x, so read' = read * (2 * gain)^2 + // and shot' = shot * (2 * gain), quadratic unchanged. The pixels themselves + // stay unsigned Q14 (RawToYuv maps a flat q to Y = q, measured on device), + // exactly as in MGC: the factor is part of the contract the luma/chroma + // strength curves were tuned against, not a pixel-domain conversion. + constexpr float full_resolution_noise_model_scale = 2.0f; + for (int channel = 0; channel < 3; ++channel) { + const float channel_gain = + normalized_rgb_white_balance[channel] * + full_resolution_noise_model_scale; + scaled_rgb_read[channel] = + std::max(normalized_rgb_read[channel], 0.0f) * + channel_gain * channel_gain; + scaled_rgb_shot[channel] = + std::max(normalized_rgb_shot[channel], 0.0f) * + channel_gain; + } + if (has_prepared_yuv_noise) { + __android_log_print( + ANDROID_LOG_INFO, + kLogTag, + "MGC RGB noise-domain remap bypassed: " + "using measured VGN YUV model"); + } else { + __android_log_print( + ANDROID_LOG_INFO, + kLogTag, + "MGC RGB noise domain input=%s " + "calculationWb=[%.6g,%.6g,%.6g] " + "read=[%.6g,%.6g,%.6g]->[%.6g,%.6g,%.6g] " + "shot=[%.6g,%.6g,%.6g]->[%.6g,%.6g,%.6g]", + bayer_input ? "BAYER" : "CAMERA_RGBA16F", + normalized_rgb_white_balance[0], + normalized_rgb_white_balance[1], + normalized_rgb_white_balance[2], + normalized_rgb_read[0], + normalized_rgb_read[1], + normalized_rgb_read[2], + scaled_rgb_read[0], + scaled_rgb_read[1], + scaled_rgb_read[2], + normalized_rgb_shot[0], + normalized_rgb_shot[1], + normalized_rgb_shot[2], + scaled_rgb_shot[0], + scaled_rgb_shot[1], + scaled_rgb_shot[2]); + } + if (bayer_input) { + float correlation_mean = 0.0f; + if (!photon::mgc_denoise::PrepareDefaultBayerDenoiseNoiseModel( + scaled_rgb_read, + scaled_rgb_shot, + scaled_rgb_quadratic, + luma_correlation, + prepared_rgb_read, + prepared_rgb_shot, + prepared_rgb_quadratic, + prepared_luma_correlation, + &correlation_mean)) { + return LogStageFailure("bayer_noise_model", -1); + } + // The default Bayer path receives one upstream Spatial spectrum. Its fixed demosaic + // remap is channel-independent, so the chroma spectrum has the same propagated shape. + std::copy_n( + prepared_luma_correlation, + 128, + prepared_chroma_correlation); + __android_log_print( + ANDROID_LOG_INFO, + kLogTag, + "MGC Bayer denoise prepare demosaicSharpness=0.1 " + "correlationMean=%.9g " + "rgbRead=[%.6g,%.6g,%.6g] " + "rgbShot=[%.6g,%.6g,%.6g]", + correlation_mean, + prepared_rgb_read[0], + prepared_rgb_read[1], + prepared_rgb_read[2], + prepared_rgb_shot[0], + prepared_rgb_shot[1], + prepared_rgb_shot[2]); + } else { + std::copy_n(scaled_rgb_read, 3, prepared_rgb_read); + std::copy_n(scaled_rgb_shot, 3, prepared_rgb_shot); + std::copy_n(scaled_rgb_quadratic, 3, prepared_rgb_quadratic); + std::copy_n(luma_correlation, 128, prepared_luma_correlation); + std::copy_n(chroma_correlation, 128, prepared_chroma_correlation); + } + float yuv_read[3] = {}; + float yuv_shot[3] = {}; + float yuv_quadratic[3] = {}; + float chroma_shared_shot = 0.0f; + float chroma_shared_quadratic = 0.0f; + if (has_prepared_yuv_noise) { + std::copy_n(prepared_normalized_yuv_read, 3, yuv_read); + yuv_shot[0] = prepared_normalized_luma_shot; + yuv_quadratic[0] = prepared_normalized_luma_quadratic; + yuv_shot[1] = yuv_shot[2] = prepared_normalized_chroma_shot; + yuv_quadratic[1] = yuv_quadratic[2] = + prepared_normalized_chroma_quadratic; + chroma_shared_shot = prepared_normalized_chroma_shot; + chroma_shared_quadratic = prepared_normalized_chroma_quadratic; + __android_log_print( + ANDROID_LOG_INFO, + kLogTag, + "MGC VGN prepared YUV noise " + "read=[%.6g,%.6g,%.6g] lumaShot=%.6g lumaQuadratic=%.6g " + "chromaShot=%.6g chromaQuadratic=%.6g", + yuv_read[0], + yuv_read[1], + yuv_read[2], + yuv_shot[0], + yuv_quadratic[0], + yuv_shot[1], + yuv_quadratic[1]); + } else { + for (int output_channel = 0; output_channel < 3; ++output_channel) { + float row_sum = 0.0f; + for (int input_channel = 0; input_channel < 3; ++input_channel) { + const float matrix_value = + rgb_to_yuv[output_channel * 3 + input_channel]; + const float matrix_squared = matrix_value * matrix_value; + row_sum += matrix_value; + yuv_read[output_channel] += + matrix_squared * prepared_rgb_read[input_channel]; + yuv_shot[output_channel] += + matrix_squared * prepared_rgb_shot[input_channel]; + yuv_quadratic[output_channel] += + matrix_squared * prepared_rgb_quadratic[input_channel]; + } + // NoiseModel::Transform at 0x5e985d8 keeps read variance in + // the matrix output domain, but normalizes the signal-dependent + // coefficients by the row's signal scale. Zero-sum chroma rows + // therefore have no independent shot/quadratic coefficient. + const float absolute_row_sum = std::abs(row_sum); + if (absolute_row_sum < 1.0e-6f) { + yuv_shot[output_channel] = 0.0f; + yuv_quadratic[output_channel] = 0.0f; + } else { + yuv_shot[output_channel] /= absolute_row_sum; + yuv_quadratic[output_channel] /= + absolute_row_sum * absolute_row_sum; + } + } + // CreateChromaDenoiseNoiseModelBuffers preserves all three read channels, then + // slices channel 0 from the shot and quadratic buffers before invoking CompleteS16. + // Keep the analytic Y/Cb/Cr model intact and reproduce that exact slice here. + chroma_shared_shot = yuv_shot[0]; + chroma_shared_quadratic = yuv_quadratic[0]; + __android_log_print( + ANDROID_LOG_INFO, + kLogTag, + "MGC analytic YUV noise read=[%.6g,%.6g,%.6g] " + "lumaShot=%.6g lumaQuadratic=%.6g " + "chromaSharedChannel0Shot=%.6g " + "chromaSharedChannel0Quadratic=%.6g", + yuv_read[0], + yuv_read[1], + yuv_read[2], + yuv_shot[0], + yuv_quadratic[0], + chroma_shared_shot, + chroma_shared_quadratic); + } + // RgbRawToYuv emits Q14 S16 samples. Pecan's generated arithmetic + // consumes variance = read + shot * sample + quadratic * sample^2 in + // that same sample domain; it does not rescale normalized + // coefficients internally. Convert the normalized NoiseModel once + // at this boundary: read variance scales by white^2, shot by white, + // while the dimensionless quadratic factor is unchanged. + constexpr float white = static_cast(kWhiteLevel); + constexpr float white_squared = white * white; + float q14_yuv_read[3] = {}; + float q14_yuv_shot[3] = {}; + for (int channel = 0; channel < 3; ++channel) { + q14_yuv_read[channel] = yuv_read[channel] * white_squared; + q14_yuv_shot[channel] = yuv_shot[channel] * white; + } + const float q14_chroma_shared_shot = chroma_shared_shot * white; + __android_log_print( + ANDROID_LOG_INFO, + kLogTag, + "MGC Q14 denoise noise luma=[read=%.6g shot=%.6g quadratic=%.6g] " + "chroma=[read=%.6g,%.6g,%.6g sharedShot=%.6g sharedQuadratic=%.6g]", + q14_yuv_read[0], + q14_yuv_shot[0], + yuv_quadratic[0], + q14_yuv_read[0], + q14_yuv_read[1], + q14_yuv_read[2], + q14_chroma_shared_shot, + chroma_shared_quadratic); + + const auto rgb_to_yuv_start = StageClock::now(); + int rgb_to_yuv_result = 0; + if (bayer_input) { + const float bayer_channel_gains[4] = { + normalized_rgb_white_balance[0], + normalized_rgb_white_balance[1], + normalized_rgb_white_balance[1], + normalized_rgb_white_balance[2], + }; + rgb_to_yuv_result = + photon::mgc_denoise::RunDefaultBayerRawToYuv( + reinterpret_cast(planar_a.get()), + padded_width, + padded_height, + cfa_pattern, + bayer_channel_gains, + apply_bayer_lens_shading && !lens.empty() + ? lens.data() + : nullptr, + apply_bayer_lens_shading ? lens_width : 0, + apply_bayer_lens_shading ? lens_height : 0, + !apply_bayer_lens_shading || lens.empty() || width <= 1 + ? 1.0f + : static_cast(lens_width - 1) / + static_cast(width - 1), + !apply_bayer_lens_shading || lens.empty() || height <= 1 + ? 1.0f + : static_cast(lens_height - 1) / + static_cast(height - 1), + planar_b.get()); + } else { + rgb_to_yuv_result = photon::mgc_denoise::RunRgbRawToYuv( + reinterpret_cast(planar_a.get()), + padded_width, + padded_height, + planar_b.get()); + } + if (rgb_to_yuv_result != 0) { + return LogStageFailure("rgb_to_yuv", rgb_to_yuv_result); + } + rgb_to_yuv_ms = elapsed_ms(rgb_to_yuv_start); + + // MGC invokes MeasureMoire after RawToYuv and passes a channel-0 slice + // of linear_yuv. The lifted AOT contract therefore sees one planar + // S16/Q14 Y channel, not the Bayer mosaic. Its output replaces only + // the strength map supplied to ChromaDenoise; Pecan keeps strength. + std::vector demoire_strength; + const uint16_t* chroma_strength_q8 = strength.data(); + if (run_measure_moire) { + const auto demoire_start = StageClock::now(); + demoire_strength.resize(strength_count * 3); + const int demoire_result = + photon::mgc_denoise::RunMeasureMoireS16( + planar_b.get(), + padded_width, + padded_height, + strength.data(), + strength_width, + strength_height, + demoire_strength.data()); + if (demoire_result != 0) { + return LogStageFailure("measure_moire", demoire_result); + } + if (run_diagnostics) { + LogMeasureMoireDiagnostics( + strength.data(), + demoire_strength.data(), + strength_count); + } + chroma_strength_q8 = demoire_strength.data(); + demoire_ms = elapsed_ms(demoire_start); + } + + // GCam ProcessRaw order: Pecan denoises luma first, its Y is copied back into + // linear_yuv (slice(2, 0).copy_from), and ChromaDenoise then runs on + // [denoised Y, Cb, Cr], so the chroma pyramid sees a clean luma plane instead + // of the noisy RawToYuv Y. MeasureMoire above still reads the RawToYuv Y. + if (run_luma) { + const auto pecan_start = StageClock::now(); + photon::mgc_denoise::DenoiseNoiseBuffers luma_noise; + if (!photon::mgc_denoise::BuildNoiseBuffers( + q14_yuv_read[0], + q14_yuv_shot[0], + yuv_quadratic[0], + prepared_luma_correlation, + denoise_response_offset, + denoise_response_cosine_offset, + luma_strength, + luma_outlier, + luma_revert, + &luma_noise)) { + return LogStageFailure("luma_noise_model", -1); + } + if (run_diagnostics) { + LogPecanInputs( + yuv_read, + yuv_shot, + yuv_quadratic, + q14_yuv_read, + q14_yuv_shot, + prepared_luma_correlation, + luma_strength, + luma_noise); + } + const int pecan_result = photon::mgc_denoise::RunPecan( + strength.data(), + strength_width, + strength_height, + luma_noise, + planar_b.get(), + padded_width, + padded_height, + planar_a.get()); + if (pecan_result != 0) { + return LogStageFailure("pecan_luma", pecan_result); + } + pecan_ms = elapsed_ms(pecan_start); + } else { + // Luma denoise disabled: keep the RawToYuv Y. + std::copy_n(planar_b.get(), pixel_count, planar_a.get()); + } + + // planar_a's Y is final from here on; ChromaDenoise owns only Cb/Cr. + std::copy_n(planar_a.get(), pixel_count, planar_b.get()); + + if (run_chroma) { + const auto chroma_start = StageClock::now(); + photon::mgc_denoise::ChromaDenoiseNoiseBuffers chroma_noise; + if (!photon::mgc_denoise::BuildChromaNoiseBuffers( + q14_yuv_read, + q14_chroma_shared_shot, + chroma_shared_quadratic, + prepared_chroma_correlation, + denoise_response_offset, + denoise_response_cosine_offset, + chroma_strength, + chroma_outlier, + &chroma_noise)) { + return LogStageFailure("chroma_noise_model", -1); + } + const int chroma_result = + photon::mgc_denoise::RunChromaDenoise( + planar_b.get(), + padded_width, + padded_height, + chroma_strength_q8, + strength_width, + strength_height, + chroma_noise, + planar_a.get()); + if (chroma_result != 0) { + return LogStageFailure("chroma_pyramid", chroma_result); + } + chroma_ms = elapsed_ms(chroma_start); + } + + if (!run_chroma) { + std::copy_n( + planar_b.get() + pixel_count, + pixel_count * 2, + planar_a.get() + pixel_count); + } + + // GCam ProcessRaw low-frequency branch: BoxDownsample of [Pecan Y, + // chroma-denoised Cb/Cr] by 2^L, the model box-downsampled L times + // (0x5e99434), then ChromaDenoise again with the same tuning and the same + // RAW/4 strength map (decimation 2 - L, downsample factor L). The pyramid + // at 1/2^L resolution reaches the coarse chroma blotches the + // full-resolution pyramid cannot. It needs the whole image, not a tile. + const int low_frequency_log2 = low_frequency_log2_downsample; + const bool whole_image = global_origin_x == 0 && global_origin_y == 0 && + width == full_width && height == full_height; + if (run_chroma && low_frequency_log2 > 0 && whole_image) { + const auto low_start = StageClock::now(); + const int low_width = padded_width >> low_frequency_log2; + const int low_height = padded_height >> low_frequency_log2; + const size_t low_count = + static_cast(low_width) * low_height * 3; + std::vector low_input(low_count); + std::vector low_output(low_count); + std::vector low_median; + BoxDownsamplePlanes( + planar_a.get(), + padded_width, + padded_height, + low_frequency_log2, + low_input.data()); + const auto median_type = + static_cast(chroma_median_filter_type); + if (median_type != ChromaMedianFilterType::kNone) { + // ProcessLowFrequency (0x4694fbc): the median replaces ds_linear_yuv + // before the low-frequency ChromaDenoise. + std::vector filtered(low_count); + ChromaMedianFilter( + median_type, low_input.data(), low_width, low_height, filtered.data()); + low_median = std::move(filtered); + } + const int16_t* low_denoise_input = + low_median.empty() ? low_input.data() : low_median.data(); + float low_read[3] = {q14_yuv_read[0], q14_yuv_read[1], q14_yuv_read[2]}; + float low_shot = q14_chroma_shared_shot; + float low_quadratic = chroma_shared_quadratic; + float low_spectrum[128]; + std::copy_n(prepared_chroma_correlation, 128, low_spectrum); + if (!photon::mgc_denoise::BoxDownsampleNoiseModel( + low_frequency_log2, + low_read, + &low_shot, + &low_quadratic, + low_spectrum)) { + return LogStageFailure("low_frequency_noise_model", -1); + } + photon::mgc_denoise::ChromaDenoiseNoiseBuffers low_noise; + if (!photon::mgc_denoise::BuildChromaNoiseBuffers( + low_read, + low_shot, + low_quadratic, + low_spectrum, + denoise_response_offset, + denoise_response_cosine_offset, + chroma_strength, + chroma_outlier, + &low_noise)) { + return LogStageFailure("low_frequency_chroma_noise_model", -1); + } + const int low_result = photon::mgc_denoise::RunChromaDenoise( + low_denoise_input, + low_width, + low_height, + chroma_strength_q8, + strength_width, + strength_height, + low_noise, + low_output.data(), + 2 - low_frequency_log2, + low_frequency_log2); + if (low_result != 0) { + return LogStageFailure("low_frequency_chroma_pyramid", low_result); + } + AddUpsampledChromaCorrection( + low_input.data(), + low_output.data(), + low_width, + low_height, + low_frequency_log2, + planar_a.get(), + padded_width, + padded_height); + __android_log_print( + ANDROID_LOG_INFO, + kLogTag, + "MGC low-frequency chroma denoise factor=%dx size=%dx%d median=%d " + "read=[%.6g,%.6g,%.6g] shot=%.6g quadratic=%.6g took=%lldms", + 1 << low_frequency_log2, + low_width, + low_height, + chroma_median_filter_type, + low_read[0], + low_read[1], + low_read[2], + low_shot, + low_quadratic, + static_cast(elapsed_ms(low_start))); + } else if (run_chroma && low_frequency_log2 > 0) { + __android_log_print( + ANDROID_LOG_WARN, + kLogTag, + "MGC low-frequency chroma denoise skipped for tile origin=(%d,%d) " + "size=%dx%d full=%dx%d", + global_origin_x, + global_origin_y, + width, + height, + full_width, + full_height); + } + + if (run_diagnostics) { + // planar_b's Y already holds the Pecan output, so this delta covers Cb/Cr + // only; the luma change is reflected in the Pecan stage timing/inputs. + const auto diagnostics_start = StageClock::now(); + const auto output_delta = MeasurePlanarDelta( + planar_b.get(), + planar_a.get(), + width, + height, + padded_width, + pixel_count); + LogDenoiseDiagnostics( + strength.data(), + strength_count, + output_delta); + diagnostics_ms = elapsed_ms(diagnostics_start); + } + + // This boundary returns linear camera RGB to Photon. The original MGC pipeline only + // sharpened after tone mapping; Photon now performs final sharpening in its GLES output + // chain. Calling the former U12 kernel here would clamp Q14 samples at 4095 and corrupt + // exposure and saturation, so the matching operation at this boundary is YuvToRgb. + const auto yuv_to_rgb_start = StageClock::now(); + const int yuv_to_rgb_result = + photon::mgc_denoise::RunYuvToRgb( + planar_a.get(), + padded_width, + padded_height, + planar_b.get()); + if (yuv_to_rgb_result != 0) { + return LogStageFailure("yuv_to_rgb", yuv_to_rgb_result); + } + yuv_to_rgb_ms = elapsed_ms(yuv_to_rgb_start); + + const auto output_pack_start = StageClock::now(); +#pragma omp parallel for schedule(static) num_threads(host_worker_count) + for (int y = 0; y < height; ++y) { + for (int x = 0; x < width; ++x) { + const size_t source_index = + static_cast(y) * padded_width + x; + const size_t destination_index = + (static_cast(y) * width + x) * 4; + for (int channel = 0; channel < 3; ++channel) { + const float normalized = + static_cast( + planar_b[ + static_cast(channel) * pixel_count + + source_index]) / + static_cast(kWhiteLevel) / + normalized_rgb_white_balance[channel]; + rgba[destination_index + channel] = + FloatToHalf(normalized); + } + rgba[destination_index + 3] = FloatToHalf(1.0f); + } + } + output_pack_ms = elapsed_ms(output_pack_start); + __android_log_print( + ANDROID_LOG_INFO, + kLogTag, + "MGC denoise stages hostWorkers=%d allocation=%lldms inputPack=%lldms strength=%lldms " + "demoire=%lldms rgbToYuv=%lldms chroma=%lldms pecan=%lldms diagnostics=%lldms " + "yuvToRgb=%lldms outputPack=%lldms total=%lldms", + host_worker_count, + static_cast(allocation_ms), + static_cast(input_pack_ms), + static_cast(strength_ms), + static_cast(demoire_ms), + static_cast(rgb_to_yuv_ms), + static_cast(chroma_ms), + static_cast(pecan_ms), + static_cast(diagnostics_ms), + static_cast(yuv_to_rgb_ms), + static_cast(output_pack_ms), + static_cast(elapsed_ms(total_start))); + return 0; + } catch (const std::bad_alloc&) { + return LogStageFailure("allocation", -2); + } +} + + + +int RunLowFrequencyChromaCorrection(const LowFrequencyChromaRequest& request) { + const int log2_factor = request.log2_downsample; + // RunChromaDenoise reads the RAW/4 strength map at decimation 2 - L. + if (request.rgba == nullptr || log2_factor < 1 || log2_factor > 2 || + request.full_width <= 0 || request.full_height <= 0 || + request.low_width != (request.full_width + (1 << log2_factor) - 1) >> log2_factor || + request.low_height != (request.full_height + (1 << log2_factor) - 1) >> log2_factor || + (request.spatial_strength_q8 != nullptr && + (request.spatial_strength_width != (request.full_width + 3) / 4 || + request.spatial_strength_height != (request.full_height + 3) / 4)) || + !std::isfinite(request.denoise_response_offset) || + !std::isfinite(request.denoise_response_cosine_offset)) { + return -1; + } + for (int channel = 0; channel < 3; ++channel) { + if (!std::isfinite(request.prepared_normalized_yuv_read[channel]) || + request.prepared_normalized_yuv_read[channel] < 0.0f) { + return -1; + } + } + if (!std::isfinite(request.prepared_normalized_chroma_shot) || + request.prepared_normalized_chroma_shot < 0.0f || + !std::isfinite(request.prepared_normalized_chroma_quadratic) || + request.prepared_normalized_chroma_quadratic < 0.0f) { + return -1; + } + // The same padded geometry as the in-call branch: the low image is the padded + // full-resolution frame box-downsampled by 2^L, the strength map its quarter. + const int padded_width = RoundUp(request.full_width, 128); + const int padded_height = RoundUp(request.full_height, 16); + const int low_width = padded_width >> log2_factor; + const int low_height = padded_height >> log2_factor; + const int strength_width = padded_width / 4; + const int strength_height = padded_height / 4; + const size_t low_plane = static_cast(low_width) * low_height; + const size_t strength_count = static_cast(strength_width) * strength_height; + try { + std::vector strength(strength_count * 3, 256); + if (request.spatial_strength_q8 != nullptr) { + for (int y = 0; y < strength_height; ++y) { + const int source_y = std::clamp( + std::min(y * 4, request.full_height - 1) / 4, + 0, + request.spatial_strength_height - 1); + for (int x = 0; x < strength_width; ++x) { + const int source_x = std::clamp( + std::min(x * 4, request.full_width - 1) / 4, + 0, + request.spatial_strength_width - 1); + const uint16_t value = request.spatial_strength_q8[ + static_cast(source_y) * request.spatial_strength_width + source_x]; + for (int plane = 0; plane < 3; ++plane) { + strength[plane * strength_count + + static_cast(y) * strength_width + x] = value; + } + } + } + } + + std::vector packed(low_plane * 3); + for (int y = 0; y < low_height; ++y) { + const int source_y = std::min(y, request.low_height - 1); + for (int x = 0; x < low_width; ++x) { + const int source_x = std::min(x, request.low_width - 1); + const size_t source = (static_cast(source_y) * request.low_width + source_x) * 4; + for (int channel = 0; channel < 3; ++channel) { + const float normalized = std::clamp( + HalfToFloat(request.rgba[source + channel]), 0.0f, 1.0f); + packed[channel * low_plane + static_cast(y) * low_width + x] = + static_cast(std::lround(normalized * kWhiteLevel)); + } + } + } + std::vector low_input(low_plane * 3); + const int to_yuv = RunRgbRawToYuv(packed.data(), low_width, low_height, low_input.data()); + if (to_yuv != 0) return LogStageFailure("low_frequency_rgb_to_yuv", to_yuv); + + constexpr float white = static_cast(kWhiteLevel); + float low_read[3]; + for (int channel = 0; channel < 3; ++channel) { + low_read[channel] = request.prepared_normalized_yuv_read[channel] * white * white; + } + float low_shot = request.prepared_normalized_chroma_shot * white; + float low_quadratic = request.prepared_normalized_chroma_quadratic; + float low_spectrum[128]; + std::copy_n(request.chroma_correlation, 128, low_spectrum); + if (!BoxDownsampleNoiseModel(log2_factor, low_read, &low_shot, &low_quadratic, low_spectrum)) { + return LogStageFailure("low_frequency_noise_model", -1); + } + ChromaDenoiseNoiseBuffers noise; + if (!BuildChromaNoiseBuffers( + low_read, + low_shot, + low_quadratic, + low_spectrum, + request.denoise_response_offset, + request.denoise_response_cosine_offset, + request.chroma_strength, + request.chroma_outlier, + &noise)) { + return LogStageFailure("low_frequency_chroma_noise_model", -1); + } + std::vector median; + const auto median_type = + static_cast(request.chroma_median_filter_type); + if (median_type != ChromaMedianFilterType::kNone) { + median.resize(low_plane * 3); + ChromaMedianFilter(median_type, low_input.data(), low_width, low_height, median.data()); + } + std::vector low_output(low_plane * 3); + const int denoise = RunChromaDenoise( + median.empty() ? low_input.data() : median.data(), + low_width, + low_height, + strength.data(), + strength_width, + strength_height, + noise, + low_output.data(), + 2 - log2_factor, + log2_factor); + if (denoise != 0) return LogStageFailure("low_frequency_chroma_pyramid", denoise); + + // The correction is the Cb/Cr change against the un-medianed input (as the in-call + // branch adds it); Y is unchanged. Both sides go through MGC's YuvToRgb. + std::copy_n(low_input.data(), low_plane, low_output.data()); + std::vector rgb_before(low_plane * 3); + std::vector rgb_after(low_plane * 3); + int to_rgb = RunYuvToRgb(low_input.data(), low_width, low_height, rgb_before.data()); + if (to_rgb == 0) { + to_rgb = RunYuvToRgb(low_output.data(), low_width, low_height, rgb_after.data()); + } + if (to_rgb != 0) return LogStageFailure("low_frequency_yuv_to_rgb", to_rgb); + for (int y = 0; y < request.low_height; ++y) { + for (int x = 0; x < request.low_width; ++x) { + const size_t pixel = static_cast(y) * low_width + x; + const size_t destination = (static_cast(y) * request.low_width + x) * 4; + for (int channel = 0; channel < 3; ++channel) { + const size_t index = channel * low_plane + pixel; + const float delta = + (static_cast(rgb_after[index]) - static_cast(rgb_before[index])) / + white; + request.rgba[destination + channel] = FloatToHalf(delta); + } + request.rgba[destination + 3] = FloatToHalf(0.0f); + } + } + __android_log_print( + ANDROID_LOG_INFO, + kLogTag, + "MGC low-frequency chroma correction factor=%dx low=%dx%d median=%d " + "read=[%.6g,%.6g,%.6g] shot=%.6g quadratic=%.6g", + 1 << log2_factor, + low_width, + low_height, + request.chroma_median_filter_type, + low_read[0], + low_read[1], + low_read[2], + low_shot, + low_quadratic); + return 0; + } catch (const std::bad_alloc&) { + return LogStageFailure("low_frequency_allocation", -2); + } +} + +} // namespace photon::mgc_denoise diff --git a/app/src/main/cpp/mgc_denoise_static/mgc_full_resolution_denoise.h b/app/src/main/cpp/mgc_denoise_static/mgc_full_resolution_denoise.h new file mode 100644 index 00000000..bd75a04a --- /dev/null +++ b/app/src/main/cpp/mgc_denoise_static/mgc_full_resolution_denoise.h @@ -0,0 +1,94 @@ +#pragma once + +#include + +namespace photon::mgc_denoise { + +/** + * One MGC full-resolution luma/chroma denoise call on an RGBA16F (or normalized + * Bayer16) buffer. Every array is owned by the caller and must outlive the call. + * Kept free of JNI so the app, offline calibration and oracle tools share it. + */ +struct FullResolutionDenoiseRequest { + // In/out pixels: width * height * 4 half floats (or Bayer16 samples). + uint16_t* rgba = nullptr; + int width = 0; + int height = 0; + int global_origin_x = 0; + int global_origin_y = 0; + int full_width = 0; + int full_height = 0; + bool input_is_bayer = false; + int cfa_pattern = 0; + bool measure_moire_enabled = false; + bool apply_lens_shading_in_bayer_aot = false; + // lens_width * lens_height * 4 gains, or null. + const float* lens_shading = nullptr; + int lens_width = 0; + int lens_height = 0; + float normalized_rgb_shot[3] = {}; + float normalized_rgb_read[3] = {}; + float normalized_rgb_white_balance[3] = {1.0f, 1.0f, 1.0f}; + bool has_prepared_yuv_noise = false; + float prepared_normalized_yuv_read[3] = {}; + float prepared_normalized_luma_shot = 0.0f; + float prepared_normalized_luma_quadratic = 0.0f; + float prepared_normalized_chroma_shot = 0.0f; + float prepared_normalized_chroma_quadratic = 0.0f; + float luma_correlation[128] = {}; + float chroma_correlation[128] = {}; + float denoise_response_offset = 0.0f; + float denoise_response_cosine_offset = 0.0f; + // spatial_strength_width * spatial_strength_height Q8 values over the full image, or null. + const uint16_t* spatial_strength_q8 = nullptr; + int spatial_strength_width = 0; + int spatial_strength_height = 0; + bool luma_enabled = false; + bool chroma_enabled = false; + float luma_strength[5] = {}; + float luma_outlier[5] = {}; + float luma_revert[5] = {}; + float chroma_strength[5] = {}; + float chroma_outlier[5] = {}; + bool diagnostics_enabled = false; + int low_frequency_log2_downsample = 0; + int chroma_median_filter_type = 0; +}; + +/** Returns 0 on success, a negative stage code otherwise. */ +int RunFullResolutionDenoise(const FullResolutionDenoiseRequest& request); + +/** + * GCam ProcessRaw's low-frequency chroma branch as a separate whole-image pass, for callers + * that run the full-resolution denoise in tiles (the in-call branch needs the whole image). + * + * [rgba] holds the full-resolution denoised linear RGB box-downsampled by 2^log2_downsample + * (low_width x low_height = ceil(full / 2^L)), white balance 1. It is replaced in place by the + * linear RGB correction to add at full resolution after bilinear upsampling (alpha 0): the + * difference ChromaDenoise (after the optional chroma median) makes to Cb/Cr at that scale. + */ +struct LowFrequencyChromaRequest { + uint16_t* rgba = nullptr; + int low_width = 0; + int low_height = 0; + int full_width = 0; + int full_height = 0; + int log2_downsample = 1; + float prepared_normalized_yuv_read[3] = {}; + float prepared_normalized_chroma_shot = 0.0f; + float prepared_normalized_chroma_quadratic = 0.0f; + float chroma_correlation[128] = {}; + float denoise_response_offset = 0.0f; + float denoise_response_cosine_offset = 0.0f; + // ((full+3)/4) Q8 strength over the full image, or null for identity. + const uint16_t* spatial_strength_q8 = nullptr; + int spatial_strength_width = 0; + int spatial_strength_height = 0; + float chroma_strength[5] = {}; + float chroma_outlier[5] = {}; + int chroma_median_filter_type = 0; +}; + +int RunLowFrequencyChromaCorrection(const LowFrequencyChromaRequest& request); + +} // namespace photon::mgc_denoise diff --git a/app/src/main/cpp/mgc_denoise_static/mgc_full_resolution_denoise_jni.cpp b/app/src/main/cpp/mgc_denoise_static/mgc_full_resolution_denoise_jni.cpp index e55b0db2..00b00a33 100644 --- a/app/src/main/cpp/mgc_denoise_static/mgc_full_resolution_denoise_jni.cpp +++ b/app/src/main/cpp/mgc_denoise_static/mgc_full_resolution_denoise_jni.cpp @@ -1,549 +1,19 @@ -#include "mgc_denoise_static.h" +#include "mgc_full_resolution_denoise.h" -#include #include -#include #include -#include -#include -#include #include -#include -#include -#include -#include -#include #include namespace { -constexpr int kWhiteLevel = 16383; -constexpr int kHostWorkers = 4; -constexpr char kLogTag[] = "PLog_MgcFullResolutionDenoise"; - -int HostWorkerCount() { - return kHostWorkers; -} - -void ZeroPlanarBuffers( - int16_t* planar_a, - int16_t* planar_b, - size_t sample_count, - int worker_count) { -#pragma omp parallel num_threads(worker_count) - { - const size_t worker = static_cast(omp_get_thread_num()); - const size_t workers = static_cast(omp_get_num_threads()); - const size_t begin = sample_count * worker / workers; - const size_t end = sample_count * (worker + 1) / workers; - const size_t byte_count = (end - begin) * sizeof(int16_t); - std::memset(planar_a + begin, 0, byte_count); - std::memset(planar_b + begin, 0, byte_count); - } -} - -int LogStageFailure(const char* stage, int result) { - __android_log_print( - ANDROID_LOG_ERROR, - kLogTag, - "MGC full-resolution denoise stage=%s failed result=%d", - stage, - result); - return result; -} - -int RoundUp(int value, int multiple) { - return ((value + multiple - 1) / multiple) * multiple; -} - -float HalfToFloat(uint16_t bits) { - _Float16 half = {}; - static_assert(sizeof(half) == sizeof(bits)); - std::memcpy(&half, &bits, sizeof(bits)); - return static_cast(half); -} - -uint16_t FloatToHalf(float value) { - const _Float16 half = static_cast<_Float16>(value); - uint16_t bits = 0; - std::memcpy(&bits, &half, sizeof(bits)); - return bits; -} - -bool CopyFive(JNIEnv* env, jfloatArray source, float output[5]) { - if (source == nullptr || env->GetArrayLength(source) != 5) return false; - env->GetFloatArrayRegion(source, 0, 5, output); +bool CopyFloats(JNIEnv* env, jfloatArray source, jsize count, float* output) { + if (source == nullptr || env->GetArrayLength(source) != count) return false; + env->GetFloatArrayRegion(source, 0, count, output); return !env->ExceptionCheck(); } -bool CopyThree(JNIEnv* env, jfloatArray source, float output[3]) { - if (source == nullptr || env->GetArrayLength(source) != 3) return false; - env->GetFloatArrayRegion(source, 0, 3, output); - return !env->ExceptionCheck(); -} - -struct SampledDelta { - int64_t sample_count = 0; - int64_t changed_count = 0; - double absolute_sum = 0.0; - double squared_sum = 0.0; - int maximum = 0; -}; - -std::array MeasurePlanarDelta( - const int16_t* source, - const int16_t* denoised, - int width, - int height, - int stride, - size_t plane_size) { - std::array result = {}; - constexpr int kSampleStep = 8; - for (int y = 0; y < height; y += kSampleStep) { - for (int x = 0; x < width; x += kSampleStep) { - const size_t pixel = static_cast(y) * stride + x; - for (int channel = 0; channel < 3; ++channel) { - const size_t index = - static_cast(channel) * plane_size + pixel; - const int difference = - static_cast(denoised[index]) - - static_cast(source[index]); - const int absolute = std::abs(difference); - SampledDelta& delta = result[channel]; - ++delta.sample_count; - if (difference != 0) ++delta.changed_count; - delta.absolute_sum += static_cast(absolute); - delta.squared_sum += - static_cast(difference) * difference; - delta.maximum = std::max(delta.maximum, absolute); - } - } - } - return result; -} - -void LogDenoiseDiagnostics( - const uint16_t* strength, - size_t strength_count, - const std::array& delta) { - std::array strength_min = { - std::numeric_limits::max(), - std::numeric_limits::max(), - std::numeric_limits::max(), - }; - std::array strength_max = {}; - std::array strength_sum = {}; - for (int channel = 0; channel < 3; ++channel) { - const uint16_t* plane = - strength + static_cast(channel) * strength_count; - for (size_t index = 0; index < strength_count; ++index) { - const uint16_t value = plane[index]; - strength_min[channel] = - std::min(strength_min[channel], value); - strength_max[channel] = - std::max(strength_max[channel], value); - strength_sum[channel] += value; - } - } - const auto mean_strength = [&](int channel) { - return strength_count > 0 - ? strength_sum[channel] / - static_cast(strength_count) - : 0.0; - }; - const auto changed_percent = [&](int channel) { - return delta[channel].sample_count > 0 - ? 100.0 * static_cast(delta[channel].changed_count) / - static_cast(delta[channel].sample_count) - : 0.0; - }; - const auto mean_absolute = [&](int channel) { - return delta[channel].sample_count > 0 - ? delta[channel].absolute_sum / - static_cast(delta[channel].sample_count) - : 0.0; - }; - const auto rms = [&](int channel) { - return delta[channel].sample_count > 0 - ? std::sqrt( - delta[channel].squared_sum / - static_cast(delta[channel].sample_count)) - : 0.0; - }; - __android_log_print( - ANDROID_LOG_INFO, - kLogTag, - "MGC denoise diagnostics strengthQ8=" - "[%u..%u/%.2f,%u..%u/%.2f,%u..%u/%.2f] " - "delta14 Y=%.2f/%.2f/%d/%.1f%% " - "Cb=%.2f/%.2f/%d/%.1f%% " - "Cr=%.2f/%.2f/%d/%.1f%% samples=%lld", - strength_min[0], - strength_max[0], - mean_strength(0), - strength_min[1], - strength_max[1], - mean_strength(1), - strength_min[2], - strength_max[2], - mean_strength(2), - mean_absolute(0), - rms(0), - delta[0].maximum, - changed_percent(0), - mean_absolute(1), - rms(1), - delta[1].maximum, - changed_percent(1), - mean_absolute(2), - rms(2), - delta[2].maximum, - changed_percent(2), - static_cast(delta[0].sample_count)); -} - -void LogMeasureMoireDiagnostics( - const uint16_t* input, - const uint16_t* output, - size_t plane_size) { - std::array input_min = { - std::numeric_limits::max(), - std::numeric_limits::max(), - std::numeric_limits::max(), - }; - std::array input_max = {}; - std::array output_min = input_min; - std::array output_max = {}; - std::array input_sum = {}; - std::array output_sum = {}; - std::array changed = {}; - for (int channel = 0; channel < 3; ++channel) { - const size_t plane_offset = - static_cast(channel) * plane_size; - for (size_t index = 0; index < plane_size; ++index) { - const uint16_t input_value = input[plane_offset + index]; - const uint16_t output_value = output[plane_offset + index]; - input_min[channel] = std::min(input_min[channel], input_value); - input_max[channel] = std::max(input_max[channel], input_value); - output_min[channel] = std::min(output_min[channel], output_value); - output_max[channel] = std::max(output_max[channel], output_value); - input_sum[channel] += input_value; - output_sum[channel] += output_value; - if (input_value != output_value) ++changed[channel]; - } - } - const auto mean = [plane_size](uint64_t sum) { - return plane_size > 0 - ? static_cast(sum) / static_cast(plane_size) - : 0.0; - }; - const auto changed_percent = [plane_size](size_t count) { - return plane_size > 0 - ? 100.0 * static_cast(count) / - static_cast(plane_size) - : 0.0; - }; - __android_log_print( - ANDROID_LOG_INFO, - kLogTag, - "MGC MeasureMoire strengthQ8 " - "in=[%u..%u/%.2f,%u..%u/%.2f,%u..%u/%.2f] " - "out=[%u..%u/%.2f,%u..%u/%.2f,%u..%u/%.2f] " - "changed=[%.1f%%,%.1f%%,%.1f%%]", - input_min[0], - input_max[0], - mean(input_sum[0]), - input_min[1], - input_max[1], - mean(input_sum[1]), - input_min[2], - input_max[2], - mean(input_sum[2]), - output_min[0], - output_max[0], - mean(output_sum[0]), - output_min[1], - output_max[1], - mean(output_sum[1]), - output_min[2], - output_max[2], - mean(output_sum[2]), - changed_percent(changed[0]), - changed_percent(changed[1]), - changed_percent(changed[2])); -} - -void LogPecanInputs( - const float normalized_yuv_read[3], - const float normalized_yuv_shot[3], - const float normalized_yuv_quadratic[3], - const float q14_yuv_read[3], - const float q14_yuv_shot[3], - const float correlation[128], - const float luma_strength[5], - const photon::mgc_denoise::DenoiseNoiseBuffers& noise) { - float correlation_min = std::numeric_limits::max(); - float correlation_max = std::numeric_limits::lowest(); - double correlation_sum = 0.0; - for (int index = 0; index < 128; ++index) { - correlation_min = std::min(correlation_min, correlation[index]); - correlation_max = std::max(correlation_max, correlation[index]); - correlation_sum += correlation[index]; - } - const auto luma_sigma_q14 = [&](float normalized_signal) { - const float variance = - std::max( - normalized_yuv_read[0] + - normalized_yuv_shot[0] * normalized_signal + - normalized_yuv_quadratic[0] * normalized_signal * - normalized_signal, - 0.0f); - return std::sqrt(variance) * - static_cast(kWhiteLevel); - }; - __android_log_print( - ANDROID_LOG_INFO, - kLogTag, - "MGC Pecan inputs " - "normalizedRead=[%.6g,%.6g,%.6g] " - "normalizedShot=[%.6g,%.6g,%.6g] " - "normalizedQuadratic=[%.6g,%.6g,%.6g] " - "q14Read=[%.6g,%.6g,%.6g] q14Shot=[%.6g,%.6g,%.6g] " - "lumaSigmaQ14(18%%/50%%)=[%.3f,%.3f] " - "correlation=%.6g..%.6g/%.6g " - "strength=[%.6g,%.6g,%.6g,%.6g,%.6g] " - "read4x2=[%.6g,%.6g,%.6g,%.6g;%.6g,%.6g,%.6g,%.6g] " - "shot4x2=[%.6g,%.6g,%.6g,%.6g;%.6g,%.6g,%.6g,%.6g] " - "outlier=[%.6g,%.6g,%.6g,%.6g,%.6g] " - "revert=[%.6g,%.6g,%.6g,%.6g,%.6g]", - normalized_yuv_read[0], - normalized_yuv_read[1], - normalized_yuv_read[2], - normalized_yuv_shot[0], - normalized_yuv_shot[1], - normalized_yuv_shot[2], - normalized_yuv_quadratic[0], - normalized_yuv_quadratic[1], - normalized_yuv_quadratic[2], - q14_yuv_read[0], - q14_yuv_read[1], - q14_yuv_read[2], - q14_yuv_shot[0], - q14_yuv_shot[1], - q14_yuv_shot[2], - luma_sigma_q14(0.18f), - luma_sigma_q14(0.5f), - correlation_min, - correlation_max, - correlation_sum / 128.0, - luma_strength[0], - luma_strength[1], - luma_strength[2], - luma_strength[3], - luma_strength[4], - noise.read[0], - noise.read[1], - noise.read[2], - noise.read[3], - noise.read[4], - noise.read[5], - noise.read[6], - noise.read[7], - noise.shot[0], - noise.shot[1], - noise.shot[2], - noise.shot[3], - noise.shot[4], - noise.shot[5], - noise.shot[6], - noise.shot[7], - noise.outlier_distance[0], - noise.outlier_distance[1], - noise.outlier_distance[2], - noise.outlier_distance[3], - noise.outlier_distance[4], - noise.revert_factor[0], - noise.revert_factor[1], - noise.revert_factor[2], - noise.revert_factor[3], - noise.revert_factor[4]); -} - -// BoxDownsampleS16Halide (0x4cc8ac8): every plane is the rounded mean of an f x f -// block, round(sum / f^2) via a rounding arithmetic shift. -void BoxDownsamplePlanes( - const int16_t* input, - int width, - int height, - int log2_factor, - int16_t* output) { - const int factor = 1 << log2_factor; - const int output_width = width >> log2_factor; - const int output_height = height >> log2_factor; - const int shift = 2 * log2_factor; - const int64_t rounding = int64_t{1} << (shift - 1); - const size_t input_plane = static_cast(width) * height; - const size_t output_plane = static_cast(output_width) * output_height; - #pragma omp parallel for collapse(2) schedule(static) - for (int channel = 0; channel < 3; ++channel) { - for (int y = 0; y < output_height; ++y) { - const int16_t* source = input + channel * input_plane; - int16_t* destination = output + channel * output_plane + - static_cast(y) * output_width; - for (int x = 0; x < output_width; ++x) { - int64_t sum = 0; - for (int dy = 0; dy < factor; ++dy) { - const int16_t* row = source + - static_cast(y * factor + dy) * width + x * factor; - for (int dx = 0; dx < factor; ++dx) sum += row[dx]; - } - destination[x] = static_cast((sum + rounding) >> shift); - } - } - } -} - -// GCam ChromaMedianFilter (V25 0x4cfb1b8; AGC 9.6 0x4c8d2a8), bit-exact model of -// ChromaDualFivePointMedianFilterS16Halide (type 1) and -// ChromaDualThreePointMedianFilterS16Halide (type 2), verified by emulation: -// Y is copied; U and V each take two medians whose floor average is blended in -// with one shared Q11 weight driven by how much more saturated the centre is. -enum class ChromaMedianFilterType : int { kNone = 0, kDualFivePoint = 1, kDualThreePoint = 2 }; - -inline int16_t Wrap16(int value) { return static_cast(static_cast(value)); } -// NEON abs on int16: abs(-32768) stays -32768. -inline int16_t Abs16(int16_t value) { return Wrap16(value < 0 ? -static_cast(value) : value); } -inline int16_t AbsDiff16(int16_t a, int16_t m) { return Wrap16(Abs16(a) - Abs16(m)); } - -inline int16_t Median3(int16_t a, int16_t b, int16_t c) { - return std::max(std::min(a, b), std::min(std::max(a, b), c)); -} - -inline int16_t Median5(int16_t a, int16_t b, int16_t c, int16_t d, int16_t e) { - int16_t v[5] = {a, b, c, d, e}; - std::sort(v, v + 5); - return v[2]; -} - -void ChromaMedianFilter( - ChromaMedianFilterType type, - const int16_t* input, - int width, - int height, - int16_t* output) { - const size_t plane = static_cast(width) * height; - std::copy_n(input, plane, output); - const int16_t* u_plane = input + plane; - const int16_t* v_plane = input + 2 * plane; - #pragma omp parallel for schedule(static) - for (int y = 0; y < height; ++y) { - const int ym = std::max(y - 1, 0); - const int yp = std::min(y + 1, height - 1); - for (int x = 0; x < width; ++x) { - const int xm = std::max(x - 1, 0); - const int xp = std::min(x + 1, width - 1); - const auto at = [&](const int16_t* p, int yy, int xx) { - return p[static_cast(yy) * width + xx]; - }; - int16_t median_a[2]; - int16_t median_b[2]; - int16_t centre[2]; - const int16_t* planes[2] = {u_plane, v_plane}; - for (int c = 0; c < 2; ++c) { - const int16_t* p = planes[c]; - centre[c] = at(p, y, x); - if (type == ChromaMedianFilterType::kDualFivePoint) { - median_a[c] = Median5(centre[c], at(p, ym, x), at(p, yp, x), - at(p, y, xm), at(p, y, xp)); - median_b[c] = Median5(centre[c], at(p, ym, xm), at(p, ym, xp), - at(p, yp, xm), at(p, yp, xp)); - } else { - median_a[c] = Median3(at(p, y, xm), centre[c], at(p, y, xp)); - median_b[c] = Median3(at(p, ym, x), centre[c], at(p, yp, x)); - } - } - int16_t average[2]; - for (int c = 0; c < 2; ++c) { - average[c] = static_cast( - (static_cast(median_a[c]) + median_b[c]) >> 1); - } - int16_t excess; - if (type == ChromaMedianFilterType::kDualFivePoint) { - excess = std::max(AbsDiff16(centre[0], average[0]), - AbsDiff16(centre[1], average[1])); - } else { - excess = std::min( - std::max(AbsDiff16(centre[0], median_a[0]), - AbsDiff16(centre[1], median_a[1])), - std::max(AbsDiff16(centre[0], median_b[0]), - AbsDiff16(centre[1], median_b[1]))); - } - const int weight = std::clamp( - std::clamp(static_cast(excess) + 1024, -32768, 32767), 0, 2047); - const size_t index = static_cast(y) * width + x; - for (int c = 0; c < 2; ++c) { - const int16_t d = Wrap16(average[c] - centre[c]); - const int delta = (static_cast(d) * weight + 1024) >> 11; - output[(c + 1) * plane + index] = Wrap16(centre[c] + delta); - } - } - } -} - -// Adds the low-frequency chroma correction back to the full-resolution Cb/Cr -// planes. The renderer derives its chroma from a box-downsampled copy of this -// output (GuidedUpsample takes chroma only from the low-resolution image, as in -// GCam), so storing the correction at full resolution makes that copy carry the -// low-frequency ChromaDenoise result, in the DNG and in every later render. -void AddUpsampledChromaCorrection( - const int16_t* low_input, - const int16_t* low_output, - int low_width, - int low_height, - int log2_factor, - int16_t* full, - int width, - int height) { - const float factor = static_cast(1 << log2_factor); - const size_t full_plane = static_cast(width) * height; - const size_t low_plane = static_cast(low_width) * low_height; - #pragma omp parallel for collapse(2) schedule(static) - for (int channel = 1; channel < 3; ++channel) { - for (int y = 0; y < height; ++y) { - const float low_y = std::clamp( - (static_cast(y) + 0.5f) / factor - 0.5f, - 0.0f, - static_cast(low_height - 1)); - const int y0 = static_cast(low_y); - const int y1 = std::min(y0 + 1, low_height - 1); - const float fy = low_y - static_cast(y0); - const size_t base = channel * low_plane; - int16_t* row = full + channel * full_plane + static_cast(y) * width; - for (int x = 0; x < width; ++x) { - const float low_x = std::clamp( - (static_cast(x) + 0.5f) / factor - 0.5f, - 0.0f, - static_cast(low_width - 1)); - const int x0 = static_cast(low_x); - const int x1 = std::min(x0 + 1, low_width - 1); - const float fx = low_x - static_cast(x0); - const auto delta = [&](int lx, int ly) { - const size_t index = base + static_cast(ly) * low_width + lx; - return static_cast(low_output[index]) - - static_cast(low_input[index]); - }; - const float correction = - (1.0f - fy) * ((1.0f - fx) * delta(x0, y0) + fx * delta(x1, y0)) + - fy * ((1.0f - fx) * delta(x0, y1) + fx * delta(x1, y1)); - const float value = static_cast(row[x]) + correction; - row[x] = static_cast( - std::lrint(std::clamp(value, -32768.0f, 32767.0f))); - } - } - } -} - } // namespace extern "C" JNIEXPORT jint JNICALL @@ -589,925 +59,156 @@ Java_com_hinnka_mycamera_raw_MgcFullResolutionDenoise_nativeDenoiseRgba16f( jboolean diagnostics_enabled, jint low_frequency_log2_downsample, jint chroma_median_filter_type) { - const bool run_luma = luma_enabled == JNI_TRUE; - const bool run_chroma = chroma_enabled == JNI_TRUE; - const bool run_diagnostics = diagnostics_enabled == JNI_TRUE; - const bool bayer_input = input_is_bayer == JNI_TRUE; - const bool run_measure_moire = measure_moire_enabled == JNI_TRUE; - const bool apply_bayer_lens_shading = - apply_lens_shading_in_bayer_aot == JNI_TRUE; - if (rgba_buffer == nullptr || width <= 0 || height <= 0 || - full_width <= 0 || full_height <= 0 || - global_origin_x < 0 || global_origin_y < 0 || - global_origin_x + width > full_width || - global_origin_y + height > full_height || - (bayer_input && (cfa_pattern < 0 || cfa_pattern > 3)) || - (run_measure_moire && - (!run_chroma || cfa_pattern < 0 || cfa_pattern > 3)) || - (apply_bayer_lens_shading && !bayer_input) || - !std::isfinite(denoise_response_offset) || - !std::isfinite(denoise_response_cosine_offset) || - (!run_luma && !run_chroma)) { - return -1; - } - auto* rgba = static_cast( - env->GetDirectBufferAddress(rgba_buffer)); + if (rgba_buffer == nullptr || width <= 0 || height <= 0) return -1; + photon::mgc_denoise::FullResolutionDenoiseRequest request; + request.rgba = static_cast(env->GetDirectBufferAddress(rgba_buffer)); const jlong capacity = env->GetDirectBufferCapacity(rgba_buffer); const int64_t required_bytes = static_cast(width) * height * 4 * sizeof(uint16_t); - if (rgba == nullptr || capacity < required_bytes) return -1; + if (request.rgba == nullptr || capacity < required_bytes) return -1; + request.width = width; + request.height = height; + request.global_origin_x = global_origin_x; + request.global_origin_y = global_origin_y; + request.full_width = full_width; + request.full_height = full_height; + request.input_is_bayer = input_is_bayer == JNI_TRUE; + request.cfa_pattern = cfa_pattern; + request.measure_moire_enabled = measure_moire_enabled == JNI_TRUE; + request.apply_lens_shading_in_bayer_aot = apply_lens_shading_in_bayer_aot == JNI_TRUE; + if (!CopyFloats(env, normalized_rgb_shot_array, 3, request.normalized_rgb_shot) || + !CopyFloats(env, normalized_rgb_read_array, 3, request.normalized_rgb_read) || + !CopyFloats( + env, normalized_rgb_white_balance_array, 3, request.normalized_rgb_white_balance) || + !CopyFloats(env, luma_strength_array, 5, request.luma_strength) || + !CopyFloats(env, luma_outlier_array, 5, request.luma_outlier) || + !CopyFloats(env, luma_revert_array, 5, request.luma_revert) || + !CopyFloats(env, chroma_strength_array, 5, request.chroma_strength) || + !CopyFloats(env, chroma_outlier_array, 5, request.chroma_outlier)) { + return -1; + } + request.has_prepared_yuv_noise = prepared_normalized_yuv_read_array != nullptr; + if (request.has_prepared_yuv_noise && + !CopyFloats( + env, prepared_normalized_yuv_read_array, 3, request.prepared_normalized_yuv_read)) { + return -1; + } + request.prepared_normalized_luma_shot = prepared_normalized_luma_shot; + request.prepared_normalized_luma_quadratic = prepared_normalized_luma_quadratic; + request.prepared_normalized_chroma_shot = prepared_normalized_chroma_shot; + request.prepared_normalized_chroma_quadratic = prepared_normalized_chroma_quadratic; + // An absent spectrum is MGC's white (unit) correlation. + std::fill_n(request.luma_correlation, 128, 1.0f); + std::fill_n(request.chroma_correlation, 128, 1.0f); + if ((luma_correlation_array != nullptr && + !CopyFloats(env, luma_correlation_array, 128, request.luma_correlation)) || + (chroma_correlation_array != nullptr && + !CopyFloats(env, chroma_correlation_array, 128, request.chroma_correlation))) { + return -1; + } + request.denoise_response_offset = denoise_response_offset; + request.denoise_response_cosine_offset = denoise_response_cosine_offset; - float normalized_rgb_shot[3] = {}; - float normalized_rgb_read[3] = {}; - float normalized_rgb_white_balance[3] = {}; - float prepared_normalized_yuv_read[3] = {}; - float luma_strength[5] = {}; - float luma_outlier[5] = {}; - float luma_revert[5] = {}; - float chroma_strength[5] = {}; - float chroma_outlier[5] = {}; - if (!CopyThree(env, normalized_rgb_shot_array, normalized_rgb_shot) || - !CopyThree(env, normalized_rgb_read_array, normalized_rgb_read) || - !CopyThree( - env, - normalized_rgb_white_balance_array, - normalized_rgb_white_balance) || - !CopyFive(env, luma_strength_array, luma_strength) || - !CopyFive(env, luma_outlier_array, luma_outlier) || - !CopyFive(env, luma_revert_array, luma_revert) || - !CopyFive(env, chroma_strength_array, chroma_strength) || - !CopyFive(env, chroma_outlier_array, chroma_outlier)) { - return -1; - } - const bool has_prepared_yuv_noise = - prepared_normalized_yuv_read_array != nullptr; - if (has_prepared_yuv_noise && - (bayer_input || - !CopyThree( - env, - prepared_normalized_yuv_read_array, - prepared_normalized_yuv_read))) { - return -1; - } - if (has_prepared_yuv_noise && - (!std::isfinite(prepared_normalized_luma_shot) || - prepared_normalized_luma_shot < 0.0f || - !std::isfinite(prepared_normalized_luma_quadratic) || - prepared_normalized_luma_quadratic < 0.0f || - !std::isfinite(prepared_normalized_chroma_shot) || - prepared_normalized_chroma_shot < 0.0f || - !std::isfinite(prepared_normalized_chroma_quadratic) || - prepared_normalized_chroma_quadratic < 0.0f)) { - return -1; - } - for (int channel = 0; channel < 3; ++channel) { - if (!std::isfinite(normalized_rgb_white_balance[channel]) || - normalized_rgb_white_balance[channel] <= 0.0f) { - return -1; - } - if (has_prepared_yuv_noise && - (!std::isfinite(prepared_normalized_yuv_read[channel]) || - prepared_normalized_yuv_read[channel] < 0.0f)) { + std::vector lens; + if (lens_shading != nullptr && lens_width > 0 && lens_height > 0) { + lens.resize(static_cast(lens_width) * lens_height * 4); + if (!CopyFloats(env, lens_shading, static_cast(lens.size()), lens.data())) { return -1; } + request.lens_shading = lens.data(); + request.lens_width = lens_width; + request.lens_height = lens_height; } - float luma_correlation[128]; - float chroma_correlation[128]; - std::fill_n(luma_correlation, 128, 1.0f); - std::fill_n(chroma_correlation, 128, 1.0f); - const auto copy_correlation = [env]( - jfloatArray source, - float destination[128]) { - if (source == nullptr) return true; - if (env->GetArrayLength(source) != 128) return false; - env->GetFloatArrayRegion(source, 0, 128, destination); - if (env->ExceptionCheck()) return false; - for (int index = 0; index < 128; ++index) { - if (!std::isfinite(destination[index]) || - destination[index] < 0.0f) { - return false; - } + std::vector spatial_strength; + if (spatial_strength_q8_array != nullptr) { + const jsize count = env->GetArrayLength(spatial_strength_q8_array); + if (spatial_strength_width <= 0 || spatial_strength_height <= 0 || + count != spatial_strength_width * spatial_strength_height) { + return -1; } - return true; - }; - if (!copy_correlation(luma_correlation_array, luma_correlation) || - !copy_correlation(chroma_correlation_array, chroma_correlation)) { + spatial_strength.resize(static_cast(count)); + env->GetShortArrayRegion( + spatial_strength_q8_array, + 0, + count, + reinterpret_cast(spatial_strength.data())); + if (env->ExceptionCheck()) return -1; + request.spatial_strength_q8 = spatial_strength.data(); + request.spatial_strength_width = spatial_strength_width; + request.spatial_strength_height = spatial_strength_height; + } else if (spatial_strength_width != 0 || spatial_strength_height != 0) { return -1; } - const int padded_width = RoundUp(width, 128); - const int padded_height = RoundUp(height, 16); - const int strength_width = padded_width / 4; - const int strength_height = padded_height / 4; - const size_t pixel_count = - static_cast(padded_width) * padded_height; - const size_t strength_count = - static_cast(strength_width) * strength_height; - const int host_worker_count = HostWorkerCount(); + request.luma_enabled = luma_enabled == JNI_TRUE; + request.chroma_enabled = chroma_enabled == JNI_TRUE; + request.diagnostics_enabled = diagnostics_enabled == JNI_TRUE; + request.low_frequency_log2_downsample = low_frequency_log2_downsample; + request.chroma_median_filter_type = chroma_median_filter_type; + return photon::mgc_denoise::RunFullResolutionDenoise(request); +} - using StageClock = std::chrono::steady_clock; - const auto elapsed_ms = [](StageClock::time_point start) -> int64_t { - return std::chrono::duration_cast( - StageClock::now() - start).count(); - }; - const auto total_start = StageClock::now(); - int64_t allocation_ms = 0; - int64_t input_pack_ms = 0; - int64_t strength_ms = 0; - int64_t demoire_ms = 0; - int64_t rgb_to_yuv_ms = 0; - int64_t chroma_ms = 0; - int64_t pecan_ms = 0; - int64_t diagnostics_ms = 0; - int64_t yuv_to_rgb_ms = 0; - int64_t output_pack_ms = 0; - try { - // Two zero-initialized planar allocations are reused across RGB -> YUV, chroma, - // Pecan luma and YUV -> RGB. The lifted AOT kernels may use untouched output regions as - // deterministic boundary state, so initialization is part of this buffer contract. - const auto allocation_start = StageClock::now(); - const size_t planar_sample_count = pixel_count * 3; - // Array make_unique value-initializes every sample before returning. - // Allocate without initialization so the explicit parallel clear below - // is the only full-buffer zeroing pass. - std::unique_ptr planar_a( - new int16_t[planar_sample_count]); - std::unique_ptr planar_b( - new int16_t[planar_sample_count]); - ZeroPlanarBuffers( - planar_a.get(), - planar_b.get(), - planar_sample_count, - host_worker_count); - allocation_ms = elapsed_ms(allocation_start); - const auto input_pack_start = StageClock::now(); - if (bayer_input) { - // BayerRawToYuv's exact input contract is a 3D U16 buffer whose - // four planes are the spatial positions in each 2x2 Bayer cell. - // Pack into planar_a's first pixel_count samples so this does not - // require another full-resolution allocation. - auto* packed_bayer = - reinterpret_cast(planar_a.get()); - const int packed_width = padded_width / 2; - const int packed_height = padded_height / 2; - const size_t packed_plane_size = - static_cast(packed_width) * packed_height; -#pragma omp parallel for schedule(static) num_threads(host_worker_count) - for (int packed_y = 0; packed_y < packed_height; ++packed_y) { - for (int packed_x = 0; packed_x < packed_width; ++packed_x) { - const size_t packed_index = - static_cast(packed_y) * packed_width + packed_x; - for (int position_y = 0; position_y < 2; ++position_y) { - const int source_y = std::min( - packed_y * 2 + position_y, - height - 1); - for (int position_x = 0; position_x < 2; ++position_x) { - const int source_x = std::min( - packed_x * 2 + position_x, - width - 1); - const int plane = position_y * 2 + position_x; - const uint16_t normalized_u16 = rgba[ - static_cast(source_y) * width + source_x]; - const uint16_t normalized_q14 = - static_cast(std::lround( - static_cast(normalized_u16) * - 16384.0 / 65535.0)); - packed_bayer[ - static_cast(plane) * packed_plane_size + - packed_index] = normalized_q14; - } - } - } - } - } else { - auto* rgb_input = - reinterpret_cast(planar_a.get()); -#pragma omp parallel for schedule(static) num_threads(host_worker_count) - for (int y = 0; y < padded_height; ++y) { - const int source_y = std::min(y, height - 1); - for (int x = 0; x < padded_width; ++x) { - const int source_x = std::min(x, width - 1); - const size_t source_index = - (static_cast(source_y) * width + source_x) * 4; - const size_t destination_index = - static_cast(y) * padded_width + x; - for (int channel = 0; channel < 3; ++channel) { - const float normalized = std::clamp( - std::max( - HalfToFloat(rgba[source_index + channel]), - 0.0f) * - normalized_rgb_white_balance[channel], - 0.0f, - 1.0f); - rgb_input[ - static_cast(channel) * pixel_count + - destination_index] = - static_cast( - std::lround(normalized * kWhiteLevel)); - } - } - } - } - input_pack_ms = elapsed_ms(input_pack_start); - - const auto strength_start = StageClock::now(); - std::vector base_strength(strength_count, 256); - std::vector strength(strength_count * 3, 256); - if (spatial_strength_q8_array != nullptr) { - const int expected_full_strength_width = - (full_width + 3) / 4; - const int expected_full_strength_height = - (full_height + 3) / 4; - if (spatial_strength_width != expected_full_strength_width || - spatial_strength_height != expected_full_strength_height || - env->GetArrayLength(spatial_strength_q8_array) != - spatial_strength_width * spatial_strength_height) { - return -1; - } - std::vector spatial_strength( - static_cast(spatial_strength_width) * - spatial_strength_height); - env->GetShortArrayRegion( - spatial_strength_q8_array, - 0, - static_cast(spatial_strength.size()), - reinterpret_cast(spatial_strength.data())); - if (env->ExceptionCheck()) return -1; - for (int y = 0; y < strength_height; ++y) { - const int local_pixel_y = std::min(y * 4, height - 1); - const int source_y = std::clamp( - (global_origin_y + local_pixel_y) / 4, - 0, - spatial_strength_height - 1); - for (int x = 0; x < strength_width; ++x) { - const int local_pixel_x = std::min(x * 4, width - 1); - const int source_x = std::clamp( - (global_origin_x + local_pixel_x) / 4, - 0, - spatial_strength_width - 1); - base_strength[ - static_cast(y) * strength_width + x] = - spatial_strength[ - static_cast(source_y) * - spatial_strength_width + - source_x]; - } - } - } else if (spatial_strength_width != 0 || - spatial_strength_height != 0) { +extern "C" JNIEXPORT jint JNICALL +Java_com_hinnka_mycamera_raw_MgcFullResolutionDenoise_nativeLowFrequencyChromaCorrection( + JNIEnv* env, + jobject, + jobject rgba_buffer, + jint low_width, + jint low_height, + jint full_width, + jint full_height, + jint log2_downsample, + jfloatArray prepared_normalized_yuv_read_array, + jfloat prepared_normalized_chroma_shot, + jfloat prepared_normalized_chroma_quadratic, + jfloatArray chroma_correlation_array, + jfloat denoise_response_offset, + jfloat denoise_response_cosine_offset, + jshortArray spatial_strength_q8_array, + jint spatial_strength_width, + jint spatial_strength_height, + jfloatArray chroma_strength_array, + jfloatArray chroma_outlier_array, + jint chroma_median_filter_type) { + if (rgba_buffer == nullptr || low_width <= 0 || low_height <= 0) return -1; + photon::mgc_denoise::LowFrequencyChromaRequest request; + request.rgba = static_cast(env->GetDirectBufferAddress(rgba_buffer)); + const jlong capacity = env->GetDirectBufferCapacity(rgba_buffer); + if (request.rgba == nullptr || + capacity < static_cast(low_width) * low_height * 4 * sizeof(uint16_t)) { + return -1; + } + request.low_width = low_width; + request.low_height = low_height; + request.full_width = full_width; + request.full_height = full_height; + request.log2_downsample = log2_downsample; + if (!CopyFloats(env, prepared_normalized_yuv_read_array, 3, request.prepared_normalized_yuv_read) || + !CopyFloats(env, chroma_correlation_array, 128, request.chroma_correlation) || + !CopyFloats(env, chroma_strength_array, 5, request.chroma_strength) || + !CopyFloats(env, chroma_outlier_array, 5, request.chroma_outlier)) { + return -1; + } + request.prepared_normalized_chroma_shot = prepared_normalized_chroma_shot; + request.prepared_normalized_chroma_quadratic = prepared_normalized_chroma_quadratic; + request.denoise_response_offset = denoise_response_offset; + request.denoise_response_cosine_offset = denoise_response_cosine_offset; + std::vector spatial_strength; + if (spatial_strength_q8_array != nullptr) { + const jsize count = env->GetArrayLength(spatial_strength_q8_array); + if (spatial_strength_width <= 0 || spatial_strength_height <= 0 || + count != spatial_strength_width * spatial_strength_height) { return -1; - } - if (run_diagnostics) { - uint16_t base_strength_min = std::numeric_limits::max(); - uint16_t base_strength_max = 0; - uint64_t base_strength_sum = 0; - for (const uint16_t value : base_strength) { - base_strength_min = std::min(base_strength_min, value); - base_strength_max = std::max(base_strength_max, value); - base_strength_sum += value; - } - __android_log_print( - ANDROID_LOG_INFO, - kLogTag, - "MGC denoise base Spatial strengthQ8=%u..%u/%.3f " - "source=%s logical=%dx%d padded=%dx%d origin=(%d,%d)", - base_strength_min, - base_strength_max, - base_strength.empty() - ? 0.0 - : static_cast(base_strength_sum) / - static_cast(base_strength.size()), - spatial_strength_q8_array == nullptr ? "identity" : "spatial-aot", - spatial_strength_width, - spatial_strength_height, - strength_width, - strength_height, - global_origin_x, - global_origin_y); - } - std::vector lens; - if (lens_shading != nullptr && lens_width > 0 && lens_height > 0) { - const jsize lens_count = env->GetArrayLength(lens_shading); - if (lens_count != lens_width * lens_height * 4) return -1; - lens.resize(static_cast(lens_count)); - env->GetFloatArrayRegion( - lens_shading, - 0, - lens_count, - lens.data()); - if (env->ExceptionCheck()) return -1; - const int full_strength_width = RoundUp(full_width, 128) / 4; - const int full_strength_height = RoundUp(full_height, 16) / 4; - const int strength_origin_x = global_origin_x / 4; - const int strength_origin_y = global_origin_y / 4; - const float sample_rate_x = full_strength_width > 1 - ? static_cast(lens_width - 1) / - static_cast(full_strength_width - 1) - : 1.0f; - const float sample_rate_y = full_strength_height > 1 - ? static_cast(lens_height - 1) / - static_cast(full_strength_height - 1) - : 1.0f; - const int strength_result = - photon::mgc_denoise::ComputeStrengthMap( - base_strength.data(), - strength_width, - strength_height, - strength_origin_x, - strength_origin_y, - lens.data(), - lens_width, - lens_height, - sample_rate_x, - sample_rate_y, - strength.data()); - if (strength_result != 0) { - return LogStageFailure("strength_map", strength_result); - } - } else { - if (apply_bayer_lens_shading) return -1; - for (int channel = 0; channel < 3; ++channel) { - std::copy_n( - base_strength.data(), - strength_count, - strength.data() + - static_cast(channel) * strength_count); - } - } - strength_ms = elapsed_ms(strength_start); - - // Exact matrix stored by MGC at libgcastartup.so+0x0d64c24. - constexpr float rgb_to_yuv[9] = { - 0.2125999927520752f, - 0.7152000069618225f, - 0.07219959795475006f, - -0.16245023906230927f, - -0.5464943051338196f, - 0.7089447379112244f, - 0.9999967217445374f, - -0.9083024859428406f, - -0.09169333428144455f, - }; - float scaled_rgb_read[3] = {}; - float scaled_rgb_shot[3] = {}; - float scaled_rgb_quadratic[3] = {}; - float prepared_rgb_read[3] = {}; - float prepared_rgb_shot[3] = {}; - float prepared_rgb_quadratic[3] = {}; - float prepared_luma_correlation[128] = {}; - float prepared_chroma_correlation[128] = {}; - // The input NoiseModel is expressed in normalized, un-white-balanced - // camera RGB: variance(x) = read + shot * x + quadratic * x^2. - // MGC FinishRaw hands the full-resolution denoiser NoiseModel.Scale(2) of - // the white-balanced model: x' = 2 * gain * x, so read' = read * (2 * gain)^2 - // and shot' = shot * (2 * gain), quadratic unchanged. The pixels themselves - // stay unsigned Q14 (RawToYuv maps a flat q to Y = q, measured on device), - // exactly as in MGC: the factor is part of the contract the luma/chroma - // strength curves were tuned against, not a pixel-domain conversion. - constexpr float full_resolution_noise_model_scale = 2.0f; - for (int channel = 0; channel < 3; ++channel) { - const float channel_gain = - normalized_rgb_white_balance[channel] * - full_resolution_noise_model_scale; - scaled_rgb_read[channel] = - std::max(normalized_rgb_read[channel], 0.0f) * - channel_gain * channel_gain; - scaled_rgb_shot[channel] = - std::max(normalized_rgb_shot[channel], 0.0f) * - channel_gain; - } - if (has_prepared_yuv_noise) { - __android_log_print( - ANDROID_LOG_INFO, - kLogTag, - "MGC RGB noise-domain remap bypassed: " - "using measured VGN YUV model"); - } else { - __android_log_print( - ANDROID_LOG_INFO, - kLogTag, - "MGC RGB noise domain input=%s " - "calculationWb=[%.6g,%.6g,%.6g] " - "read=[%.6g,%.6g,%.6g]->[%.6g,%.6g,%.6g] " - "shot=[%.6g,%.6g,%.6g]->[%.6g,%.6g,%.6g]", - bayer_input ? "BAYER" : "CAMERA_RGBA16F", - normalized_rgb_white_balance[0], - normalized_rgb_white_balance[1], - normalized_rgb_white_balance[2], - normalized_rgb_read[0], - normalized_rgb_read[1], - normalized_rgb_read[2], - scaled_rgb_read[0], - scaled_rgb_read[1], - scaled_rgb_read[2], - normalized_rgb_shot[0], - normalized_rgb_shot[1], - normalized_rgb_shot[2], - scaled_rgb_shot[0], - scaled_rgb_shot[1], - scaled_rgb_shot[2]); - } - if (bayer_input) { - float correlation_mean = 0.0f; - if (!photon::mgc_denoise::PrepareDefaultBayerDenoiseNoiseModel( - scaled_rgb_read, - scaled_rgb_shot, - scaled_rgb_quadratic, - luma_correlation, - prepared_rgb_read, - prepared_rgb_shot, - prepared_rgb_quadratic, - prepared_luma_correlation, - &correlation_mean)) { - return LogStageFailure("bayer_noise_model", -1); - } - // The default Bayer path receives one upstream Spatial spectrum. Its fixed demosaic - // remap is channel-independent, so the chroma spectrum has the same propagated shape. - std::copy_n( - prepared_luma_correlation, - 128, - prepared_chroma_correlation); - __android_log_print( - ANDROID_LOG_INFO, - kLogTag, - "MGC Bayer denoise prepare demosaicSharpness=0.1 " - "correlationMean=%.9g " - "rgbRead=[%.6g,%.6g,%.6g] " - "rgbShot=[%.6g,%.6g,%.6g]", - correlation_mean, - prepared_rgb_read[0], - prepared_rgb_read[1], - prepared_rgb_read[2], - prepared_rgb_shot[0], - prepared_rgb_shot[1], - prepared_rgb_shot[2]); - } else { - std::copy_n(scaled_rgb_read, 3, prepared_rgb_read); - std::copy_n(scaled_rgb_shot, 3, prepared_rgb_shot); - std::copy_n(scaled_rgb_quadratic, 3, prepared_rgb_quadratic); - std::copy_n(luma_correlation, 128, prepared_luma_correlation); - std::copy_n(chroma_correlation, 128, prepared_chroma_correlation); - } - float yuv_read[3] = {}; - float yuv_shot[3] = {}; - float yuv_quadratic[3] = {}; - float chroma_shared_shot = 0.0f; - float chroma_shared_quadratic = 0.0f; - if (has_prepared_yuv_noise) { - std::copy_n(prepared_normalized_yuv_read, 3, yuv_read); - yuv_shot[0] = prepared_normalized_luma_shot; - yuv_quadratic[0] = prepared_normalized_luma_quadratic; - yuv_shot[1] = yuv_shot[2] = prepared_normalized_chroma_shot; - yuv_quadratic[1] = yuv_quadratic[2] = - prepared_normalized_chroma_quadratic; - chroma_shared_shot = prepared_normalized_chroma_shot; - chroma_shared_quadratic = prepared_normalized_chroma_quadratic; - __android_log_print( - ANDROID_LOG_INFO, - kLogTag, - "MGC VGN prepared YUV noise " - "read=[%.6g,%.6g,%.6g] lumaShot=%.6g lumaQuadratic=%.6g " - "chromaShot=%.6g chromaQuadratic=%.6g", - yuv_read[0], - yuv_read[1], - yuv_read[2], - yuv_shot[0], - yuv_quadratic[0], - yuv_shot[1], - yuv_quadratic[1]); - } else { - for (int output_channel = 0; output_channel < 3; ++output_channel) { - float row_sum = 0.0f; - for (int input_channel = 0; input_channel < 3; ++input_channel) { - const float matrix_value = - rgb_to_yuv[output_channel * 3 + input_channel]; - const float matrix_squared = matrix_value * matrix_value; - row_sum += matrix_value; - yuv_read[output_channel] += - matrix_squared * prepared_rgb_read[input_channel]; - yuv_shot[output_channel] += - matrix_squared * prepared_rgb_shot[input_channel]; - yuv_quadratic[output_channel] += - matrix_squared * prepared_rgb_quadratic[input_channel]; - } - // NoiseModel::Transform at 0x5e985d8 keeps read variance in - // the matrix output domain, but normalizes the signal-dependent - // coefficients by the row's signal scale. Zero-sum chroma rows - // therefore have no independent shot/quadratic coefficient. - const float absolute_row_sum = std::abs(row_sum); - if (absolute_row_sum < 1.0e-6f) { - yuv_shot[output_channel] = 0.0f; - yuv_quadratic[output_channel] = 0.0f; - } else { - yuv_shot[output_channel] /= absolute_row_sum; - yuv_quadratic[output_channel] /= - absolute_row_sum * absolute_row_sum; - } - } - // CreateChromaDenoiseNoiseModelBuffers preserves all three read channels, then - // slices channel 0 from the shot and quadratic buffers before invoking CompleteS16. - // Keep the analytic Y/Cb/Cr model intact and reproduce that exact slice here. - chroma_shared_shot = yuv_shot[0]; - chroma_shared_quadratic = yuv_quadratic[0]; - __android_log_print( - ANDROID_LOG_INFO, - kLogTag, - "MGC analytic YUV noise read=[%.6g,%.6g,%.6g] " - "lumaShot=%.6g lumaQuadratic=%.6g " - "chromaSharedChannel0Shot=%.6g " - "chromaSharedChannel0Quadratic=%.6g", - yuv_read[0], - yuv_read[1], - yuv_read[2], - yuv_shot[0], - yuv_quadratic[0], - chroma_shared_shot, - chroma_shared_quadratic); - } - // RgbRawToYuv emits Q14 S16 samples. Pecan's generated arithmetic - // consumes variance = read + shot * sample + quadratic * sample^2 in - // that same sample domain; it does not rescale normalized - // coefficients internally. Convert the normalized NoiseModel once - // at this boundary: read variance scales by white^2, shot by white, - // while the dimensionless quadratic factor is unchanged. - constexpr float white = static_cast(kWhiteLevel); - constexpr float white_squared = white * white; - float q14_yuv_read[3] = {}; - float q14_yuv_shot[3] = {}; - for (int channel = 0; channel < 3; ++channel) { - q14_yuv_read[channel] = yuv_read[channel] * white_squared; - q14_yuv_shot[channel] = yuv_shot[channel] * white; - } - const float q14_chroma_shared_shot = chroma_shared_shot * white; - __android_log_print( - ANDROID_LOG_INFO, - kLogTag, - "MGC Q14 denoise noise luma=[read=%.6g shot=%.6g quadratic=%.6g] " - "chroma=[read=%.6g,%.6g,%.6g sharedShot=%.6g sharedQuadratic=%.6g]", - q14_yuv_read[0], - q14_yuv_shot[0], - yuv_quadratic[0], - q14_yuv_read[0], - q14_yuv_read[1], - q14_yuv_read[2], - q14_chroma_shared_shot, - chroma_shared_quadratic); - - const auto rgb_to_yuv_start = StageClock::now(); - int rgb_to_yuv_result = 0; - if (bayer_input) { - const float bayer_channel_gains[4] = { - normalized_rgb_white_balance[0], - normalized_rgb_white_balance[1], - normalized_rgb_white_balance[1], - normalized_rgb_white_balance[2], - }; - rgb_to_yuv_result = - photon::mgc_denoise::RunDefaultBayerRawToYuv( - reinterpret_cast(planar_a.get()), - padded_width, - padded_height, - cfa_pattern, - bayer_channel_gains, - apply_bayer_lens_shading && !lens.empty() - ? lens.data() - : nullptr, - apply_bayer_lens_shading ? lens_width : 0, - apply_bayer_lens_shading ? lens_height : 0, - !apply_bayer_lens_shading || lens.empty() || width <= 1 - ? 1.0f - : static_cast(lens_width - 1) / - static_cast(width - 1), - !apply_bayer_lens_shading || lens.empty() || height <= 1 - ? 1.0f - : static_cast(lens_height - 1) / - static_cast(height - 1), - planar_b.get()); - } else { - rgb_to_yuv_result = photon::mgc_denoise::RunRgbRawToYuv( - reinterpret_cast(planar_a.get()), - padded_width, - padded_height, - planar_b.get()); - } - if (rgb_to_yuv_result != 0) { - return LogStageFailure("rgb_to_yuv", rgb_to_yuv_result); - } - rgb_to_yuv_ms = elapsed_ms(rgb_to_yuv_start); - - // MGC invokes MeasureMoire after RawToYuv and passes a channel-0 slice - // of linear_yuv. The lifted AOT contract therefore sees one planar - // S16/Q14 Y channel, not the Bayer mosaic. Its output replaces only - // the strength map supplied to ChromaDenoise; Pecan keeps strength. - std::vector demoire_strength; - const uint16_t* chroma_strength_q8 = strength.data(); - if (run_measure_moire) { - const auto demoire_start = StageClock::now(); - demoire_strength.resize(strength_count * 3); - const int demoire_result = - photon::mgc_denoise::RunMeasureMoireS16( - planar_b.get(), - padded_width, - padded_height, - strength.data(), - strength_width, - strength_height, - demoire_strength.data()); - if (demoire_result != 0) { - return LogStageFailure("measure_moire", demoire_result); - } - if (run_diagnostics) { - LogMeasureMoireDiagnostics( - strength.data(), - demoire_strength.data(), - strength_count); - } - chroma_strength_q8 = demoire_strength.data(); - demoire_ms = elapsed_ms(demoire_start); - } - - // GCam ProcessRaw order: Pecan denoises luma first, its Y is copied back into - // linear_yuv (slice(2, 0).copy_from), and ChromaDenoise then runs on - // [denoised Y, Cb, Cr], so the chroma pyramid sees a clean luma plane instead - // of the noisy RawToYuv Y. MeasureMoire above still reads the RawToYuv Y. - if (run_luma) { - const auto pecan_start = StageClock::now(); - photon::mgc_denoise::DenoiseNoiseBuffers luma_noise; - if (!photon::mgc_denoise::BuildNoiseBuffers( - q14_yuv_read[0], - q14_yuv_shot[0], - yuv_quadratic[0], - prepared_luma_correlation, - denoise_response_offset, - denoise_response_cosine_offset, - luma_strength, - luma_outlier, - luma_revert, - &luma_noise)) { - return LogStageFailure("luma_noise_model", -1); - } - if (run_diagnostics) { - LogPecanInputs( - yuv_read, - yuv_shot, - yuv_quadratic, - q14_yuv_read, - q14_yuv_shot, - prepared_luma_correlation, - luma_strength, - luma_noise); - } - const int pecan_result = photon::mgc_denoise::RunPecan( - strength.data(), - strength_width, - strength_height, - luma_noise, - planar_b.get(), - padded_width, - padded_height, - planar_a.get()); - if (pecan_result != 0) { - return LogStageFailure("pecan_luma", pecan_result); - } - pecan_ms = elapsed_ms(pecan_start); - } else { - // Luma denoise disabled: keep the RawToYuv Y. - std::copy_n(planar_b.get(), pixel_count, planar_a.get()); - } - - // planar_a's Y is final from here on; ChromaDenoise owns only Cb/Cr. - std::copy_n(planar_a.get(), pixel_count, planar_b.get()); - - if (run_chroma) { - const auto chroma_start = StageClock::now(); - photon::mgc_denoise::ChromaDenoiseNoiseBuffers chroma_noise; - if (!photon::mgc_denoise::BuildChromaNoiseBuffers( - q14_yuv_read, - q14_chroma_shared_shot, - chroma_shared_quadratic, - prepared_chroma_correlation, - denoise_response_offset, - denoise_response_cosine_offset, - chroma_strength, - chroma_outlier, - &chroma_noise)) { - return LogStageFailure("chroma_noise_model", -1); - } - const int chroma_result = - photon::mgc_denoise::RunChromaDenoise( - planar_b.get(), - padded_width, - padded_height, - chroma_strength_q8, - strength_width, - strength_height, - chroma_noise, - planar_a.get()); - if (chroma_result != 0) { - return LogStageFailure("chroma_pyramid", chroma_result); - } - chroma_ms = elapsed_ms(chroma_start); - } - - if (!run_chroma) { - std::copy_n( - planar_b.get() + pixel_count, - pixel_count * 2, - planar_a.get() + pixel_count); - } - - // GCam ProcessRaw low-frequency branch: BoxDownsample of [Pecan Y, - // chroma-denoised Cb/Cr] by 2^L, the model box-downsampled L times - // (0x5e99434), then ChromaDenoise again with the same tuning and the same - // RAW/4 strength map (decimation 2 - L, downsample factor L). The pyramid - // at 1/2^L resolution reaches the coarse chroma blotches the - // full-resolution pyramid cannot. It needs the whole image, not a tile. - const int low_frequency_log2 = low_frequency_log2_downsample; - const bool whole_image = global_origin_x == 0 && global_origin_y == 0 && - width == full_width && height == full_height; - if (run_chroma && low_frequency_log2 > 0 && whole_image) { - const auto low_start = StageClock::now(); - const int low_width = padded_width >> low_frequency_log2; - const int low_height = padded_height >> low_frequency_log2; - const size_t low_count = - static_cast(low_width) * low_height * 3; - std::vector low_input(low_count); - std::vector low_output(low_count); - std::vector low_median; - BoxDownsamplePlanes( - planar_a.get(), - padded_width, - padded_height, - low_frequency_log2, - low_input.data()); - const auto median_type = - static_cast(chroma_median_filter_type); - if (median_type != ChromaMedianFilterType::kNone) { - // ProcessLowFrequency (0x4694fbc): the median replaces ds_linear_yuv - // before the low-frequency ChromaDenoise. - std::vector filtered(low_count); - ChromaMedianFilter( - median_type, low_input.data(), low_width, low_height, filtered.data()); - low_median = std::move(filtered); - } - const int16_t* low_denoise_input = - low_median.empty() ? low_input.data() : low_median.data(); - float low_read[3] = {q14_yuv_read[0], q14_yuv_read[1], q14_yuv_read[2]}; - float low_shot = q14_chroma_shared_shot; - float low_quadratic = chroma_shared_quadratic; - float low_spectrum[128]; - std::copy_n(prepared_chroma_correlation, 128, low_spectrum); - if (!photon::mgc_denoise::BoxDownsampleNoiseModel( - low_frequency_log2, - low_read, - &low_shot, - &low_quadratic, - low_spectrum)) { - return LogStageFailure("low_frequency_noise_model", -1); - } - photon::mgc_denoise::ChromaDenoiseNoiseBuffers low_noise; - if (!photon::mgc_denoise::BuildChromaNoiseBuffers( - low_read, - low_shot, - low_quadratic, - low_spectrum, - denoise_response_offset, - denoise_response_cosine_offset, - chroma_strength, - chroma_outlier, - &low_noise)) { - return LogStageFailure("low_frequency_chroma_noise_model", -1); - } - const int low_result = photon::mgc_denoise::RunChromaDenoise( - low_denoise_input, - low_width, - low_height, - chroma_strength_q8, - strength_width, - strength_height, - low_noise, - low_output.data(), - 2 - low_frequency_log2, - low_frequency_log2); - if (low_result != 0) { - return LogStageFailure("low_frequency_chroma_pyramid", low_result); - } - AddUpsampledChromaCorrection( - low_input.data(), - low_output.data(), - low_width, - low_height, - low_frequency_log2, - planar_a.get(), - padded_width, - padded_height); - __android_log_print( - ANDROID_LOG_INFO, - kLogTag, - "MGC low-frequency chroma denoise factor=%dx size=%dx%d median=%d " - "read=[%.6g,%.6g,%.6g] shot=%.6g quadratic=%.6g took=%lldms", - 1 << low_frequency_log2, - low_width, - low_height, - chroma_median_filter_type, - low_read[0], - low_read[1], - low_read[2], - low_shot, - low_quadratic, - static_cast(elapsed_ms(low_start))); - } else if (run_chroma && low_frequency_log2 > 0) { - __android_log_print( - ANDROID_LOG_WARN, - kLogTag, - "MGC low-frequency chroma denoise skipped for tile origin=(%d,%d) " - "size=%dx%d full=%dx%d", - global_origin_x, - global_origin_y, - width, - height, - full_width, - full_height); - } - - if (run_diagnostics) { - // planar_b's Y already holds the Pecan output, so this delta covers Cb/Cr - // only; the luma change is reflected in the Pecan stage timing/inputs. - const auto diagnostics_start = StageClock::now(); - const auto output_delta = MeasurePlanarDelta( - planar_b.get(), - planar_a.get(), - width, - height, - padded_width, - pixel_count); - LogDenoiseDiagnostics( - strength.data(), - strength_count, - output_delta); - diagnostics_ms = elapsed_ms(diagnostics_start); - } - - // This JNI boundary returns linear camera RGB to Photon. The original MGC pipeline only - // sharpened after tone mapping; Photon now performs final sharpening in its GLES output - // chain. Calling the former U12 kernel here would clamp Q14 samples at 4095 and corrupt - // exposure and saturation, so the matching operation at this boundary is YuvToRgb. - const auto yuv_to_rgb_start = StageClock::now(); - const int yuv_to_rgb_result = - photon::mgc_denoise::RunYuvToRgb( - planar_a.get(), - padded_width, - padded_height, - planar_b.get()); - if (yuv_to_rgb_result != 0) { - return LogStageFailure("yuv_to_rgb", yuv_to_rgb_result); - } - yuv_to_rgb_ms = elapsed_ms(yuv_to_rgb_start); - - const auto output_pack_start = StageClock::now(); -#pragma omp parallel for schedule(static) num_threads(host_worker_count) - for (int y = 0; y < height; ++y) { - for (int x = 0; x < width; ++x) { - const size_t source_index = - static_cast(y) * padded_width + x; - const size_t destination_index = - (static_cast(y) * width + x) * 4; - for (int channel = 0; channel < 3; ++channel) { - const float normalized = - static_cast( - planar_b[ - static_cast(channel) * pixel_count + - source_index]) / - static_cast(kWhiteLevel) / - normalized_rgb_white_balance[channel]; - rgba[destination_index + channel] = - FloatToHalf(normalized); - } - rgba[destination_index + 3] = FloatToHalf(1.0f); - } } - output_pack_ms = elapsed_ms(output_pack_start); - __android_log_print( - ANDROID_LOG_INFO, - kLogTag, - "MGC denoise stages hostWorkers=%d allocation=%lldms inputPack=%lldms strength=%lldms " - "demoire=%lldms rgbToYuv=%lldms chroma=%lldms pecan=%lldms diagnostics=%lldms " - "yuvToRgb=%lldms outputPack=%lldms total=%lldms", - host_worker_count, - static_cast(allocation_ms), - static_cast(input_pack_ms), - static_cast(strength_ms), - static_cast(demoire_ms), - static_cast(rgb_to_yuv_ms), - static_cast(chroma_ms), - static_cast(pecan_ms), - static_cast(diagnostics_ms), - static_cast(yuv_to_rgb_ms), - static_cast(output_pack_ms), - static_cast(elapsed_ms(total_start))); - return 0; - } catch (const std::bad_alloc&) { - return LogStageFailure("allocation", -2); + spatial_strength.resize(static_cast(count)); + env->GetShortArrayRegion( + spatial_strength_q8_array, 0, count, reinterpret_cast(spatial_strength.data())); + if (env->ExceptionCheck()) return -1; + request.spatial_strength_q8 = spatial_strength.data(); + request.spatial_strength_width = spatial_strength_width; + request.spatial_strength_height = spatial_strength_height; } + request.chroma_median_filter_type = chroma_median_filter_type; + return photon::mgc_denoise::RunLowFrequencyChromaCorrection(request); } diff --git a/app/src/main/java/com/hinnka/mycamera/gallery/PhotoProcessor.kt b/app/src/main/java/com/hinnka/mycamera/gallery/PhotoProcessor.kt index 3c7c3176..a279499f 100644 --- a/app/src/main/java/com/hinnka/mycamera/gallery/PhotoProcessor.kt +++ b/app/src/main/java/com/hinnka/mycamera/gallery/PhotoProcessor.kt @@ -39,6 +39,7 @@ import com.hinnka.mycamera.raw.fotufilm.FotufilmDocumentStorage import com.hinnka.mycamera.utils.PLog import android.net.Uri import com.hinnka.mycamera.processor.DenoiseStrength +import com.hinnka.mycamera.raw.MgcBitmapNoiseModel import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.sync.Mutex @@ -105,6 +106,7 @@ class PhotoProcessor( source: File, noiseReduction: Float, chromaNoiseReduction: Float, + sensorIso: Int?, onBuild: () -> Unit = {}, ): Boolean { val luma = DenoiseStrength.clamp(noiseReduction) @@ -112,12 +114,12 @@ class PhotoProcessor( if (luma <= 0f && chroma <= 0f) return false val dir = GalleryManager.getPhotonDenoiseDir(context, photoId) photonDenoiseBaseMutex.withLock { - val key = withContext(Dispatchers.IO) { photonDenoiseKey(source, luma, chroma) } + val key = withContext(Dispatchers.IO) { photonDenoiseKey(source, luma, chroma, sensorIso) } if (withContext(Dispatchers.IO) { findPhotonDenoiseEntry(dir, key)?.touch() } != null) return false onBuild() val input = GalleryManager.loadBitmap(context, Uri.fromFile(source)) ?: return false val denoised = try { - lutImageProcessor.applyBitmapDenoise(input, luma, chroma) + lutImageProcessor.applyBitmapDenoise(input, luma, chroma, sensorIso) } catch (e: Throwable) { input.recycle() throw e @@ -155,6 +157,7 @@ class PhotoProcessor( source: File, noiseReduction: Float, chromaNoiseReduction: Float, + sensorIso: Int?, maxEdge: Int? = null, ): Bitmap? { val luma = DenoiseStrength.clamp(noiseReduction) @@ -163,7 +166,7 @@ class PhotoProcessor( val dir = GalleryManager.getPhotonDenoiseDir(context, photoId) return photonDenoiseBaseMutex.withLock { withContext(Dispatchers.IO) { - findPhotonDenoiseEntry(dir, photonDenoiseKey(source, luma, chroma))?.touch()?.let { + findPhotonDenoiseEntry(dir, photonDenoiseKey(source, luma, chroma, sensorIso))?.touch()?.let { GalleryManager.loadBitmap(context, Uri.fromFile(it.image), maxEdge) } } @@ -202,7 +205,7 @@ class PhotoProcessor( * 源文件以内容 CRC32 标识(按路径、修改时间、大小缓存):bokeh.jpg 等派生文件会被原样重写, * 只看修改时间会让内容未变的基底失效。 */ - private fun photonDenoiseKey(source: File, luma: Float, chroma: Float): String { + private fun photonDenoiseKey(source: File, luma: Float, chroma: Float, sensorIso: Int?): String { val stamp = "${source.absolutePath}|${source.lastModified()}|${source.length()}" val crc = photonDenoiseSourceCrc[stamp] ?: CRC32().run { source.inputStream().use { input -> @@ -218,7 +221,9 @@ class PhotoProcessor( if (photonDenoiseSourceCrc.size > 64) photonDenoiseSourceCrc.clear() photonDenoiseSourceCrc[stamp] = it } - return "v2|${source.name}|${source.length()}|$crc|$luma|$chroma" + // The noise model signature retires bases built by another denoiser or calibration. + val model = MgcBitmapNoiseModel.cacheSignature(sensorIso) + return "v3|${source.name}|${source.length()}|$crc|$luma|$chroma|$model" } private fun resolveNoiseReduction(metadata: MediaMetadata, fallback: Float): Float { @@ -439,8 +444,6 @@ class PhotoProcessor( sdrBitmap, colorCorrection.baselineLayer, colorCorrection.creativeLayer, - noiseReductionValue = 0f, - chromaNoiseReductionValue = 0f, luminanceGainDownsample = RawGainmapMath.DOWNSAMPLE, ) sdrBitmap = lutStackResult.bitmap @@ -688,6 +691,7 @@ class PhotoProcessor( source = if (bokehBaked) bokehFile else source, noiseReduction = resolveNoiseReduction(metadata, 0f), chromaNoiseReduction = resolveChromaNoiseReduction(metadata, 0f), + sensorIso = metadata.iso, ) return processBitmap( context = context, @@ -862,9 +866,7 @@ class PhotoProcessor( lutImageProcessor.applyLutStack( b, colorCorrection.baselineLayer, - colorCorrection.creativeLayer, - noiseReductionValue = 0f, - chromaNoiseReductionValue = 0f + colorCorrection.creativeLayer ) } @@ -917,8 +919,6 @@ class PhotoProcessor( result, colorCorrection.baselineLayer, colorCorrection.creativeLayer, - noiseReductionValue = 0f, - chromaNoiseReductionValue = 0f, luminanceGainDownsample = lutLuminanceGainDownsample, ) result = lutStackResult.bitmap @@ -927,9 +927,7 @@ class PhotoProcessor( result = lutImageProcessor.applyLutStack( result, colorCorrection.baselineLayer, - colorCorrection.creativeLayer, - noiseReductionValue = 0f, - chromaNoiseReductionValue = 0f + colorCorrection.creativeLayer ) } diff --git a/app/src/main/java/com/hinnka/mycamera/lut/BitmapMgcDenoiser.kt b/app/src/main/java/com/hinnka/mycamera/lut/BitmapMgcDenoiser.kt new file mode 100644 index 00000000..ef4af80e --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/lut/BitmapMgcDenoiser.kt @@ -0,0 +1,649 @@ +package com.hinnka.mycamera.lut + +import android.content.Context +import android.opengl.GLES30 +import android.util.Half +import com.hinnka.mycamera.processor.DenoiseStrength +import com.hinnka.mycamera.raw.MgcBitmapNoiseModel +import com.hinnka.mycamera.raw.MgcFullResolutionDenoise +import com.hinnka.mycamera.raw.RawFloatTextureTransfer +import com.hinnka.mycamera.raw.RawFullscreenQuad +import com.hinnka.mycamera.raw.RawGlesProgram +import com.hinnka.mycamera.utils.PLog +import kotlin.math.ceil +import kotlin.math.min +import kotlin.math.roundToInt + +/** + * MGC luma/chroma denoise for ISP-rendered bitmaps on the caller's GL context. + * + * The source texture holds sRGB-transfer encoded RGB (sRGB, Display P3 or extended sRGB, as + * LutImageProcessor interprets it). The pass order: + * 1. the mean linear luma gives the MGC tuning SNR under the [MgcBitmapNoiseModel] for the ISO; + * 2. a noise-aware detail map: local luma variance at 2x and 4x box scales against the model + * (scaled by its measured box variance ratios). Where structure clearly exceeds noise the + * map lowers MGC's spatial strength (a Q8 noise scale), so Pecan and ChromaDenoise keep + * texture; in noise it stays 1. At low SNR structure cannot be told from noise and the map + * stays near 1; + * 3. tiles, each with [TILE_SUPPORT_PX] of overlap, are decoded to linear RGBA16F, denoised by + * [MgcFullResolutionDenoise.denoiseLinearBitmap] and their cores written to a full linear image; + * 4. GCam's low-frequency chroma branch over the whole image: the linear result box-downsampled + * by 2^[LOW_FREQUENCY_LOG2] is chroma-denoised again and its correction upsampled back; + * 5. the linear result plus that correction is encoded into the output, keeping source alpha. + */ +internal class BitmapMgcDenoiser { + private val quad = RawFullscreenQuad() + private val transfer = RawFloatTextureTransfer(RawFloatTextureTransfer.Layout.HALF) + private val programs = HashMap() + + /** An immutable RGBA16F texture with its framebuffer (the transfer's upload requires immutability). */ + private class Surface(val label: String) { + var texture = 0 + var framebuffer = 0 + var width = 0 + var height = 0 + } + + private val linear = Surface("bitmap MGC linear") + private val output = Surface("bitmap MGC output") + private val tile = Surface("bitmap MGC tile") + private val half = Surface("bitmap MGC half") + private val quarter = Surface("bitmap MGC quarter") + private val map = Surface("bitmap MGC detail map") + private val mean = Surface("bitmap MGC mean") + private val outputTexture get() = output.texture + + private data class Tile( + val coreLeft: Int, + val coreTop: Int, + val coreRight: Int, + val coreBottom: Int, + val workLeft: Int, + val workTop: Int, + val workRight: Int, + val workBottom: Int, + ) { + val workWidth get() = workRight - workLeft + val workHeight get() = workBottom - workTop + } + + /** + * Returns a texture owned by this denoiser holding the denoised, re-encoded image, or + * [sourceTextureId] itself when both strengths are zero. [sensorIso] is the capture's ISO + * (EXIF/metadata), or null when unknown. + */ + fun denoise( + context: Context, + sourceTextureId: Int, + width: Int, + height: Int, + lumaStrength: Float, + chromaStrength: Float, + sensorIso: Int?, + ): Int { + val luma = DenoiseStrength.clamp(lumaStrength) + val chroma = DenoiseStrength.clamp(chromaStrength) + if (luma <= 0f && chroma <= 0f) return sourceTextureId + require(width > 0 && height > 0) + check(MgcFullResolutionDenoise.ensureInitialized(context)) { + "MGC RunFullResolutionDenoise is not initialized" + } + val startNs = System.nanoTime() + val tiles = planTiles(width, height) + val maxWorkWidth = tiles.maxOf { it.workWidth } + val maxWorkHeight = tiles.maxOf { it.workHeight } + ensureFullTextures(width, height) + ensureTile(maxWorkWidth, maxWorkHeight) + val noiseModel = MgcBitmapNoiseModel.forIso(sensorIso) + val snr = noiseModel.tuningSnr(meanLinearLuma(sourceTextureId, width, height)) + val strengthMap = detailStrengthMap(sourceTextureId, width, height, noiseModel) + try { + transfer.prepare(maxWorkWidth, maxWorkHeight) + for (tile in tiles) { + decodeTile(sourceTextureId, tile) + var succeeded = false + transfer.read( + texture = this.tile.texture, + width = tile.workWidth, + height = tile.workHeight, + capacityPixels = maxWorkWidth.toLong() * maxWorkHeight, + label = "MGC bitmap tile", + ) { mapped -> + succeeded = MgcFullResolutionDenoise.denoiseLinearBitmap( + rgba16f = mapped, + width = tile.workWidth, + height = tile.workHeight, + globalOriginX = tile.workLeft, + globalOriginY = tile.workTop, + fullWidth = width, + fullHeight = height, + noiseModel = noiseModel.denoiserModel, + spatialStrengthQ8 = strengthMap, + tuningSnr = snr, + lumaStrengthScale = luma, + chromaStrengthScale = chroma, + ) + } + check(succeeded) { "MGC bitmap denoise failed for tile $tile of ${width}x$height" } + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) + transfer.upload(this.tile.texture, tile.workWidth, tile.workHeight) + copyTileCore(tile) + } + } finally { + transfer.releaseBuffers() + } + val lowFrequency = chroma > 0f && + lowFrequencyChroma(width, height, noiseModel, strengthMap, snr, chroma) + encodeOutput(sourceTextureId, width, height, lowFrequency) + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) + RawGlesProgram.logErrors("BitmapMgcDenoiser") + PLog.i( + TAG, + "MGC bitmap denoise ${width}x$height tiles=${tiles.size} iso=$sensorIso " + + "modelIso=${noiseModel.iso} snr=$snr luma=$luma chroma=$chroma " + + "detailMap=${strengthMap.averageQ8()} lowFrequency=$lowFrequency " + + "took=${(System.nanoTime() - startNs) / 1_000_000}ms", + ) + return outputTexture + } + + fun release() { + programs.values.forEach { program -> if (program != 0) GLES30.glDeleteProgram(program) } + programs.clear() + listOf(linear, output, tile, half, quarter, map, mean).forEach(::releaseSurface) + transfer.release() + } + + private fun planTiles(width: Int, height: Int): List { + val columns = ceil(width / TILE_CORE_PX.toDouble()).toInt() + val rows = ceil(height / TILE_CORE_PX.toDouble()).toInt() + return buildList { + for (row in 0 until rows) { + val coreTop = row * height / rows + val coreBottom = (row + 1) * height / rows + for (column in 0 until columns) { + val coreLeft = column * width / columns + val coreRight = (column + 1) * width / columns + add( + Tile( + coreLeft = coreLeft, + coreTop = coreTop, + coreRight = coreRight, + coreBottom = coreBottom, + workLeft = (coreLeft - TILE_SUPPORT_PX).coerceAtLeast(0), + workTop = (coreTop - TILE_SUPPORT_PX).coerceAtLeast(0), + workRight = min(coreRight + TILE_SUPPORT_PX, width), + workBottom = min(coreBottom + TILE_SUPPORT_PX, height), + ), + ) + } + } + } + } + + /** Mean linear MGC luma of the whole image: a GPU cell reduction read back as halves. */ + private fun meanLinearLuma(sourceTextureId: Int, width: Int, height: Int): Float { + ensureSurface(mean, MEAN_GRID, MEAN_GRID) + val cellWidth = ceil(width / MEAN_GRID.toDouble()).toInt() + val cellHeight = ceil(height / MEAN_GRID.toDouble()).toInt() + draw("mean", MEAN_SHADER, mean, 0, 0, MEAN_GRID, MEAN_GRID) { program -> + bindTexture(program, "uSource", 0, sourceTextureId) + GLES30.glUniform2i(location(program, "uImageSize"), width, height) + GLES30.glUniform2i(location(program, "uCellSize"), cellWidth, cellHeight) + } + var weightedSum = 0.0 + var totalWeight = 0.0 + readHalves(mean, "MGC bitmap mean") { halves -> + for (cell in 0 until MEAN_GRID * MEAN_GRID) { + val cellMean = Half.toFloat(halves.get(cell * 4)).toDouble() + val weight = Half.toFloat(halves.get(cell * 4 + 1)).toDouble() + if (weight > 0.0 && cellMean.isFinite()) { + weightedSum += cellMean * weight + totalWeight += weight + } + } + } + check(totalWeight > 0.0) { "Bitmap luma reduction covered no pixels" } + return (weightedSum / totalWeight).toFloat() + } + + /** + * Q8 spatial strength over the ((width + 3) / 4) x ((height + 3) / 4) grid MGC expects: + * 256 where the local luma variance is explained by noise, down to [DETAIL_MIN_STRENGTH] where + * structure exceeds it by [DETAIL_HIGH_EXCESS] at both the 2x and 4x box scales. + */ + private fun detailStrengthMap( + sourceTextureId: Int, + width: Int, + height: Int, + model: MgcBitmapNoiseModel.Calibration, + ): ShortArray { + val halfWidth = (width + 1) / 2 + val halfHeight = (height + 1) / 2 + val gridWidth = (width + 3) / 4 + val gridHeight = (height + 3) / 4 + ensureSurface(half, halfWidth, halfHeight) + ensureSurface(quarter, gridWidth, gridHeight) + ensureSurface(map, gridWidth, gridHeight) + for ((surface, factor) in listOf(half to 2, quarter to 4)) { + draw("boxLuma", BOX_LUMA_SHADER, surface, 0, 0, surface.width, surface.height) { program -> + bindTexture(program, "uSource", 0, sourceTextureId) + GLES30.glUniform2i(location(program, "uImageSize"), width, height) + GLES30.glUniform1i(location(program, "uFactor"), factor) + } + } + draw("structure", STRUCTURE_SHADER, map, 0, 0, gridWidth, gridHeight) { program -> + bindTexture(program, "uBox2", 0, half.texture) + bindTexture(program, "uBox4", 1, quarter.texture) + GLES30.glUniform2i(location(program, "uBox2Size"), halfWidth, halfHeight) + GLES30.glUniform2i(location(program, "uBox4Size"), gridWidth, gridHeight) + GLES30.glUniform3f( + location(program, "uLumaNoise"), + model.lumaRead, + model.lumaShot, + model.lumaQuadratic, + ) + GLES30.glUniform2f( + location(program, "uBoxVarianceRatio"), + model.boxVarianceRatio2, + model.boxVarianceRatio4, + ) + GLES30.glUniform3f( + location(program, "uDetail"), + DETAIL_MIN_STRENGTH, + kotlin.math.ln(DETAIL_LOW_EXCESS), + kotlin.math.ln(DETAIL_HIGH_EXCESS), + ) + } + val strength = FloatArray(gridWidth * gridHeight) + readHalves(map, "MGC bitmap detail map") { halves -> + for (index in strength.indices) strength[index] = Half.toFloat(halves.get(index * 4)) + } + // 3x3 box with edge clamp: no block-shaped steps between neighbouring map cells. + return ShortArray(strength.size) { index -> + val x = index % gridWidth + val y = index / gridWidth + var sum = 0f + for (dy in -1..1) { + val yy = (y + dy).coerceIn(0, gridHeight - 1) + for (dx in -1..1) { + sum += strength[yy * gridWidth + (x + dx).coerceIn(0, gridWidth - 1)] + } + } + (sum / 9f * 256f).roundToInt().coerceIn(0, 256).toShort() + } + } + + private fun decodeTile(sourceTextureId: Int, tile: Tile) { + draw("decode", DECODE_SHADER, this.tile, 0, 0, tile.workWidth, tile.workHeight) { program -> + bindTexture(program, "uSource", 0, sourceTextureId) + GLES30.glUniform2i(location(program, "uSourceOffset"), tile.workLeft, tile.workTop) + } + } + + private fun copyTileCore(tile: Tile) { + draw( + "copyCore", COPY_CORE_SHADER, linear, + tile.coreLeft, tile.coreTop, tile.coreRight - tile.coreLeft, tile.coreBottom - tile.coreTop, + ) { program -> + bindTexture(program, "uTile", 0, this.tile.texture) + GLES30.glUniform2i(location(program, "uTileOrigin"), tile.workLeft, tile.workTop) + } + } + + /** Leaves the upsampling correction in [half]; returns whether it ran. */ + private fun lowFrequencyChroma( + width: Int, + height: Int, + model: MgcBitmapNoiseModel.Calibration, + strengthMap: ShortArray, + snr: Float, + chroma: Float, + ): Boolean { + val factor = 1 shl LOW_FREQUENCY_LOG2 + val lowWidth = (width + factor - 1) / factor + val lowHeight = (height + factor - 1) / factor + ensureSurface(half, lowWidth, lowHeight) + draw("boxRgb", BOX_RGB_SHADER, half, 0, 0, lowWidth, lowHeight) { program -> + bindTexture(program, "uLinear", 0, linear.texture) + GLES30.glUniform2i(location(program, "uImageSize"), width, height) + GLES30.glUniform1i(location(program, "uFactor"), factor) + } + var succeeded = false + try { + transfer.read(half.texture, lowWidth, lowHeight, label = "MGC bitmap low frequency") { mapped -> + succeeded = MgcFullResolutionDenoise.lowFrequencyChromaBitmap( + rgba16f = mapped, + lowWidth = lowWidth, + lowHeight = lowHeight, + fullWidth = width, + fullHeight = height, + log2Downsample = LOW_FREQUENCY_LOG2, + noiseModel = model.denoiserModel, + spatialStrengthQ8 = strengthMap, + tuningSnr = snr, + chromaStrengthScale = chroma, + ) + } + check(succeeded) { "MGC bitmap low-frequency chroma failed for ${width}x$height" } + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) + transfer.upload(half.texture, lowWidth, lowHeight) + } finally { + transfer.releaseBuffers() + } + return true + } + + private fun encodeOutput(sourceTextureId: Int, width: Int, height: Int, lowFrequency: Boolean) { + draw("encode", ENCODE_SHADER, output, 0, 0, width, height) { program -> + bindTexture(program, "uLinear", 0, linear.texture) + bindTexture(program, "uSource", 1, sourceTextureId) + bindTexture(program, "uCorrection", 2, if (lowFrequency) half.texture else linear.texture) + GLES30.glUniform1i(location(program, "uApplyCorrection"), if (lowFrequency) 1 else 0) + GLES30.glUniform2i(location(program, "uCorrectionSize"), half.width, half.height) + GLES30.glUniform1i(location(program, "uFactor"), 1 shl LOW_FREQUENCY_LOG2) + } + } + + private fun draw( + name: String, + shader: String, + target: Surface, + x: Int, + y: Int, + width: Int, + height: Int, + setup: (Int) -> Unit, + ) { + val program = programs.getOrPut(name) { + quad.createProgram(shader, "BitmapMgc_$name").also { + check(it != 0) { "Bitmap MGC program $name failed to link" } + } + } + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, target.framebuffer) + GLES30.glViewport(x, y, width, height) + GLES30.glUseProgram(program) + quad.bindIdentityTextureMatrix(program) + setup(program) + quad.draw(program) + } + + private inline fun readHalves(surface: Surface, label: String, crossinline consume: (java.nio.ShortBuffer) -> Unit) { + try { + transfer.read(surface.texture, surface.width, surface.height, label = label, writable = false) { + consume(it.asShortBuffer()) + } + } finally { + transfer.releaseBuffers() + } + } + + private fun location(program: Int, name: String) = GLES30.glGetUniformLocation(program, name) + + private fun bindTexture(program: Int, name: String, unit: Int, texture: Int) { + GLES30.glActiveTexture(GLES30.GL_TEXTURE0 + unit) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, texture) + GLES30.glUniform1i(location(program, name), unit) + } + + private fun ensureFullTextures(width: Int, height: Int) { + ensureSurface(linear, width, height) + ensureSurface(output, width, height) + } + + private fun ensureTile(width: Int, height: Int) = ensureSurface(tile, width, height) + + private fun ensureSurface(surface: Surface, width: Int, height: Int) { + if (surface.texture != 0 && surface.width == width && surface.height == height) return + releaseSurface(surface) + val textures = IntArray(1) + GLES30.glGenTextures(1, textures, 0) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textures[0]) + GLES30.glTexStorage2D(GLES30.GL_TEXTURE_2D, 1, GLES30.GL_RGBA16F, width, height) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_NEAREST) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_NEAREST) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE) + GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE) + GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0) + val framebuffers = IntArray(1) + GLES30.glGenFramebuffers(1, framebuffers, 0) + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebuffers[0]) + GLES30.glFramebufferTexture2D( + GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, textures[0], 0, + ) + check(GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) == GLES30.GL_FRAMEBUFFER_COMPLETE) { + "${surface.label} framebuffer is incomplete" + } + GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) + surface.texture = textures[0] + surface.framebuffer = framebuffers[0] + surface.width = width + surface.height = height + } + + private fun releaseSurface(surface: Surface) { + if (surface.framebuffer != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(surface.framebuffer), 0) + if (surface.texture != 0) GLES30.glDeleteTextures(1, intArrayOf(surface.texture), 0) + surface.framebuffer = 0 + surface.texture = 0 + surface.width = 0 + surface.height = 0 + } + + private fun ShortArray.averageQ8(): String = + "%.3f".format(if (isEmpty()) 1.0 else sumOf { it.toInt() } / (size * 256.0)) + + companion object { + private const val TAG = "BitmapMgcDenoiser" + /** Tile core edge; with its apron a tile stays near 2.3k px (about 40 MiB of PBO). */ + private const val TILE_CORE_PX = 2048 + /** MGC pyramid reach, the same apron RAW tiles give the full-resolution denoise. */ + private const val TILE_SUPPORT_PX = 112 + private const val MEAN_GRID = 64 + /** GCam's low-frequency chroma branch factor (2x): 4x drains small saturated detail. */ + private const val LOW_FREQUENCY_LOG2 = 1 + /** Spatial strength in confirmed structure (tools/bitmap_noise_calibration/experiments.py). */ + private const val DETAIL_MIN_STRENGTH = 0.35f + /** Structure/noise variance ratio where protection starts and where it is complete. */ + private const val DETAIL_LOW_EXCESS = 1.5f + private const val DETAIL_HIGH_EXCESS = 6f + + // Sign-symmetric sRGB transfer, so extended-range (F16) values keep their sign. + private const val SRGB_TRANSFER = """ + vec3 srgbDecode(vec3 encoded) { + vec3 magnitude = abs(encoded); + vec3 linear = mix( + magnitude / 12.92, + pow((magnitude + 0.055) / 1.055, vec3(2.4)), + step(vec3(0.04045), magnitude) + ); + return sign(encoded) * linear; + } + + vec3 srgbEncode(vec3 linear) { + vec3 magnitude = abs(linear); + vec3 encoded = mix( + magnitude * 12.92, + 1.055 * pow(magnitude, vec3(1.0 / 2.4)) - 0.055, + step(vec3(0.0031308), magnitude) + ); + return sign(linear) * encoded; + } + + const vec3 MGC_LUMA = vec3(0.2125999927520752, 0.7152000069618225, 0.07219959795475006); + """ + + // Prepended, not interpolated: #version must be the first line of the source. + private const val PREAMBLE = "#version 300 es\n" + + "precision highp float;\n" + + "precision highp int;\n" + + "in vec2 vTexCoord;\n" + + "out vec4 fragColor;\n" + + private val DECODE_SHADER = PREAMBLE + """ + uniform highp sampler2D uSource; + uniform ivec2 uSourceOffset; + $SRGB_TRANSFER + + void main() { + ivec2 p = ivec2(gl_FragCoord.xy) + uSourceOffset; + fragColor = vec4(srgbDecode(texelFetch(uSource, p, 0).rgb), 1.0); + } + """.trimIndent() + + private val COPY_CORE_SHADER = PREAMBLE + """ + uniform highp sampler2D uTile; + uniform ivec2 uTileOrigin; + + void main() { + fragColor = vec4(texelFetch(uTile, ivec2(gl_FragCoord.xy) - uTileOrigin, 0).rgb, 1.0); + } + """.trimIndent() + + // Adds the low-frequency correction with AddUpsampledChromaCorrection's bilinear sampling. + private val ENCODE_SHADER = PREAMBLE + """ + uniform highp sampler2D uLinear; + uniform highp sampler2D uSource; + uniform highp sampler2D uCorrection; + uniform int uApplyCorrection; + uniform ivec2 uCorrectionSize; + uniform int uFactor; + $SRGB_TRANSFER + + void main() { + ivec2 p = ivec2(gl_FragCoord.xy); + vec3 linear = texelFetch(uLinear, p, 0).rgb; + if (uApplyCorrection != 0) { + vec2 l = clamp((vec2(p) + 0.5) / float(uFactor) - 0.5, vec2(0.0), + vec2(uCorrectionSize - ivec2(1))); + ivec2 p0 = ivec2(l); + ivec2 p1 = min(p0 + ivec2(1), uCorrectionSize - ivec2(1)); + vec2 f = l - vec2(p0); + vec3 top = mix(texelFetch(uCorrection, p0, 0).rgb, + texelFetch(uCorrection, ivec2(p1.x, p0.y), 0).rgb, f.x); + vec3 bottom = mix(texelFetch(uCorrection, ivec2(p0.x, p1.y), 0).rgb, + texelFetch(uCorrection, p1, 0).rgb, f.x); + linear += mix(top, bottom, f.y); + } + fragColor = vec4(srgbEncode(linear), texelFetch(uSource, p, 0).a); + } + """.trimIndent() + + // Mean decoded linear luma of each uFactor x uFactor block (partial edge blocks included). + private val BOX_LUMA_SHADER = PREAMBLE + """ + uniform highp sampler2D uSource; + uniform ivec2 uImageSize; + uniform int uFactor; + $SRGB_TRANSFER + + void main() { + ivec2 origin = ivec2(gl_FragCoord.xy) * uFactor; + ivec2 end = min(origin + ivec2(uFactor), uImageSize); + float sum = 0.0; + float count = 0.0; + for (int y = origin.y; y < end.y; ++y) { + for (int x = origin.x; x < end.x; ++x) { + sum += dot(srgbDecode(texelFetch(uSource, ivec2(x, y), 0).rgb), MGC_LUMA); + count += 1.0; + } + } + fragColor = vec4(sum / max(count, 1.0), 0.0, 0.0, 1.0); + } + """.trimIndent() + + // Mean linear RGB of each uFactor x uFactor block of the denoised image. + private val BOX_RGB_SHADER = PREAMBLE + """ + uniform highp sampler2D uLinear; + uniform ivec2 uImageSize; + uniform int uFactor; + + void main() { + ivec2 origin = ivec2(gl_FragCoord.xy) * uFactor; + ivec2 end = min(origin + ivec2(uFactor), uImageSize); + vec3 sum = vec3(0.0); + float count = 0.0; + for (int y = origin.y; y < end.y; ++y) { + for (int x = origin.x; x < end.x; ++x) { + sum += texelFetch(uLinear, ivec2(x, y), 0).rgb; + count += 1.0; + } + } + fragColor = vec4(sum / max(count, 1.0), 1.0); + } + """.trimIndent() + + // Per quarter-resolution cell: local 5x5 variance of the 2x and 4x luma blocks against the + // noise model scaled by its box variance ratio; their geometric mean is the structure + // excess, mapped smoothly from uDetail.y..uDetail.z (log) to strength 1..uDetail.x. + private val STRUCTURE_SHADER = PREAMBLE + """ + uniform highp sampler2D uBox2; + uniform highp sampler2D uBox4; + uniform ivec2 uBox2Size; + uniform ivec2 uBox4Size; + uniform vec3 uLumaNoise; + uniform vec2 uBoxVarianceRatio; + uniform vec3 uDetail; + + float noiseVariance(float signal) { + float s = max(signal, 0.0); + return uLumaNoise.x + uLumaNoise.y * s + uLumaNoise.z * s * s; + } + + float excess(highp sampler2D boxes, ivec2 size, ivec2 center, float ratio) { + float sum = 0.0; + float sumSquares = 0.0; + for (int dy = -2; dy <= 2; ++dy) { + for (int dx = -2; dx <= 2; ++dx) { + ivec2 q = clamp(center + ivec2(dx, dy), ivec2(0), size - ivec2(1)); + float value = texelFetch(boxes, q, 0).r; + sum += value; + sumSquares += value * value; + } + } + float mean = sum / 25.0; + float variance = max(sumSquares / 25.0 - mean * mean, 0.0); + return variance / max(noiseVariance(mean) * ratio, 1e-20); + } + + void main() { + ivec2 cell = ivec2(gl_FragCoord.xy); + float excess4 = excess(uBox4, uBox4Size, cell, uBoxVarianceRatio.y); + float excess2 = 0.0; + for (int sy = 0; sy < 2; ++sy) { + for (int sx = 0; sx < 2; ++sx) { + ivec2 q = min(cell * 2 + ivec2(sx, sy), uBox2Size - ivec2(1)); + excess2 += excess(uBox2, uBox2Size, q, uBoxVarianceRatio.x); + } + } + excess2 *= 0.25; + float structure = sqrt(excess2 * excess4); + float t = clamp((log(max(structure, 1e-6)) - uDetail.y) / (uDetail.z - uDetail.y), 0.0, 1.0); + float confidence = t * t * (3.0 - 2.0 * t); + fragColor = vec4(1.0 - confidence * (1.0 - uDetail.x), 0.0, 0.0, 1.0); + } + """.trimIndent() + + // r: mean linear luma of the cell (MGC RGB->YUV row 0); g: covered fraction of the cell. + private val MEAN_SHADER = PREAMBLE + """ + uniform highp sampler2D uSource; + uniform ivec2 uImageSize; + uniform ivec2 uCellSize; + $SRGB_TRANSFER + + void main() { + ivec2 origin = ivec2(gl_FragCoord.xy) * uCellSize; + ivec2 end = min(origin + uCellSize, uImageSize); + float sum = 0.0; + float count = 0.0; + for (int y = origin.y; y < end.y; ++y) { + for (int x = origin.x; x < end.x; ++x) { + sum += dot(srgbDecode(texelFetch(uSource, ivec2(x, y), 0).rgb), MGC_LUMA); + count += 1.0; + } + } + float area = float(uCellSize.x * uCellSize.y); + fragColor = vec4(count > 0.0 ? sum / count : 0.0, count / area, 0.0, 1.0); + } + """.trimIndent() + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/lut/ChromaDenoiseDefaults.kt b/app/src/main/java/com/hinnka/mycamera/lut/ChromaDenoiseDefaults.kt index e429e70b..c55fe674 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/ChromaDenoiseDefaults.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/ChromaDenoiseDefaults.kt @@ -4,43 +4,8 @@ import com.hinnka.mycamera.processor.DenoiseStrength object ChromaDenoiseDefaults { const val RAW_CAPTURE_DEFAULT_STRENGTH = 0.0f - private const val MIN_ACTIVE_NOISE_BANDWIDTH = 1.0f - private const val STRENGTH_ONE_NOISE_BANDWIDTH = 8.0f - private const val FULL_OUTPUT_STRENGTH_POINT = 0.5f - private const val EDGE_GUIDANCE_START_POINT = 0.75f fun forRawCapture(requested: Float): Float = DenoiseStrength.clamp( maxOf(requested, RAW_CAPTURE_DEFAULT_STRENGTH) ) - - /** - * Keeps the bilateral kernel wide enough to recognize noise at every active - * slider value. Once output mixing reaches full strength, the remaining slider - * range continues widening chroma similarity. Strength 2 therefore extends the - * noise bandwidth beyond the former strength-1 endpoint instead of saturating. - */ - fun noiseBandwidth(strength: Float): Float { - val clamped = DenoiseStrength.clamp(strength) - if (clamped <= 0f) return 0f - return MIN_ACTIVE_NOISE_BANDWIDTH + - clamped * (STRENGTH_ONE_NOISE_BANDWIDTH - MIN_ACTIVE_NOISE_BANDWIDTH) - } - - /** Smoothly reaches full filter output at strength 0.5. */ - fun outputStrength(strength: Float): Float { - val t = (DenoiseStrength.clamp(strength) / FULL_OUTPUT_STRENGTH_POINT) - .coerceIn(0f, 1f) - return t * t * (3f - 2f * t) - } - - /** - * Uses strict edge rejection through the lower part of the slider. Above 0.75 - * the guide is relaxed smoothly so stronger settings can cross weak or noisy - * pseudo-edges and establish enough support for dense chroma noise. - */ - fun edgeGuidanceRelaxation(strength: Float): Float { - val t = ((DenoiseStrength.clamp(strength) - EDGE_GUIDANCE_START_POINT) / - (1f - EDGE_GUIDANCE_START_POINT)).coerceIn(0f, 1f) - return t * t * (3f - 2f * t) - } } diff --git a/app/src/main/java/com/hinnka/mycamera/lut/ChromaDenoiseShaders.kt b/app/src/main/java/com/hinnka/mycamera/lut/ChromaDenoiseShaders.kt deleted file mode 100644 index 9d78d49b..00000000 --- a/app/src/main/java/com/hinnka/mycamera/lut/ChromaDenoiseShaders.kt +++ /dev/null @@ -1,293 +0,0 @@ -package com.hinnka.mycamera.lut - - -/** - * Shared multi-scale edge-guided chroma denoise shader. - * - * RAW input is filtered in linear camera RGB opponent space before white - * balance and color conversion. Bitmap input retains its luma/chroma transform. - * Both paths use a prefiltered luminance guide. RAW luminance is the symmetric - * camera-RGB mean; bitmap luminance retains its display-space coefficients. - */ -object ChromaDenoiseShaders { - val PASS_EDGE_GUIDE = """ - #version 300 es - precision highp float; - in vec2 vTexCoord; - out vec4 fragColor; - uniform sampler2D uInputTexture; - uniform vec2 uTexelSize; - uniform int uCameraRgbInput; - - float guideSignal(vec3 rgb) { - if (uCameraRgbInput != 0) { - return (rgb.r + rgb.g + rgb.b) / 3.0; - } - return dot(rgb, vec3(0.2126, 0.7152, 0.0722)); - } - - float guideAt(vec2 coord) { - return guideSignal(texture(uInputTexture, coord).rgb); - } - - void main() { - float guide = guideAt(vTexCoord) * 0.5; - guide += guideAt(vTexCoord + vec2( uTexelSize.x, 0.0)) * 0.125; - guide += guideAt(vTexCoord + vec2(-uTexelSize.x, 0.0)) * 0.125; - guide += guideAt(vTexCoord + vec2(0.0, uTexelSize.y)) * 0.125; - guide += guideAt(vTexCoord + vec2(0.0, -uTexelSize.y)) * 0.125; - fragColor = vec4(guide, 0.0, 0.0, 1.0); - } - """.trimIndent() - - val PASS_CHROMA_DENOISE = """ - #version 300 es - precision highp float; - in vec2 vTexCoord; - out vec4 fragColor; - uniform sampler2D uInputTexture; - uniform sampler2D uGuideTexture; - uniform vec2 uTexelSize; - uniform float uH; - uniform float uOutputStrength; - uniform float uEdgeGuidanceRelaxation; - uniform int uCameraRgbInput; - // Camera-domain variance models. RB order is - // [red slope, red offset, blue slope, blue offset]. - uniform vec4 uNoiseModelRB; - // [green slope, green offset]. - uniform vec2 uNoiseModelG; - - vec3 rgb2ycbcr(vec3 rgb) { - float y = dot(rgb, vec3(0.2126, 0.7152, 0.0722)); - return vec3(y, - dot(rgb, vec3(-0.114572, -0.385428, 0.5 )), - dot(rgb, vec3( 0.5, -0.454153, -0.045847))); - } - vec3 ycbcr2rgb(vec3 yuv) { - return vec3(yuv.x + 1.5748 * yuv.z, - yuv.x - 0.187324 * yuv.y - 0.468124 * yuv.z, - yuv.x + 1.8556 * yuv.y); - } - - vec3 channelNoiseVariance(vec3 rgb) { - return max( - vec3( - uNoiseModelRB.x * max(rgb.r, 0.0) + uNoiseModelRB.y, - uNoiseModelG.x * max(rgb.g, 0.0) + uNoiseModelG.y, - uNoiseModelRB.z * max(rgb.b, 0.0) + uNoiseModelRB.w - ), - vec3(1e-10) - ); - } - - vec3 rgbToFilterSpace(vec3 rgb) { - if (uCameraRgbInput != 0) { - // Keep every sample in one linear camera-RGB coordinate system. - // Exposure invariance is restored after each weighted mean, not - // by averaging unstable per-pixel ratios in the shadows. - return vec3( - (rgb.r + rgb.g + rgb.b) / 3.0, - rgb.r - rgb.g, - rgb.b - rgb.g - ); - } - return rgb2ycbcr(rgb); - } - - vec3 filterSpaceToRgb(vec3 value) { - if (uCameraRgbInput != 0) { - // value.x is the symmetric camera-RGB mean, not green. Recover - // the three channels from mean, R-G and B-G without giving any - // channel a privileged luminance role. - float green = value.x - (value.y + value.z) / 3.0; - return max( - vec3( - green + value.y, - green, - green + value.z - ), - vec3(0.0) - ); - } - return ycbcr2rgb(value); - } - - vec2 chromaNoiseSigma(vec3 rgb) { - vec3 variance = channelNoiseVariance(rgb); - if (uCameraRgbInput != 0) { - // Var(R-G) = Var(R) + Var(G), likewise for B-G. - return sqrt(max(variance.rb + variance.gg, vec2(1e-10))); - } - const vec3 cb = vec3(-0.114572, -0.385428, 0.5); - const vec3 cr = vec3(0.5, -0.454153, -0.045847); - return sqrt(max( - vec2(dot(cb * cb, variance), dot(cr * cr, variance)), - vec2(1e-10) - )); - } - - float guideNoiseSigma(vec3 rgb) { - vec3 variance = channelNoiseVariance(rgb); - if (uCameraRgbInput != 0) { - return sqrt(max((variance.r + variance.g + variance.b) / 9.0, 1e-10)); - } - const vec3 luma = vec3(0.2126, 0.7152, 0.0722); - return sqrt(max(dot(luma * luma, variance), 1e-10)); - } - - void filterScale( - float radius, - float centerGuide, - float centerSignal, - vec2 baseChroma, - vec2 chromaGuide, - float invGuideH2, - vec2 invChromaH2, - out vec2 filteredChroma, - out float edgeSupport - ) { - // The center estimate anchors each wider scale and prevents a sparse - // coarse neighborhood from replacing a small valid color feature. - vec2 sumChroma = baseChroma; - float sumSignal = centerSignal; - float sumWeight = 1.0; - float acceptedLumaSupport = 0.0; - float totalSupport = 0.0; - - for (int x = -1; x <= 1; x++) { - for (int y = -1; y <= 1; y++) { - if (x == 0 && y == 0) continue; - - vec2 gridOffset = vec2(float(x), float(y)); - float distance2 = dot(gridOffset, gridOffset); - float spatialWeight = exp(-0.72 * distance2); - vec2 offset = gridOffset * uTexelSize * radius; - vec2 sampleCoord = vTexCoord + offset; - vec3 sampleValue = rgbToFilterSpace( - texture(uInputTexture, sampleCoord).rgb - ); - - float guideDelta = - texture(uGuideTexture, sampleCoord).r - centerGuide; - float guideWeight = - exp(-(guideDelta * guideDelta) * invGuideH2); - vec2 chromaDelta = sampleValue.yz - chromaGuide; - float chromaDistance = - dot(chromaDelta * chromaDelta, invChromaH2); - float chromaWeight = exp(-chromaDistance); - float weight = spatialWeight * guideWeight * chromaWeight; - - sumChroma += sampleValue.yz * weight; - sumSignal += sampleValue.x * weight; - sumWeight += weight; - acceptedLumaSupport += spatialWeight * guideWeight; - totalSupport += spatialWeight; - } - } - - vec2 averageChroma = sumChroma / max(sumWeight, 1e-6); - if (uCameraRgbInput != 0) { - // averageChroma is the opponent component of the weighted RGB - // mean. Scale that mean back to the center RGB mean so exposure - // differences in sparse/coarse samples cannot turn into color. - // This ratio-of-means is stable in shadows and exactly preserves - // a constant camera chromaticity across an exposure gradient. - float averageSignal = sumSignal / max(sumWeight, 1e-6); - float signalScale = centerSignal / max(averageSignal, 1e-6); - filteredChroma = averageChroma * signalScale; - } else { - filteredChroma = averageChroma; - } - // Support reflects the shared luminance guide in both input domains. - edgeSupport = acceptedLumaSupport / max(totalSupport, 1e-6); - } - - float featheredEdgeSupport(float support, float exponent) { - return pow(clamp(support, 0.0, 1.0), exponent); - } - - void main() { - vec4 source = texture(uInputTexture, vTexCoord); - if (uH <= 0.00001) { - fragColor = source; - return; - } - - vec3 centerValue = rgbToFilterSpace(source.rgb); - vec2 noiseSigma = chromaNoiseSigma(source.rgb); - - float centerGuide = texture(uGuideTexture, vTexCoord).r; - float guideSigma = guideNoiseSigma(source.rgb); - float guideBandwidthScale = - mix(1.0, 4.0, uEdgeGuidanceRelaxation); - float guideH = - guideSigma * 4.0 * guideBandwidthScale; - float invGuideH2 = 1.0 / max(guideH * guideH, 1e-8); - // Denoise strength may relax the range threshold slightly, but every - // spatial scale shares the same bounded color-edge bandwidth. Large - // radii must never gain permission to cross a red/blue boundary. - float strengthT = clamp((uH - 1.0) / 7.0, 0.0, 1.0); - float chromaEdgeSigmaMultiplier = mix(2.75, 3.5, strengthT); - vec2 chromaEdgeH = - max(noiseSigma * chromaEdgeSigmaMultiplier, vec2(1e-5)); - vec2 invChromaEdgeH2 = - 1.0 / max(chromaEdgeH * chromaEdgeH, vec2(1e-8)); - - vec2 fineCandidate; - float fineSupport; - // Radius one directly covers the one-to-two-pixel sensor grain that - // was skipped by the previous sparse fine scale. - filterScale( - 1.0, - centerGuide, - centerValue.x, - centerValue.yz, - centerValue.yz, - invGuideH2, - invChromaEdgeH2, - fineCandidate, - fineSupport - ); - vec2 fineChroma = - mix(centerValue.yz, fineCandidate, uOutputStrength); - - vec2 mediumCandidate; - float mediumSupport; - filterScale( - 4.0, - centerGuide, - centerValue.x, - fineChroma, - fineChroma, - invGuideH2, - invChromaEdgeH2, - mediumCandidate, - mediumSupport - ); - float mediumMix = - uOutputStrength * featheredEdgeSupport(mediumSupport, 1.5); - vec2 mediumChroma = mix(fineChroma, mediumCandidate, mediumMix); - - vec2 coarseCandidate; - float coarseSupport; - filterScale( - 14.0, - centerGuide, - centerValue.x, - mediumChroma, - mediumChroma, - invGuideH2, - invChromaEdgeH2, - coarseCandidate, - coarseSupport - ); - float coarseMix = - uOutputStrength * featheredEdgeSupport(coarseSupport, 2.0); - vec2 coarseChroma = mix(mediumChroma, coarseCandidate, coarseMix); - - centerValue.yz = coarseChroma; - fragColor = vec4(filterSpaceToRgb(centerValue), source.a); - } - """.trimIndent() -} diff --git a/app/src/main/java/com/hinnka/mycamera/lut/LutImageProcessor.kt b/app/src/main/java/com/hinnka/mycamera/lut/LutImageProcessor.kt index a35b9a77..a7c256d8 100644 --- a/app/src/main/java/com/hinnka/mycamera/lut/LutImageProcessor.kt +++ b/app/src/main/java/com/hinnka/mycamera/lut/LutImageProcessor.kt @@ -12,11 +12,8 @@ import android.opengl.GLES30 import android.opengl.GLES31 import androidx.core.graphics.createBitmap import com.hinnka.mycamera.model.ColorRecipeParams -import com.hinnka.mycamera.lut.ChromaDenoiseShaders import com.hinnka.mycamera.processor.GlesComputeWorkGroup import com.hinnka.mycamera.processor.DenoiseStrength -import com.hinnka.mycamera.raw.DenoiseProfileNlmConfig -import com.hinnka.mycamera.raw.DenoiseProfileShaders import com.hinnka.mycamera.utils.LargeDirectBuffer import com.hinnka.mycamera.utils.PLog import kotlinx.coroutines.asCoroutineDispatcher @@ -84,24 +81,9 @@ class LutImageProcessor(context: Context? = null) { private var texCoordBuffer: FloatBuffer? = null private var indexBuffer: ShortBuffer? = null - private var bitmapDenoisePreconditionProgram = 0 - private var bitmapDenoiseNlmInitProgram = 0 - private var bitmapDenoiseNlmFusedAccuProgram = 0 - private var bitmapDenoiseNlmFinishProgram = 0 - private var bitmapDenoisePassthroughProgram = 0 - private var computeCapabilitiesChecked = false - private var computeCapabilitiesSupported = false - private var bitmapChromaDenoiseGuideProgram = 0 - private var bitmapChromaDenoiseProgram = 0 + private val bitmapMgcDenoiser = BitmapMgcDenoiser() private var lutSharpenProgram = 0 private var lutLuminanceGainProgram = 0 - - private val bitmapDenoiseTexId = IntArray(2) - private val bitmapDenoiseFboId = IntArray(2) - private var bitmapDenoiseNlmU2BufferId = 0 - private var bitmapDenoiseNlmBufferPixels = 0 - private var bitmapDenoiseWidth = 0 - private var bitmapDenoiseHeight = 0 private var lutSharpenTextureId = 0 private var lutSharpenFboId = 0 private var lutSharpenWidth = 0 @@ -311,8 +293,6 @@ class LutImageProcessor(context: Context? = null) { * @param argbData RGBA 16-bit 格式的像素数据 (ShortBuffer) [width, height, r1, g1, b1, a1, ...] * @param lutConfig LUT 配置 * @param colorRecipeParams 色彩配方参数 - * @param noiseReductionValue 降噪强度 - * @param chromaNoiseReductionValue 减少杂色强度 */ suspend fun applyLut( argbData: ShortBuffer, @@ -321,8 +301,6 @@ class LutImageProcessor(context: Context? = null) { colorSpace: ColorSpace, lutConfig: LutConfig?, colorRecipeParams: ColorRecipeParams?, - noiseReductionValue: Float = 0f, - chromaNoiseReductionValue: Float = 0f, lutMaskType: Int = 0, ): Bitmap = withContext(glDispatcher) { currentCoroutineContext().ensureActive() @@ -339,9 +317,6 @@ class LutImageProcessor(context: Context? = null) { // 锐度属于色彩配方,在完成 sRGB 调色后统一处理;不读取 RAW/元数据锐化值。 val sharpening: Float = colorRecipeParams?.sharpness?.coerceIn(-1f, 1f) ?: 0f - val noiseReduction: Float = noiseReductionValue - val chromaNoiseReduction: Float = chromaNoiseReductionValue - val chromaDenoiseStrength = DenoiseStrength.clamp(chromaNoiseReduction) // 激活上下文 EGL14.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext) @@ -354,15 +329,13 @@ class LutImageProcessor(context: Context? = null) { uploadImageTextureFromArgb(argbData, width, height) currentCoroutineContext().ensureActive() - val denoisedTexId = renderBitmapDenoise(imageTextureId, width, height, noiseReduction, chromaDenoiseStrength) - currentCoroutineContext().ensureActive() // 上传 LUT 纹理 if (lutConfig != null) { uploadLutTexture(lutConfig) } - val inputTexId = denoisedTexId + val inputTexId = imageTextureId // HDF 光晕效果预处理(在主 shader 之前,需要模糊的光晕纹理) if (halation > 0f) { @@ -395,8 +368,6 @@ class LutImageProcessor(context: Context? = null) { colorSpace: ColorSpace, baselineLayer: LutRenderLayer?, creativeLayer: LutRenderLayer?, - noiseReductionValue: Float = 0f, - chromaNoiseReductionValue: Float = 0f, ): Bitmap { val hasBaseline = baselineLayer?.lutConfig != null || baselineLayer?.colorRecipeParams != null val hasCreative = creativeLayer?.lutConfig != null || creativeLayer?.colorRecipeParams != null @@ -408,16 +379,12 @@ class LutImageProcessor(context: Context? = null) { height = height, colorSpace = colorSpace, lutConfig = baselineLayer.lutConfig, - colorRecipeParams = baselineLayer.colorRecipeParams, - noiseReductionValue = 0f, - chromaNoiseReductionValue = 0f, + colorRecipeParams = baselineLayer.colorRecipeParams ) applyLut( bitmap = baseBitmap, lutConfig = creativeLayer.lutConfig, - colorRecipeParams = creativeLayer.colorRecipeParams, - noiseReductionValue = noiseReductionValue, - chromaNoiseReductionValue = chromaNoiseReductionValue + colorRecipeParams = creativeLayer.colorRecipeParams ) } hasBaseline -> applyLut( @@ -426,9 +393,7 @@ class LutImageProcessor(context: Context? = null) { height = height, colorSpace = colorSpace, lutConfig = baselineLayer.lutConfig, - colorRecipeParams = baselineLayer.colorRecipeParams, - noiseReductionValue = noiseReductionValue, - chromaNoiseReductionValue = chromaNoiseReductionValue + colorRecipeParams = baselineLayer.colorRecipeParams ) else -> applyLut( argbData = argbData, @@ -436,9 +401,7 @@ class LutImageProcessor(context: Context? = null) { height = height, colorSpace = colorSpace, lutConfig = creativeLayer?.lutConfig, - colorRecipeParams = creativeLayer?.colorRecipeParams, - noiseReductionValue = noiseReductionValue, - chromaNoiseReductionValue = chromaNoiseReductionValue + colorRecipeParams = creativeLayer?.colorRecipeParams ) } } @@ -449,15 +412,11 @@ class LutImageProcessor(context: Context? = null) { * @param bitmap 输入图片 * @param lutConfig LUT 配置 * @param colorRecipeParams 色彩配方参数 - * @param noiseReductionValue 降噪强度 - * @param chromaNoiseReductionValue 减少杂色强度 */ suspend fun applyLut( bitmap: Bitmap, lutConfig: LutConfig?, colorRecipeParams: ColorRecipeParams?, - noiseReductionValue: Float = 0f, - chromaNoiseReductionValue: Float = 0f, lutMaskType: Int = 0, ): Bitmap = withContext(glDispatcher) { currentCoroutineContext().ensureActive() @@ -473,9 +432,6 @@ class LutImageProcessor(context: Context? = null) { // 锐度属于色彩配方,在完成 sRGB 调色后统一处理;不读取 RAW/元数据锐化值。 val sharpening: Float = colorRecipeParams?.sharpness?.coerceIn(-1f, 1f) ?: 0f - val noiseReduction: Float = noiseReductionValue - val chromaNoiseReduction: Float = chromaNoiseReductionValue - val chromaDenoiseStrength = DenoiseStrength.clamp(chromaNoiseReduction) // 确保上下文激活 EGL14.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext) @@ -491,15 +447,13 @@ class LutImageProcessor(context: Context? = null) { uploadImageTexture(bitmap) currentCoroutineContext().ensureActive() - val denoisedTexId = renderBitmapDenoise(imageTextureId, width, height, noiseReduction, chromaDenoiseStrength) - currentCoroutineContext().ensureActive() // 上传 LUT 纹理 if (lutConfig != null) { uploadLutTexture(lutConfig) } - val inputTexId = denoisedTexId + val inputTexId = imageTextureId val renderColorSpace = bitmap.colorSpace ?: ColorSpace.get(ColorSpace.Named.SRGB) // HDF 光晕效果预处理 @@ -530,8 +484,6 @@ class LutImageProcessor(context: Context? = null) { bitmap: Bitmap, baselineLayer: LutRenderLayer?, creativeLayer: LutRenderLayer?, - noiseReductionValue: Float = 0f, - chromaNoiseReductionValue: Float = 0f, ): Bitmap { val hasBaseline = baselineLayer?.lutConfig != null || baselineLayer?.colorRecipeParams != null val hasCreative = creativeLayer?.lutConfig != null || creativeLayer?.colorRecipeParams != null @@ -540,31 +492,23 @@ class LutImageProcessor(context: Context? = null) { val baseBitmap = applyLut( bitmap = bitmap, lutConfig = baselineLayer.lutConfig, - colorRecipeParams = baselineLayer.colorRecipeParams, - noiseReductionValue = 0f, - chromaNoiseReductionValue = 0f, + colorRecipeParams = baselineLayer.colorRecipeParams ) applyLut( bitmap = baseBitmap, lutConfig = creativeLayer.lutConfig, - colorRecipeParams = creativeLayer.colorRecipeParams, - noiseReductionValue = noiseReductionValue, - chromaNoiseReductionValue = chromaNoiseReductionValue + colorRecipeParams = creativeLayer.colorRecipeParams ) } hasBaseline -> applyLut( bitmap = bitmap, lutConfig = baselineLayer.lutConfig, - colorRecipeParams = baselineLayer.colorRecipeParams, - noiseReductionValue = noiseReductionValue, - chromaNoiseReductionValue = chromaNoiseReductionValue + colorRecipeParams = baselineLayer.colorRecipeParams ) else -> applyLut( bitmap = bitmap, lutConfig = creativeLayer?.lutConfig, - colorRecipeParams = creativeLayer?.colorRecipeParams, - noiseReductionValue = noiseReductionValue, - chromaNoiseReductionValue = chromaNoiseReductionValue + colorRecipeParams = creativeLayer?.colorRecipeParams ) } } @@ -578,16 +522,12 @@ class LutImageProcessor(context: Context? = null) { bitmap: Bitmap, baselineLayer: LutRenderLayer?, creativeLayer: LutRenderLayer?, - noiseReductionValue: Float = 0f, - chromaNoiseReductionValue: Float = 0f, luminanceGainDownsample: Int = 1, ): LutStackRenderResult { val rendered = applyLutStack( bitmap = bitmap, baselineLayer = baselineLayer, - creativeLayer = creativeLayer, - noiseReductionValue = noiseReductionValue, - chromaNoiseReductionValue = chromaNoiseReductionValue, + creativeLayer = creativeLayer ) val luminanceGainMap = if (!bitmap.colorSpace.isEncodedSrgbFamily() || !rendered.colorSpace.isEncodedSrgbFamily() @@ -741,14 +681,18 @@ class LutImageProcessor(context: Context? = null) { if (uploadBitmap !== bitmap) uploadBitmap.recycle() } - suspend fun applyChromaDenoise(bitmap: Bitmap, strength: Float = 0.1f): Bitmap = - applyBitmapDenoise(bitmap, 0f, strength) + suspend fun applyChromaDenoise(bitmap: Bitmap, strength: Float, sensorIso: Int?): Bitmap = + applyBitmapDenoise(bitmap, 0f, strength, sensorIso) - /** Bitmap 降噪(不含 LUT/配方):色度降噪 + NLM 亮度降噪,两个强度都为 0 时原样返回。 */ + /** + * Bitmap 降噪(不含 LUT/配方):MGC 亮度/色度降噪,两个强度都为 0 时原样返回。 + * [sensorIso] 为拍摄 ISO(元数据/EXIF),选择对应的噪声模型;未知时为 null。 + */ suspend fun applyBitmapDenoise( bitmap: Bitmap, lumaStrength: Float, chromaStrength: Float, + sensorIso: Int?, ): Bitmap = withContext(glDispatcher) { currentCoroutineContext().ensureActive() val luma = DenoiseStrength.clamp(lumaStrength) @@ -767,7 +711,7 @@ class LutImageProcessor(context: Context? = null) { setupFramebuffer(width, height) uploadImageTexture(bitmap) - val denoisedTexId = renderBitmapDenoise(imageTextureId, width, height, luma, chroma) + val denoisedTexId = renderBitmapDenoise(width, height, luma, chroma, sensorIso) performRender( width = width, height = height, @@ -1328,77 +1272,34 @@ class LutImageProcessor(context: Context? = null) { ) } - private fun ensureBitmapDenoiseProfilePrograms() { - if (!computeCapabilitiesChecked) { - computeCapabilitiesSupported = logAndValidateComputeCapabilities() - computeCapabilitiesChecked = true + /** + * MGC luma/chroma denoise of the uploaded image ([imageTextureId]); returns the texture the + * render consumes: the denoiser's output, or [imageTextureId] when both strengths are zero. + */ + private fun renderBitmapDenoise( + width: Int, + height: Int, + lumaStrength: Float, + chromaStrength: Float, + sensorIso: Int?, + ): Int { + if (DenoiseStrength.clamp(lumaStrength) <= 0f && DenoiseStrength.clamp(chromaStrength) <= 0f) { + return imageTextureId } - if (!computeCapabilitiesSupported) { - ensureBitmapDenoisePassthroughProgram() - return + val context = checkNotNull(appContext) { + "Bitmap MGC denoise requires the LutImageProcessor application context" } - if (bitmapDenoisePreconditionProgram == 0) { - bitmapDenoisePreconditionProgram = compileComputeProgram( - DenoiseProfileShaders.PRECONDITION_V2, - "BitmapDenoise_PreconditionV2", - ) - } - if (bitmapDenoiseNlmInitProgram == 0) { - bitmapDenoiseNlmInitProgram = compileComputeProgram( - DenoiseProfileShaders.INIT, - "BitmapDenoise_NLM_Init", - ) - } - if (bitmapDenoiseNlmFusedAccuProgram == 0) { - bitmapDenoiseNlmFusedAccuProgram = compileComputeProgram( - DenoiseProfileShaders.FUSED_ACCU, - "BitmapDenoise_NLM_FusedAccu", - ) - } - if (bitmapDenoiseNlmFinishProgram == 0) { - bitmapDenoiseNlmFinishProgram = compileComputeProgram( - DenoiseProfileShaders.FINISH_V2, - "BitmapDenoise_NLM_FinishV2", - ) - } - ensureBitmapDenoisePassthroughProgram() - PLog.d( - TAG, - "Bitmap denoiseprofile programs initialized: pre=$bitmapDenoisePreconditionProgram " + - "init=$bitmapDenoiseNlmInitProgram fusedAccu=$bitmapDenoiseNlmFusedAccuProgram " + - "finish=$bitmapDenoiseNlmFinishProgram " + - "pass=$bitmapDenoisePassthroughProgram" + return bitmapMgcDenoiser.denoise( + context = context, + sourceTextureId = imageTextureId, + width = width, + height = height, + lumaStrength = lumaStrength, + chromaStrength = chromaStrength, + sensorIso = sensorIso, ) } - private fun ensureBitmapDenoisePassthroughProgram() { - if (bitmapDenoisePassthroughProgram == 0) { - bitmapDenoisePassthroughProgram = createFragmentProgram( - IMAGE_VERTEX_SHADER, - TEXTURE_PASSTHROUGH_SHADER, - "BitmapDenoise_Passthrough", - ) - } - } - - private fun ensureBitmapChromaDenoisePrograms() { - ensureBitmapDenoisePassthroughProgram() - if (bitmapChromaDenoiseGuideProgram == 0) { - bitmapChromaDenoiseGuideProgram = createFragmentProgram( - IMAGE_VERTEX_SHADER, - ChromaDenoiseShaders.PASS_EDGE_GUIDE, - "BitmapChromaDenoise_EdgeGuide", - ) - } - if (bitmapChromaDenoiseProgram == 0) { - bitmapChromaDenoiseProgram = createFragmentProgram( - IMAGE_VERTEX_SHADER, - ChromaDenoiseShaders.PASS_CHROMA_DENOISE, - "BitmapChromaDenoise_MultiScale", - ) - } - } - private fun ensureLutSharpenProgram() { if (lutSharpenProgram == 0) { lutSharpenProgram = createFragmentProgram( @@ -1463,245 +1364,6 @@ class LutImageProcessor(context: Context? = null) { ) } - private fun setupBitmapDenoiseFramebuffers(width: Int, height: Int) { - if (bitmapDenoiseWidth == width && bitmapDenoiseHeight == height && bitmapDenoiseTexId[0] != 0) return - bitmapDenoiseWidth = width - bitmapDenoiseHeight = height - - for (i in 0..1) { - if (bitmapDenoiseTexId[i] != 0) GLES30.glDeleteTextures(1, intArrayOf(bitmapDenoiseTexId[i]), 0) - if (bitmapDenoiseFboId[i] != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(bitmapDenoiseFboId[i]), 0) - } - - for (i in 0..1) { - val t = IntArray(1) - val f = IntArray(1) - GLES30.glGenTextures(1, t, 0) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, t[0]) - GLES30.glTexStorage2D(GLES30.GL_TEXTURE_2D, 1, GLES30.GL_RGBA16F, width, height) - GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_NEAREST) - GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_NEAREST) - GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE) - GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE) - GLES30.glGenFramebuffers(1, f, 0) - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, f[0]) - GLES30.glFramebufferTexture2D( - GLES30.GL_FRAMEBUFFER, - GLES30.GL_COLOR_ATTACHMENT0, - GLES30.GL_TEXTURE_2D, - t[0], - 0 - ) - bitmapDenoiseTexId[i] = t[0] - bitmapDenoiseFboId[i] = f[0] - - val status = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) - if (status != GLES30.GL_FRAMEBUFFER_COMPLETE) { - PLog.e(TAG, "Bitmap denoiseprofile FBO $i incomplete: $status") - } - } - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0) - } - - /** - * 色度降噪(写入 bitmapDenoiseTexId[0])后接 NLM 亮度降噪(写入 bitmapDenoiseTexId[1]), - * 返回降噪结果所在纹理;两个强度都为 0 时返回 [sourceTextureId]。 - */ - private fun renderBitmapDenoise( - sourceTextureId: Int, - width: Int, - height: Int, - lumaStrength: Float, - chromaStrength: Float, - ): Int { - var current = sourceTextureId - if (chromaStrength > 0f) { - renderBitmapChromaDenoise(current, width, height, chromaStrength) - current = bitmapDenoiseTexId[0] - } - if (lumaStrength > 0f) { - renderBitmapDenoiseProfile(current, width, height, lumaStrength) - current = bitmapDenoiseTexId[1] - } - return current - } - - private fun renderBitmapDenoiseProfile( - sourceTextureId: Int, - width: Int, - height: Int, - noiseReduction: Float - ) { - ensureBitmapDenoiseProfilePrograms() - setupBitmapDenoiseFramebuffers(width, height) - - val strength = DenoiseStrength.clamp(noiseReduction) - if (strength <= 0f || width * height < 2) { - renderTexturePassthrough(sourceTextureId, bitmapDenoiseFboId[1], width, height) - return - } - if (!isBitmapDenoiseProfileReady()) { - renderTexturePassthrough(sourceTextureId, bitmapDenoiseFboId[1], width, height) - return - } - setupBitmapDenoiseResources(width, height) - - val preconditionTextureId = if (sourceTextureId == bitmapDenoiseTexId[0]) { - bitmapDenoiseTexId[1] - } else { - bitmapDenoiseTexId[0] - } - val params = buildBitmapDenoiseParams(strength) - dispatchBitmapDenoisePreconditionV2(sourceTextureId, preconditionTextureId, width, height, params) - dispatchBitmapDenoiseNlm(sourceTextureId, preconditionTextureId, bitmapDenoiseTexId[1], width, height, params) - checkGlError("renderBitmapDenoiseProfile") - } - - private fun renderBitmapChromaDenoise( - sourceTextureId: Int, - width: Int, - height: Int, - chromaNoiseReduction: Float, - targetIndex: Int = 0 - ) { - ensureBitmapChromaDenoisePrograms() - setupBitmapDenoiseFramebuffers(width, height) - - val strength = DenoiseStrength.clamp(chromaNoiseReduction) - val target = targetIndex.coerceIn(0, bitmapDenoiseTexId.lastIndex) - val edgeGuidanceRelaxation = - ChromaDenoiseDefaults.edgeGuidanceRelaxation(strength) - if (strength <= 0f || bitmapChromaDenoiseProgram == 0 || - bitmapChromaDenoiseGuideProgram == 0 - ) { - renderTexturePassthrough(sourceTextureId, bitmapDenoiseFboId[target], width, height) - return - } - - val identityMatrix = FloatArray(16) - android.opengl.Matrix.setIdentityM(identityMatrix, 0) - val h = ChromaDenoiseDefaults.noiseBandwidth(strength) - val guideIndex = if (target == 0) 1 else 0 - renderBitmapChromaDenoiseEdgeGuide( - sourceTextureId, - bitmapDenoiseFboId[guideIndex], - width, - height - ) - val guideTextureId = bitmapDenoiseTexId[guideIndex] - - GLES30.glUseProgram(bitmapChromaDenoiseProgram) - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, bitmapDenoiseFboId[target]) - GLES30.glViewport(0, 0, width, height) - GLES30.glActiveTexture(GLES30.GL_TEXTURE0) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, sourceTextureId) - GLES30.glUniform1i(GLES30.glGetUniformLocation(bitmapChromaDenoiseProgram, "uInputTexture"), 0) - GLES30.glActiveTexture(GLES30.GL_TEXTURE1) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, guideTextureId) - GLES30.glUniform1i( - GLES30.glGetUniformLocation(bitmapChromaDenoiseProgram, "uGuideTexture"), - 1 - ) - GLES30.glUniform2f( - GLES30.glGetUniformLocation(bitmapChromaDenoiseProgram, "uTexelSize"), - 1.0f / width, - 1.0f / height - ) - GLES30.glUniformMatrix4fv( - GLES30.glGetUniformLocation(bitmapChromaDenoiseProgram, "uMVPMatrix"), - 1, - false, - identityMatrix, - 0 - ) - GLES30.glUniform1f( - GLES30.glGetUniformLocation(bitmapChromaDenoiseProgram, "uOutputStrength"), - ChromaDenoiseDefaults.outputStrength(strength) - ) - GLES30.glUniform1f( - GLES30.glGetUniformLocation( - bitmapChromaDenoiseProgram, - "uEdgeGuidanceRelaxation" - ), - edgeGuidanceRelaxation - ) - GLES30.glUniform1i( - GLES30.glGetUniformLocation(bitmapChromaDenoiseProgram, "uCameraRgbInput"), - 0 - ) - GLES30.glUniform1f(GLES30.glGetUniformLocation(bitmapChromaDenoiseProgram, "uH"), h) - GLES30.glUniform4f( - GLES30.glGetUniformLocation(bitmapChromaDenoiseProgram, "uNoiseModelRB"), - BITMAP_DENOISE_A * 2f, - BITMAP_DENOISE_B * 2f, - BITMAP_DENOISE_A * 2f, - BITMAP_DENOISE_B * 2f - ) - GLES30.glUniform2f( - GLES30.glGetUniformLocation(bitmapChromaDenoiseProgram, "uNoiseModelG"), - BITMAP_DENOISE_A * 2f, - BITMAP_DENOISE_B * 2f - ) - drawQuad(bitmapChromaDenoiseProgram) - checkGlError("renderBitmapChromaDenoise") - } - - private fun renderBitmapChromaDenoiseEdgeGuide( - sourceTextureId: Int, - targetFramebufferId: Int, - width: Int, - height: Int, - ) { - GLES30.glUseProgram(bitmapChromaDenoiseGuideProgram) - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, targetFramebufferId) - GLES30.glViewport(0, 0, width, height) - GLES30.glActiveTexture(GLES30.GL_TEXTURE0) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, sourceTextureId) - GLES30.glUniform1i( - GLES30.glGetUniformLocation(bitmapChromaDenoiseGuideProgram, "uInputTexture"), - 0 - ) - GLES30.glUniform2f( - GLES30.glGetUniformLocation(bitmapChromaDenoiseGuideProgram, "uTexelSize"), - 1.0f / width, - 1.0f / height - ) - GLES30.glUniform1i( - GLES30.glGetUniformLocation(bitmapChromaDenoiseGuideProgram, "uCameraRgbInput"), - 0 - ) - val identityMatrix = FloatArray(16) - android.opengl.Matrix.setIdentityM(identityMatrix, 0) - GLES30.glUniformMatrix4fv( - GLES30.glGetUniformLocation(bitmapChromaDenoiseGuideProgram, "uMVPMatrix"), - 1, - false, - identityMatrix, - 0 - ) - drawQuad(bitmapChromaDenoiseGuideProgram) - checkGlError("renderBitmapChromaDenoiseEdgeGuide") - } - - private fun renderTexturePassthrough(sourceTextureId: Int, targetFboId: Int, width: Int, height: Int) { - GLES30.glUseProgram(bitmapDenoisePassthroughProgram) - GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, targetFboId) - GLES30.glViewport(0, 0, width, height) - GLES30.glActiveTexture(GLES30.GL_TEXTURE0) - GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, sourceTextureId) - GLES30.glUniform1i(GLES30.glGetUniformLocation(bitmapDenoisePassthroughProgram, "uInputTexture"), 0) - val identityMatrix = FloatArray(16) - android.opengl.Matrix.setIdentityM(identityMatrix, 0) - GLES30.glUniformMatrix4fv( - GLES30.glGetUniformLocation(bitmapDenoisePassthroughProgram, "uMVPMatrix"), - 1, - false, - identityMatrix, - 0 - ) - drawQuad(bitmapDenoisePassthroughProgram) - } - private fun setupLutSharpenFramebuffer(width: Int, height: Int): Boolean { if (lutSharpenFboId != 0 && lutSharpenTextureId != 0 && @@ -1828,220 +1490,6 @@ class LutImageProcessor(context: Context? = null) { lutSharpenHeight = 0 } - private data class BitmapDenoiseParams( - val strength: Float, - val patchRadius: Int, - val expectedFineDistance: Float, - val expectedGuideDistance: Float, - val inverseBandwidth: Float, - val coarseGuideWeight: Float, - val centralPixelWeight: Float, - val p: FloatArray, - val signalScale: FloatArray, - val aa: FloatArray, - val bb: FloatArray, - val bias: Float, - val scale: Float - ) - - private fun isBitmapDenoiseProfileReady(): Boolean { - return bitmapDenoisePreconditionProgram != 0 && - bitmapDenoiseNlmInitProgram != 0 && - bitmapDenoiseNlmFusedAccuProgram != 0 && - bitmapDenoiseNlmFinishProgram != 0 && - bitmapDenoisePassthroughProgram != 0 - } - - private fun setupBitmapDenoiseResources(width: Int, height: Int) { - val pixelCount = width * height - if ( - bitmapDenoiseNlmBufferPixels == pixelCount && - bitmapDenoiseNlmU2BufferId != 0 - ) { - return - } - - if (bitmapDenoiseNlmU2BufferId != 0) { - GLES31.glDeleteBuffers(1, intArrayOf(bitmapDenoiseNlmU2BufferId), 0) - bitmapDenoiseNlmU2BufferId = 0 - } - - val buffers = IntArray(1) - GLES31.glGenBuffers(buffers.size, buffers, 0) - bitmapDenoiseNlmU2BufferId = buffers[0] - - GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, bitmapDenoiseNlmU2BufferId) - GLES31.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, pixelCount * 4 * 4, null, GLES31.GL_DYNAMIC_DRAW) - GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0) - bitmapDenoiseNlmBufferPixels = pixelCount - } - - private fun buildBitmapDenoiseParams(strengthValue: Float): BitmapDenoiseParams { - val strength = DenoiseStrength.clamp(strengthValue) - val varianceScale = DenoiseStrength.noiseVarianceScale(strength) - val a = BITMAP_DENOISE_A * varianceScale - val b = BITMAP_DENOISE_B * varianceScale - val scale = 1.0f - val shadows = max(0.1f - 0.1f * ln(a), 0.7f).coerceAtMost(1.8f) - val bias = -max(5f + 0.5f * ln(a), 0.0f) - val compensateP = 0.05f / 0.05f.pow(shadows) - val patchRadius = DenoiseProfileShaders.PATCH_RADIUS - val weightTuning = DenoiseProfileNlmConfig.weightTuning(patchRadius) - val centralPixelWeight = 0.1f * scale - return BitmapDenoiseParams( - strength = DenoiseStrength.outputMix(strength), - patchRadius = patchRadius, - expectedFineDistance = weightTuning.expectedFineDistance, - expectedGuideDistance = weightTuning.expectedGuideDistance, - inverseBandwidth = weightTuning.inverseBandwidth, - coarseGuideWeight = weightTuning.coarseGuideWeight, - centralPixelWeight = centralPixelWeight, - p = floatArrayOf(shadows, shadows, shadows, 1.0f), - signalScale = floatArrayOf( - scale, - scale, - scale, - 1.0f - ), - aa = floatArrayOf(a * compensateP, a * compensateP, a * compensateP, 1.0f), - bb = floatArrayOf(b, b, b, 1.0f), - bias = bias, - scale = scale - ) - } - - private fun dispatchBitmapDenoisePreconditionV2(input: Int, output: Int, width: Int, height: Int, params: BitmapDenoiseParams) { - GLES31.glUseProgram(bitmapDenoisePreconditionProgram) - bindComputeSampler(bitmapDenoisePreconditionProgram, "uInput", 0, input) - GLES31.glBindImageTexture(1, output, 0, false, 0, GLES31.GL_WRITE_ONLY, GLES31.GL_RGBA16F) - setBitmapDenoiseCommonUniforms(bitmapDenoisePreconditionProgram, width, height, params) - dispatchBitmapDenoiseImage(width, height, "BitmapDenoise NLM precondition") - } - - private fun dispatchBitmapDenoiseNlm( - originalTextureId: Int, - preconditionedTextureId: Int, - outputTextureId: Int, - width: Int, - height: Int, - params: BitmapDenoiseParams - ) { - dispatchBitmapDenoiseNlmInit(width, height) - - for (offset in DenoiseProfileNlmConfig.searchOffsets) { - dispatchBitmapDenoiseNlmFusedAccumulate( - preconditionedTextureId, - width, - height, - offset.x, - offset.y, - params - ) - } - - dispatchBitmapDenoiseNlmFinish(originalTextureId, outputTextureId, width, height, params) - } - - private fun dispatchBitmapDenoiseNlmInit(width: Int, height: Int) { - GLES31.glUseProgram(bitmapDenoiseNlmInitProgram) - GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, bitmapDenoiseNlmU2BufferId) - GLES31.glUniform2i(GLES31.glGetUniformLocation(bitmapDenoiseNlmInitProgram, "uImageSize"), width, height) - setBitmapDenoiseStripeUniforms(bitmapDenoiseNlmInitProgram, height) - dispatchBitmapDenoiseImage(width, height, "BitmapDenoise NLM init") - GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT) - } - - private fun dispatchBitmapDenoiseNlmFusedAccumulate( - input: Int, - width: Int, - height: Int, - qx: Int, - qy: Int, - params: BitmapDenoiseParams - ) { - GLES31.glUseProgram(bitmapDenoiseNlmFusedAccuProgram) - bindComputeSampler(bitmapDenoiseNlmFusedAccuProgram, "uInput", 0, input) - GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, bitmapDenoiseNlmU2BufferId) - GLES31.glUniform2i(GLES31.glGetUniformLocation(bitmapDenoiseNlmFusedAccuProgram, "uImageSize"), width, height) - setBitmapDenoiseStripeUniforms(bitmapDenoiseNlmFusedAccuProgram, height) - GLES31.glUniform2i(GLES31.glGetUniformLocation(bitmapDenoiseNlmFusedAccuProgram, "uQ"), qx, qy) - GLES31.glUniform1f( - GLES31.glGetUniformLocation(bitmapDenoiseNlmFusedAccuProgram, "uExpectedFineDistance"), - params.expectedFineDistance - ) - GLES31.glUniform1f( - GLES31.glGetUniformLocation(bitmapDenoiseNlmFusedAccuProgram, "uExpectedGuideDistance"), - params.expectedGuideDistance - ) - GLES31.glUniform1f( - GLES31.glGetUniformLocation(bitmapDenoiseNlmFusedAccuProgram, "uInverseBandwidth"), - params.inverseBandwidth - ) - GLES31.glUniform1f( - GLES31.glGetUniformLocation(bitmapDenoiseNlmFusedAccuProgram, "uCoarseGuideWeight"), - params.coarseGuideWeight - ) - GLES31.glUniform1f( - GLES31.glGetUniformLocation(bitmapDenoiseNlmFusedAccuProgram, "uCentralPixelWeight"), - params.centralPixelWeight - ) - dispatchBitmapDenoiseImage(width, height, "BitmapDenoise NLM fused accu q=($qx,$qy)") - GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT) - } - - private fun dispatchBitmapDenoiseNlmFinish(input: Int, output: Int, width: Int, height: Int, params: BitmapDenoiseParams) { - GLES31.glUseProgram(bitmapDenoiseNlmFinishProgram) - bindComputeSampler(bitmapDenoiseNlmFinishProgram, "uInput", 0, input) - GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, bitmapDenoiseNlmU2BufferId) - GLES31.glBindImageTexture(1, output, 0, false, 0, GLES31.GL_WRITE_ONLY, GLES31.GL_RGBA16F) - setBitmapDenoiseCommonUniforms(bitmapDenoiseNlmFinishProgram, width, height, params) - setBitmapDenoiseStripeUniforms(bitmapDenoiseNlmFinishProgram, height) - GLES31.glUniform1f(GLES31.glGetUniformLocation(bitmapDenoiseNlmFinishProgram, "uBias"), params.bias - 0.5f * ln(params.scale)) - GLES31.glUniform1f( - GLES31.glGetUniformLocation(bitmapDenoiseNlmFinishProgram, "uDenoiseMix"), - params.strength - ) - dispatchBitmapDenoiseImage(width, height, "BitmapDenoise NLM finish") - } - - private fun setBitmapDenoiseStripeUniforms(program: Int, height: Int) { - GLES31.glUniform1i(GLES31.glGetUniformLocation(program, "uStripeRowOffset"), 0) - GLES31.glUniform1i(GLES31.glGetUniformLocation(program, "uStripeRowCount"), height) - } - - private fun setBitmapDenoiseCommonUniforms(program: Int, width: Int, height: Int, params: BitmapDenoiseParams) { - GLES31.glUniform2i(GLES31.glGetUniformLocation(program, "uImageSize"), width, height) - GLES31.glUniform4fv(GLES31.glGetUniformLocation(program, "uA"), 1, params.aa, 0) - GLES31.glUniform4fv(GLES31.glGetUniformLocation(program, "uP"), 1, params.p, 0) - GLES31.glUniform4fv(GLES31.glGetUniformLocation(program, "uB"), 1, params.bb, 0) - GLES31.glUniform4fv( - GLES31.glGetUniformLocation(program, "uSignalScale"), - 1, - params.signalScale, - 0 - ) - } - - private fun bindComputeSampler(program: Int, name: String, unit: Int, textureId: Int) { - GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + unit) - GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, textureId) - GLES31.glUniform1i(GLES31.glGetUniformLocation(program, name), unit) - } - - private fun dispatchBitmapDenoiseImage(width: Int, height: Int, tag: String) { - GLES31.glDispatchCompute( - GlesComputeWorkGroup.imageGroupCount(width), - GlesComputeWorkGroup.imageGroupCount(height), - 1, - ) - GLES31.glMemoryBarrier( - GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or - GLES31.GL_TEXTURE_FETCH_BARRIER_BIT or - GLES31.GL_FRAMEBUFFER_BARRIER_BIT - ) - checkGlError(tag) - } - /** * 设置 HDF 光晕效果 FBO * 使用 1/4 分辨率进行模糊,然后在全分辨率合成 @@ -2685,13 +2133,7 @@ class LutImageProcessor(context: Context? = null) { } releaseReadbackBuffer() - if (bitmapDenoisePreconditionProgram != 0) GLES31.glDeleteProgram(bitmapDenoisePreconditionProgram) - if (bitmapDenoiseNlmInitProgram != 0) GLES31.glDeleteProgram(bitmapDenoiseNlmInitProgram) - if (bitmapDenoiseNlmFusedAccuProgram != 0) GLES31.glDeleteProgram(bitmapDenoiseNlmFusedAccuProgram) - if (bitmapDenoiseNlmFinishProgram != 0) GLES31.glDeleteProgram(bitmapDenoiseNlmFinishProgram) - if (bitmapDenoisePassthroughProgram != 0) GLES30.glDeleteProgram(bitmapDenoisePassthroughProgram) - if (bitmapChromaDenoiseGuideProgram != 0) GLES30.glDeleteProgram(bitmapChromaDenoiseGuideProgram) - if (bitmapChromaDenoiseProgram != 0) GLES30.glDeleteProgram(bitmapChromaDenoiseProgram) + bitmapMgcDenoiser.release() if (lutSharpenProgram != 0) { GLES30.glDeleteProgram(lutSharpenProgram) lutSharpenProgram = 0 @@ -2700,16 +2142,7 @@ class LutImageProcessor(context: Context? = null) { GLES30.glDeleteProgram(lutLuminanceGainProgram) lutLuminanceGainProgram = 0 } - for (i in 0..1) { - if (bitmapDenoiseTexId[i] != 0) GLES30.glDeleteTextures(1, intArrayOf(bitmapDenoiseTexId[i]), 0) - if (bitmapDenoiseFboId[i] != 0) GLES30.glDeleteFramebuffers(1, intArrayOf(bitmapDenoiseFboId[i]), 0) - } releaseLutSharpenFramebuffer() - if (bitmapDenoiseNlmU2BufferId != 0) { - GLES31.glDeleteBuffers(1, intArrayOf(bitmapDenoiseNlmU2BufferId), 0) - bitmapDenoiseNlmU2BufferId = 0 - } - bitmapDenoiseNlmBufferPixels = 0 // 释放 HDF 资源 if (hdfExtractBlurHProgram != 0) GLES30.glDeleteProgram(hdfExtractBlurHProgram) @@ -2742,8 +2175,6 @@ class LutImageProcessor(context: Context? = null) { companion object { private const val TAG = "LutImageProcessor" - private const val BITMAP_DENOISE_A = 0.008f - private const val BITMAP_DENOISE_B = 0.0005f private const val LUT_LUMINANCE_OFFSET = 1e-4f private const val CLARITY_PYRAMID_LEVELS = 3 private const val EGL_CONTEXT_PRIORITY_LEVEL_IMG = 0x3100 diff --git a/app/src/main/java/com/hinnka/mycamera/processor/DenoiseStrength.kt b/app/src/main/java/com/hinnka/mycamera/processor/DenoiseStrength.kt index dfdba791..51063a70 100644 --- a/app/src/main/java/com/hinnka/mycamera/processor/DenoiseStrength.kt +++ b/app/src/main/java/com/hinnka/mycamera/processor/DenoiseStrength.kt @@ -12,15 +12,4 @@ object DenoiseStrength { ?.takeIf { it.isFinite() } ?.coerceIn(MIN_VALUE, MAX_VALUE) ?: MIN_VALUE - - /** - * Bitmap NLM reaches a full output mix at 1. Values above 1 strengthen its - * assumed noise standard deviation, so the corresponding variance is squared. - */ - fun noiseVarianceScale(value: Float): Float { - val sigmaScale = clamp(value).coerceAtLeast(1.0f) - return sigmaScale * sigmaScale - } - - fun outputMix(value: Float): Float = clamp(value).coerceAtMost(1.0f) } diff --git a/app/src/main/java/com/hinnka/mycamera/raw/DenoiseProfileNlmConfig.kt b/app/src/main/java/com/hinnka/mycamera/raw/DenoiseProfileNlmConfig.kt deleted file mode 100644 index 94670b25..00000000 --- a/app/src/main/java/com/hinnka/mycamera/raw/DenoiseProfileNlmConfig.kt +++ /dev/null @@ -1,72 +0,0 @@ -package com.hinnka.mycamera.raw - -import kotlin.math.max - -internal data class DenoiseProfileOffset( - val x: Int, - val y: Int, -) - -internal data class DenoiseProfileWeightTuning( - val expectedFineDistance: Float, - val expectedGuideDistance: Float, - val inverseBandwidth: Float, - val coarseGuideWeight: Float, -) - -/** - * Statistical and traversal configuration shared by the RAW and bitmap NLM hosts. - * - * The variance-stabilizing transform targets unit noise variance per color channel. The - * difference between two independent samples therefore has variance two. Noise-only patch - * energy is removed before applying the NLM bandwidth so that the weight curve starts falling - * as soon as a candidate contains energy that the sensor noise model cannot explain. - */ -internal object DenoiseProfileNlmConfig { - private const val COLOR_CHANNEL_COUNT = 3 - private const val DIFFERENCE_VARIANCE = 2.0f - - // Squared-energy of the separable 3x3 Gaussian kernel [1 2 1]^T[1 2 1] / 16. - private const val GUIDE_FILTER_ENERGY = 36.0f / 256.0f - - // Coarse guide differences describe structure rather than independent RGB noise. Give them - // enough leverage to reject low-contrast contours without turning the decision into a hard - // threshold. - const val COARSE_GUIDE_WEIGHT = 8.0f - - val searchOffsets: List = buildSearchOffsets( - DenoiseProfileShaders.SEARCH_RADIUS - ) - - fun buildSearchOffsets(radius: Int): List { - require(radius >= 0) { "radius must be non-negative" } - return buildList { - for (qy in -radius..0) { - // FUSED_ACCU evaluates +q and -q together. At y == 0 only one horizontal - // half-axis is needed; visiting both halves would double horizontal weights. - val qxEnd = if (qy == 0) 0 else radius - for (qx in -radius..qxEnd) { - add(DenoiseProfileOffset(qx, qy)) - } - } - } - } - - fun weightTuning(patchRadius: Int): DenoiseProfileWeightTuning { - require(patchRadius >= 0) { "patchRadius must be non-negative" } - val patchWidth = 2 * patchRadius + 1 - val patchPixels = patchWidth * patchWidth - val expectedFineDistance = - DIFFERENCE_VARIANCE * COLOR_CHANNEL_COUNT * patchPixels.toFloat() - val expectedGuideDistance = - DIFFERENCE_VARIANCE * GUIDE_FILTER_ENERGY * patchPixels.toFloat() - - return DenoiseProfileWeightTuning( - expectedFineDistance = expectedFineDistance, - expectedGuideDistance = expectedGuideDistance, - // One additional noise-floor worth of unexplained RGB energy halves the weight. - inverseBandwidth = 1.0f / max(expectedFineDistance, 1.0f), - coarseGuideWeight = COARSE_GUIDE_WEIGHT, - ) - } -} diff --git a/app/src/main/java/com/hinnka/mycamera/raw/DenoiseProfileShaders.kt b/app/src/main/java/com/hinnka/mycamera/raw/DenoiseProfileShaders.kt deleted file mode 100644 index 23e2f593..00000000 --- a/app/src/main/java/com/hinnka/mycamera/raw/DenoiseProfileShaders.kt +++ /dev/null @@ -1,276 +0,0 @@ -package com.hinnka.mycamera.raw - -import com.hinnka.mycamera.processor.GlesComputeWorkGroup - -/** - * OpenGL ES 3.1 compute port of darktable's denoiseprofile NLM path. - * - * Input and output stay in un-white-balanced camera RGB. The host keeps darktable's - * white-balance-adaptive exponent, but removes WB from the reversible signal scale. - * The pipeline mirrors darktable process_nlmeans_cl with a mobile fused accumulator and a - * low-frequency green guide used to keep low-contrast structure out of the noise estimate: - * precondition_v2 -> init -> repeated local-tile accu -> finish_v2. - */ -object DenoiseProfileShaders { - const val SEARCH_RADIUS = 5 - const val PATCH_RADIUS = 1 - // darktable's neutral bias setting makes finish_v2 the exact inverse when NLM leaves a - // transformed sample unchanged. This is required to keep sensor black and channel ratios. - const val BLACK_PRESERVING_BIAS = 0.0f - const val IMAGE_LOCAL_X = GlesComputeWorkGroup.IMAGE_TILE_SIZE - const val IMAGE_LOCAL_Y = GlesComputeWorkGroup.IMAGE_TILE_SIZE - private const val FUSED_TILE_X = IMAGE_LOCAL_X + SEARCH_RADIUS + 2 * PATCH_RADIUS - private const val FUSED_TILE_Y = IMAGE_LOCAL_Y + SEARCH_RADIUS + 2 * PATCH_RADIUS - - private const val COMMON = """ - precision highp float; - precision highp int; - - vec4 readPixel(sampler2D image, ivec2 coord, ivec2 size) { - ivec2 c = clamp(coord, ivec2(0), size - ivec2(1)); - return texelFetch(image, c, 0); - } - - vec4 dtPow(vec4 a, vec4 b) { - return pow(a, b); - } - - float fastMexp2(float x) { - const float i1 = float(0x3f800000u); - const float i2 = float(0x3f000000u); - float k0 = i1 + x * (i2 - i1); - uint bits = (k0 >= float(0x800000u)) ? uint(k0) : 0u; - return uintBitsToFloat(bits); - } - - float ddirac(ivec2 q) { - return (q.x != 0 || q.y != 0) ? 1.0 : 0.0; - } - - int pixelIndex(ivec2 coord, ivec2 size) { - return coord.y * size.x + coord.x; - } - """ - - val PRECONDITION_V2 = """ - #version 310 es - $COMMON - layout(local_size_x = $IMAGE_LOCAL_X, local_size_y = $IMAGE_LOCAL_Y) in; - layout(binding = 0) uniform highp sampler2D uInput; - layout(rgba16f, binding = 1) writeonly uniform highp image2D uOutput; - - uniform ivec2 uImageSize; - uniform vec4 uA; - uniform vec4 uP; - uniform vec4 uB; - uniform vec4 uSignalScale; - - vec4 preconditionSignal(vec4 pixel) { - return max( - 2.0 * dtPow(max(vec4(0.0), pixel / uSignalScale + uB), 1.0 - uP / 2.0) / - ((-uP + 2.0) * sqrt(uA)), - vec4(0.0) - ); - } - - float preconditionGreen(float signal) { - return max( - 2.0 * pow(max(0.0, signal / uSignalScale.g + uB.g), 1.0 - uP.g / 2.0) / - ((-uP.g + 2.0) * sqrt(uA.g)), - 0.0 - ); - } - - void main() { - ivec2 coord = ivec2(gl_GlobalInvocationID.xy); - if (coord.x >= uImageSize.x || coord.y >= uImageSize.y) return; - - vec4 t = preconditionSignal(readPixel(uInput, coord, uImageSize)); - - // Alpha is scratch space after preconditioning: FUSED_ACCU replaces it with the - // accumulated weight and FINISH_V2 restores alpha from the original input. A 3x3 - // Gaussian green guide expands the effective structural support of the 3x3 RGB - // patch without another full-resolution intermediate texture. - float guide = - preconditionGreen(readPixel(uInput, coord + ivec2(-1, -1), uImageSize).g) + - 2.0 * preconditionGreen(readPixel(uInput, coord + ivec2(0, -1), uImageSize).g) + - preconditionGreen(readPixel(uInput, coord + ivec2(1, -1), uImageSize).g) + - 2.0 * preconditionGreen(readPixel(uInput, coord + ivec2(-1, 0), uImageSize).g) + - 4.0 * t.g + - 2.0 * preconditionGreen(readPixel(uInput, coord + ivec2(1, 0), uImageSize).g) + - preconditionGreen(readPixel(uInput, coord + ivec2(-1, 1), uImageSize).g) + - 2.0 * preconditionGreen(readPixel(uInput, coord + ivec2(0, 1), uImageSize).g) + - preconditionGreen(readPixel(uInput, coord + ivec2(1, 1), uImageSize).g); - t.a = guide * (1.0 / 16.0); - imageStore(uOutput, coord, t); - } - """.trimIndent() - - val INIT = """ - #version 310 es - $COMMON - layout(local_size_x = $IMAGE_LOCAL_X, local_size_y = $IMAGE_LOCAL_Y) in; - layout(std430, binding = 0) buffer AccuBuffer { vec4 u2[]; }; - - uniform ivec2 uImageSize; - uniform int uStripeRowCount; - - void main() { - ivec2 stripeCoord = ivec2(gl_GlobalInvocationID.xy); - if (stripeCoord.x >= uImageSize.x || stripeCoord.y >= uStripeRowCount) return; - - u2[stripeCoord.y * uImageSize.x + stripeCoord.x] = vec4(0.0); - } - """.trimIndent() - - val FUSED_ACCU = """ - #version 310 es - $COMMON - layout(local_size_x = $IMAGE_LOCAL_X, local_size_y = $IMAGE_LOCAL_Y) in; - layout(binding = 0) uniform highp sampler2D uInput; - layout(std430, binding = 0) buffer AccuBuffer { vec4 u2[]; }; - - shared vec2 sDistance[$FUSED_TILE_X * $FUSED_TILE_Y]; - - uniform ivec2 uImageSize; - uniform int uStripeRowOffset; - uniform int uStripeRowCount; - uniform ivec2 uQ; - uniform float uExpectedFineDistance; - uniform float uExpectedGuideDistance; - uniform float uInverseBandwidth; - uniform float uCoarseGuideWeight; - uniform float uCentralPixelWeight; - - vec2 pixelDistance(ivec2 coord, ivec2 q) { - ivec2 shifted = coord + q; - bool inBounds = shifted.x >= 0 && shifted.x < uImageSize.x && - shifted.y >= 0 && shifted.y < uImageSize.y; - if (!inBounds) return vec2(0.0); - - vec4 p1 = readPixel(uInput, coord, uImageSize); - vec4 p2 = readPixel(uInput, shifted, uImageSize); - vec4 tmp = (p1 - p2) * (p1 - p2); - return vec2(tmp.x + tmp.y + tmp.z, tmp.a); - } - - vec2 tileDistance(ivec2 imageCoord, ivec2 groupOrigin, ivec2 tileMin, int tileWidth) { - ivec2 tileCoord = imageCoord - groupOrigin - tileMin; - return sDistance[tileCoord.y * tileWidth + tileCoord.x]; - } - - float patchWeight(ivec2 center, ivec2 groupOrigin, ivec2 tileMin, int tileWidth) { - vec2 distacc = vec2(0.0); - for (int pj = -$PATCH_RADIUS; pj <= $PATCH_RADIUS; pj++) { - for (int pi = -$PATCH_RADIUS; pi <= $PATCH_RADIUS; pi++) { - ivec2 patchCoord = clamp( - center + ivec2(pi, pj), - ivec2(0), - uImageSize - ivec2(1) - ); - distacc += tileDistance(patchCoord, groupOrigin, tileMin, tileWidth); - } - } - - float patchPixels = float((2 * $PATCH_RADIUS + 1) * (2 * $PATCH_RADIUS + 1)); - distacc += tileDistance(center, groupOrigin, tileMin, tileWidth) * - patchPixels * uCentralPixelWeight; - distacc /= 1.0 + uCentralPixelWeight; - - float unexplainedFine = max(distacc.x - uExpectedFineDistance, 0.0); - float unexplainedGuide = max(distacc.y - uExpectedGuideDistance, 0.0); - float unexplainedDistance = - unexplainedFine + uCoarseGuideWeight * unexplainedGuide; - return fastMexp2(unexplainedDistance * uInverseBandwidth); - } - - void main() { - ivec2 groupOrigin = ivec2( - int(gl_WorkGroupID.x) * $IMAGE_LOCAL_X, - uStripeRowOffset + int(gl_WorkGroupID.y) * $IMAGE_LOCAL_Y - ); - ivec2 tileMin = min(ivec2(-$PATCH_RADIUS), -uQ - ivec2($PATCH_RADIUS)); - ivec2 tileMax = max(ivec2($PATCH_RADIUS), -uQ + ivec2($PATCH_RADIUS)); - int tileWidth = $IMAGE_LOCAL_X + tileMax.x - tileMin.x; - int tileHeight = $IMAGE_LOCAL_Y + tileMax.y - tileMin.y; - int tilePixels = tileWidth * tileHeight; - int localIndex = int(gl_LocalInvocationID.y) * $IMAGE_LOCAL_X + - int(gl_LocalInvocationID.x); - int localCount = $IMAGE_LOCAL_X * $IMAGE_LOCAL_Y; - - for (int i = localIndex; i < tilePixels; i += localCount) { - int tileX = i - (i / tileWidth) * tileWidth; - int tileY = i / tileWidth; - ivec2 imageCoord = groupOrigin + ivec2(tileX, tileY) + tileMin; - imageCoord = clamp(imageCoord, ivec2(0), uImageSize - ivec2(1)); - sDistance[i] = pixelDistance(imageCoord, uQ); - } - - memoryBarrierShared(); - barrier(); - - ivec2 stripeCoord = ivec2(gl_GlobalInvocationID.xy); - if (stripeCoord.x >= uImageSize.x || stripeCoord.y >= uStripeRowCount) return; - ivec2 coord = stripeCoord + ivec2(0, uStripeRowOffset); - - ivec2 plusCoord = coord + uQ; - ivec2 minusCoord = coord - uQ; - bool plusInBounds = plusCoord.x >= 0 && plusCoord.x < uImageSize.x && - plusCoord.y >= 0 && plusCoord.y < uImageSize.y; - bool minusInBounds = minusCoord.x >= 0 && minusCoord.x < uImageSize.x && - minusCoord.y >= 0 && minusCoord.y < uImageSize.y; - - float weight = plusInBounds ? patchWeight(coord, groupOrigin, tileMin, tileWidth) : 0.0; - float weightMinus = (minusInBounds && ddirac(uQ) > 0.0) - ? patchWeight(minusCoord, groupOrigin, tileMin, tileWidth) - : 0.0; - - vec4 u1Pq = plusInBounds ? readPixel(uInput, plusCoord, uImageSize) : vec4(0.0); - vec4 u1Mq = minusInBounds ? readPixel(uInput, minusCoord, uImageSize) : vec4(0.0); - vec4 accu = weight * u1Pq + weightMinus * u1Mq; - accu.a = weight + weightMinus; - - int idx = stripeCoord.y * uImageSize.x + stripeCoord.x; - u2[idx] = u2[idx] + accu; - } - """.trimIndent() - - val FINISH_V2 = """ - #version 310 es - $COMMON - layout(local_size_x = $IMAGE_LOCAL_X, local_size_y = $IMAGE_LOCAL_Y) in; - layout(binding = 0) uniform highp sampler2D uInput; - layout(std430, binding = 0) readonly buffer AccuBuffer { vec4 u2[]; }; - layout(rgba16f, binding = 1) writeonly uniform highp image2D uOutput; - - uniform ivec2 uImageSize; - uniform int uStripeRowOffset; - uniform int uStripeRowCount; - uniform vec4 uA; - uniform vec4 uP; - uniform vec4 uB; - uniform float uBias; - uniform float uDenoiseMix; - uniform vec4 uSignalScale; - - void main() { - ivec2 stripeCoord = ivec2(gl_GlobalInvocationID.xy); - if (stripeCoord.x >= uImageSize.x || stripeCoord.y >= uStripeRowCount) return; - ivec2 coord = stripeCoord + ivec2(0, uStripeRowOffset); - - int idx = stripeCoord.y * uImageSize.x + stripeCoord.x; - vec4 accu = u2[idx]; - vec4 original = readPixel(uInput, coord, uImageSize); - vec4 px = accu.a > 0.0 ? accu / accu.a : vec4(0.0); - - vec4 delta = px * px + vec4(uBias); - vec4 denominator = 4.0 / (sqrt(uA) * (2.0 - uP)); - vec4 z1 = (px + sqrt(max(vec4(0.0), delta))) / denominator; - px = max(dtPow(z1, 1.0 / (1.0 - uP / 2.0)) - uB, vec4(0.0)); - px *= uSignalScale; - px.rgb = mix(original.rgb, px.rgb, clamp(uDenoiseMix, 0.0, 1.0)); - px.a = original.a; - imageStore(uOutput, coord, px); - } - """.trimIndent() -} diff --git a/app/src/main/java/com/hinnka/mycamera/raw/MgcBitmapNoiseCalibrations.kt b/app/src/main/java/com/hinnka/mycamera/raw/MgcBitmapNoiseCalibrations.kt new file mode 100644 index 00000000..04de1b8a --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/raw/MgcBitmapNoiseCalibrations.kt @@ -0,0 +1,137 @@ +package com.hinnka.mycamera.raw + +// Generated by tools/bitmap_noise_calibration/generate_kotlin.py. Do not edit by hand. + +/** Offline bitmap noise calibrations (calibrate.py), ascending by ISO. */ +internal object MgcBitmapNoiseCalibrations { + val ENTRIES: List = listOf( + // PhotonCamera_20261109_143038.标准.jpg, ISO 270; source: tools/bitmap_noise_calibration/oppo_a3x_iso270.json + MgcBitmapNoiseModel.Calibration( + iso = 270, + lumaRead = 0f, + lumaShot = 0.001698564f, + lumaQuadratic = 0.004053289f, + boxVarianceRatio2 = 0.727823f, + boxVarianceRatio4 = 0.5807647f, + denoiserModel = MgcFullResolutionDenoise.PreparedYuvNoiseModel( + normalizedRead = floatArrayOf(0f, 0f, 0f), + normalizedLumaShot = 0.003397128f, + normalizedLumaQuadratic = 0.004053289f, + normalizedChromaShot = 0.003397128f, + normalizedChromaQuadratic = 0.004053289f, + lumaCorrelation = floatArrayOf( + 0.2370727f, 0.1647024f, 0.148228f, 0.1472644f, 0.1499985f, 0.1517085f, + 0.1549584f, 0.1657112f, 0.1775394f, 0.1784397f, 0.18351f, 0.1879864f, + 0.2059089f, 0.2247925f, 0.2308894f, 0.2439626f, 0.259771f, 0.2635828f, + 0.2835664f, 0.3082006f, 0.3315156f, 0.3533951f, 0.3773934f, 0.3827962f, + 0.4088563f, 0.4331712f, 0.4276295f, 0.4717214f, 0.4892584f, 0.4880814f, + 0.5357004f, 0.547161f, 0.5904874f, 0.5569481f, 0.5757658f, 0.5865457f, + 0.6105018f, 0.6066094f, 0.6293522f, 0.633817f, 0.6595704f, 0.6663031f, + 0.6572506f, 0.6542949f, 0.6885165f, 0.6695643f, 0.7106166f, 0.7547786f, + 0.7965492f, 0.8218433f, 0.8018763f, 0.7723972f, 0.8399447f, 0.9354574f, + 0.9923136f, 0.9620705f, 1.024072f, 1.341096f, 1.744655f, 2.065495f, + 2.493847f, 3.902611f, 10.66583f, 14.27455f, 14.27455f, 10.66583f, + 3.902611f, 2.493847f, 2.065495f, 1.744655f, 1.341096f, 1.024072f, + 0.9620705f, 0.9923136f, 0.9354574f, 0.8399447f, 0.7723972f, 0.8018763f, + 0.8218433f, 0.7965492f, 0.7547786f, 0.7106166f, 0.6695643f, 0.6885165f, + 0.6542949f, 0.6572506f, 0.6663031f, 0.6595704f, 0.633817f, 0.6293522f, + 0.6066094f, 0.6105018f, 0.5865457f, 0.5757658f, 0.5569481f, 0.5904874f, + 0.547161f, 0.5357004f, 0.4880814f, 0.4892584f, 0.4717214f, 0.4276295f, + 0.4331712f, 0.4088563f, 0.3827962f, 0.3773934f, 0.3533951f, 0.3315156f, + 0.3082006f, 0.2835664f, 0.2635828f, 0.259771f, 0.2439626f, 0.2308894f, + 0.2247925f, 0.2059089f, 0.1879864f, 0.18351f, 0.1784397f, 0.1775394f, + 0.1657112f, 0.1549584f, 0.1517085f, 0.1499985f, 0.1472644f, 0.148228f, + 0.1647024f, 0.2370727f, + ), + chromaCorrelation = floatArrayOf( + 0.06788593f, 0.04708519f, 0.0448037f, 0.0443403f, 0.04515055f, 0.0465143f, + 0.04816711f, 0.048743f, 0.05081074f, 0.05199204f, 0.05242346f, 0.05159559f, + 0.05145567f, 0.05259706f, 0.05406489f, 0.05264108f, 0.05425233f, 0.05361206f, + 0.05616313f, 0.05854646f, 0.0609109f, 0.06033442f, 0.06400992f, 0.06591436f, + 0.07099266f, 0.07149659f, 0.07550936f, 0.07692385f, 0.08176214f, 0.0822932f, + 0.08955874f, 0.09599174f, 0.09952724f, 0.09897214f, 0.1072705f, 0.1150873f, + 0.1228051f, 0.1300161f, 0.1424562f, 0.1541165f, 0.1646127f, 0.1805898f, + 0.1988008f, 0.2354062f, 0.2731975f, 0.3227035f, 0.4231182f, 0.560808f, + 0.6988397f, 0.9792791f, 1.143923f, 1.429045f, 1.847879f, 2.044252f, + 2.464851f, 3.085948f, 3.432729f, 3.76707f, 4.198544f, 4.649198f, + 5.634794f, 5.948845f, 8.49351f, 8.923265f, 8.923265f, 8.49351f, + 5.948845f, 5.634794f, 4.649198f, 4.198544f, 3.76707f, 3.432729f, + 3.085948f, 2.464851f, 2.044252f, 1.847879f, 1.429045f, 1.143923f, + 0.9792791f, 0.6988397f, 0.560808f, 0.4231182f, 0.3227035f, 0.2731975f, + 0.2354062f, 0.1988008f, 0.1805898f, 0.1646127f, 0.1541165f, 0.1424562f, + 0.1300161f, 0.1228051f, 0.1150873f, 0.1072705f, 0.09897214f, 0.09952724f, + 0.09599174f, 0.08955874f, 0.0822932f, 0.08176214f, 0.07692385f, 0.07550936f, + 0.07149659f, 0.07099266f, 0.06591436f, 0.06400992f, 0.06033442f, 0.0609109f, + 0.05854646f, 0.05616313f, 0.05361206f, 0.05425233f, 0.05264108f, 0.05406489f, + 0.05259706f, 0.05145567f, 0.05159559f, 0.05242346f, 0.05199204f, 0.05081074f, + 0.048743f, 0.04816711f, 0.0465143f, 0.04515055f, 0.0443403f, 0.0448037f, + 0.04708519f, 0.06788593f, + ), + ), + ), + // PhotonCamera_20261109_134217.标准.jpg, ISO 6400; source: tools/bitmap_noise_calibration/oppo_a3x_iso6400.json + MgcBitmapNoiseModel.Calibration( + iso = 6400, + lumaRead = 0.001729636f, + lumaShot = 0.01133283f, + lumaQuadratic = 0f, + boxVarianceRatio2 = 0.5546569f, + boxVarianceRatio4 = 0.2427601f, + denoiserModel = MgcFullResolutionDenoise.PreparedYuvNoiseModel( + normalizedRead = floatArrayOf(0.006918545f, 0.004793569f, 0.03163469f), + normalizedLumaShot = 0.02266566f, + normalizedLumaQuadratic = 0f, + normalizedChromaShot = 0.02266566f, + normalizedChromaQuadratic = 0f, + lumaCorrelation = floatArrayOf( + 0.2849099f, 0.1892967f, 0.1856172f, 0.1941112f, 0.1857321f, 0.206578f, + 0.209216f, 0.2139979f, 0.2192574f, 0.2341152f, 0.2418339f, 0.2551319f, + 0.2721379f, 0.2833573f, 0.3124941f, 0.3128699f, 0.3319263f, 0.3623236f, + 0.400154f, 0.4215496f, 0.4444607f, 0.4679012f, 0.4761536f, 0.5215382f, + 0.5808329f, 0.600072f, 0.6346785f, 0.6624425f, 0.7013004f, 0.7358205f, + 0.8115942f, 0.8074724f, 0.866868f, 0.9058378f, 0.8829234f, 0.945763f, + 0.9880208f, 1.004558f, 1.02639f, 1.096725f, 1.076676f, 1.110294f, + 1.180143f, 1.210591f, 1.277392f, 1.230035f, 1.270713f, 1.331771f, + 1.327f, 1.400249f, 1.44426f, 1.448319f, 1.476424f, 1.590698f, + 1.652265f, 1.652337f, 1.776714f, 1.870995f, 1.98167f, 2.042017f, + 2.373291f, 2.872722f, 3.461228f, 5.464234f, 5.464234f, 3.461228f, + 2.872722f, 2.373291f, 2.042017f, 1.98167f, 1.870995f, 1.776714f, + 1.652337f, 1.652265f, 1.590698f, 1.476424f, 1.448319f, 1.44426f, + 1.400249f, 1.327f, 1.331771f, 1.270713f, 1.230035f, 1.277392f, + 1.210591f, 1.180143f, 1.110294f, 1.076676f, 1.096725f, 1.02639f, + 1.004558f, 0.9880208f, 0.945763f, 0.8829234f, 0.9058378f, 0.866868f, + 0.8074724f, 0.8115942f, 0.7358205f, 0.7013004f, 0.6624425f, 0.6346785f, + 0.600072f, 0.5808329f, 0.5215382f, 0.4761536f, 0.4679012f, 0.4444607f, + 0.4215496f, 0.400154f, 0.3623236f, 0.3319263f, 0.3128699f, 0.3124941f, + 0.2833573f, 0.2721379f, 0.2551319f, 0.2418339f, 0.2341152f, 0.2192574f, + 0.2139979f, 0.209216f, 0.206578f, 0.1857321f, 0.1941112f, 0.1856172f, + 0.1892967f, 0.2849099f, + ), + chromaCorrelation = floatArrayOf( + 0.03265955f, 0.02332009f, 0.02302547f, 0.02278608f, 0.02277681f, 0.02413007f, + 0.023925f, 0.02569323f, 0.0272321f, 0.02778324f, 0.02920323f, 0.03051508f, + 0.03303627f, 0.03560619f, 0.03806804f, 0.0404683f, 0.0431758f, 0.04475632f, + 0.0497294f, 0.05260224f, 0.05709018f, 0.06007614f, 0.06085153f, 0.06537153f, + 0.06918297f, 0.07286539f, 0.07363435f, 0.07909254f, 0.08658081f, 0.09007621f, + 0.09224977f, 0.09544551f, 0.1036612f, 0.1127405f, 0.1157037f, 0.1242169f, + 0.13441f, 0.1482904f, 0.1671728f, 0.1864466f, 0.2154091f, 0.2479165f, + 0.3079063f, 0.3778761f, 0.4747187f, 0.5914111f, 0.7651589f, 0.8794243f, + 1.11843f, 1.362278f, 1.645642f, 1.920733f, 2.219147f, 2.690244f, + 3.124821f, 3.475304f, 3.766885f, 4.445485f, 4.78106f, 4.952844f, + 5.220719f, 5.672083f, 5.685087f, 5.413767f, 5.413767f, 5.685087f, + 5.672083f, 5.220719f, 4.952844f, 4.78106f, 4.445485f, 3.766885f, + 3.475304f, 3.124821f, 2.690244f, 2.219147f, 1.920733f, 1.645642f, + 1.362278f, 1.11843f, 0.8794243f, 0.7651589f, 0.5914111f, 0.4747187f, + 0.3778761f, 0.3079063f, 0.2479165f, 0.2154091f, 0.1864466f, 0.1671728f, + 0.1482904f, 0.13441f, 0.1242169f, 0.1157037f, 0.1127405f, 0.1036612f, + 0.09544551f, 0.09224977f, 0.09007621f, 0.08658081f, 0.07909254f, 0.07363435f, + 0.07286539f, 0.06918297f, 0.06537153f, 0.06085153f, 0.06007614f, 0.05709018f, + 0.05260224f, 0.0497294f, 0.04475632f, 0.0431758f, 0.0404683f, 0.03806804f, + 0.03560619f, 0.03303627f, 0.03051508f, 0.02920323f, 0.02778324f, 0.0272321f, + 0.02569323f, 0.023925f, 0.02413007f, 0.02277681f, 0.02278608f, 0.02302547f, + 0.02332009f, 0.03265955f, + ), + ), + ), + ) +} diff --git a/app/src/main/java/com/hinnka/mycamera/raw/MgcBitmapNoiseModel.kt b/app/src/main/java/com/hinnka/mycamera/raw/MgcBitmapNoiseModel.kt new file mode 100644 index 00000000..35df61c6 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/raw/MgcBitmapNoiseModel.kt @@ -0,0 +1,129 @@ +package com.hinnka.mycamera.raw + +import com.hinnka.mycamera.utils.PLog +import kotlin.math.ln +import kotlin.math.sqrt + +/** + * ISO-indexed MGC noise model for ISP-rendered bitmaps (JPEG/HEIF/YUV captures), in the linear + * (inverse sRGB transfer) working RGB with white balance (1, 1, 1). + * + * Each [Calibration] comes from tools/bitmap_noise_calibration/calibrate.py and follows the + * DemosaicNoisePropagationCalibrator conventions: MGC RGB->YUV matrix, NoiseModel.Scale(2) + * (read x4, shot x2), Cb/Cr sharing the luma signal-dependent slice, and 128-bin half-bin + * directional spectra normalized to mean 1. Between calibrated ISOs every coefficient and + * spectrum bin is interpolated linearly in log(ISO); outside the calibrated range the nearest + * calibration applies. + */ +internal object MgcBitmapNoiseModel { + private const val TAG = "MgcBitmapNoiseModel" + + data class Calibration( + val iso: Int, + /** Un-scaled linear luma variance: read + shot * s + quadratic * s^2, for the tuning SNR. */ + val lumaRead: Float, + val lumaShot: Float, + val lumaQuadratic: Float, + /** + * Luma noise variance kept by a factor-2 / factor-4 box downsample. The noise is spatially + * correlated, so these exceed 1/4 and 1/16; the detail map compares coarse local + * variance against the model scaled by them. + */ + val boxVarianceRatio2: Float, + val boxVarianceRatio4: Float, + val denoiserModel: MgcFullResolutionDenoise.PreparedYuvNoiseModel, + ) { + /** Un-scaled linear luma noise variance at [signal]. */ + fun lumaVariance(signal: Float): Float { + val s = signal.coerceAtLeast(0f) + return lumaRead + lumaShot * s + lumaQuadratic * s * s + } + + /** MGC tuning coordinate at the image's mean linear luma, as withMgcRenderTuning() for RAW. */ + fun tuningSnr(meanLinearLuma: Float): Float { + val signal = meanLinearLuma.coerceAtLeast(0f) + val variance = lumaRead + lumaShot * signal + lumaQuadratic * signal * signal + return if (variance > 0f) signal / sqrt(variance) else 0f + } + } + + /** + * The model for a capture at [iso]. Without an ISO the lowest calibration applies: it assumes + * the least noise and so removes the least detail. + */ + fun forIso(iso: Int?): Calibration { + val calibrations = MgcBitmapNoiseCalibrations.ENTRIES + check(calibrations.isNotEmpty() && calibrations.zipWithNext().all { (a, b) -> a.iso < b.iso }) { + "Bitmap noise calibrations must be non-empty and strictly ascending by ISO" + } + val validIso = iso?.takeIf { it > 0 } + if (validIso == null) { + PLog.w(TAG, "Bitmap has no ISO; using the ISO ${calibrations.first().iso} calibration") + return calibrations.first() + } + if (validIso <= calibrations.first().iso) return calibrations.first() + if (validIso >= calibrations.last().iso) return calibrations.last() + val upperIndex = calibrations.indexOfFirst { it.iso >= validIso } + val lower = calibrations[upperIndex - 1] + val upper = calibrations[upperIndex] + if (upper.iso == validIso) return upper + val amount = ((ln(validIso.toFloat()) - ln(lower.iso.toFloat())) / + (ln(upper.iso.toFloat()) - ln(lower.iso.toFloat()))).coerceIn(0f, 1f) + return interpolate(lower, upper, amount, validIso) + } + + /** Identifies the model [forIso] resolves to, for caches of denoised output. */ + fun cacheSignature(iso: Int?): String { + val model = forIso(iso) + val crc = java.util.zip.CRC32() + fun add(value: Float) { + val bits = value.toRawBits() + crc.update(byteArrayOf((bits ushr 24).toByte(), (bits ushr 16).toByte(), (bits ushr 8).toByte(), bits.toByte())) + } + add(model.lumaRead) + add(model.lumaShot) + add(model.lumaQuadratic) + add(model.boxVarianceRatio2) + add(model.boxVarianceRatio4) + with(model.denoiserModel) { + normalizedRead.forEach(::add) + add(normalizedLumaShot) + add(normalizedLumaQuadratic) + add(normalizedChromaShot) + add(normalizedChromaQuadratic) + lumaCorrelation.forEach(::add) + chromaCorrelation.forEach(::add) + } + return "mgc-${model.iso}-${java.lang.Long.toHexString(crc.value)}" + } + + private fun interpolate(lower: Calibration, upper: Calibration, amount: Float, iso: Int): Calibration { + fun mix(a: Float, b: Float) = a + (b - a) * amount + fun mixArray(a: FloatArray, b: FloatArray) = FloatArray(a.size) { mix(a[it], b[it]) } + fun mixSpectrum(a: FloatArray, b: FloatArray): FloatArray { + val mixed = mixArray(a, b) + val mean = mixed.average().toFloat() + check(mean > 0f) { "Interpolated bitmap noise spectrum has no power" } + return FloatArray(mixed.size) { mixed[it] / mean } + } + val a = lower.denoiserModel + val b = upper.denoiserModel + return Calibration( + iso = iso, + lumaRead = mix(lower.lumaRead, upper.lumaRead), + lumaShot = mix(lower.lumaShot, upper.lumaShot), + lumaQuadratic = mix(lower.lumaQuadratic, upper.lumaQuadratic), + boxVarianceRatio2 = mix(lower.boxVarianceRatio2, upper.boxVarianceRatio2), + boxVarianceRatio4 = mix(lower.boxVarianceRatio4, upper.boxVarianceRatio4), + denoiserModel = MgcFullResolutionDenoise.PreparedYuvNoiseModel( + normalizedRead = mixArray(a.normalizedRead, b.normalizedRead), + normalizedLumaShot = mix(a.normalizedLumaShot, b.normalizedLumaShot), + normalizedLumaQuadratic = mix(a.normalizedLumaQuadratic, b.normalizedLumaQuadratic), + normalizedChromaShot = mix(a.normalizedChromaShot, b.normalizedChromaShot), + normalizedChromaQuadratic = mix(a.normalizedChromaQuadratic, b.normalizedChromaQuadratic), + lumaCorrelation = mixSpectrum(a.lumaCorrelation, b.lumaCorrelation), + chromaCorrelation = mixSpectrum(a.chromaCorrelation, b.chromaCorrelation), + ), + ) + } +} diff --git a/app/src/main/java/com/hinnka/mycamera/raw/MgcFullResolutionDenoise.kt b/app/src/main/java/com/hinnka/mycamera/raw/MgcFullResolutionDenoise.kt index 5379e08d..c39feafd 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/MgcFullResolutionDenoise.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/MgcFullResolutionDenoise.kt @@ -415,6 +415,186 @@ internal object MgcFullResolutionDenoise { return true } + /** + * Denoises linear RGBA16F produced from an ISP-rendered bitmap (white balance 1, 1, 1) with + * the [MgcBitmapNoiseModel] calibration for its ISO. Tunings follow the USER_ADJUSTMENT pass; there is no CFA + * (no MeasureMoire) and no lens shading. [spatialStrengthQ8] is the bitmap detail map over the + * whole image ((full + 3) / 4 Q8 noise scale), or null. The low-frequency chroma branch runs + * separately over the whole image ([lowFrequencyChromaBitmap]). + */ + fun denoiseLinearBitmap( + rgba16f: ByteBuffer, + width: Int, + height: Int, + globalOriginX: Int, + globalOriginY: Int, + fullWidth: Int, + fullHeight: Int, + noiseModel: PreparedYuvNoiseModel, + spatialStrengthQ8: ShortArray?, + tuningSnr: Float, + lumaStrengthScale: Float, + chromaStrengthScale: Float, + ): Boolean { + val finiteLumaScale = DenoiseStrength.clamp(lumaStrengthScale) + val finiteChromaScale = DenoiseStrength.clamp(chromaStrengthScale) + val lumaEnabled = finiteLumaScale > 0f + val chromaEnabled = finiteChromaScale > 0f + if (!initialized || !rgba16f.isDirect || width <= 0 || height <= 0 || + (!lumaEnabled && !chromaEnabled) + ) { + return false + } + val model = noiseModel + check(validPreparedYuvNoise(model) && validCorrelation(model.lumaCorrelation) && + validCorrelation(model.chromaCorrelation)) { "Malformed bitmap MGC noise model" } + val strengthWidth = (fullWidth + 3) / 4 + val strengthHeight = (fullHeight + 3) / 4 + check(spatialStrengthQ8 == null || spatialStrengthQ8.size == strengthWidth * strengthHeight) { + "Bitmap strength map does not cover ${fullWidth}x$fullHeight" + } + val coreTuning = PhotonCoreImagingTuning + val lumaTuning = bitmapLumaTuning(tuningSnr, finiteLumaScale) + val chromaTuning = bitmapChromaTuning(tuningSnr, finiteChromaScale) + rgba16f.clear() + val result = nativeDenoiseRgba16f( + rgbaBuffer = rgba16f, + width = width, + height = height, + globalOriginX = globalOriginX, + globalOriginY = globalOriginY, + fullWidth = fullWidth, + fullHeight = fullHeight, + inputIsBayer = false, + cfaPattern = 0, + measureMoireEnabled = false, + applyLensShadingInBayerAot = false, + lensShading = null, + lensWidth = 0, + lensHeight = 0, + // The prepared YUV model replaces the analytic RGB model in the native bridge. + normalizedRgbShot = FloatArray(3), + normalizedRgbRead = FloatArray(3), + normalizedRgbWhiteBalance = floatArrayOf(1f, 1f, 1f), + preparedNormalizedYuvRead = model.normalizedRead, + preparedNormalizedLumaShot = model.normalizedLumaShot, + preparedNormalizedLumaQuadratic = model.normalizedLumaQuadratic, + preparedNormalizedChromaShot = model.normalizedChromaShot, + preparedNormalizedChromaQuadratic = model.normalizedChromaQuadratic, + lumaCorrelation = model.lumaCorrelation, + chromaCorrelation = model.chromaCorrelation, + denoiseResponseOffset = coreTuning.denoise.frequencyResponse.responseOffset, + denoiseResponseCosineOffset = coreTuning.denoise.frequencyResponse.cosineOffset, + spatialStrengthQ8 = spatialStrengthQ8, + spatialStrengthWidth = if (spatialStrengthQ8 != null) strengthWidth else 0, + spatialStrengthHeight = if (spatialStrengthQ8 != null) strengthHeight else 0, + lumaEnabled = lumaEnabled, + chromaEnabled = chromaEnabled, + lumaStrength = lumaTuning.strength, + lumaOutlierDistance = lumaTuning.outlierDistance, + lumaRevertFactor = lumaTuning.revertFactor, + chromaStrength = chromaTuning.strength, + chromaOutlierThreshold = chromaTuning.outlierDistance, + diagnosticsEnabled = RawStackRuntimeDebug.mgcFullResolutionDenoiseDiagnosticsEnabled, + lowFrequencyLog2Downsample = 0, + chromaMedianFilterType = coreTuning.denoise.chromaMedianFilterType, + ) + rgba16f.position(0) + if (result != 0) { + PLog.e( + TAG, + "MGC bitmap denoise kernel failed: result=0x${result.toString(16)} " + + "size=${width}x$height origin=($globalOriginX,$globalOriginY)", + ) + return false + } + PLog.d( + TAG, + "MGC bitmap denoise complete: size=${width}x$height " + + "origin=($globalOriginX,$globalOriginY) full=${fullWidth}x$fullHeight " + + "snr=$tuningSnr luma=$lumaEnabled($finiteLumaScale) " + + "chroma=$chromaEnabled($finiteChromaScale) " + + "lumaStrength=${lumaTuning.strength.contentToString()} " + + "chromaStrength=${chromaTuning.strength.contentToString()}", + ) + return true + } + + private fun bitmapLumaTuning(tuningSnr: Float, scale: Float): Tuning { + val coreTuning = PhotonCoreImagingTuning + return applyCoreDenoiseScales( + tuning = interpolateTuning(tuningSnr, lumaTuningPoints), + globalStrengthScale = scale, + strengthLevelScales = coreTuning.denoise.lumaStrengthScale.toFloatArray(), + revertLevelScales = coreTuning.denoise.detailReconstructionScale.toFloatArray(), + outlierLevelScales = coreTuning.denoise.outlierRejectionScale.toFloatArray(), + ) + } + + private fun bitmapChromaTuning(tuningSnr: Float, scale: Float): Tuning = + applyCoreDenoiseScales( + tuning = interpolateTuning(tuningSnr, chromaTuningPoints), + globalStrengthScale = scale, + strengthLevelScales = PhotonCoreImagingTuning.denoise.chromaStrengthScale.toFloatArray(), + revertLevelScales = FloatArray(5) { 1f }, + outlierLevelScales = FloatArray(5) { 1f }, + ) + + /** + * GCam's low-frequency chroma branch for a tiled bitmap denoise: [rgba16f] holds the whole + * denoised linear image box-downsampled by 2^[log2Downsample] (lowWidth x lowHeight = + * ceil(full / 2^L)) and is replaced by the linear RGB correction to upsample bilinearly and + * add at full resolution. Uses the same model, chroma tuning and strength map as the tiles. + */ + fun lowFrequencyChromaBitmap( + rgba16f: ByteBuffer, + lowWidth: Int, + lowHeight: Int, + fullWidth: Int, + fullHeight: Int, + log2Downsample: Int, + noiseModel: PreparedYuvNoiseModel, + spatialStrengthQ8: ShortArray?, + tuningSnr: Float, + chromaStrengthScale: Float, + ): Boolean { + val chromaScale = DenoiseStrength.clamp(chromaStrengthScale) + if (!initialized || !rgba16f.isDirect || chromaScale <= 0f) return false + val chromaTuning = bitmapChromaTuning(tuningSnr, chromaScale) + val coreTuning = PhotonCoreImagingTuning + rgba16f.clear() + val result = nativeLowFrequencyChromaCorrection( + rgbaBuffer = rgba16f, + lowWidth = lowWidth, + lowHeight = lowHeight, + fullWidth = fullWidth, + fullHeight = fullHeight, + log2Downsample = log2Downsample, + preparedNormalizedYuvRead = noiseModel.normalizedRead, + preparedNormalizedChromaShot = noiseModel.normalizedChromaShot, + preparedNormalizedChromaQuadratic = noiseModel.normalizedChromaQuadratic, + chromaCorrelation = noiseModel.chromaCorrelation, + denoiseResponseOffset = coreTuning.denoise.frequencyResponse.responseOffset, + denoiseResponseCosineOffset = coreTuning.denoise.frequencyResponse.cosineOffset, + spatialStrengthQ8 = spatialStrengthQ8, + spatialStrengthWidth = if (spatialStrengthQ8 != null) (fullWidth + 3) / 4 else 0, + spatialStrengthHeight = if (spatialStrengthQ8 != null) (fullHeight + 3) / 4 else 0, + chromaStrength = chromaTuning.strength, + chromaOutlierThreshold = chromaTuning.outlierDistance, + chromaMedianFilterType = coreTuning.denoise.chromaMedianFilterType, + ) + rgba16f.position(0) + if (result != 0) { + PLog.e( + TAG, + "MGC bitmap low-frequency chroma failed: result=0x${result.toString(16)} " + + "low=${lowWidth}x$lowHeight full=${fullWidth}x$fullHeight", + ) + return false + } + return true + } + private fun validPreparedYuvNoise(model: PreparedYuvNoiseModel): Boolean = validRgbNoise(model.normalizedRead) && model.normalizedLumaShot.isFinite() && model.normalizedLumaShot >= 0f && @@ -769,6 +949,27 @@ internal object MgcFullResolutionDenoise { return result.sortedBy(TuningPoint::snr) } + private external fun nativeLowFrequencyChromaCorrection( + rgbaBuffer: ByteBuffer, + lowWidth: Int, + lowHeight: Int, + fullWidth: Int, + fullHeight: Int, + log2Downsample: Int, + preparedNormalizedYuvRead: FloatArray, + preparedNormalizedChromaShot: Float, + preparedNormalizedChromaQuadratic: Float, + chromaCorrelation: FloatArray, + denoiseResponseOffset: Float, + denoiseResponseCosineOffset: Float, + spatialStrengthQ8: ShortArray?, + spatialStrengthWidth: Int, + spatialStrengthHeight: Int, + chromaStrength: FloatArray, + chromaOutlierThreshold: FloatArray, + chromaMedianFilterType: Int, + ): Int + private external fun nativeDenoiseRgba16f( rgbaBuffer: ByteBuffer, width: Int, 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 bc206e79..709b1d7a 100644 --- a/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt +++ b/app/src/main/java/com/hinnka/mycamera/viewmodel/GalleryViewModel.kt @@ -653,8 +653,12 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) if (!isRawInGallery(photo.id)) { // 非 RAW 照片,先进行一次色度降噪 - val lutProcessor = com.hinnka.mycamera.lut.LutImageProcessor() - val chromaDenoised = lutProcessor.applyChromaDenoise(bitmap, strength = 0.8f) + 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() @@ -3477,6 +3481,7 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) val source = photonDenoiseSource(context, photo.id, metadata) ?: return@launch val built = contentRepository.photoProcessor.updatePhotonDenoiseBase( context, photo.id, source, noiseReduction, chromaNoiseReduction, + sensorIso = metadata.iso, onBuild = { _isPhotonDenoising.value = true }, ) val strengths = noiseReduction to chromaNoiseReduction @@ -3681,7 +3686,9 @@ class GalleryViewModel(application: Application) : AndroidViewModel(application) val source = photonDenoiseSource(context, photo.id, finalMetadata) if (strengths != null && source != null) { contentRepository.photoProcessor.loadPhotonDenoiseBase( - context, photo.id, source, strengths.first, strengths.second, maxEdge, + context, photo.id, source, strengths.first, strengths.second, + sensorIso = finalMetadata.iso, + maxEdge = maxEdge, ) } else { null diff --git a/app/src/test/java/com/hinnka/mycamera/lut/ChromaDenoiseShadersTest.kt b/app/src/test/java/com/hinnka/mycamera/lut/ChromaDenoiseShadersTest.kt deleted file mode 100644 index e842a4e3..00000000 --- a/app/src/test/java/com/hinnka/mycamera/lut/ChromaDenoiseShadersTest.kt +++ /dev/null @@ -1,60 +0,0 @@ -package com.hinnka.mycamera.lut - -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Test - -class ChromaDenoiseShadersTest { - @Test - fun rawOpponentValuesStayInOneLinearCameraRgbDomain() { - val shader = ChromaDenoiseShaders.PASS_CHROMA_DENOISE - - assertTrue(shader.contains("rgb.r - rgb.g")) - assertTrue(shader.contains("rgb.b - rgb.g")) - assertTrue(shader.contains("(rgb.r + rgb.g + rgb.b) / 3.0")) - assertTrue(shader.contains("value.x - (value.y + value.z) / 3.0")) - assertTrue(shader.contains("green + value.y")) - assertTrue(shader.contains("green + value.z")) - assertFalse(shader.contains("cameraChromaScale")) - } - - @Test - fun rawNeighborMeanIsNormalizedBackToTheCenterSignal() { - val shader = ChromaDenoiseShaders.PASS_CHROMA_DENOISE - - assertTrue(shader.contains("sumSignal += sampleValue.x * weight")) - assertTrue(shader.contains("centerSignal / max(averageSignal, 1e-6)")) - assertTrue(shader.contains("averageChroma * signalScale")) - } - - @Test - fun rawOpponentAndGuideBandwidthsIncludeGreenNoise() { - val shader = ChromaDenoiseShaders.PASS_CHROMA_DENOISE - - assertTrue(shader.contains("uniform vec2 uNoiseModelG;")) - assertTrue(shader.contains("variance.rb + variance.gg")) - assertTrue(shader.contains("variance.r + variance.g + variance.b")) - } - - @Test - fun everyScaleUsesTheSameBoundedChromaEdgeThreshold() { - val shader = ChromaDenoiseShaders.PASS_CHROMA_DENOISE - - assertTrue(shader.contains("exp(-chromaDistance)")) - assertTrue(shader.contains("float chromaEdgeSigmaMultiplier")) - assertFalse(shader.contains("signalSnr")) - assertFalse(shader.contains("cloudRadius")) - assertFalse(shader.contains("vec2 cloudH")) - } - - @Test - fun rawCameraRgbUsesSymmetricLuminanceInsteadOfGreenGuide() { - val shader = ChromaDenoiseShaders.PASS_CHROMA_DENOISE - - assertTrue(shader.contains("texture(uGuideTexture, sampleCoord).r - centerGuide")) - assertTrue(ChromaDenoiseShaders.PASS_EDGE_GUIDE.contains( - "(rgb.r + rgb.g + rgb.b) / 3.0" - )) - assertFalse(ChromaDenoiseShaders.PASS_EDGE_GUIDE.contains("return rgb.g")) - } -} diff --git a/app/src/test/java/com/hinnka/mycamera/processor/DenoiseStrengthTest.kt b/app/src/test/java/com/hinnka/mycamera/processor/DenoiseStrengthTest.kt index 96fcaaa4..145a4b07 100644 --- a/app/src/test/java/com/hinnka/mycamera/processor/DenoiseStrengthTest.kt +++ b/app/src/test/java/com/hinnka/mycamera/processor/DenoiseStrengthTest.kt @@ -1,6 +1,5 @@ package com.hinnka.mycamera.processor -import com.hinnka.mycamera.lut.ChromaDenoiseDefaults import org.junit.Assert.assertEquals import org.junit.Test @@ -13,20 +12,4 @@ class DenoiseStrengthTest { assertEquals(0f, DenoiseStrength.clamp(Float.NaN), 0f) assertEquals(0f, DenoiseStrength.clamp(Float.POSITIVE_INFINITY), 0f) } - - @Test - fun strengthAboveOneScalesNoiseVarianceQuadratically() { - assertEquals(1f, DenoiseStrength.noiseVarianceScale(0.5f), 0f) - assertEquals(1f, DenoiseStrength.noiseVarianceScale(1f), 0f) - assertEquals(2.25f, DenoiseStrength.noiseVarianceScale(1.5f), 0f) - assertEquals(4f, DenoiseStrength.noiseVarianceScale(2f), 0f) - assertEquals(1f, DenoiseStrength.outputMix(2f), 0f) - } - - @Test - fun chromaBandwidthContinuesGrowingAboveOne() { - assertEquals(8f, ChromaDenoiseDefaults.noiseBandwidth(1f), 0f) - assertEquals(15f, ChromaDenoiseDefaults.noiseBandwidth(2f), 0f) - assertEquals(15f, ChromaDenoiseDefaults.noiseBandwidth(3f), 0f) - } } diff --git a/app/src/test/java/com/hinnka/mycamera/raw/RawNoiseProfileSelectionTest.kt b/app/src/test/java/com/hinnka/mycamera/raw/RawNoiseProfileSelectionTest.kt index cfcf6ee6..a2fbb5a9 100644 --- a/app/src/test/java/com/hinnka/mycamera/raw/RawNoiseProfileSelectionTest.kt +++ b/app/src/test/java/com/hinnka/mycamera/raw/RawNoiseProfileSelectionTest.kt @@ -178,87 +178,4 @@ class RawNoiseProfileSelectionTest { 0f, ) } - - @Test - fun denoiseProfileShaderUsesCameraDomainSignalScaleInsteadOfWhiteBalanceScale() { - val shader = DenoiseProfileShaders.PRECONDITION_V2 + DenoiseProfileShaders.FINISH_V2 - - assertTrue(shader.contains("uniform vec4 uSignalScale;")) - assertTrue(shader.contains("pixel / uSignalScale")) - assertTrue(shader.contains("px *= uSignalScale")) - assertFalse(shader.contains("uWb")) - } - - @Test - fun nlmSearchOffsetsCoverSymmetricWindowExactlyOnce() { - val radius = DenoiseProfileShaders.SEARCH_RADIUS - val candidates = buildList { - DenoiseProfileNlmConfig.buildSearchOffsets(radius).forEach { q -> - add(q.x to q.y) - if (q.x != 0 || q.y != 0) { - add(-q.x to -q.y) - } - } - } - - val windowWidth = 2 * radius + 1 - assertEquals(windowWidth * windowWidth, candidates.size) - assertEquals(candidates.size, candidates.toSet().size) - assertTrue(candidates.all { (x, y) -> x in -radius..radius && y in -radius..radius }) - } - - @Test - fun nlmWeightTuningSubtractsVarianceStabilizedNoiseFloor() { - val tuning = DenoiseProfileNlmConfig.weightTuning( - DenoiseProfileShaders.PATCH_RADIUS - ) - - assertEquals(54f, tuning.expectedFineDistance, 0f) - assertEquals(2.53125f, tuning.expectedGuideDistance, 1e-6f) - assertEquals(1f / 54f, tuning.inverseBandwidth, 1e-7f) - assertEquals(8f, tuning.coarseGuideWeight, 0f) - } - - @Test - fun nlmShaderUsesCoarseGuideAndExplicitNoiseFloor() { - val shader = DenoiseProfileShaders.PRECONDITION_V2 + - DenoiseProfileShaders.FUSED_ACCU + - DenoiseProfileShaders.FINISH_V2 - - assertTrue(shader.contains("t.a = guide")) - assertTrue(shader.contains("uExpectedFineDistance")) - assertTrue(shader.contains("uExpectedGuideDistance")) - assertTrue(shader.contains("uCoarseGuideWeight")) - assertTrue(shader.contains("uDenoiseMix")) - assertFalse(shader.contains("distacc * uNorm - 2.0")) - } - - @Test - fun zeroBiasBacktransformExactlyPreservesAnUnchangedDarkSample() { - val input = 0.003f - val signalScale = 0.38f - val a = 0.0089f - val b = 3.55e-7f - val p = 0.62f - val transformed = 2f * max(input / signalScale + b, 0f).pow(1f - p / 2f) / - ((2f - p) * sqrt(a)) - - val delta = transformed * transformed + DenoiseProfileShaders.BLACK_PRESERVING_BIAS - val denominator = 4f / (sqrt(a) * (2f - p)) - val z1 = (transformed + sqrt(max(delta, 0f))) / denominator - val restored = max(z1.pow(1f / (1f - p / 2f)) - b, 0f) * signalScale - - assertEquals(0f, DenoiseProfileShaders.BLACK_PRESERVING_BIAS, 0f) - assertEquals(input, restored, 1e-6f) - } - - @Test - fun nlmStripeShaderKeepsSamplingInFullImageCoordinates() { - val shader = DenoiseProfileShaders.FUSED_ACCU + DenoiseProfileShaders.FINISH_V2 - - assertTrue(shader.contains("uStripeRowOffset")) - assertTrue(shader.contains("coord = stripeCoord + ivec2(0, uStripeRowOffset)")) - assertTrue(shader.contains("stripeCoord.y * uImageSize.x + stripeCoord.x")) - assertFalse(shader.contains("pixelIndex(coord, uImageSize)")) - } }