From 9d91dd48ac41c2a8e7aca44ef5256c234d08d117 Mon Sep 17 00:00:00 2001 From: Hinnka Date: Sat, 5 Sep 2026 17:46:30 +0800 Subject: [PATCH] feat: HDRNet post-exposure SLM rolloff --- app/src/main/cpp/dng_hdrnet_pgtm_jni.cpp | 181 ++++++++-------- app/src/main/cpp/raw_hdrnet_post_exposure.h | 40 ++++ .../cpp/raw_legacy_auto_exposure_solver.cpp | 189 ++++++++--------- .../raw/DngHdrNetProfileGainTableNative.kt | 25 ++- .../raw/DngPhotonProfileGainTableAlgorithm.kt | 20 +- .../raw/DngPhotonProfileGainTableGenerator.kt | 4 +- .../mycamera/raw/RawDngProfilePreparation.kt | 2 +- .../raw/RawLegacyAutoExposureMatcher.kt | 34 ++- .../raw/RawLegacyAutoExposureNativeBridge.kt | 21 +- .../raw/DngHdrNetViewfinderGridTest.kt | 118 ++++++++++- docs/photon-core-imaging-tuning.md | 7 +- docs/photon-dehaze-pipeline.md | 59 +++++- tools/dng_hdrnet_dehaze_test.cpp | 40 +++- .../raw_hdrnet_post_exposure_solver_test.cpp | 194 +++++++++++++++--- 14 files changed, 653 insertions(+), 281 deletions(-) create mode 100644 app/src/main/cpp/raw_hdrnet_post_exposure.h diff --git a/app/src/main/cpp/dng_hdrnet_pgtm_jni.cpp b/app/src/main/cpp/dng_hdrnet_pgtm_jni.cpp index f5cc6faf..2df9e093 100644 --- a/app/src/main/cpp/dng_hdrnet_pgtm_jni.cpp +++ b/app/src/main/cpp/dng_hdrnet_pgtm_jni.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -7,6 +8,8 @@ #include #include +#include "raw_hdrnet_post_exposure.h" + #if defined(__ANDROID__) #include #endif @@ -135,11 +138,7 @@ AxisSample MakeNormalizedAxisSample(float coordinate, int source_size) { }; } -struct RgbSample { - float red; - float green; - float blue; -}; +using RgbSample = photon::hdrnet_post_exposure::Rgb; RgbSample SampleModelRgb(const float* model_input, int input_width, int input_channels, const AxisSample& sample_x, @@ -453,31 +452,36 @@ RgbSample ApplyDehaze(const RgbSample& rgb, const DehazeCurve& curve) { }; } -float DehazedHdrNetTargetLuma(float short_intensity, float render_gain, - const RgbSample& cell_rgb, - float cell_intensity, - const DehazeCurve& curve) { - const float hdrnet_target_luma = std::clamp( - short_intensity * render_gain, 0.0f, 1.0f); - const float source_scale = cell_intensity > kHdrNetGainEpsilon - ? short_intensity / cell_intensity - : 0.0f; - const RgbSample hdrnet_rgb = cell_intensity > kHdrNetGainEpsilon - ? RgbSample{ - std::clamp(cell_rgb.red * source_scale * render_gain, 0.0f, 1.0f), - std::clamp(cell_rgb.green * source_scale * render_gain, 0.0f, 1.0f), - std::clamp(cell_rgb.blue * source_scale * render_gain, 0.0f, 1.0f), - } - : RgbSample{ - hdrnet_target_luma, - hdrnet_target_luma, - hdrnet_target_luma, - }; - const float hdrnet_mean = - (hdrnet_rgb.red + hdrnet_rgb.green + hdrnet_rgb.blue) / 3.0f; - const float dehaze_gain = MappedDehazeLuminance(hdrnet_mean, curve) / - std::max(std::clamp(hdrnet_mean, 0.0f, 1.0f), 1.0e-6f); - return std::clamp(hdrnet_target_luma * dehaze_gain, 0.0f, 1.0f); +float HdrNetLuma(const RgbSample& rgb) { + return rgb.red * kHdrNetLumaRed + rgb.green * kHdrNetLumaGreen + rgb.blue * kHdrNetLumaBlue; +} + +float TableIntensity(const RgbSample& rgb, const float* weights) { + return rgb.red * weights[0] + rgb.green * weights[1] + rgb.blue * weights[2] + + std::min({rgb.red, rgb.green, rgb.blue}) * weights[3] + + std::max({rgb.red, rgb.green, rgb.blue}) * weights[4]; +} + +RgbSample RgbForTableCoordinate(float coordinate, const RgbSample& cell_rgb, + float cell_coordinate, float weight_sum) { + // A positive scalar table cannot reproduce a positive target from non-positive + // source luma. Define black/signed-noise cells on the neutral axis instead. + if (cell_coordinate <= kHdrNetGainEpsilon || HdrNetLuma(cell_rgb) <= kHdrNetGainEpsilon) { + const float gray = coordinate / weight_sum; + return {gray, gray, gray}; + } + const float scale = coordinate / cell_coordinate; + return {cell_rgb.red * scale, cell_rgb.green * scale, cell_rgb.blue * scale}; +} + +float PostExposedHdrNetTargetLuma(const RgbSample& short_rgb, float render_gain, + const DehazeCurve& curve, + const photon::hdrnet_post_exposure::Gains& gains) { + const RgbSample hdrnet_rgb{ + std::clamp(short_rgb.red * render_gain, 0.0f, 1.0f), + std::clamp(short_rgb.green * render_gain, 0.0f, 1.0f), + std::clamp(short_rgb.blue * render_gain, 0.0f, 1.0f)}; + return HdrNetLuma(photon::hdrnet_post_exposure::Apply(ApplyDehaze(hdrnet_rgb, curve), gains)); } void WriteDehazeCurve(const DehazeCurve& curve, float* values) { @@ -522,11 +526,11 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeEvaluateDispl jint output_rotation, jfloatArray guide_shifts_array, jfloatArray guide_slopes_array, jfloatArray output_lumas_array, jfloatArray output_dehaze_curve_array, - jfloatArray output_metrics_array) { + jfloatArray output_metrics_array, jfloatArray output_rgb_array) { if (coefficients_array == nullptr || model_input_array == nullptr || guide_shifts_array == nullptr || guide_slopes_array == nullptr || output_lumas_array == nullptr || output_dehaze_curve_array == nullptr || - output_metrics_array == nullptr || + output_metrics_array == nullptr || output_rgb_array == nullptr || source_grid_width <= 0 || source_grid_height <= 0 || source_grid_depth <= 0 || coefficient_count != 2 || input_width <= 0 || input_height <= 0 || @@ -563,6 +567,7 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeEvaluateDispl env->GetArrayLength(guide_slopes_array) != guide_count || env->GetArrayLength(output_lumas_array) != output_values || env->GetArrayLength(output_dehaze_curve_array) != kDehazeCurveValueCount || + env->GetArrayLength(output_rgb_array) != static_cast(input_width) * input_height * 3 || env->GetArrayLength(output_metrics_array) != kEvaluationMetricCount) { LogError("Rejected mismatched HDRNet display-grid geometry"); return JNI_FALSE; @@ -575,10 +580,11 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeEvaluateDispl ScopedFloatArray output_lumas(env, output_lumas_array); ScopedFloatArray output_dehaze_curve(env, output_dehaze_curve_array); ScopedFloatArray output_metrics(env, output_metrics_array); + ScopedFloatArray output_rgb(env, output_rgb_array); if (coefficients.data() == nullptr || model_input.data() == nullptr || guide_shifts.data() == nullptr || guide_slopes.data() == nullptr || output_lumas.data() == nullptr || output_dehaze_curve.data() == nullptr || - output_metrics.data() == nullptr) { + output_metrics.data() == nullptr || output_rgb.data() == nullptr) { LogError("Unable to acquire HDRNet display-grid arrays"); return JNI_FALSE; } @@ -684,12 +690,16 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeEvaluateDispl (static_cast(output_x) + 0.5f) / oriented_width; const NormalizedImagePoint source = MapTopLeftOutputToSource( output_u, output_v_top, output_rotation); - const int source_x = std::clamp( + const int source_x = std::clamp( static_cast(source.u * input_width), 0, input_width - 1); - const int source_y = std::clamp( + const int source_y = std::clamp( static_cast(source.v * input_height), 0, input_height - 1); const RgbSample display_rgb = full_image_display_rgb[ static_cast(source_y * input_width + source_x)]; + const size_t output_offset = (static_cast(output_y) * oriented_width + output_x) * 3; + output_rgb.data()[output_offset] = display_rgb.red; + output_rgb.data()[output_offset + 1] = display_rgb.green; + output_rgb.data()[output_offset + 2] = display_rgb.blue; luma_sum += display_rgb.red * kDisplayLumaRed + display_rgb.green * kDisplayLumaGreen + display_rgb.blue * kDisplayLumaBlue; @@ -710,6 +720,7 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeEvaluateDispl output_lumas.CommitOnRelease(); output_dehaze_curve.CommitOnRelease(); output_metrics.CommitOnRelease(); + output_rgb.CommitOnRelease(); return env->ExceptionCheck() ? JNI_FALSE : JNI_TRUE; } @@ -727,12 +738,12 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeGenerateGains jfloat min_table_gain, jfloat max_table_gain, jfloatArray guide_shifts_array, jfloatArray guide_slopes_array, jfloatArray acr_curve_array, - jfloatArray dehaze_curve_array, jfloat post_exposure_gain, + jfloatArray dehaze_curve_array, jfloat post_exposure_gain, jfloatArray map_input_weights_array, jfloatArray output_gains_array) { if (coefficients_array == nullptr || model_input_array == nullptr || guide_shifts_array == nullptr || guide_slopes_array == nullptr || acr_curve_array == nullptr || - dehaze_curve_array == nullptr || output_gains_array == nullptr || + dehaze_curve_array == nullptr || map_input_weights_array == nullptr || output_gains_array == nullptr || input_width <= 0 || input_height <= 0 || input_channels < 3 || source_grid_width <= 0 || source_grid_height <= 0 || source_grid_depth <= 0 || @@ -772,6 +783,7 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeGenerateGains env->GetArrayLength(guide_slopes_array) != guide_count || acr_curve_count < 2 || env->GetArrayLength(dehaze_curve_array) != kDehazeCurveValueCount || + env->GetArrayLength(map_input_weights_array) != 5 || env->GetArrayLength(output_gains_array) != output_values) { LogError("Rejected mismatched HDRNet PGTM array geometry"); return JNI_FALSE; @@ -782,11 +794,12 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeGenerateGains ScopedFloatArray guide_slopes(env, guide_slopes_array); ScopedFloatArray acr_curve(env, acr_curve_array); ScopedFloatArray dehaze_curve_values(env, dehaze_curve_array); + ScopedFloatArray map_input_weights(env, map_input_weights_array); ScopedFloatArray output_gains(env, output_gains_array); if (coefficients.data() == nullptr || model_input.data() == nullptr || guide_shifts.data() == nullptr || guide_slopes.data() == nullptr || acr_curve.data() == nullptr || - dehaze_curve_values.data() == nullptr || output_gains.data() == nullptr) { + dehaze_curve_values.data() == nullptr || map_input_weights.data() == nullptr || output_gains.data() == nullptr) { LogError("Unable to acquire HDRNet PGTM arrays"); return JNI_FALSE; } @@ -795,6 +808,7 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeGenerateGains !IsFiniteArray(model_input.data(), static_cast(input_values)) || !IsFiniteArray(guide_shifts.data(), guide_count) || !IsFiniteArray(guide_slopes.data(), guide_count) || + !IsFiniteArray(map_input_weights.data(), 5) || !IsValidAcrCurve(acr_curve.data(), acr_curve_count) || !ReadDehazeCurve( dehaze_curve_values.data(), kDehazeCurveValueCount, &dehaze_curve)) { @@ -802,13 +816,27 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeGenerateGains return JNI_FALSE; } + std::array short_input_weights{}; + float weight_sum = 0.0f; + for (int index = 0; index < 5; ++index) { + const float weight = map_input_weights.data()[index] * renderer_baseline_gain / source_to_short_gain; + if (!std::isfinite(weight) || weight < 0.0f) return JNI_FALSE; + short_input_weights[index] = weight; + weight_sum += weight; + } + if (!std::isfinite(weight_sum) || weight_sum <= 0.0f) return JNI_FALSE; + const auto post_exposure = photon::hdrnet_post_exposure::SplitGain(post_exposure_gain); +#if defined(__ANDROID__) + __android_log_print(ANDROID_LOG_INFO, kLogTag, + "POST_EXPOSURE gain=%.4f rolloffGain=%.4f digitalGain=%.4f", + post_exposure_gain, post_exposure.rolloff, post_exposure.digital); +#endif + try { std::vector x_samples(static_cast(output_grid_width)); std::vector y_samples(static_cast(output_grid_height)); std::vector model_x_samples(static_cast(output_grid_width)); std::vector model_y_samples(static_cast(output_grid_height)); - std::vector range_samples(static_cast(point_count)); - std::vector short_intensities(static_cast(point_count)); std::vector local_model_rgb(static_cast(cell_count)); for (int x = 0; x < output_grid_width; ++x) { x_samples[static_cast(x)] = @@ -830,44 +858,27 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeGenerateGains model_x_samples[static_cast(x)], model_y_samples[static_cast(y)]); } - for (int point = 0; point < point_count; ++point) { - const int evaluated_point = point == 0 ? 1 : point; - // Adobe indexes a table with weight * tableSize, so entry p represents p / tableSize. - // MapInputWeights already reparameterizes this N axis into Pixel's final-short intensity. - const float short_intensity = - static_cast(evaluated_point) / point_count; - short_intensities[static_cast(point)] = short_intensity; - const float guide = - EvaluateGuide(short_intensity, guide_shifts.data(), guide_slopes.data(), - guide_count); - const float range_position = guide * source_grid_depth - 0.5f; - const float range_floor = std::floor(range_position); - const int lower_unclamped = static_cast(range_floor); - range_samples[static_cast(point)] = { - std::clamp(lower_unclamped, 0, source_grid_depth - 1), - std::clamp(lower_unclamped + 1, 0, source_grid_depth - 1), - range_position - range_floor, - }; - } - std::atomic targets_valid{true}; #pragma omp parallel for schedule(static) for (int cell = 0; cell < cell_count; ++cell) { const int x = cell % output_grid_width; const int y = cell / output_grid_width; const RgbSample cell_rgb = local_model_rgb[static_cast(cell)]; - const float cell_intensity = std::clamp( - cell_rgb.red * kHdrNetLumaRed + - cell_rgb.green * kHdrNetLumaGreen + - cell_rgb.blue * kHdrNetLumaBlue, - 0.0f, 1.0f); + const float cell_coordinate = TableIntensity(cell_rgb, short_input_weights.data()); float* const gain_curve = output_gains.data() + static_cast(cell) * point_count; for (int point = 0; point < point_count; ++point) { - const float short_intensity = - short_intensities[static_cast(point)]; - const AxisSample& range_sample = - range_samples[static_cast(point)]; + // PXL N includes min/max RGB weights; it is not HDRNet Rec.601 luma. + // Reconstruct RGB first so colored highlights enter rolloff at the same level + // as the image evaluated by the viewfinder solver. + const float coordinate = static_cast(point == 0 ? 1 : point) / point_count; + const RgbSample short_rgb = RgbForTableCoordinate( + coordinate, cell_rgb, cell_coordinate, weight_sum); + const float source_luma = HdrNetLuma(short_rgb); + const float short_intensity = std::clamp(source_luma, 0.0f, 1.0f); + const float guide = EvaluateGuide( + short_intensity, guide_shifts.data(), guide_slopes.data(), guide_count); + const AxisSample range_sample = MakeNormalizedAxisSample(guide, source_grid_depth); const float raw_scale = SampleCoefficient( coefficients.data(), source_grid_width, source_grid_depth, coefficient_count, x_samples[static_cast(x)], @@ -888,34 +899,28 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeGenerateGains // prediction to a gain first, then apply uGainLimits. Clamping the // affine output itself to zero would turn negative local predictions // into DNG's 1/4096 legal minimum and produce grid-shaped black areas. - float render_max_gain_for_luma = render_max_gain; - if (render_max_gain_blend_threshold > 0.0f) { - const float blend = std::clamp( - short_intensity / render_max_gain_blend_threshold, 0.0f, 1.0f); - render_max_gain_for_luma = Lerp(1.0f, render_max_gain, blend); - } const float render_gain = std::clamp( predicted_luma / (short_intensity + kHdrNetGainEpsilon), - render_min_gain, render_max_gain_for_luma); - // Dehaze + DHA is downstream of HDRNet. Folding its scalar neutral-axis response into - // the same table makes the runtime order HdrNet -> Dehaze/DHA -> profile processing. - // Reuse the selected model input's local chromaticity so the arithmetic-RGB curve lookup - // agrees with candidate evaluation instead of assuming every table cell is neutral gray. - const float target_luma = std::clamp( - DehazedHdrNetTargetLuma( - short_intensity, render_gain, cell_rgb, cell_intensity, - dehaze_curve) * post_exposure_gain, - 0.0f, 1.0f); + render_min_gain, RenderMaximumGain( + short_intensity, render_max_gain, render_max_gain_blend_threshold)); + // Apply the same post-Dehaze RGB rolloff/clipping response used by matching. + const float target_luma = PostExposedHdrNetTargetLuma( + short_rgb, render_gain, dehaze_curve, post_exposure); + if (!std::isfinite(target_luma)) { + targets_valid.store(false, std::memory_order_relaxed); + gain_curve[point] = min_table_gain; + continue; + } const float pre_curve_target = InputForAcrOutput( target_luma, acr_curve.data(), acr_curve_count); - // The N axis is final-short intensity = stored source * sourceToShortGain. PGTM itself is - // applied before the renderer's BaselineExposure, so divide by the source value after that + // PGTM is applied before BaselineExposure, so divide by source luma after that // pending exposure. The subsequent exposure ramp then restores pre_curve_target exactly. const float baseline_applied_source_intensity = - short_intensity * renderer_baseline_gain / source_to_short_gain; + source_luma * renderer_baseline_gain / source_to_short_gain; const float gain = std::clamp( pre_curve_target / baseline_applied_source_intensity, min_table_gain, max_table_gain); + if (!std::isfinite(gain)) targets_valid.store(false, std::memory_order_relaxed); gain_curve[point] = gain; } } diff --git a/app/src/main/cpp/raw_hdrnet_post_exposure.h b/app/src/main/cpp/raw_hdrnet_post_exposure.h new file mode 100644 index 00000000..ac424e8c --- /dev/null +++ b/app/src/main/cpp/raw_hdrnet_post_exposure.h @@ -0,0 +1,40 @@ +#pragma once + +#include +#include + +namespace photon::hdrnet_post_exposure { + +struct Rgb { float red, green, blue; }; +struct Gains { float rolloff, digital; }; + +// MGC V25 SLM further-gain split (0x46f9598..0x46f95f0). This is only the +// downstream gain stage; Photon keeps its existing viewfinder target and HDRNet image. +inline Gains SplitGain(float gain) { + if (gain <= 1.0f) return {1.0f, gain}; + if (gain < 1.25f) return {gain, 1.0f}; + const float t = std::clamp(2.0f * (gain - 1.25f), 0.0f, 1.0f); + const float rolloff = 1.25f + 0.5f * (t - 0.5f * t * t); + return {rolloff, gain / rolloff}; +} + +// ApplySlm's max-RGB rolloff. Shared by matching and PGTM generation so clipping +// and reduced highlight gain are part of the exposure solve, not a later correction. +inline Rgb Apply(const Rgb& rgb, const Gains& gains) { + constexpr float kEpsilon = 1.0e-7f; + const float peak = std::max({rgb.red, rgb.green, rgb.blue}); + const float shadow = 1.0f - peak; + const float rolloff = 1.0f + (gains.rolloff - 1.0f) * shadow * shadow; + const float gain = gains.rolloff * gains.digital < 1.0f + ? gains.digital + : (kEpsilon + peak * gains.digital * rolloff) / (peak + kEpsilon); + return {std::clamp(rgb.red * gain, 0.0f, 1.0f), + std::clamp(rgb.green * gain, 0.0f, 1.0f), + std::clamp(rgb.blue * gain, 0.0f, 1.0f)}; +} + +inline float DisplayLuma(const Rgb& rgb) { + return rgb.red * 0.2126f + rgb.green * 0.7152f + rgb.blue * 0.0722f; +} + +} // namespace photon::hdrnet_post_exposure diff --git a/app/src/main/cpp/raw_legacy_auto_exposure_solver.cpp b/app/src/main/cpp/raw_legacy_auto_exposure_solver.cpp index 307e65e1..9f511a85 100644 --- a/app/src/main/cpp/raw_legacy_auto_exposure_solver.cpp +++ b/app/src/main/cpp/raw_legacy_auto_exposure_solver.cpp @@ -1,4 +1,5 @@ #include +#include "raw_hdrnet_post_exposure.h" #if defined(__ANDROID__) #include @@ -86,6 +87,12 @@ float ReferenceReliabilityWeight(float luma) { return std::clamp(shadow_weight * highlight_weight, 0.0f, 1.0f); } +float HdrNetShadowPriority(float reference_luma) { + // Modest preference only within the existing reliable-reference cells. + // Near-black rejection, spatial weights and portrait priority remain in effect. + return 1.0f + 0.25f * (1.0f - SmoothStep(0.02f, 0.25f, reference_luma)); +} + float SpatialGridWeight(int cell) { const int grid_x = cell % kGridColumns; const int grid_y = cell / kGridColumns; @@ -440,116 +447,94 @@ public: } /** - * Solves a fixed 8 x 6 result with one downstream exposure. Candidate EVs are derived from - * every +/-0.1 EV interval boundary, so the primary selection is the exact maximum weighted - * overlap rather than an iterative approximation. HDRNet and Dehaze/DHA are never rerun. + * Retains the reference's 8 x 6 scoring, using the full RGB pixels to evaluate + * the nonlinear SLM gain response before averaging each cell. Invert that + * monotone response at each reference match boundary to retain weighted + * interval selection without rerunning HDRNet or Dehaze/DHA. */ std::optional SolveSingleGridExposure( - const float* display_linear_lumas, - int columns, - int rows, + const float* display_linear_rgb, + int width, + int height, float minimum_ev, float maximum_ev) const { - if (display_linear_lumas == nullptr || columns != kGridColumns || - rows != kGridRows || !std::isfinite(minimum_ev) || - !std::isfinite(maximum_ev)) { + if (display_linear_rgb == nullptr || width < kGridColumns || height < kGridRows || + !std::isfinite(minimum_ev) || !std::isfinite(maximum_ev) || + static_cast(width) * height > std::numeric_limits::max() / 3) { return std::nullopt; } const float safe_minimum = std::clamp(minimum_ev, kMinExposureEv, kMaxExposureEv); const float safe_maximum = std::clamp(maximum_ev, kMinExposureEv, kMaxExposureEv); if (safe_minimum > safe_maximum) return std::nullopt; - std::vector corrections; - std::vector initial_residuals; - std::vector interval_boundaries; - corrections.reserve(eligible_cell_indices_.size()); - initial_residuals.reserve(eligible_cell_indices_.size()); - interval_boundaries.reserve(eligible_cell_indices_.size() * 2 + 2); - interval_boundaries.push_back(safe_minimum); - interval_boundaries.push_back(safe_maximum); - for (size_t index = 0; index < eligible_cell_indices_.size(); ++index) { - const float candidate_luma = - display_linear_lumas[eligible_cell_indices_[index]]; - if (!std::isfinite(candidate_luma) || candidate_luma < 0.0f) { - return std::nullopt; + namespace post = photon::hdrnet_post_exposure; + std::vector> cells(kGridCellCount); + for (int y = 0; y < height; ++y) { + for (int x = 0; x < width; ++x) { + const int offset = (y * width + x) * 3; + const post::Rgb rgb{display_linear_rgb[offset], display_linear_rgb[offset + 1], + display_linear_rgb[offset + 2]}; + if (!std::isfinite(rgb.red) || !std::isfinite(rgb.green) || !std::isfinite(rgb.blue) || + std::min({rgb.red, rgb.green, rgb.blue}) < 0.0f || + std::max({rgb.red, rgb.green, rgb.blue}) > 1.0f) return std::nullopt; + const int cell = (y * kGridRows / height) * kGridColumns + x * kGridColumns / width; + cells[cell].push_back(rgb); } - const float candidate_ev = std::log2( - std::max(candidate_luma, kDisplayLinearLumaFloor)); - const float residual_ev = std::clamp( - candidate_ev - reference_cell_log2_lumas_[index], - -kMaximumAbsoluteLog2Residual, - kMaximumAbsoluteLog2Residual); - const float correction_ev = -residual_ev; - const float weight = reference_cell_weights_[index]; - corrections.push_back(WeightedValue{correction_ev, weight}); - initial_residuals.push_back(WeightedValue{residual_ev, weight}); - interval_boundaries.push_back(std::clamp( - correction_ev - kMatchResidualToleranceEv, - safe_minimum, - safe_maximum)); - interval_boundaries.push_back(std::clamp( - correction_ev + kMatchResidualToleranceEv, - safe_minimum, - safe_maximum)); } - if (corrections.empty()) return std::nullopt; + const auto response = [&](int cell, float ev) { + const auto gains = post::SplitGain(std::exp2(ev)); + double sum = 0.0; + for (const auto& rgb : cells[cell]) sum += post::DisplayLuma(post::Apply(rgb, gains)); + return static_cast(sum / cells[cell].size()); + }; + const auto exposure_for_luma = [&](int cell, float target) { + if (response(cell, safe_minimum) >= target) return safe_minimum; + if (response(cell, safe_maximum) <= target) return safe_maximum; + float lower = safe_minimum, upper = safe_maximum; + for (int iteration = 0; iteration < 24; ++iteration) { + const float middle = (lower + upper) * 0.5f; + if (response(cell, middle) < target) lower = middle; + else upper = middle; + } + return (lower + upper) * 0.5f; + }; - std::sort(interval_boundaries.begin(), interval_boundaries.end()); - interval_boundaries.erase( - std::unique( - interval_boundaries.begin(), - interval_boundaries.end(), - [](float first, float second) { - return std::abs(first - second) <= kScoreEqualityEpsilon; - }), - interval_boundaries.end()); - std::vector proposals = interval_boundaries; - proposals.reserve(interval_boundaries.size() * 2 + 2); - for (size_t index = 0; index + 1 < interval_boundaries.size(); ++index) { - proposals.push_back( - (interval_boundaries[index] + interval_boundaries[index + 1]) * 0.5f); + std::vector weights = reference_cell_weights_; + std::vector boundaries{safe_minimum, safe_maximum}; + std::vector proposals{std::clamp(0.0f, safe_minimum, safe_maximum)}; + for (size_t index = 0; index < eligible_cell_indices_.size(); ++index) { + const int cell = eligible_cell_indices_[index]; + const float reference_luma = reference_grid_lumas_[cell]; + weights[index] *= HdrNetShadowPriority(reference_luma); + boundaries.push_back(exposure_for_luma(cell, + reference_luma * std::exp2(-kMatchResidualToleranceEv))); + boundaries.push_back(exposure_for_luma(cell, + reference_luma * std::exp2(kMatchResidualToleranceEv))); + proposals.push_back(exposure_for_luma(cell, reference_luma)); } - const float weighted_median = WeightedMedian( - &corrections, - reference_weight_sum_); - const float robust_correction = RobustExposureCorrection( - initial_residuals, - reference_weight_sum_); - if (std::isfinite(weighted_median)) { - proposals.push_back(std::clamp( - weighted_median, safe_minimum, safe_maximum)); - } - if (std::isfinite(robust_correction)) { - proposals.push_back(std::clamp( - robust_correction, safe_minimum, safe_maximum)); + std::sort(boundaries.begin(), boundaries.end()); + boundaries.erase(std::unique(boundaries.begin(), boundaries.end()), boundaries.end()); + proposals.insert(proposals.end(), boundaries.begin(), boundaries.end()); + for (size_t index = 0; index + 1 < boundaries.size(); ++index) { + proposals.push_back((boundaries[index] + boundaries[index + 1]) * 0.5f); } + std::sort(proposals.begin(), proposals.end()); + proposals.erase(std::unique(proposals.begin(), proposals.end()), proposals.end()); std::vector adjusted_lumas(kGridCellCount); std::optional selected; for (float exposure_ev : proposals) { - const float exposure_gain = std::exp2(exposure_ev); - for (int cell = 0; cell < kGridCellCount; ++cell) { - const float luma = display_linear_lumas[cell]; - if (!std::isfinite(luma) || luma < 0.0f) return std::nullopt; - adjusted_lumas[cell] = std::clamp(luma * exposure_gain, 0.0f, 1.0f); - } + for (int cell : eligible_cell_indices_) adjusted_lumas[cell] = response(cell, exposure_ev); MatchResult match; - if (!EvaluateGridLumas( - adjusted_lumas.data(), kGridCellCount, &match)) { + if (!EvaluateGridLumas(adjusted_lumas.data(), kGridCellCount, &match, &weights)) { return std::nullopt; } const Sample sample{exposure_ev, match}; - if (!selected.has_value() || IsBetter(sample, *selected)) { - selected = sample; - } - } - if (selected.has_value()) { - LogSelectedMatch( - "HDRNET_POST", selected->exposure_ev, selected->match); + if (!selected.has_value() || IsBetter(sample, *selected)) selected = sample; } + if (selected.has_value()) LogSelectedMatch("HDRNET_ROLLOFF", selected->exposure_ev, selected->match); return selected; } - bool ConfigureExposureBounds(float minimum_ev, float maximum_ev) { if (!std::isfinite(minimum_ev) || !std::isfinite(maximum_ev) || pending_exposure_ev_.has_value()) { @@ -704,9 +689,11 @@ private: bool EvaluateGridLumas( const float* candidate_grid_lumas, int candidate_count, - MatchResult* output) const { + MatchResult* output, + const std::vector* weights_override = nullptr) const { if (candidate_grid_lumas == nullptr || output == nullptr || - candidate_count != kGridCellCount) { + candidate_count != kGridCellCount || + (weights_override != nullptr && weights_override->size() != reference_cell_weights_.size())) { return false; } const int valid_count = static_cast(eligible_cell_indices_.size()); @@ -726,7 +713,8 @@ private: log2_ratios[index] = WeightedValue{}; continue; } - const float weight = reference_cell_weights_[index]; + const float weight = weights_override != nullptr + ? (*weights_override)[index] : reference_cell_weights_[index]; const float safe_candidate = std::max(candidate_luma, kDisplayLinearLumaFloor); const float candidate_ev = std::log2(safe_candidate); const float log2_ratio = std::clamp( @@ -1062,32 +1050,33 @@ Java_com_hinnka_mycamera_raw_RawLegacyAutoExposureNativeBridge_nativeSolveSingle JNIEnv* env, jobject, jlong handle, - jfloatArray candidate_display_linear_lumas, - jint columns, - jint rows, + jfloatArray candidate_display_linear_rgb, + jint width, + jint height, jfloat minimum_exposure_ev, jfloat maximum_exposure_ev) { ExposureSolver* solver = FromHandle(handle); - if (solver == nullptr || candidate_display_linear_lumas == nullptr || - columns != kGridColumns || rows != kGridRows || - env->GetArrayLength(candidate_display_linear_lumas) != kGridCellCount) { + const int64_t value_count = static_cast(width) * height * 3; + if (solver == nullptr || candidate_display_linear_rgb == nullptr || + width < kGridColumns || height < kGridRows || + value_count > std::numeric_limits::max() || + env->GetArrayLength(candidate_display_linear_rgb) != value_count) { return nullptr; } - jfloat* lumas = - env->GetFloatArrayElements(candidate_display_linear_lumas, nullptr); - if (lumas == nullptr) return nullptr; + jfloat* rgb = env->GetFloatArrayElements(candidate_display_linear_rgb, nullptr); + if (rgb == nullptr) return nullptr; std::optional result; try { result = solver->SolveSingleGridExposure( - lumas, - columns, - rows, + rgb, + width, + height, minimum_exposure_ev, maximum_exposure_ev); } catch (const std::bad_alloc&) { result.reset(); } - env->ReleaseFloatArrayElements(candidate_display_linear_lumas, lumas, JNI_ABORT); + env->ReleaseFloatArrayElements(candidate_display_linear_rgb, rgb, JNI_ABORT); if (!result.has_value()) return nullptr; const jfloat values[] = { result->exposure_ev, diff --git a/app/src/main/java/com/hinnka/mycamera/raw/DngHdrNetProfileGainTableNative.kt b/app/src/main/java/com/hinnka/mycamera/raw/DngHdrNetProfileGainTableNative.kt index 3a480da8..947868d2 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/DngHdrNetProfileGainTableNative.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/DngHdrNetProfileGainTableNative.kt @@ -53,6 +53,7 @@ internal object DngHdrNetProfileGainTableNative { acr3Curve = acr3Curve, dehazeCurve = dehazeCurve.toNativeArray(), postExposureGain = postExposureGain, + mapInputWeights = plan.mapInputWeights, outputGains = output, ) return output.takeIf { completed } @@ -63,6 +64,10 @@ internal object DngHdrNetProfileGainTableNative { val dehazeCurve: PhotonDehazeCurveParameters, /** Full 256 x 192 post-Dehaze/DHA p99 maximum RGB channel. */ val postDehazeP99Peak: Float, + /** Post-Dehaze/DHA RGB in clockwise-rotated, top-left row-major order. */ + val displayLinearRgb: FloatArray, + val sampleWidth: Int, + val sampleHeight: Int, ) fun evaluateDehazedDisplayLinearLumaGrid( @@ -79,9 +84,21 @@ internal object DngHdrNetProfileGainTableNative { outputGridWidth: Int, outputGridHeight: Int, ): Evaluation? { + val swapsAxes = when (outputRotation) { + 0, 180 -> false + 90, 270 -> true + else -> return null + } + val inputWidth = DngPhotonProfileGainTableGenerator.HDRNET_INPUT_WIDTH + val inputHeight = DngPhotonProfileGainTableGenerator.HDRNET_INPUT_HEIGHT + val sampleWidth = if (swapsAxes) inputHeight else inputWidth + val sampleHeight = if (swapsAxes) inputWidth else inputHeight val outputCount = outputGridWidth.toLong() * outputGridHeight - if (outputCount !in 1..Int.MAX_VALUE.toLong()) return null + if (outputGridWidth <= 0 || outputGridHeight <= 0 || + outputCount !in 1..Int.MAX_VALUE.toLong() + ) return null val output = FloatArray(outputCount.toInt()) + val outputRgb = FloatArray(sampleWidth * sampleHeight * 3) val curveValues = FloatArray(PhotonDehazeCurveParameters.NATIVE_VALUE_COUNT) val metrics = FloatArray(EVALUATION_METRIC_COUNT) val normalizedTuning = dehazeTuning.normalized() @@ -110,6 +127,7 @@ internal object DngHdrNetProfileGainTableNative { outputLumas = output, outputDehazeCurve = curveValues, outputMetrics = metrics, + outputRgb = outputRgb, ) if (!completed) return null val curve = PhotonDehazeCurveParameters.fromNativeArray(curveValues) ?: return null @@ -120,6 +138,9 @@ internal object DngHdrNetProfileGainTableNative { displayLinearLumas = output, dehazeCurve = curve, postDehazeP99Peak = postDehazeP99Peak, + displayLinearRgb = outputRgb, + sampleWidth = sampleWidth, + sampleHeight = sampleHeight, ) } @@ -148,6 +169,7 @@ internal object DngHdrNetProfileGainTableNative { outputLumas: FloatArray, outputDehazeCurve: FloatArray, outputMetrics: FloatArray, + outputRgb: FloatArray, ): Boolean private external fun nativeGenerateGains( @@ -176,6 +198,7 @@ internal object DngHdrNetProfileGainTableNative { acr3Curve: FloatArray, dehazeCurve: FloatArray, postExposureGain: Float, + mapInputWeights: FloatArray, outputGains: FloatArray, ): Boolean diff --git a/app/src/main/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableAlgorithm.kt b/app/src/main/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableAlgorithm.kt index 0ff9f9bd..809bb659 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableAlgorithm.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableAlgorithm.kt @@ -1648,16 +1648,14 @@ internal class DngPhotonProfileGainTableAlgorithm { outputRotation = input.outputRotation, dehazeTuning = dehazeTuning, ) ?: return null - val maximumPostExposureEv = hdrNetPostExposureLimitEv( - evaluation.postDehazeP99Peak, - ) val match = input.viewfinderReference ?.takeIf { HDRNET_VIEWFINDER_BRIGHTNESS_MATCH_ENABLED } ?.let { reference -> RawLegacyAutoExposureMatcher.solveHdrNetPostExposure( referenceFrame = reference, - displayLinearLumas = evaluation.displayLinearLumas, - maximumExposureEv = maximumPostExposureEv, + displayLinearRgb = evaluation.displayLinearRgb, + sampleWidth = evaluation.sampleWidth, + sampleHeight = evaluation.sampleHeight, ) } val restoredPostExposureEv = input.hdrNetPostExposureEv @@ -1665,7 +1663,7 @@ internal class DngPhotonProfileGainTableAlgorithm { ?.takeIf(Float::isFinite) ?.coerceIn( MeteringSystem.RAW_EXPOSURE_MIN_EV, - maximumPostExposureEv, + MeteringSystem.RAW_EXPOSURE_MAX_EV, ) val postExposureEv = match?.exposureEv ?: restoredPostExposureEv ?: 0f val postExposureSource = when { @@ -1680,7 +1678,6 @@ internal class DngPhotonProfileGainTableAlgorithm { "hdrRatio=${plan.hdrRatio} " + "postExposureEv=$postExposureEv " + "postExposureSource=$postExposureSource " + - "maximumPostExposureEv=$maximumPostExposureEv " + "matchRate=${match?.matchRate} " + "meanAbsoluteErrorEv=${match?.meanAbsoluteErrorEv} " + "postDehazeP99Peak=${evaluation.postDehazeP99Peak} " + @@ -3067,14 +3064,5 @@ internal class DngPhotonProfileGainTableAlgorithm { const val GLES31_MIN_SSBO_BYTES = 16L * 1024L * 1024L const val STREAMING_TILE_CORE_EDGE_PX = 3072 const val HDRNET_VIEWFINDER_BRIGHTNESS_MATCH_ENABLED = true - const val HDRNET_POST_EXPOSURE_P99_TARGET = 0.98f - } - - private fun hdrNetPostExposureLimitEv(postDehazeP99Peak: Float): Float { - if (!postDehazeP99Peak.isFinite() || postDehazeP99Peak <= 0f) { - return MeteringSystem.RAW_EXPOSURE_MAX_EV - } - val headroomEv = ln(HDRNET_POST_EXPOSURE_P99_TARGET / postDehazeP99Peak) / ln(2f) - return max(0f, headroomEv).coerceAtMost(MeteringSystem.RAW_EXPOSURE_MAX_EV) } } diff --git a/app/src/main/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableGenerator.kt b/app/src/main/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableGenerator.kt index 11d4c3b6..afe5d605 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableGenerator.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/DngPhotonProfileGainTableGenerator.kt @@ -171,8 +171,8 @@ internal object DngPhotonProfileGainTableGenerator { * coordinate uses MGC's learned 16-segment luma guide from guide_coeffs.pb before trilinear * sampling of the bilateral grid. The selected model input supplies each cell's local * chromaticity so the downstream arithmetic-RGB Dehaze curve is represented by the scalar - * table without reverting to a neutral-gray assumption. [postExposureEv] is applied after - * that composed target, so viewfinder matching cannot alter HDRNet inference or its tone shape. + * table without reverting to a neutral-gray assumption. [postExposureEv] controls the SLM + * rolloff/digital response after that composed target, independently of HDRNet inference. */ fun mapFromHdrNetCoefficients( plan: HdrNetProfileGainTablePlan, diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawDngProfilePreparation.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawDngProfilePreparation.kt index 11723ff6..e9af17a5 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawDngProfilePreparation.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawDngProfilePreparation.kt @@ -154,7 +154,7 @@ internal object RawPhotonHdrMetadata { private const val POST_EXPOSURE_CONTRACT_PROPERTY = "photonHdrNetPostExposureEvContract" private const val CURRENT_POST_EXPOSURE_CONTRACT = - "hdrnet_post_dehaze_viewfinder_v1" + "hdrnet_post_dehaze_viewfinder_rolloff_v2" fun read(properties: Map): Float? = properties[PROPERTY] ?.toFloatOrNull() diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawLegacyAutoExposureMatcher.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawLegacyAutoExposureMatcher.kt index 7ec3ab04..c073f15c 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawLegacyAutoExposureMatcher.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawLegacyAutoExposureMatcher.kt @@ -256,23 +256,20 @@ internal object RawLegacyAutoExposureMatcher { } /** - * Matches a fully composed HDRNet -> Dehaze/DHA grid with one downstream exposure only. - * HDRNet input exposure and HDR ratio remain fixed, so viewfinder matching cannot flatten the - * model or Dehaze/DHA tone shape. Native selection maximizes the weighted number of 8 x 6 - * cells within 0.1 EV, retaining the same spatial and portrait-priority weights as every - * other capture path. + * Matches the composed HDRNet -> Dehaze/DHA RGB through the downstream SLM gain response. + * HDRNet input exposure and HDR ratio remain fixed. Native selection maximizes the weighted + * number of 8 x 6 cells within 0.1 EV, retaining the spatial and portrait-priority weights + * with a modest shadow preference. Positive gain splits into rolloff and digital gain. */ fun solveHdrNetPostExposure( referenceFrame: RawLegacyExposurePreviewFrame, - displayLinearLumas: FloatArray, - maximumExposureEv: Float, + displayLinearRgb: FloatArray, + sampleWidth: Int, + sampleHeight: Int, ): HdrNetPostExposureMatch? { - if (displayLinearLumas.size != - DngPhotonProfileGainTableGenerator.HDRNET_MATCH_GRID_WIDTH * - DngPhotonProfileGainTableGenerator.HDRNET_MATCH_GRID_HEIGHT || - displayLinearLumas.any { !it.isFinite() || it < 0f } || - !maximumExposureEv.isFinite() || - maximumExposureEv < MeteringSystem.RAW_EXPOSURE_MIN_EV + if (sampleWidth <= 0 || sampleHeight <= 0 || + displayLinearRgb.size.toLong() != sampleWidth.toLong() * sampleHeight * 3 || + displayLinearRgb.any { !it.isFinite() || it < 0f } ) return null val solver = RawLegacyAutoExposureNativeBridge.Solver.create(referenceFrame) ?: run { @@ -281,14 +278,11 @@ internal object RawLegacyAutoExposureMatcher { } return solver.use { solver.solveSingleGridExposure( - displayLinearLumas = displayLinearLumas, - columns = DngPhotonProfileGainTableGenerator.HDRNET_MATCH_GRID_WIDTH, - rows = DngPhotonProfileGainTableGenerator.HDRNET_MATCH_GRID_HEIGHT, + displayLinearRgb = displayLinearRgb, + width = sampleWidth, + height = sampleHeight, minimumExposureEv = MeteringSystem.RAW_EXPOSURE_MIN_EV, - maximumExposureEv = minOf( - maximumExposureEv, - MeteringSystem.RAW_EXPOSURE_MAX_EV, - ), + maximumExposureEv = MeteringSystem.RAW_EXPOSURE_MAX_EV, )?.let { result -> PLog.i( TAG, diff --git a/app/src/main/java/com/hinnka/mycamera/raw/RawLegacyAutoExposureNativeBridge.kt b/app/src/main/java/com/hinnka/mycamera/raw/RawLegacyAutoExposureNativeBridge.kt index fcca4cbe..d064569a 100644 --- a/app/src/main/java/com/hinnka/mycamera/raw/RawLegacyAutoExposureNativeBridge.kt +++ b/app/src/main/java/com/hinnka/mycamera/raw/RawLegacyAutoExposureNativeBridge.kt @@ -51,14 +51,15 @@ internal object RawLegacyAutoExposureNativeBridge { } fun solveSingleGridExposure( - displayLinearLumas: FloatArray, - columns: Int, - rows: Int, + displayLinearRgb: FloatArray, + width: Int, + height: Int, minimumExposureEv: Float, maximumExposureEv: Float, ): SingleExposureResult? { check(handle != 0L) { "Native exposure solver is closed" } - if (columns <= 0 || rows <= 0 || displayLinearLumas.size != columns * rows || + if (width <= 0 || height <= 0 || + displayLinearRgb.size.toLong() != width.toLong() * height * 3 || !minimumExposureEv.isFinite() || !maximumExposureEv.isFinite() || minimumExposureEv > maximumExposureEv ) { @@ -66,9 +67,9 @@ internal object RawLegacyAutoExposureNativeBridge { } val values = nativeSolveSingleGridExposure( handle = handle, - candidateDisplayLinearLumas = displayLinearLumas, - columns = columns, - rows = rows, + candidateDisplayLinearRgb = displayLinearRgb, + width = width, + height = height, minimumExposureEv = minimumExposureEv, maximumExposureEv = maximumExposureEv, ) @@ -141,9 +142,9 @@ internal object RawLegacyAutoExposureNativeBridge { private external fun nativeSolveSingleGridExposure( handle: Long, - candidateDisplayLinearLumas: FloatArray, - columns: Int, - rows: Int, + candidateDisplayLinearRgb: FloatArray, + width: Int, + height: Int, minimumExposureEv: Float, maximumExposureEv: Float, ): FloatArray? diff --git a/app/src/test/java/com/hinnka/mycamera/raw/DngHdrNetViewfinderGridTest.kt b/app/src/test/java/com/hinnka/mycamera/raw/DngHdrNetViewfinderGridTest.kt index 0c72c0d7..03fb14eb 100644 --- a/app/src/test/java/com/hinnka/mycamera/raw/DngHdrNetViewfinderGridTest.kt +++ b/app/src/test/java/com/hinnka/mycamera/raw/DngHdrNetViewfinderGridTest.kt @@ -3,6 +3,7 @@ package com.hinnka.mycamera.raw import com.hinnka.mycamera.processor.PhotonDehazeTuning import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull import org.junit.Assume.assumeNoException import org.junit.Test @@ -51,7 +52,7 @@ class DngHdrNetViewfinderGridTest { outputRotation = 270, dehazeTuning = PhotonDehazeTuning.DISABLED, ) - } catch (error: UnsatisfiedLinkError) { + } catch (error: LinkageError) { assumeNoException("Android HDRNet JNI is unavailable on this host", error) return } @@ -67,6 +68,26 @@ class DngHdrNetViewfinderGridTest { ) neutralGrid.forEach { assertEquals(0.249999f, it, 2e-6f) } assertArrayEquals(neutralGrid, brightBaselineGrid, 2e-6f) + assertEquals( + DngPhotonProfileGainTableGenerator.HDRNET_INPUT_WIDTH, + neutralEvaluation.sampleWidth, + ) + assertEquals( + DngPhotonProfileGainTableGenerator.HDRNET_INPUT_HEIGHT, + neutralEvaluation.sampleHeight, + ) + assertEquals(neutralEvaluation.sampleWidth, brightBaselineEvaluation.sampleHeight) + assertEquals(neutralEvaluation.sampleHeight, brightBaselineEvaluation.sampleWidth) + assertEquals( + neutralEvaluation.sampleWidth * neutralEvaluation.sampleHeight * 3, + neutralEvaluation.displayLinearRgb.size, + ) + neutralEvaluation.displayLinearRgb.forEach { assertEquals(0.249999f, it, 2e-6f) } + assertArrayEquals( + neutralEvaluation.displayLinearRgb, + brightBaselineEvaluation.displayLinearRgb, + 2e-6f, + ) assertEquals(0.249999f, neutralEvaluation.postDehazeP99Peak, 2e-6f) assertEquals( neutralEvaluation.postDehazeP99Peak, @@ -74,4 +95,99 @@ class DngHdrNetViewfinderGridTest { 2e-6f, ) } + + @Test + fun displayLinearRgbKeepsTopLeftRowOrderAcrossClockwiseRotations() { + val width = DngPhotonProfileGainTableGenerator.HDRNET_INPUT_WIDTH + val height = DngPhotonProfileGainTableGenerator.HDRNET_INPUT_HEIGHT + val modelInput = FloatArray(width * height * 4) + for (y in 0 until height) { + for (x in 0 until width) { + val offset = (y * width + x) * 4 + modelInput[offset] = 0.1f + 0.4f * x / (width - 1) + modelInput[offset + 1] = 0.15f + 0.3f * y / (height - 1) + modelInput[offset + 2] = 0.2f + 0.05f * ((x + y) % 7) + modelInput[offset + 3] = 1f + } + } + val coefficients = FloatArray(DngPhotonProfileGainTableGenerator.HDRNET_OUTPUT_FLOAT_COUNT) + val plan = checkNotNull( + DngPhotonProfileGainTableGenerator.hdrNetPlan( + rendererBaselineExposureEv = 0f, + hdrRatio = 2f, + sourceToShortGain = 1f, + ), + ) + val rotations = listOf(0, 90, 180, 270) + val evaluations = try { + rotations.map { rotation -> + checkNotNull( + DngPhotonProfileGainTableGenerator.evaluateHdrNetDehaze( + plan = plan, + coefficients = coefficients, + modelInput = modelInput, + outputRotation = rotation, + dehazeTuning = PhotonDehazeTuning.DISABLED, + ), + ) + } + } catch (error: LinkageError) { + assumeNoException("Android HDRNet JNI is unavailable on this host", error) + return + } + val sourceRgb = evaluations.first().displayLinearRgb + for ((index, rotation) in rotations.withIndex()) { + val evaluation = evaluations[index] + val swapsAxes = rotation == 90 || rotation == 270 + val orientedWidth = if (swapsAxes) height else width + val orientedHeight = if (swapsAxes) width else height + assertEquals(orientedWidth, evaluation.sampleWidth) + assertEquals(orientedHeight, evaluation.sampleHeight) + val expectedRgb = FloatArray(orientedWidth * orientedHeight * 3) + for (y in 0 until orientedHeight) { + for (x in 0 until orientedWidth) { + val (sourceX, sourceY) = when (rotation) { + 90 -> y to height - 1 - x + 180 -> width - 1 - x to height - 1 - y + 270 -> width - 1 - y to x + else -> x to y + } + val sourceOffset = (sourceY * width + sourceX) * 3 + val outputOffset = (y * orientedWidth + x) * 3 + for (channel in 0 until 3) { + expectedRgb[outputOffset + channel] = sourceRgb[sourceOffset + channel] + } + } + } + assertArrayEquals( + "Clockwise rotation $rotation", + expectedRgb, + evaluation.displayLinearRgb, + 2e-6f, + ) + } + } + + @Test + fun postExposureMetadataRestoresOnlyTheRolloffContract() { + val legacyProperties = mapOf( + "photonHdrNetPostExposureEv" to "1.25", + "photonHdrNetPostExposureEvContract" to "hdrnet_post_dehaze_viewfinder_v1", + ) + assertNull(RawPhotonHdrMetadata.readPostExposureEv(legacyProperties)) + + val properties = RawPhotonHdrMetadata.write( + properties = legacyProperties, + hdrRatio = 2f, + finalShortGain = 0.5f, + postExposureEv = 1.25f, + ) + assertEquals( + "hdrnet_post_dehaze_viewfinder_rolloff_v2", + properties["photonHdrNetPostExposureEvContract"], + ) + assertEquals(1.25f, checkNotNull(RawPhotonHdrMetadata.readPostExposureEv(properties)), 0f) + assertEquals(2f, checkNotNull(RawPhotonHdrMetadata.read(properties)), 0f) + assertEquals(0.5f, checkNotNull(RawPhotonHdrMetadata.readFinalShortGain(properties)), 0f) + } } diff --git a/docs/photon-core-imaging-tuning.md b/docs/photon-core-imaging-tuning.md index 7bd772f8..11bda8a0 100644 --- a/docs/photon-core-imaging-tuning.md +++ b/docs/photon-core-imaging-tuning.md @@ -76,10 +76,11 @@ GPU 强度。锐化不读取 SNR,不触发 RAW 像素统计或 GPU→CPU 回 - `0` 保持白点比例 `1`。 - `1` 完整采用高光直方图估算的比例;中间值在线性比例域插值。 -处理顺序为:固定 final-short 线性工作 RGB → 一次 HDRNet → Dehaze/DHA → 单一取景器匹配曝光 +处理顺序为:固定 final-short 线性工作 RGB → 一次 HDRNet → Dehaze/DHA → 取景器匹配与 SLM rolloff → PGTM 烘焙 → DCP 色彩映射与 profile tone → 最终锐化。完整 256×192 HDRNet 输出只建立一次 -两组 12-bit 直方图;合成结果按每格全部像素统计为 8×6,匹配只产生 HDRNet 下游曝光,不修改 -short gain 或 HDR ratio。最终渲染只应用烘焙后的 PGTM,不存在独立 Dehaze pass,也不会逐 tile +两组 12-bit 直方图;匹配沿用 8×6 网格权重,可靠暗部最多增加 25% 权重。候选先对每个像素 +执行 rolloff/digital gain,再统计每格亮度;不施加 P99 匹配限制,不修改 short gain 或 HDR +ratio。最终渲染只应用烘焙后的 PGTM,不存在独立 Dehaze pass,也不会逐 tile 重新统计曲线。Classic 与 Local Laplacian 路径不消费这些参数。 ## 生命周期与持久化 diff --git a/docs/photon-dehaze-pipeline.md b/docs/photon-dehaze-pipeline.md index dc59977e..d91ea317 100644 --- a/docs/photon-dehaze-pipeline.md +++ b/docs/photon-dehaze-pipeline.md @@ -14,16 +14,52 @@ final-short linear working RGB -> HDRNet output (256 x 192) -> whole-image Dehaze + DHA histogram and curve -> composed HDRNet + Dehaze/DHA output - -> full-coverage 8 x 6 viewfinder matching for one downstream exposure - -> bake the fixed HDRNet grid, Dehaze/DHA curve and downstream exposure into PGTM + -> full-coverage 8 x 6 viewfinder matching with modest shadow preference + -> downstream SLM rolloff / digital gain + -> bake the fixed HDRNet grid, Dehaze/DHA curve and gain response into PGTM -> DCP HueSatMap / profile exposure / LookTable / tone / output ``` Dehaze 不进入 HDRNet 模型输入。HDR ratio 与 short gain 由拍摄阶段确定,取景器匹配不得修改 这两个量,否则会把 HDRNet 与 Dehaze/DHA 形成的动态范围和反差当作曝光误差抵消。Dehaze 的 统计源是唯一一次推理后的完整 256×192 HDRNet 输出;8×6 网格的每格覆盖对应区域的全部像素, -只用于求一个 HDRNet 下游曝光,不用于估算 Dehaze 曲线。后处理结果的全图 P99 最大通道限制 -正向曝光,避免匹配增益破坏高光余量。 +只用于求一个 HDRNet 下游增益参数,不用于估算 Dehaze 曲线。后处理结果的全图 P99 最大通道 +只用于诊断,不再限制正向匹配或重生成时恢复的参数。通用匹配范围仍为 `-4..4 EV`。 + +## 取景器权重与 rolloff + +目标仍是拍摄时对齐后的取景器图。保留现有参考可靠性、8×6 空间权重、人像优先和 ±0.1 EV +匹配评分;HDRNet 路径只在原权重上叠加 `1 + 0.25*(1-smoothstep(0.02, 0.25, referenceLuma))`。 +亮度为取景器 sRGB 解码后的线性 Rec.709 luma,可靠暗部最多增加 25% 权重;原有近黑和 +饱和参考排除规则继续生效。Classic/Local Laplacian 的权重不变。 + +匹配输出 `g=2^postExposureEv`,按照 MGC V25 SLM 的 further-gain split 处理: + +```text +g <= 1: rolloff = 1, digital = g +1 < g < 1.25: rolloff = g, digital = 1 +g >= 1.25: + t = clamp(2*(g-1.25), 0, 1) + rolloff = 1.25 + 0.5*(t-0.5*t*t) + digital = g / rolloff +``` + +逐像素取 Dehaze/DHA 后的 `m=max(RGB)`,使用共享增益: + +```text +G = 1 + (rolloff-1)*(1-m)^2 +gain = digital // rolloff*digital < 1 +gain = (1e-7 + m*digital*G) / (m+1e-7) // 其余情况 +outputRGB = clamp(RGB * gain, 0, 1) +``` + +亮部的 rolloff 增益自然减弱,rolloff 最大为 1.5,剩余增益由 digital 承担;不再用 P99 +硬裁剪匹配 EV。这里只使用 SLM 的增益拆分和 rolloff,保留单路 HDRNet 图像与取景器目标。 + +求解器接收完整的旋转对齐 RGB,每个候选先逐像素执行上述响应及通道截断,再计算每格平均 +Rec.709 亮度。不能先平均亮度再做 rolloff:同格内亮暗/彩色混合的结果会不同。求解器反解 +各格 ±0.1 EV 匹配区间边界,沿用加权匹配率、平均 EV 误差及 robust loss 的选择顺序。 +HDRNet 和 Dehaze 只计算一次。 ## 曲线契约 @@ -36,8 +72,11 @@ HDRNet 输出先转换到原版 12-bit 统计域: - 最终曲线由低端二次段和高端线性段组成,数值和斜率连续。 合成时,曲线按 `(R+G+B)/3` 求共享 gain 并同时乘到三个通道。PGTM 是标量表,生成时使用 -固定的模型输入,从每个 64×48 空间 cell 保留局部色度与 HDRNet luma 的比例,再把相同的 -arithmetic-RGB 曲线及单一匹配曝光合成到 257 点强度轴并反解 ACR3 输入。运行期只查一次 +固定的模型输入,从每个 64×48 空间 cell 保留局部色度与 PXL N 强度的比例,在 257 点强度轴 +上重建 RGB,再单独计算 Rec.601 HDRNet guide。PXL N 包含 min/max 通道权重,不能直接当作 +HDRNet luma,否则彩色区域的 rolloff 强度会偏移。随后执行相同的 Dehaze/DHA 和 RGB rolloff, +取结果亮度并反解 ACR3 输入。黑色或负噪声使源 luma 不可由正标量增益表达时,该 cell 的表 +曲线定义在中性灰轴上。PGTM 的空间/强度采样与标量格式仍有限制。运行期只查一次 PGTM,不会再次执行 HDRNet、Dehaze 或 DHA。 ## 控制与持久化 @@ -50,11 +89,15 @@ PGTM,不会再次执行 HDRNet、Dehaze 或 DHA。 默认启用,强度均为 `1`。参数只在 HDRNet PGTM 生成或重新生成时消费;Classic 与 Local Laplacian 路径不执行 Dehaze/DHA。拍摄时得到的 HDRNet 下游匹配曝光独立保存,重新生成 PGTM -时恢复并按新的 P99 高光余量重新约束;不会折回 short gain、HDR ratio 或 BaselineExposure。 +时恢复并使用相同 rolloff,仅按通用 EV 范围约束;不会折回 short gain、HDR ratio 或 +BaselineExposure。持久化契约为 `hdrnet_post_dehaze_viewfinder_rolloff_v2`;旧的线性增益 +`hdrnet_post_dehaze_viewfinder_v1` 参数不作为新响应的匹配结果恢复。没有兼容匹配值且没有 +取景器时使用 0 EV。 已有 DNG 的 PGTM 不在最终渲染时叠加独立去雾。 ## 匹配日志 `PLog_RawExposureMatch` 输出 Classic/Local Laplacian 的候选结果,以及 HDRNet 单曝光最终匹配率、 平均 EV 误差和校正量。`DngPhotonProfileGainTableAlgorithm` 另外输出固定的 short/ratio、匹配 -曝光及上限、P99 peak、haze point、DHA scale 与全图统计样本数。 +参数、诊断用 P99 peak、haze point、DHA scale 与全图统计样本数。native PGTM 的 +`POST_EXPOSURE` 日志同时记录总 gain、rolloffGain 与 digitalGain。 diff --git a/tools/dng_hdrnet_dehaze_test.cpp b/tools/dng_hdrnet_dehaze_test.cpp index 4733deeb..63f3b8ab 100644 --- a/tools/dng_hdrnet_dehaze_test.cpp +++ b/tools/dng_hdrnet_dehaze_test.cpp @@ -73,17 +73,46 @@ void TestHdrNetOutputFeedsWholeImageDehaze() { 0.25f * render_gain, }; const RgbSample composed = ApplyDehaze(hdr_rgb, curve); - const float baked_target = DehazedHdrNetTargetLuma( - 0.25f, render_gain, RgbSample{0.25f, 0.25f, 0.25f}, 0.25f, curve); + const float baked_target = PostExposedHdrNetTargetLuma( + RgbSample{0.25f, 0.25f, 0.25f}, render_gain, curve, + photon::hdrnet_post_exposure::SplitGain(1.0f)); assert(curve.sampled_pixel_count == input_width * input_height); assert(std::abs( composed.red - MappedDehazeLuminance(hdr_rgb.red, curve)) < 1.0e-6f); assert(std::abs(composed.red - baked_target) < 1.0e-6f); assert(composed.red > 0.25f); constexpr float post_exposure_gain = 1.25f; - const float exposed_target = std::clamp( - baked_target * post_exposure_gain, 0.0f, 1.0f); - assert(std::abs(exposed_target - composed.red * post_exposure_gain) < 1.0e-6f); + const auto gains = photon::hdrnet_post_exposure::SplitGain(post_exposure_gain); + const float exposed_target = PostExposedHdrNetTargetLuma( + RgbSample{0.25f, 0.25f, 0.25f}, render_gain, curve, gains); + const auto expected = photon::hdrnet_post_exposure::Apply(composed, gains); + assert(std::abs(exposed_target - expected.red) < 1.0e-6f); + assert(exposed_target < composed.red * post_exposure_gain); +} + +void TestColoredPgtmCoordinateAndRolloffAgreeWithEvaluation() { + const float weights[] = {0.1495f, 0.2935f, 0.057f, 0.125f, 0.375f}; + const RgbSample source{0.3f, 0.05f, 0.05f}; + const float coordinate = TableIntensity(source, weights); + assert(std::abs(coordinate - 0.181125f) < 1.0e-7f); + assert(std::abs(HdrNetLuma(source) - 0.12470703125f) < 1.0e-7f); + const auto reconstructed = RgbForTableCoordinate(coordinate, source, coordinate, 1.0f); + assert(std::abs(reconstructed.red - source.red) < 1.0e-7f); + assert(std::abs(reconstructed.green - source.green) < 1.0e-7f); + const DehazeCurve identity; + const auto gains = photon::hdrnet_post_exposure::SplitGain(1.5f); + const auto expected = photon::hdrnet_post_exposure::Apply(source, gains); + const float baked = PostExposedHdrNetTargetLuma(reconstructed, 1.0f, identity, gains); + assert(std::abs(baked - HdrNetLuma(expected)) < 1.0e-7f); + // Applying the shared gain to a colored pixel depends on peak RGB, not PXL N or Rec.601 Y. + const auto gray = photon::hdrnet_post_exposure::Apply( + {HdrNetLuma(source), HdrNetLuma(source), HdrNetLuma(source)}, gains); + assert(gray.red > baked); + + const RgbSample signed_noise{0.1f, -0.05f, -0.05f}; + const auto neutral = RgbForTableCoordinate( + 0.2f, signed_noise, TableIntensity(signed_noise, weights), 1.0f); + assert(neutral.red == 0.2f && neutral.green == 0.2f && neutral.blue == 0.2f); } } // namespace @@ -91,6 +120,7 @@ void TestHdrNetOutputFeedsWholeImageDehaze() { int main() { TestDisabledCurveIsIdentity(); TestHdrNetOutputFeedsWholeImageDehaze(); + TestColoredPgtmCoordinateAndRolloffAgreeWithEvaluation(); std::cout << "HDRNet Dehaze/DHA composition tests passed\n"; return 0; } diff --git a/tools/raw_hdrnet_post_exposure_solver_test.cpp b/tools/raw_hdrnet_post_exposure_solver_test.cpp index eeada8b2..c6d84ac0 100644 --- a/tools/raw_hdrnet_post_exposure_solver_test.cpp +++ b/tools/raw_hdrnet_post_exposure_solver_test.cpp @@ -1,56 +1,72 @@ +#include #include #include #include #include #include -// Include the production implementation so this host test exercises the exact 8 x 6 weighting, -// portrait priority, +/-0.1 EV match intervals, and one-pass exposure selection. +// Exercise production 8 x 6 spatial/portrait scoring and the per-pixel SLM response. #include "../app/src/main/cpp/raw_legacy_auto_exposure_solver.cpp" namespace { +namespace post = photon::hdrnet_post_exposure; constexpr int kReferenceCode = 128; jint GrayPixel(int code) { const uint32_t channel = static_cast(code & 0xff); - return static_cast( - 0xff000000U | (channel << 16U) | (channel << 8U) | channel); + return static_cast(0xff000000U | (channel << 16U) | (channel << 8U) | channel); } -float ReferenceLuma() { - return *DisplayLinearLuma(GrayPixel(kReferenceCode)); +float ReferenceLuma() { return *DisplayLinearLuma(GrayPixel(kReferenceCode)); } + +std::unique_ptr CreateSolver(const std::vector* portrait_weights = nullptr) { + const std::vector pixels(kGridCellCount, GrayPixel(kReferenceCode)); + return ExposureSolver::Create(pixels.data(), + portrait_weights != nullptr ? portrait_weights->data() : nullptr, kGridColumns, kGridRows); } -std::unique_ptr CreateSolver( - const std::vector* portrait_weights = nullptr) { - std::vector pixels(kGridCellCount, GrayPixel(kReferenceCode)); - return ExposureSolver::Create( - pixels.data(), - portrait_weights != nullptr ? portrait_weights->data() : nullptr, - kGridColumns, - kGridRows); +post::Rgb RgbAt(const std::vector& pixels, int index) { + return {pixels[index * 3], pixels[index * 3 + 1], pixels[index * 3 + 2]}; } -void TestUniformGridResolvesExactExposure() { +float ResponseLuma(const post::Rgb& rgb, float exposure_ev) { + return post::DisplayLuma(post::Apply(rgb, post::SplitGain(std::exp2(exposure_ev)))); +} + +float ErrorEv(float actual, float reference) { return std::abs(std::log2(actual / reference)); } + +jint EncodeDisplayRgb(const post::Rgb& rgb) { + const auto encode = [](float linear) { + const float srgb = linear <= 0.0031308f ? 12.92f * linear + : 1.055f * std::pow(linear, 1.0f / 2.4f) - 0.055f; + return static_cast(std::lround(std::clamp(srgb, 0.0f, 1.0f) * 255.0f)); + }; + return static_cast(0xff000000U | (encode(rgb.red) << 16U) | + (encode(rgb.green) << 8U) | encode(rgb.blue)); +} + +void TestUniformGridMatchesThroughRolloffResponse() { auto solver = CreateSolver(); assert(solver != nullptr); - std::vector candidate(kGridCellCount, ReferenceLuma() * 0.5f); + const std::vector candidate(kGridCellCount * 3, ReferenceLuma() * 0.5f); const auto result = solver->SolveSingleGridExposure( candidate.data(), kGridColumns, kGridRows, -4.0f, 4.0f); assert(result.has_value()); - assert(std::abs(result->exposure_ev - 1.0f) < 1.0e-4f); + // The rolloff reduces gain above black, so halving the input now needs more than +1 EV. + assert(result->exposure_ev > 1.05f); + assert(ErrorEv(ResponseLuma(RgbAt(candidate, 0), result->exposure_ev), ReferenceLuma()) < 1.0e-4f); assert(std::abs(result->match.match_rate - 1.0f) < 1.0e-6f); } void TestPortraitPriorityOutweighsBackground() { std::vector portrait_weights(kGridCellCount, 0.0f); - std::vector candidate(kGridCellCount, ReferenceLuma() * 2.0f); + std::vector candidate(kGridCellCount * 3, ReferenceLuma() * 2.0f); for (int y = 2; y <= 3; ++y) { for (int x = 2; x <= 5; ++x) { const int cell = y * kGridColumns + x; portrait_weights[cell] = 1.0f; - candidate[cell] = ReferenceLuma() * 0.5f; + for (int channel = 0; channel < 3; ++channel) candidate[cell * 3 + channel] = ReferenceLuma() * 0.5f; } } auto solver = CreateSolver(&portrait_weights); @@ -58,26 +74,152 @@ void TestPortraitPriorityOutweighsBackground() { const auto result = solver->SolveSingleGridExposure( candidate.data(), kGridColumns, kGridRows, -4.0f, 4.0f); assert(result.has_value()); - assert(std::abs(result->exposure_ev - 1.0f) < 1.0e-4f); + assert(result->exposure_ev > 0.0f); + assert(ErrorEv(ResponseLuma(RgbAt(candidate, 2 * kGridColumns + 2), result->exposure_ev), + ReferenceLuma()) < 1.0e-4f); assert(result->match.match_rate > 0.70f); } -void TestHighlightHeadroomBoundsPositiveMatch() { +void TestGenericExposureBoundsRemainEffective() { auto solver = CreateSolver(); assert(solver != nullptr); - std::vector candidate(kGridCellCount, ReferenceLuma() * 0.5f); + const std::vector dark(kGridCellCount * 3, ReferenceLuma() * 0.5f); + const auto limited = solver->SolveSingleGridExposure(dark.data(), kGridColumns, kGridRows, -4.0f, 0.25f); + assert(limited.has_value() && std::abs(limited->exposure_ev - 0.25f) < 1.0e-6f); + const std::vector bright(kGridCellCount * 3, ReferenceLuma() * 2.0f); + const auto negative = solver->SolveSingleGridExposure(bright.data(), kGridColumns, kGridRows, -0.25f, 4.0f); + assert(negative.has_value() && std::abs(negative->exposure_ev + 0.25f) < 1.0e-6f); + const std::vector very_dark(kGridCellCount * 3, ReferenceLuma() / 64.0f); + const auto global = solver->SolveSingleGridExposure(very_dark.data(), kGridColumns, kGridRows, -20.0f, 20.0f); + assert(global.has_value() && std::abs(global->exposure_ev - 4.0f) < 1.0e-6f); +} + +void TestWhitePixelsDoNotCapPositiveMatchingAtZero() { + auto solver = CreateSolver(); + assert(solver != nullptr); + std::vector candidate(kGridCellCount * 3, ReferenceLuma() * 0.5f); + // More than 1% of the image is white, which used to force the p99 exposure cap to zero. + for (int channel = 0; channel < 3; ++channel) candidate[channel] = 1.0f; const auto result = solver->SolveSingleGridExposure( - candidate.data(), kGridColumns, kGridRows, -4.0f, 0.25f); + candidate.data(), kGridColumns, kGridRows, -4.0f, 4.0f); + assert(result.has_value() && result->exposure_ev > 1.0f); + assert(result->match.match_rate > 0.95f); + assert(ErrorEv(ResponseLuma(RgbAt(candidate, 1), result->exposure_ev), ReferenceLuma()) < 1.0e-4f); + assert(ResponseLuma(RgbAt(candidate, 0), result->exposure_ev) > 0.9999f); +} + +void TestShadowPreferenceIsModestAndKeepsReliability() { + assert(std::abs(HdrNetShadowPriority(0.02f) - 1.25f) < 1.0e-6f); + assert(std::abs(HdrNetShadowPriority(0.135f) - 1.125f) < 1.0e-6f); + assert(std::abs(HdrNetShadowPriority(0.25f) - 1.0f) < 1.0e-6f); + float previous = 1.25f; + for (int index = 0; index <= 1000; ++index) { + const float priority = HdrNetShadowPriority(index / 1000.0f); + assert(priority >= 1.0f && priority <= 1.25f && priority <= previous); + previous = priority; + } + assert(ReferenceReliabilityWeight(0.0f) * HdrNetShadowPriority(0.0f) == 0.0f); + const std::vector black(kGridCellCount, GrayPixel(0)); + assert(ExposureSolver::Create(black.data(), nullptr, kGridColumns, kGridRows) == nullptr); + + // Left and right halves have exactly equal spatial weight; the shadow preference breaks + // the competing +/-EV match without allowing dark cells to dominate by more than 25%. + std::vector reference(kGridCellCount); + std::vector candidate(kGridCellCount * 3); + for (int cell = 0; cell < kGridCellCount; ++cell) { + const bool shadow = cell % kGridColumns < kGridColumns / 2; + reference[cell] = GrayPixel(shadow ? 64 : 180); + const float value = *DisplayLinearLuma(reference[cell]) * (shadow ? 0.5f : 2.0f); + for (int channel = 0; channel < 3; ++channel) candidate[cell * 3 + channel] = value; + } + auto solver = ExposureSolver::Create(reference.data(), nullptr, kGridColumns, kGridRows); + assert(solver != nullptr); + const auto result = solver->SolveSingleGridExposure( + candidate.data(), kGridColumns, kGridRows, -4.0f, 4.0f); + assert(result.has_value() && result->exposure_ev > 0.0f); + assert(result->match.match_rate > 0.50f && result->match.match_rate <= 1.25f / 2.25f + 1.0e-6f); + assert(ErrorEv(ResponseLuma(RgbAt(candidate, 0), result->exposure_ev), + *DisplayLinearLuma(reference[0])) <= 0.10001f); +} + +void TestPerPixelResponseBeforeCellMean(const std::array& pattern, float known_gain) { + constexpr int width = kGridColumns * 4; + constexpr int height = kGridRows; + const auto known_gains = post::SplitGain(known_gain); + std::vector candidate(width * height * 3); + std::vector reference(width * height); + for (int y = 0; y < height; ++y) { + for (int x = 0; x < width; ++x) { + const auto rgb = pattern[x % pattern.size()]; + const int pixel = y * width + x; + candidate[pixel * 3] = rgb.red; + candidate[pixel * 3 + 1] = rgb.green; + candidate[pixel * 3 + 2] = rgb.blue; + reference[pixel] = EncodeDisplayRgb(post::Apply(rgb, known_gains)); + } + } + auto solver = ExposureSolver::Create(reference.data(), nullptr, width, height); + assert(solver != nullptr); + const auto result = solver->SolveSingleGridExposure(candidate.data(), width, height, -4.0f, 4.0f); assert(result.has_value()); - assert(std::abs(result->exposure_ev - 0.25f) < 1.0e-6f); + assert(std::abs(result->exposure_ev - std::log2(known_gain)) < 0.02f); + assert(std::abs(result->match.match_rate - 1.0f) < 1.0e-6f); + + float reference_mean = 0.0f, processed_mean = 0.0f; + post::Rgb rgb_mean{}; + bool clips_channel = false; + for (size_t index = 0; index < pattern.size(); ++index) { + const auto rgb = pattern[index]; + reference_mean += *DisplayLinearLuma(reference[index]) / pattern.size(); + processed_mean += ResponseLuma(rgb, result->exposure_ev) / pattern.size(); + rgb_mean.red += rgb.red / pattern.size(); + rgb_mean.green += rgb.green / pattern.size(); + rgb_mean.blue += rgb.blue / pattern.size(); + const auto mapped = post::Apply(rgb, known_gains); + clips_channel |= std::max({mapped.red, mapped.green, mapped.blue}) == 1.0f; + } + assert(clips_channel); + assert(ErrorEv(processed_mean, reference_mean) < 1.0e-4f); + // Guard against replacing the nonlinear pixel response by either a mean RGB or mean luma. + assert(ErrorEv(ResponseLuma(rgb_mean, result->exposure_ev), reference_mean) > 0.1f); + const float luma_mean = post::DisplayLuma(rgb_mean); + assert(ErrorEv(ResponseLuma({luma_mean, luma_mean, luma_mean}, result->exposure_ev), reference_mean) > 0.1f); +} + +void TestMgcRolloffOracles() { + assert(std::abs(post::SplitGain(1.5f).rolloff - 1.4375f) < 1.0e-7f); + assert(std::abs(post::SplitGain(1.5f).digital - 1.5f / 1.4375f) < 1.0e-7f); + assert(std::abs(post::SplitGain(3.0f).rolloff - 1.5f) < 1.0e-7f); + assert(std::abs(post::SplitGain(3.0f).digital - 2.0f) < 1.0e-7f); + // ARM64 MGC V25 ApplySlm 0x471a0e4, identical LTM0/LTM1 and zero short input: + // this isolates its post-interpolation gain stage. Allow only one 12-bit quantization step. + const auto check = [](const std::array& input, post::Gains gains, + const std::array& expected) { + const auto output = post::Apply({input[0] / 4095.0f, input[1] / 4095.0f, input[2] / 4095.0f}, gains); + const std::array actual{output.red, output.green, output.blue}; + for (int channel = 0; channel < 3; ++channel) { + assert(std::abs(std::lround(actual[channel] * 4095.0f) - expected[channel]) <= 1); + } + }; + check({1000, 2000, 3000}, {1.5f, 1.0f}, {1036, 2071, 3107}); + check({1000, 2000, 3000}, {1.5f, 2.0f}, {2071, 4095, 4095}); + check({1000, 2000, 3000}, {1.5f, 0.5f}, {500, 1000, 1500}); + check({1, 4, 16}, {1.5f, 1.0f}, {1, 6, 24}); } } // namespace int main() { - TestUniformGridResolvesExactExposure(); + TestUniformGridMatchesThroughRolloffResponse(); TestPortraitPriorityOutweighsBackground(); - TestHighlightHeadroomBoundsPositiveMatch(); + TestGenericExposureBoundsRemainEffective(); + TestWhitePixelsDoNotCapPositiveMatchingAtZero(); + TestShadowPreferenceIsModestAndKeepsReliability(); + TestPerPixelResponseBeforeCellMean({post::Rgb{0.015f, 0.015f, 0.015f}, {0.15f, 0.15f, 0.15f}, + {0.4f, 0.4f, 0.4f}, {0.8f, 0.8f, 0.8f}}, 2.8f); + TestPerPixelResponseBeforeCellMean({post::Rgb{0.04f, 0.02f, 0.01f}, {0.9f, 0.08f, 0.015f}, + {0.1f, 0.7f, 0.2f}, {0.01f, 0.03f, 0.95f}}, 3.0f); + TestMgcRolloffOracles(); std::cout << "raw HDRNet post-exposure solver tests passed\n"; return 0; }