feat: HDRNet post-exposure SLM rolloff
This commit is contained in:
1 parent
3b8a596ad5
commit
9d91dd48ac
14 files changed
+653
-281
No files matched your search
@@ -1,4 +1,5 @@
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
@@ -7,6 +8,8 @@
|
||||
#include <new>
|
||||
#include <vector>
|
||||
|
||||
#include "raw_hdrnet_post_exposure.h"
|
||||
|
||||
#if defined(__ANDROID__)
|
||||
#include <android/log.h>
|
||||
#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<int64_t>(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<float>(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<int>(
|
||||
static_cast<int>(source.u * input_width), 0, input_width - 1);
|
||||
const int source_y = std::clamp(
|
||||
const int source_y = std::clamp<int>(
|
||||
static_cast<int>(source.v * input_height), 0, input_height - 1);
|
||||
const RgbSample display_rgb = full_image_display_rgb[
|
||||
static_cast<size_t>(source_y * input_width + source_x)];
|
||||
const size_t output_offset = (static_cast<size_t>(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<int>(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<float, 5> 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<AxisSample> x_samples(static_cast<size_t>(output_grid_width));
|
||||
std::vector<AxisSample> y_samples(static_cast<size_t>(output_grid_height));
|
||||
std::vector<AxisSample> model_x_samples(static_cast<size_t>(output_grid_width));
|
||||
std::vector<AxisSample> model_y_samples(static_cast<size_t>(output_grid_height));
|
||||
std::vector<AxisSample> range_samples(static_cast<size_t>(point_count));
|
||||
std::vector<float> short_intensities(static_cast<size_t>(point_count));
|
||||
std::vector<RgbSample> local_model_rgb(static_cast<size_t>(cell_count));
|
||||
for (int x = 0; x < output_grid_width; ++x) {
|
||||
x_samples[static_cast<size_t>(x)] =
|
||||
@@ -830,44 +858,27 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeGenerateGains
|
||||
model_x_samples[static_cast<size_t>(x)],
|
||||
model_y_samples[static_cast<size_t>(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<float>(evaluated_point) / point_count;
|
||||
short_intensities[static_cast<size_t>(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<int>(range_floor);
|
||||
range_samples[static_cast<size_t>(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<bool> 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<size_t>(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<size_t>(cell) * point_count;
|
||||
for (int point = 0; point < point_count; ++point) {
|
||||
const float short_intensity =
|
||||
short_intensities[static_cast<size_t>(point)];
|
||||
const AxisSample& range_sample =
|
||||
range_samples[static_cast<size_t>(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<float>(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<size_t>(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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
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
|
||||
@@ -1,4 +1,5 @@
|
||||
#include <jni.h>
|
||||
#include "raw_hdrnet_post_exposure.h"
|
||||
|
||||
#if defined(__ANDROID__)
|
||||
#include <android/log.h>
|
||||
@@ -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<Sample> 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<int64_t>(width) * height > std::numeric_limits<int>::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<WeightedValue> corrections;
|
||||
std::vector<WeightedValue> initial_residuals;
|
||||
std::vector<float> 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<std::vector<post::Rgb>> 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<float>(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<float> 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<float> weights = reference_cell_weights_;
|
||||
std::vector<float> boundaries{safe_minimum, safe_maximum};
|
||||
std::vector<float> 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<float> adjusted_lumas(kGridCellCount);
|
||||
std::optional<Sample> 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<float>* 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<int>(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<int64_t>(width) * height * 3;
|
||||
if (solver == nullptr || candidate_display_linear_rgb == nullptr ||
|
||||
width < kGridColumns || height < kGridRows ||
|
||||
value_count > std::numeric_limits<jsize>::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<Sample> 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,
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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<String, String>): Float? = properties[PROPERTY]
|
||||
?.toFloatOrNull()
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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?
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user