fix: hdrnet + dehazeAndDha
This commit is contained in:
1 parent
f476c23af0
commit
f5577f9119
32 files changed
+1468
-2773
No files matched your search
@@ -1,5 +1,4 @@
|
||||
#include <algorithm>
|
||||
#include <android/log.h>
|
||||
#include <atomic>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
@@ -8,6 +7,10 @@
|
||||
#include <new>
|
||||
#include <vector>
|
||||
|
||||
#if defined(__ANDROID__)
|
||||
#include <android/log.h>
|
||||
#endif
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr char kLogTag[] = "PLog_DngHdrNetPgtm";
|
||||
@@ -18,6 +21,29 @@ constexpr float kHdrNetLumaBlue = 0.1142578125f;
|
||||
constexpr float kDisplayLumaRed = 0.2126f;
|
||||
constexpr float kDisplayLumaGreen = 0.7152f;
|
||||
constexpr float kDisplayLumaBlue = 0.0722f;
|
||||
constexpr int kDehazeCurveValueCount = 8;
|
||||
constexpr int kEvaluationMetricCount = 1;
|
||||
constexpr int kPostDehazeP99PeakMetric = 0;
|
||||
constexpr float kPostDehazePeakQuantile = 0.99f;
|
||||
constexpr int kDehazeHistogramSize = 877;
|
||||
constexpr int kHighlightHistogramSize = 5251;
|
||||
constexpr float kDehazeSignalMax = 4095.0f;
|
||||
constexpr int kDehazeQuantileSampleCount = 20;
|
||||
constexpr int kHighlightQuantileSampleCount = 5;
|
||||
constexpr float kDehazeQuantile = 0.001f;
|
||||
constexpr float kDehazeQuantileLow = 0.1f;
|
||||
constexpr float kDehazeQuantileHigh = 1.9f;
|
||||
constexpr float kDehazeLevelLimit = 172.0f;
|
||||
constexpr float kDehazePointLowScale = 0.6f;
|
||||
constexpr float kDehazePointHighScale = 1.2f;
|
||||
constexpr float kDehazeDamping = 0.98f;
|
||||
constexpr float kHighlightQuantile = 0.993f;
|
||||
constexpr float kHighlightTarget = 0.88f;
|
||||
constexpr float kHighlightWindowMin = 0.01f;
|
||||
constexpr float kHighlightWindowMax = 0.05f;
|
||||
constexpr float kHighlightScaleMin = 0.78f;
|
||||
constexpr float kHighlightScaleMax = 1.7f;
|
||||
constexpr float kMinimumCurveInterval = 1.0e-6f;
|
||||
|
||||
struct AxisSample {
|
||||
int lower;
|
||||
@@ -73,7 +99,11 @@ class ScopedFloatArray {
|
||||
};
|
||||
|
||||
void LogError(const char* message) {
|
||||
#if defined(__ANDROID__)
|
||||
__android_log_print(ANDROID_LOG_ERROR, kLogTag, "%s", message);
|
||||
#else
|
||||
(void)message;
|
||||
#endif
|
||||
}
|
||||
|
||||
float Lerp(float first, float second, float amount) {
|
||||
@@ -207,6 +237,275 @@ bool IsValidAcrCurve(const float* curve, int count) {
|
||||
return curve[count - 1] > curve[0];
|
||||
}
|
||||
|
||||
struct DehazeCurve {
|
||||
float haze_point_low = 0.0f;
|
||||
float haze_point_high = 0.0f;
|
||||
float highlight_scale = 1.0f;
|
||||
float quadratic_coefficient = 0.0f;
|
||||
float linear_slope = 1.0f;
|
||||
float shoulder_value = 0.0f;
|
||||
float detected_highlight_scale = 1.0f;
|
||||
int sampled_pixel_count = 1;
|
||||
};
|
||||
|
||||
float RenderMaximumGain(float short_intensity, float render_max_gain,
|
||||
float blend_threshold) {
|
||||
if (!(blend_threshold > 0.0f)) return render_max_gain;
|
||||
const float blend = std::clamp(
|
||||
short_intensity / blend_threshold, 0.0f, 1.0f);
|
||||
return Lerp(1.0f, render_max_gain, blend);
|
||||
}
|
||||
|
||||
bool EvaluateHdrNetRgb(
|
||||
const float* coefficients, int source_grid_width, int source_grid_height,
|
||||
int source_grid_depth, int coefficient_count, const float* model_input, int input_width,
|
||||
int input_height, int input_channels, float source_u, float source_v, float hdr_ratio,
|
||||
float render_min_gain, float render_max_gain,
|
||||
float render_max_gain_blend_threshold, const float* guide_shifts,
|
||||
const float* guide_slopes, int guide_count, RgbSample* output) {
|
||||
if (output == nullptr) return false;
|
||||
const AxisSample input_x =
|
||||
MakeNormalizedAxisSample(source_u, input_width);
|
||||
const AxisSample input_y =
|
||||
MakeNormalizedAxisSample(source_v, input_height);
|
||||
const RgbSample short_rgb = SampleModelRgb(
|
||||
model_input, input_width, input_channels, input_x, input_y);
|
||||
const float short_intensity = std::clamp(
|
||||
short_rgb.red * kHdrNetLumaRed +
|
||||
short_rgb.green * kHdrNetLumaGreen +
|
||||
short_rgb.blue * kHdrNetLumaBlue,
|
||||
0.0f, 1.0f);
|
||||
const float guide = EvaluateGuide(
|
||||
short_intensity, guide_shifts, guide_slopes, guide_count);
|
||||
const AxisSample grid_x_sample =
|
||||
MakeNormalizedAxisSample(source_u, source_grid_width);
|
||||
const AxisSample grid_y_sample =
|
||||
MakeNormalizedAxisSample(source_v, source_grid_height);
|
||||
const AxisSample range_sample =
|
||||
MakeNormalizedAxisSample(guide, source_grid_depth);
|
||||
const float raw_scale = SampleCoefficient(
|
||||
coefficients, source_grid_width, source_grid_depth, coefficient_count,
|
||||
grid_x_sample, grid_y_sample, range_sample, 0);
|
||||
const float bias = SampleCoefficient(
|
||||
coefficients, source_grid_width, source_grid_depth, coefficient_count,
|
||||
grid_x_sample, grid_y_sample, range_sample, 1);
|
||||
const float scale = raw_scale * (hdr_ratio - 1.0f) + 1.0f;
|
||||
const float predicted_luma = scale * short_intensity + bias;
|
||||
if (!std::isfinite(predicted_luma)) return false;
|
||||
const float render_gain = std::clamp(
|
||||
predicted_luma / (short_intensity + kHdrNetGainEpsilon),
|
||||
render_min_gain,
|
||||
RenderMaximumGain(short_intensity, render_max_gain,
|
||||
render_max_gain_blend_threshold));
|
||||
*output = {
|
||||
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 std::isfinite(output->red) && std::isfinite(output->green) &&
|
||||
std::isfinite(output->blue);
|
||||
}
|
||||
|
||||
float HistogramQuantile(const std::vector<uint32_t>& cumulative,
|
||||
float target) {
|
||||
if (cumulative.empty()) return 0.0f;
|
||||
const float bounded_target = std::clamp(
|
||||
target, 0.0f, static_cast<float>(cumulative.back()));
|
||||
const auto found = std::lower_bound(
|
||||
cumulative.begin(), cumulative.end(), bounded_target,
|
||||
[](uint32_t count, float requested) {
|
||||
return static_cast<float>(count) < requested;
|
||||
});
|
||||
const int index = found == cumulative.end()
|
||||
? static_cast<int>(cumulative.size()) - 1
|
||||
: static_cast<int>(found - cumulative.begin());
|
||||
if (index == 0) return 0.0f;
|
||||
const float previous = static_cast<float>(cumulative[index - 1]);
|
||||
const float current = static_cast<float>(cumulative[index]);
|
||||
if (!(current > previous)) return static_cast<float>(index);
|
||||
const float fraction = std::clamp(
|
||||
(bounded_target - previous) / (current - previous), 0.0f, 1.0f);
|
||||
return static_cast<float>(index - 1) + fraction;
|
||||
}
|
||||
|
||||
std::vector<uint32_t> CumulativeHistogram(
|
||||
const std::vector<uint32_t>& histogram) {
|
||||
std::vector<uint32_t> cumulative(histogram.size());
|
||||
uint32_t sum = 0;
|
||||
for (size_t index = 0; index < histogram.size(); ++index) {
|
||||
sum += histogram[index];
|
||||
cumulative[index] = sum;
|
||||
}
|
||||
return cumulative;
|
||||
}
|
||||
|
||||
void AddDehazeHistogramSample(
|
||||
const RgbSample& rgb, std::vector<uint32_t>* haze_histogram,
|
||||
std::vector<uint32_t>* highlight_histogram, int* sample_count) {
|
||||
const int red = static_cast<int>(std::floor(
|
||||
std::clamp(rgb.red, 0.0f, 1.0f) * kDehazeSignalMax + 0.5f));
|
||||
const int green = static_cast<int>(std::floor(
|
||||
std::clamp(rgb.green, 0.0f, 1.0f) * kDehazeSignalMax + 0.5f));
|
||||
const int blue = static_cast<int>(std::floor(
|
||||
std::clamp(rgb.blue, 0.0f, 1.0f) * kDehazeSignalMax + 0.5f));
|
||||
const int minimum = std::min({red, green, blue});
|
||||
const int maximum = std::max({red, green, blue});
|
||||
const int haze_bin = std::clamp(
|
||||
red + green + blue, 0, kDehazeHistogramSize - 1);
|
||||
const int highlight_bin = std::clamp(
|
||||
maximum + (maximum - minimum) / 8,
|
||||
0, kHighlightHistogramSize - 1);
|
||||
++(*haze_histogram)[static_cast<size_t>(haze_bin)];
|
||||
++(*highlight_histogram)[static_cast<size_t>(highlight_bin)];
|
||||
++(*sample_count);
|
||||
}
|
||||
|
||||
DehazeCurve EstimateDehazeCurve(
|
||||
const std::vector<uint32_t>& haze_histogram,
|
||||
const std::vector<uint32_t>& highlight_histogram, int sample_count,
|
||||
float strength, float dynamic_highlight_strength) {
|
||||
DehazeCurve curve;
|
||||
curve.sampled_pixel_count = std::max(sample_count, 1);
|
||||
if (sample_count <= 0) return curve;
|
||||
const std::vector<uint32_t> cumulative_haze =
|
||||
CumulativeHistogram(haze_histogram);
|
||||
const std::vector<uint32_t> cumulative_highlight =
|
||||
CumulativeHistogram(highlight_histogram);
|
||||
|
||||
const float distance_from_white = 1.0f - kHighlightQuantile;
|
||||
const float adaptive_window_mix =
|
||||
std::clamp(distance_from_white * 5.0f, 0.0f, 1.0f);
|
||||
const float maximum_half_window = kHighlightWindowMin +
|
||||
(kHighlightWindowMax - kHighlightWindowMin) * adaptive_window_mix;
|
||||
const float half_window = std::min(distance_from_white, maximum_half_window);
|
||||
float highlight_sum = 0.0f;
|
||||
for (int index = 0; index < kHighlightQuantileSampleCount; ++index) {
|
||||
const float position = static_cast<float>(index) /
|
||||
static_cast<float>(kHighlightQuantileSampleCount - 1);
|
||||
const float quantile_position =
|
||||
(kHighlightQuantile - half_window) + 2.0f * half_window * position;
|
||||
highlight_sum += HistogramQuantile(
|
||||
cumulative_highlight, quantile_position * sample_count) /
|
||||
kDehazeSignalMax;
|
||||
}
|
||||
const float mean_highlight =
|
||||
highlight_sum / kHighlightQuantileSampleCount;
|
||||
const float raw_highlight_scale = mean_highlight > 1.0e-6f
|
||||
? kHighlightTarget / mean_highlight
|
||||
: kHighlightScaleMax;
|
||||
curve.detected_highlight_scale = std::clamp(
|
||||
raw_highlight_scale, kHighlightScaleMin, kHighlightScaleMax);
|
||||
curve.highlight_scale = 1.0f +
|
||||
(curve.detected_highlight_scale - 1.0f) * dynamic_highlight_strength;
|
||||
|
||||
float haze_level_sum = 0.0f;
|
||||
for (int index = 0; index < kDehazeQuantileSampleCount; ++index) {
|
||||
const float position = static_cast<float>(index) /
|
||||
static_cast<float>(kDehazeQuantileSampleCount - 1);
|
||||
const float multiplier = kDehazeQuantileLow +
|
||||
(kDehazeQuantileHigh - kDehazeQuantileLow) * position;
|
||||
const float summed_rgb_bin = HistogramQuantile(
|
||||
cumulative_haze, kDehazeQuantile * multiplier * sample_count);
|
||||
haze_level_sum += std::min(summed_rgb_bin / 3.0f, kDehazeLevelLimit);
|
||||
}
|
||||
const float haze_level = haze_level_sum / kDehazeQuantileSampleCount;
|
||||
const float haze_base = curve.highlight_scale * haze_level *
|
||||
kDehazeDamping * strength;
|
||||
curve.haze_point_low = std::clamp(
|
||||
kDehazePointLowScale * haze_base / kDehazeSignalMax, 0.0f, 1.0f);
|
||||
curve.haze_point_high = std::clamp(
|
||||
kDehazePointHighScale * haze_base / kDehazeSignalMax,
|
||||
curve.haze_point_low, 1.0f);
|
||||
const float interval = curve.haze_point_high - curve.haze_point_low;
|
||||
if (interval > kMinimumCurveInterval) {
|
||||
curve.quadratic_coefficient = 1.0f /
|
||||
(interval * interval +
|
||||
2.0f * (1.0f - curve.haze_point_high) * interval);
|
||||
curve.shoulder_value =
|
||||
interval * interval * curve.quadratic_coefficient;
|
||||
curve.linear_slope = curve.haze_point_high < 1.0f
|
||||
? (1.0f - curve.shoulder_value) /
|
||||
(1.0f - curve.haze_point_high)
|
||||
: 0.0f;
|
||||
}
|
||||
return curve;
|
||||
}
|
||||
|
||||
float MappedDehazeLuminance(float input, const DehazeCurve& curve) {
|
||||
const float normalized = std::clamp(input, 0.0f, 1.0f);
|
||||
const float scaled = std::min(normalized * curve.highlight_scale, 1.0f);
|
||||
const float distance = std::max(scaled - curve.haze_point_low, 0.0f);
|
||||
const float mapped = scaled < curve.haze_point_high
|
||||
? distance * distance * curve.quadratic_coefficient
|
||||
: curve.shoulder_value +
|
||||
(scaled - curve.haze_point_high) * curve.linear_slope;
|
||||
return std::clamp(mapped, 0.0f, 1.0f);
|
||||
}
|
||||
|
||||
RgbSample ApplyDehaze(const RgbSample& rgb, const DehazeCurve& curve) {
|
||||
const float mean = (rgb.red + rgb.green + rgb.blue) / 3.0f;
|
||||
const float gain = MappedDehazeLuminance(mean, curve) /
|
||||
std::max(std::clamp(mean, 0.0f, 1.0f), 1.0e-6f);
|
||||
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),
|
||||
};
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
void WriteDehazeCurve(const DehazeCurve& curve, float* values) {
|
||||
values[0] = curve.haze_point_low;
|
||||
values[1] = curve.haze_point_high;
|
||||
values[2] = curve.highlight_scale;
|
||||
values[3] = curve.quadratic_coefficient;
|
||||
values[4] = curve.linear_slope;
|
||||
values[5] = curve.shoulder_value;
|
||||
values[6] = curve.detected_highlight_scale;
|
||||
values[7] = static_cast<float>(curve.sampled_pixel_count);
|
||||
}
|
||||
|
||||
bool ReadDehazeCurve(const float* values, int count, DehazeCurve* curve) {
|
||||
if (values == nullptr || curve == nullptr || count != kDehazeCurveValueCount ||
|
||||
!IsFiniteArray(values, count)) {
|
||||
return false;
|
||||
}
|
||||
*curve = DehazeCurve{
|
||||
values[0], values[1], values[2], values[3], values[4], values[5],
|
||||
values[6], std::max(static_cast<int>(std::lround(values[7])), 1),
|
||||
};
|
||||
return curve->haze_point_low >= 0.0f &&
|
||||
curve->haze_point_high >= curve->haze_point_low &&
|
||||
curve->haze_point_high <= 1.0f && curve->highlight_scale > 0.0f &&
|
||||
curve->quadratic_coefficient >= 0.0f && curve->linear_slope >= 0.0f;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" JNIEXPORT jboolean JNICALL
|
||||
@@ -216,21 +515,31 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeEvaluateDispl
|
||||
jint coefficient_count, jfloatArray model_input_array,
|
||||
jint input_width, jint input_height, jint input_channels,
|
||||
jint output_grid_width, jint output_grid_height,
|
||||
jint footprint_samples_per_axis, jfloat hdr_ratio,
|
||||
jfloat render_min_gain, jfloat render_max_gain, jint output_rotation,
|
||||
jfloat hdr_ratio,
|
||||
jfloat render_min_gain, jfloat render_max_gain,
|
||||
jfloat render_max_gain_blend_threshold, jboolean dehaze_enabled,
|
||||
jfloat dehaze_strength, jfloat dynamic_highlight_strength,
|
||||
jint output_rotation,
|
||||
jfloatArray guide_shifts_array, jfloatArray guide_slopes_array,
|
||||
jfloatArray output_lumas_array) {
|
||||
jfloatArray output_lumas_array, jfloatArray output_dehaze_curve_array,
|
||||
jfloatArray output_metrics_array) {
|
||||
if (coefficients_array == nullptr || model_input_array == nullptr ||
|
||||
guide_shifts_array == nullptr || guide_slopes_array == nullptr ||
|
||||
output_lumas_array == nullptr || source_grid_width <= 0 ||
|
||||
output_lumas_array == nullptr || output_dehaze_curve_array == nullptr ||
|
||||
output_metrics_array == nullptr ||
|
||||
source_grid_width <= 0 ||
|
||||
source_grid_height <= 0 || source_grid_depth <= 0 ||
|
||||
coefficient_count != 2 || input_width <= 0 || input_height <= 0 ||
|
||||
input_channels < 3 || output_grid_width <= 0 || output_grid_height <= 0 ||
|
||||
footprint_samples_per_axis <= 0 || footprint_samples_per_axis > 16 ||
|
||||
!std::isfinite(hdr_ratio) ||
|
||||
hdr_ratio < 1.0f || !std::isfinite(render_min_gain) ||
|
||||
render_min_gain <= 0.0f || !std::isfinite(render_max_gain) ||
|
||||
render_max_gain < render_min_gain ||
|
||||
!std::isfinite(render_max_gain_blend_threshold) ||
|
||||
render_max_gain_blend_threshold < 0.0f ||
|
||||
!std::isfinite(dehaze_strength) || dehaze_strength < 0.0f ||
|
||||
!std::isfinite(dynamic_highlight_strength) ||
|
||||
dynamic_highlight_strength < 0.0f || dynamic_highlight_strength > 1.0f ||
|
||||
(output_rotation != 0 && output_rotation != 90 &&
|
||||
output_rotation != 180 && output_rotation != 270)) {
|
||||
LogError("Rejected invalid HDRNet display-grid parameters");
|
||||
@@ -252,7 +561,9 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeEvaluateDispl
|
||||
env->GetArrayLength(coefficients_array) != coefficient_values ||
|
||||
env->GetArrayLength(model_input_array) != input_values ||
|
||||
env->GetArrayLength(guide_slopes_array) != guide_count ||
|
||||
env->GetArrayLength(output_lumas_array) != output_values) {
|
||||
env->GetArrayLength(output_lumas_array) != output_values ||
|
||||
env->GetArrayLength(output_dehaze_curve_array) != kDehazeCurveValueCount ||
|
||||
env->GetArrayLength(output_metrics_array) != kEvaluationMetricCount) {
|
||||
LogError("Rejected mismatched HDRNet display-grid geometry");
|
||||
return JNI_FALSE;
|
||||
}
|
||||
@@ -262,9 +573,12 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeEvaluateDispl
|
||||
ScopedFloatArray guide_shifts(env, guide_shifts_array);
|
||||
ScopedFloatArray guide_slopes(env, guide_slopes_array);
|
||||
ScopedFloatArray output_lumas(env, output_lumas_array);
|
||||
ScopedFloatArray output_dehaze_curve(env, output_dehaze_curve_array);
|
||||
ScopedFloatArray output_metrics(env, output_metrics_array);
|
||||
if (coefficients.data() == nullptr || model_input.data() == nullptr ||
|
||||
guide_shifts.data() == nullptr || guide_slopes.data() == nullptr ||
|
||||
output_lumas.data() == nullptr) {
|
||||
output_lumas.data() == nullptr || output_dehaze_curve.data() == nullptr ||
|
||||
output_metrics.data() == nullptr) {
|
||||
LogError("Unable to acquire HDRNet display-grid arrays");
|
||||
return JNI_FALSE;
|
||||
}
|
||||
@@ -276,80 +590,117 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeEvaluateDispl
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
DehazeCurve dehaze_curve;
|
||||
std::vector<RgbSample> full_image_display_rgb;
|
||||
try {
|
||||
const int full_image_pixel_count = input_width * input_height;
|
||||
full_image_display_rgb.resize(static_cast<size_t>(full_image_pixel_count));
|
||||
std::vector<uint32_t> haze_histogram;
|
||||
std::vector<uint32_t> highlight_histogram;
|
||||
int sample_count = 0;
|
||||
if (dehaze_enabled == JNI_TRUE) {
|
||||
haze_histogram.assign(kDehazeHistogramSize, 0);
|
||||
highlight_histogram.assign(kHighlightHistogramSize, 0);
|
||||
}
|
||||
for (int y = 0; y < input_height; ++y) {
|
||||
const float source_v = (static_cast<float>(y) + 0.5f) / input_height;
|
||||
for (int x = 0; x < input_width; ++x) {
|
||||
const float source_u = (static_cast<float>(x) + 0.5f) / input_width;
|
||||
RgbSample hdr_rgb{};
|
||||
if (!EvaluateHdrNetRgb(
|
||||
coefficients.data(), source_grid_width, source_grid_height,
|
||||
source_grid_depth, coefficient_count, model_input.data(),
|
||||
input_width, input_height, input_channels, source_u, source_v,
|
||||
hdr_ratio, render_min_gain, render_max_gain,
|
||||
render_max_gain_blend_threshold, guide_shifts.data(),
|
||||
guide_slopes.data(), guide_count, &hdr_rgb)) {
|
||||
LogError("HDRNet full-image evaluation produced a non-finite value");
|
||||
return JNI_FALSE;
|
||||
}
|
||||
full_image_display_rgb[static_cast<size_t>(y * input_width + x)] = hdr_rgb;
|
||||
if (dehaze_enabled == JNI_TRUE) {
|
||||
AddDehazeHistogramSample(
|
||||
hdr_rgb, &haze_histogram, &highlight_histogram, &sample_count);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (dehaze_enabled == JNI_TRUE) {
|
||||
dehaze_curve = EstimateDehazeCurve(
|
||||
haze_histogram, highlight_histogram, sample_count,
|
||||
dehaze_strength, dynamic_highlight_strength);
|
||||
} else {
|
||||
dehaze_curve.sampled_pixel_count = full_image_pixel_count;
|
||||
}
|
||||
std::vector<float> post_dehaze_peaks(
|
||||
static_cast<size_t>(full_image_pixel_count));
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int index = 0; index < full_image_pixel_count; ++index) {
|
||||
const RgbSample rgb = ApplyDehaze(
|
||||
full_image_display_rgb[static_cast<size_t>(index)], dehaze_curve);
|
||||
full_image_display_rgb[static_cast<size_t>(index)] = rgb;
|
||||
post_dehaze_peaks[static_cast<size_t>(index)] =
|
||||
std::max({rgb.red, rgb.green, rgb.blue});
|
||||
}
|
||||
const size_t quantile_index = static_cast<size_t>(std::floor(
|
||||
kPostDehazePeakQuantile * (full_image_pixel_count - 1)));
|
||||
std::nth_element(
|
||||
post_dehaze_peaks.begin(),
|
||||
post_dehaze_peaks.begin() + quantile_index,
|
||||
post_dehaze_peaks.end());
|
||||
output_metrics.data()[kPostDehazeP99PeakMetric] =
|
||||
post_dehaze_peaks[quantile_index];
|
||||
} catch (const std::bad_alloc&) {
|
||||
LogError("Unable to allocate HDRNet full-image evaluation buffers");
|
||||
return JNI_FALSE;
|
||||
}
|
||||
WriteDehazeCurve(dehaze_curve, output_dehaze_curve.data());
|
||||
|
||||
const int output_count = static_cast<int>(output_values);
|
||||
const int footprint_sample_count =
|
||||
footprint_samples_per_axis * footprint_samples_per_axis;
|
||||
const bool swaps_axes = output_rotation == 90 || output_rotation == 270;
|
||||
const int oriented_width = swaps_axes ? input_height : input_width;
|
||||
const int oriented_height = swaps_axes ? input_width : input_height;
|
||||
std::atomic<bool> output_valid{true};
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int cell = 0; cell < output_count; ++cell) {
|
||||
const int grid_x = cell % output_grid_width;
|
||||
const int grid_y = cell / output_grid_width;
|
||||
const int x_begin =
|
||||
(grid_x * oriented_width + output_grid_width - 1) / output_grid_width;
|
||||
const int x_end =
|
||||
((grid_x + 1) * oriented_width + output_grid_width - 1) /
|
||||
output_grid_width;
|
||||
const int y_begin =
|
||||
(grid_y * oriented_height + output_grid_height - 1) / output_grid_height;
|
||||
const int y_end =
|
||||
((grid_y + 1) * oriented_height + output_grid_height - 1) /
|
||||
output_grid_height;
|
||||
double luma_sum = 0.0;
|
||||
for (int sample_y = 0; sample_y < footprint_samples_per_axis; ++sample_y) {
|
||||
int sample_count = 0;
|
||||
for (int output_y = y_begin; output_y < y_end; ++output_y) {
|
||||
const float output_v_top =
|
||||
(grid_y + (sample_y + 0.5f) / footprint_samples_per_axis) /
|
||||
output_grid_height;
|
||||
for (int sample_x = 0; sample_x < footprint_samples_per_axis; ++sample_x) {
|
||||
(static_cast<float>(output_y) + 0.5f) / oriented_height;
|
||||
for (int output_x = x_begin; output_x < x_end; ++output_x) {
|
||||
const float output_u =
|
||||
(grid_x + (sample_x + 0.5f) / footprint_samples_per_axis) /
|
||||
output_grid_width;
|
||||
// HDRNet now samples the same top-left/clockwise coordinates as the RAW render and the
|
||||
// already-rotated Android Bitmap used as the viewfinder reference.
|
||||
(static_cast<float>(output_x) + 0.5f) / oriented_width;
|
||||
const NormalizedImagePoint source = MapTopLeftOutputToSource(
|
||||
output_u, output_v_top, output_rotation);
|
||||
const float source_u = source.u;
|
||||
const float source_v = source.v;
|
||||
|
||||
const AxisSample input_x =
|
||||
MakeNormalizedAxisSample(source_u, input_width);
|
||||
const AxisSample input_y =
|
||||
MakeNormalizedAxisSample(source_v, input_height);
|
||||
const RgbSample short_rgb = SampleModelRgb(
|
||||
model_input.data(), input_width, input_channels, input_x, input_y);
|
||||
const float short_intensity = std::clamp(
|
||||
short_rgb.red * kHdrNetLumaRed +
|
||||
short_rgb.green * kHdrNetLumaGreen +
|
||||
short_rgb.blue * kHdrNetLumaBlue,
|
||||
0.0f, 1.0f);
|
||||
const float guide =
|
||||
EvaluateGuide(short_intensity, guide_shifts.data(),
|
||||
guide_slopes.data(), guide_count);
|
||||
const AxisSample grid_x_sample =
|
||||
MakeNormalizedAxisSample(source_u, source_grid_width);
|
||||
const AxisSample grid_y_sample =
|
||||
MakeNormalizedAxisSample(source_v, source_grid_height);
|
||||
const AxisSample range_sample =
|
||||
MakeNormalizedAxisSample(guide, source_grid_depth);
|
||||
const float raw_scale = SampleCoefficient(
|
||||
coefficients.data(), source_grid_width, source_grid_depth,
|
||||
coefficient_count, grid_x_sample, grid_y_sample, range_sample, 0);
|
||||
const float bias = SampleCoefficient(
|
||||
coefficients.data(), source_grid_width, source_grid_depth,
|
||||
coefficient_count, grid_x_sample, grid_y_sample, range_sample, 1);
|
||||
const float scale = raw_scale * (hdr_ratio - 1.0f) + 1.0f;
|
||||
const float predicted_luma = scale * short_intensity + bias;
|
||||
if (!std::isfinite(predicted_luma)) {
|
||||
output_valid.store(false, std::memory_order_relaxed);
|
||||
continue;
|
||||
}
|
||||
const float render_gain = std::clamp(
|
||||
predicted_luma / (short_intensity + kHdrNetGainEpsilon),
|
||||
render_min_gain, render_max_gain);
|
||||
// Match the classic ARGB path after its per-channel sRGB EOTF: clamp the rendered
|
||||
// linear RGB channels, compute Rec.709 display-linear luma, then average the footprint.
|
||||
// This is exactly the domain consumed by the shared exposure solver.
|
||||
const float display_red = std::clamp(short_rgb.red * render_gain, 0.0f, 1.0f);
|
||||
const float display_green =
|
||||
std::clamp(short_rgb.green * render_gain, 0.0f, 1.0f);
|
||||
const float display_blue =
|
||||
std::clamp(short_rgb.blue * render_gain, 0.0f, 1.0f);
|
||||
luma_sum += display_red * kDisplayLumaRed +
|
||||
display_green * kDisplayLumaGreen +
|
||||
display_blue * kDisplayLumaBlue;
|
||||
const int source_x = std::clamp(
|
||||
static_cast<int>(source.u * input_width), 0, input_width - 1);
|
||||
const int source_y = std::clamp(
|
||||
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)];
|
||||
luma_sum += display_rgb.red * kDisplayLumaRed +
|
||||
display_rgb.green * kDisplayLumaGreen +
|
||||
display_rgb.blue * kDisplayLumaBlue;
|
||||
++sample_count;
|
||||
}
|
||||
}
|
||||
output_lumas.data()[cell] =
|
||||
static_cast<float>(luma_sum / footprint_sample_count);
|
||||
if (sample_count <= 0) {
|
||||
output_valid.store(false, std::memory_order_relaxed);
|
||||
} else {
|
||||
output_lumas.data()[cell] = static_cast<float>(luma_sum / sample_count);
|
||||
}
|
||||
}
|
||||
if (!output_valid.load(std::memory_order_relaxed) ||
|
||||
!IsFiniteArray(output_lumas.data(), static_cast<int>(output_values))) {
|
||||
@@ -357,12 +708,16 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeEvaluateDispl
|
||||
return JNI_FALSE;
|
||||
}
|
||||
output_lumas.CommitOnRelease();
|
||||
output_dehaze_curve.CommitOnRelease();
|
||||
output_metrics.CommitOnRelease();
|
||||
return env->ExceptionCheck() ? JNI_FALSE : JNI_TRUE;
|
||||
}
|
||||
|
||||
extern "C" JNIEXPORT jboolean JNICALL
|
||||
Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeGenerateGains(
|
||||
JNIEnv* env, jobject, jfloatArray coefficients_array,
|
||||
jfloatArray model_input_array,
|
||||
jint input_width, jint input_height, jint input_channels,
|
||||
jint source_grid_width, jint source_grid_height, jint source_grid_depth,
|
||||
jint coefficient_count, jint output_grid_width, jint output_grid_height,
|
||||
jint point_count, jfloat hdr_ratio, jfloat source_to_short_gain,
|
||||
@@ -372,16 +727,21 @@ 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 output_gains_array) {
|
||||
if (coefficients_array == nullptr || guide_shifts_array == nullptr ||
|
||||
if (coefficients_array == nullptr || model_input_array == nullptr ||
|
||||
guide_shifts_array == nullptr ||
|
||||
guide_slopes_array == nullptr || acr_curve_array == nullptr ||
|
||||
output_gains_array == nullptr || source_grid_width <= 0 ||
|
||||
dehaze_curve_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 ||
|
||||
coefficient_count != 2 || output_grid_width <= 0 ||
|
||||
output_grid_height <= 0 || point_count <= 1 ||
|
||||
!std::isfinite(hdr_ratio) || hdr_ratio < 1.0f ||
|
||||
!std::isfinite(source_to_short_gain) || source_to_short_gain <= 0.0f ||
|
||||
!std::isfinite(renderer_baseline_gain) || renderer_baseline_gain <= 0.0f ||
|
||||
!std::isfinite(post_exposure_gain) || post_exposure_gain <= 0.0f ||
|
||||
!std::isfinite(render_min_gain) || render_min_gain <= 0.0f ||
|
||||
!std::isfinite(render_max_gain) ||
|
||||
render_max_gain < render_min_gain ||
|
||||
@@ -396,36 +756,48 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeGenerateGains
|
||||
const int64_t coefficient_values =
|
||||
static_cast<int64_t>(source_grid_width) * source_grid_height *
|
||||
source_grid_depth * coefficient_count;
|
||||
const int64_t input_values =
|
||||
static_cast<int64_t>(input_width) * input_height * input_channels;
|
||||
const int64_t cell_count =
|
||||
static_cast<int64_t>(output_grid_width) * output_grid_height;
|
||||
const int64_t output_values = cell_count * point_count;
|
||||
const int guide_count = env->GetArrayLength(guide_shifts_array);
|
||||
const int acr_curve_count = env->GetArrayLength(acr_curve_array);
|
||||
if (coefficient_values <= 0 || output_values <= 0 ||
|
||||
if (coefficient_values <= 0 || input_values <= 0 || output_values <= 0 ||
|
||||
coefficient_values > std::numeric_limits<jsize>::max() ||
|
||||
input_values > std::numeric_limits<jsize>::max() ||
|
||||
output_values > std::numeric_limits<jsize>::max() || guide_count <= 0 ||
|
||||
env->GetArrayLength(coefficients_array) != coefficient_values ||
|
||||
env->GetArrayLength(model_input_array) != input_values ||
|
||||
env->GetArrayLength(guide_slopes_array) != guide_count ||
|
||||
acr_curve_count < 2 ||
|
||||
env->GetArrayLength(dehaze_curve_array) != kDehazeCurveValueCount ||
|
||||
env->GetArrayLength(output_gains_array) != output_values) {
|
||||
LogError("Rejected mismatched HDRNet PGTM array geometry");
|
||||
return JNI_FALSE;
|
||||
}
|
||||
ScopedFloatArray coefficients(env, coefficients_array);
|
||||
ScopedFloatArray model_input(env, model_input_array);
|
||||
ScopedFloatArray guide_shifts(env, guide_shifts_array);
|
||||
ScopedFloatArray guide_slopes(env, guide_slopes_array);
|
||||
ScopedFloatArray acr_curve(env, acr_curve_array);
|
||||
ScopedFloatArray dehaze_curve_values(env, dehaze_curve_array);
|
||||
ScopedFloatArray output_gains(env, output_gains_array);
|
||||
if (coefficients.data() == nullptr || guide_shifts.data() == nullptr ||
|
||||
if (coefficients.data() == nullptr || model_input.data() == nullptr ||
|
||||
guide_shifts.data() == nullptr ||
|
||||
guide_slopes.data() == nullptr || acr_curve.data() == nullptr ||
|
||||
output_gains.data() == nullptr) {
|
||||
dehaze_curve_values.data() == nullptr || output_gains.data() == nullptr) {
|
||||
LogError("Unable to acquire HDRNet PGTM arrays");
|
||||
return JNI_FALSE;
|
||||
}
|
||||
DehazeCurve dehaze_curve;
|
||||
if (!IsFiniteArray(coefficients.data(), static_cast<int>(coefficient_values)) ||
|
||||
!IsFiniteArray(model_input.data(), static_cast<int>(input_values)) ||
|
||||
!IsFiniteArray(guide_shifts.data(), guide_count) ||
|
||||
!IsFiniteArray(guide_slopes.data(), guide_count) ||
|
||||
!IsValidAcrCurve(acr_curve.data(), acr_curve_count)) {
|
||||
!IsValidAcrCurve(acr_curve.data(), acr_curve_count) ||
|
||||
!ReadDehazeCurve(
|
||||
dehaze_curve_values.data(), kDehazeCurveValueCount, &dehaze_curve)) {
|
||||
LogError("Rejected non-finite HDRNet PGTM input");
|
||||
return JNI_FALSE;
|
||||
}
|
||||
@@ -433,15 +805,30 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeGenerateGains
|
||||
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)] =
|
||||
MakeAxisSample(x, output_grid_width, source_grid_width);
|
||||
model_x_samples[static_cast<size_t>(x)] =
|
||||
MakeAxisSample(x, output_grid_width, input_width);
|
||||
}
|
||||
for (int y = 0; y < output_grid_height; ++y) {
|
||||
y_samples[static_cast<size_t>(y)] =
|
||||
MakeAxisSample(y, output_grid_height, source_grid_height);
|
||||
model_y_samples[static_cast<size_t>(y)] =
|
||||
MakeAxisSample(y, output_grid_height, input_height);
|
||||
}
|
||||
for (int cell = 0; cell < cell_count; ++cell) {
|
||||
const int x = cell % output_grid_width;
|
||||
const int y = cell / output_grid_width;
|
||||
local_model_rgb[static_cast<size_t>(cell)] = SampleModelRgb(
|
||||
model_input.data(), input_width, input_channels,
|
||||
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;
|
||||
@@ -468,6 +855,12 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeGenerateGains
|
||||
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);
|
||||
float* const gain_curve =
|
||||
output_gains.data() + static_cast<size_t>(cell) * point_count;
|
||||
for (int point = 0; point < point_count; ++point) {
|
||||
@@ -504,8 +897,15 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeGenerateGains
|
||||
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(
|
||||
short_intensity * render_gain, 0.0f, 1.0f);
|
||||
DehazedHdrNetTargetLuma(
|
||||
short_intensity, render_gain, cell_rgb, cell_intensity,
|
||||
dehaze_curve) * post_exposure_gain,
|
||||
0.0f, 1.0f);
|
||||
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
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -69,21 +69,6 @@ private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
|
||||
},
|
||||
)
|
||||
|
||||
private fun resolveStoredRawAutoExposure(mode: String?, legacyValue: Boolean?): Boolean {
|
||||
return when {
|
||||
mode.equals("OFF", ignoreCase = true) -> false
|
||||
mode.equals(RawAdaptiveExposureMode.PHOTON_HDR.persistedValue, ignoreCase = true) -> false
|
||||
mode.equals(
|
||||
RawAdaptiveExposureMode.LEGACY_AUTO_EXPOSURE.persistedValue,
|
||||
ignoreCase = true,
|
||||
) -> true
|
||||
// Read the removed thumbnail-matching value as enabled for backward compatibility.
|
||||
mode.equals("VIEWFINDER_MATCH", ignoreCase = true) -> true
|
||||
mode.equals("DYNAMIC_SCENE_ESTIMATION", ignoreCase = true) -> true
|
||||
else -> legacyValue ?: true
|
||||
}
|
||||
}
|
||||
|
||||
enum class VolumeKeyAction {
|
||||
NONE,
|
||||
CAPTURE,
|
||||
@@ -134,7 +119,7 @@ data class UserPreferences(
|
||||
val rawRenderingEngine: RawRenderingEngine = RawRenderingEngine.AdobeCurve,
|
||||
val rawToneMappingParameters: RawToneMappingParameters = RawToneMappingParameters.DEFAULT,
|
||||
val rawExposureCompensation: Float = 0f,
|
||||
val rawAutoExposure: Boolean = true,
|
||||
val rawAutoExposure: Boolean = false,
|
||||
val rawHighlightsAdjustment: Float = 0f,
|
||||
val rawShadowsAdjustment: Float = 0f,
|
||||
val rawMinShutterSpeedNs: Long = 0L,
|
||||
@@ -614,16 +599,12 @@ class UserPreferencesRepository(private val context: Context) {
|
||||
?: RawToneMappingParameters.FILMIC_WHITE_RELATIVE_EXPOSURE_DEFAULT,
|
||||
useProfileToneMap = preferences[RAW_PROFILE_TONE_MAP_KEY] ?: true,
|
||||
useOppoMasterToneMap = preferences[RAW_OPPO_MASTER_TONE_MAP_KEY] ?: false,
|
||||
usePhotonHdr =
|
||||
(preferences[RAW_PHOTON_HDR_KEY] ?: RawToneMappingParameters.PHOTON_HDR_DEFAULT) ||
|
||||
(preferences[LEGACY_RAW_PHOTON_PGTM_TONE_MAP_KEY] ?: false) ||
|
||||
(preferences[LEGACY_PROFILE_TONE_MAP_KEY] ?: false)
|
||||
// Capture development has one supported adaptive-exposure path: HDRNet.
|
||||
// Photo-level metadata may still disable it for an imported DNG.
|
||||
usePhotonHdr = true
|
||||
).normalized(),
|
||||
rawExposureCompensation = preferences[RAW_EXPOSURE_COMPENSATION_KEY] ?: 0f,
|
||||
rawAutoExposure = resolveStoredRawAutoExposure(
|
||||
mode = preferences[RAW_AUTO_EXPOSURE_MODE_KEY],
|
||||
legacyValue = preferences[RAW_AUTO_EXPOSURE_KEY],
|
||||
),
|
||||
rawAutoExposure = false,
|
||||
rawHighlightsAdjustment = preferences[RAW_HIGHLIGHTS_ADJUSTMENT_KEY] ?: 0f,
|
||||
rawShadowsAdjustment = preferences[RAW_SHADOWS_ADJUSTMENT_KEY] ?: 0f,
|
||||
rawMinShutterSpeedNs = preferences[RAW_MIN_SHUTTER_SPEED_NS_KEY] ?: 0L,
|
||||
@@ -1222,7 +1203,7 @@ class UserPreferencesRepository(private val context: Context) {
|
||||
}
|
||||
|
||||
suspend fun saveRawToneMappingParameters(value: RawToneMappingParameters) {
|
||||
val normalized = value.normalized()
|
||||
val normalized = value.withPhotonHdr(true)
|
||||
context.dataStore.edit { preferences ->
|
||||
preferences[RAW_AGX_BLACK_RELATIVE_EXPOSURE_KEY] = normalized.agxBlackRelativeExposure
|
||||
preferences[RAW_AGX_WHITE_RELATIVE_EXPOSURE_KEY] = normalized.agxWhiteRelativeExposure
|
||||
@@ -1235,15 +1216,9 @@ class UserPreferencesRepository(private val context: Context) {
|
||||
preferences[RAW_OPPO_MASTER_TONE_MAP_KEY] = normalized.useOppoMasterToneMap
|
||||
preferences[RAW_PHOTON_HDR_KEY] = normalized.usePhotonHdr
|
||||
preferences[LEGACY_RAW_PHOTON_PGTM_TONE_MAP_KEY] = false
|
||||
val exposureMode = RawAdaptiveExposureMode.resolve(
|
||||
usePhotonHdr = normalized.usePhotonHdr,
|
||||
useLegacyAutoExposure = resolveStoredRawAutoExposure(
|
||||
mode = preferences[RAW_AUTO_EXPOSURE_MODE_KEY],
|
||||
legacyValue = preferences[RAW_AUTO_EXPOSURE_KEY],
|
||||
),
|
||||
)
|
||||
preferences[RAW_AUTO_EXPOSURE_KEY] = exposureMode.usesLegacyAutoExposure
|
||||
preferences[RAW_AUTO_EXPOSURE_MODE_KEY] = exposureMode.persistedValue
|
||||
preferences[RAW_AUTO_EXPOSURE_KEY] = false
|
||||
preferences[RAW_AUTO_EXPOSURE_MODE_KEY] =
|
||||
RawAdaptiveExposureMode.PHOTON_HDR.persistedValue
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1253,37 +1228,18 @@ class UserPreferencesRepository(private val context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveRawAdaptiveExposureMode(mode: RawAdaptiveExposureMode) {
|
||||
context.dataStore.edit { preferences ->
|
||||
preferences[RAW_AUTO_EXPOSURE_KEY] = mode.usesLegacyAutoExposure
|
||||
preferences[RAW_AUTO_EXPOSURE_MODE_KEY] = mode.persistedValue
|
||||
preferences[RAW_PHOTON_HDR_KEY] = mode.usesPhotonHdr
|
||||
preferences[LEGACY_RAW_PHOTON_PGTM_TONE_MAP_KEY] = false
|
||||
preferences[LEGACY_PROFILE_TONE_MAP_KEY] = false
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun restoreCameraStartupDefaultsOnce(): Boolean {
|
||||
var restored = false
|
||||
context.dataStore.edit { preferences ->
|
||||
if (preferences[CAMERA_STARTUP_DEFAULTS_RESTORED_V1] == true) {
|
||||
return@edit
|
||||
}
|
||||
val exposureMode = RawAdaptiveExposureMode.fromPersistedValue(
|
||||
value = preferences[RAW_AUTO_EXPOSURE_MODE_KEY],
|
||||
usePhotonHdr =
|
||||
(preferences[RAW_PHOTON_HDR_KEY]
|
||||
?: RawToneMappingParameters.PHOTON_HDR_DEFAULT) ||
|
||||
(preferences[LEGACY_RAW_PHOTON_PGTM_TONE_MAP_KEY] ?: false) ||
|
||||
(preferences[LEGACY_PROFILE_TONE_MAP_KEY] ?: false),
|
||||
useLegacyAutoExposure = resolveStoredRawAutoExposure(
|
||||
mode = preferences[RAW_AUTO_EXPOSURE_MODE_KEY],
|
||||
legacyValue = preferences[RAW_AUTO_EXPOSURE_KEY],
|
||||
),
|
||||
)
|
||||
preferences[RAW_AUTO_EXPOSURE_KEY] = exposureMode.usesLegacyAutoExposure
|
||||
preferences[RAW_AUTO_EXPOSURE_MODE_KEY] = exposureMode.persistedValue
|
||||
preferences[RAW_PHOTON_HDR_KEY] = exposureMode.usesPhotonHdr
|
||||
preferences[RAW_AUTO_EXPOSURE_KEY] = false
|
||||
preferences[RAW_AUTO_EXPOSURE_MODE_KEY] =
|
||||
RawAdaptiveExposureMode.PHOTON_HDR.persistedValue
|
||||
preferences[RAW_PHOTON_HDR_KEY] = true
|
||||
preferences[LEGACY_RAW_PHOTON_PGTM_TONE_MAP_KEY] = false
|
||||
preferences[LEGACY_PROFILE_TONE_MAP_KEY] = false
|
||||
preferences[CAMERA_STARTUP_DEFAULTS_RESTORED_V1] = true
|
||||
restored = true
|
||||
}
|
||||
@@ -2395,7 +2351,7 @@ class UserPreferencesRepository(private val context: Context) {
|
||||
preferences[RAW_COLOR_ENGINE_KEY] = it.value.name
|
||||
}
|
||||
update.rawToneMappingParameters?.let {
|
||||
val normalized = it.value.normalized()
|
||||
val normalized = it.value.withPhotonHdr(true)
|
||||
preferences[RAW_AGX_BLACK_RELATIVE_EXPOSURE_KEY] = normalized.agxBlackRelativeExposure
|
||||
preferences[RAW_AGX_WHITE_RELATIVE_EXPOSURE_KEY] = normalized.agxWhiteRelativeExposure
|
||||
preferences[RAW_AGX_TOE_KEY] = normalized.agxToe
|
||||
@@ -2406,15 +2362,9 @@ class UserPreferencesRepository(private val context: Context) {
|
||||
preferences[RAW_OPPO_MASTER_TONE_MAP_KEY] = normalized.useOppoMasterToneMap
|
||||
preferences[RAW_PHOTON_HDR_KEY] = normalized.usePhotonHdr
|
||||
preferences[LEGACY_RAW_PHOTON_PGTM_TONE_MAP_KEY] = false
|
||||
val exposureMode = RawAdaptiveExposureMode.resolve(
|
||||
usePhotonHdr = normalized.usePhotonHdr,
|
||||
useLegacyAutoExposure = resolveStoredRawAutoExposure(
|
||||
mode = preferences[RAW_AUTO_EXPOSURE_MODE_KEY],
|
||||
legacyValue = preferences[RAW_AUTO_EXPOSURE_KEY],
|
||||
),
|
||||
)
|
||||
preferences[RAW_AUTO_EXPOSURE_KEY] = exposureMode.usesLegacyAutoExposure
|
||||
preferences[RAW_AUTO_EXPOSURE_MODE_KEY] = exposureMode.persistedValue
|
||||
preferences[RAW_AUTO_EXPOSURE_KEY] = false
|
||||
preferences[RAW_AUTO_EXPOSURE_MODE_KEY] =
|
||||
RawAdaptiveExposureMode.PHOTON_HDR.persistedValue
|
||||
}
|
||||
update.rawMaxSharpening?.let {
|
||||
preferences[RAW_MAX_SHARPENING_KEY] = RawSharpeningDefaults.normalize(it.value)
|
||||
@@ -2429,16 +2379,11 @@ class UserPreferencesRepository(private val context: Context) {
|
||||
update.rawExposureCompensation?.let {
|
||||
preferences[RAW_EXPOSURE_COMPENSATION_KEY] = it.value.coerceIn(-4f, 4f)
|
||||
}
|
||||
update.rawAutoExposure?.let {
|
||||
val exposureMode = when {
|
||||
it.value -> RawAdaptiveExposureMode.LEGACY_AUTO_EXPOSURE
|
||||
preferences[RAW_PHOTON_HDR_KEY] == true ->
|
||||
RawAdaptiveExposureMode.PHOTON_HDR
|
||||
else -> RawAdaptiveExposureMode.OFF
|
||||
}
|
||||
preferences[RAW_AUTO_EXPOSURE_KEY] = exposureMode.usesLegacyAutoExposure
|
||||
preferences[RAW_AUTO_EXPOSURE_MODE_KEY] = exposureMode.persistedValue
|
||||
preferences[RAW_PHOTON_HDR_KEY] = exposureMode.usesPhotonHdr
|
||||
if (update.rawAutoExposure != null) {
|
||||
preferences[RAW_AUTO_EXPOSURE_KEY] = false
|
||||
preferences[RAW_AUTO_EXPOSURE_MODE_KEY] =
|
||||
RawAdaptiveExposureMode.PHOTON_HDR.persistedValue
|
||||
preferences[RAW_PHOTON_HDR_KEY] = true
|
||||
}
|
||||
update.rawHighlightsAdjustment?.let {
|
||||
preferences[RAW_HIGHLIGHTS_ADJUSTMENT_KEY] = it.value.coerceIn(-1f, 1f)
|
||||
|
||||
@@ -64,7 +64,7 @@ import com.hinnka.mycamera.raw.RawDenoiseDefaults
|
||||
import com.hinnka.mycamera.raw.RawSharpeningDefaults
|
||||
import com.hinnka.mycamera.raw.RawAdaptiveExposureMode
|
||||
import com.hinnka.mycamera.raw.RawCaptureProfileCoordinator
|
||||
import com.hinnka.mycamera.raw.RawPhotonHdrRatioMetadata
|
||||
import com.hinnka.mycamera.raw.RawPhotonHdrMetadata
|
||||
import com.hinnka.mycamera.raw.RawProfileToneMapMode
|
||||
import com.hinnka.mycamera.raw.SpectralFilmTuning
|
||||
import com.hinnka.mycamera.raw.RawToneMappingParameters
|
||||
@@ -276,7 +276,8 @@ object GalleryManager {
|
||||
?: repository.getAvailableLuts().firstOrNull { it.isDefault }?.id
|
||||
val baselineLutId = preferences?.rawBaselineLutId
|
||||
val rawToneMappingParameters =
|
||||
(preferences?.rawToneMappingParameters ?: RawToneMappingParameters.DEFAULT).normalized()
|
||||
(preferences?.rawToneMappingParameters ?: RawToneMappingParameters.DEFAULT)
|
||||
.withPhotonHdr(true)
|
||||
val spectralFilmStock = preferences?.rawSpectralFilmStock ?: "kodak_portra_400"
|
||||
val spectralFilmTuning = (
|
||||
preferences?.rawSpectralFilmTuningsByStock?.get(spectralFilmStock)
|
||||
@@ -304,7 +305,7 @@ object GalleryManager {
|
||||
chromaNoiseReduction = rawChromaNoiseReduction,
|
||||
rawDcpId = preferences?.rawDcpIdForLens(null),
|
||||
rawExposureCompensation = preferences?.rawExposureCompensation ?: 0f,
|
||||
rawAutoExposure = preferences?.rawAutoExposure ?: true,
|
||||
rawAutoExposure = false,
|
||||
rawHighlightsAdjustment = preferences?.rawHighlightsAdjustment ?: 0f,
|
||||
rawShadowsAdjustment = preferences?.rawShadowsAdjustment ?: 0f,
|
||||
rawBlackPointCorrection = preferences?.rawBlackPointCorrection ?: 0f,
|
||||
@@ -2255,10 +2256,11 @@ object GalleryManager {
|
||||
) ?: return@withContext
|
||||
preparedDemosaicSourceToRelease = preparedProfile.gpuDemosaicedRawSource
|
||||
updatedMetadata = updatedMetadata.copy(
|
||||
customProperties = RawPhotonHdrRatioMetadata.write(
|
||||
customProperties = RawPhotonHdrMetadata.write(
|
||||
updatedMetadata.customProperties,
|
||||
preparedProfile.hdrRatio,
|
||||
preparedProfile.finalShortGain,
|
||||
preparedProfile.hdrNetPostExposureEv,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -3557,10 +3559,11 @@ object GalleryManager {
|
||||
return@withContext
|
||||
}
|
||||
updatedMetadata = updatedMetadata.copy(
|
||||
customProperties = RawPhotonHdrRatioMetadata.write(
|
||||
customProperties = RawPhotonHdrMetadata.write(
|
||||
updatedMetadata.customProperties,
|
||||
dngProfilePreparation.hdrRatio,
|
||||
dngProfilePreparation.finalShortGain,
|
||||
dngProfilePreparation.hdrNetPostExposureEv,
|
||||
),
|
||||
)
|
||||
val profileElapsedMs = System.currentTimeMillis() - profileStartMs
|
||||
@@ -5623,10 +5626,13 @@ object GalleryManager {
|
||||
rawRenderingEngine = updatedMetadata?.rawRenderingEngine ?: MediaMetadata().rawRenderingEngine,
|
||||
rawToneMappingParameters = updatedMetadata?.rawToneMappingParameters ?: MediaMetadata().rawToneMappingParameters,
|
||||
forceRegeneratePhotonPgtm = forceRegeneratePhotonPgtm,
|
||||
photonHdrRatio = RawPhotonHdrRatioMetadata.read(
|
||||
photonHdrRatio = RawPhotonHdrMetadata.read(
|
||||
rawMetadata.customProperties,
|
||||
),
|
||||
photonSourceToShortGain = RawPhotonHdrRatioMetadata.readFinalShortGain(
|
||||
photonSourceToShortGain = RawPhotonHdrMetadata.readFinalShortGain(
|
||||
rawMetadata.customProperties,
|
||||
),
|
||||
photonHdrNetPostExposureEv = RawPhotonHdrMetadata.readPostExposureEv(
|
||||
rawMetadata.customProperties,
|
||||
),
|
||||
rawCfaCorrectionMode = updatedMetadata?.rawCfaCorrectionMode,
|
||||
|
||||
@@ -11,7 +11,7 @@ package com.hinnka.mycamera.processor
|
||||
data class PhotonCoreImagingTuning(
|
||||
val fusion: PhotonFusionTuning = PhotonFusionTuning.DEFAULT,
|
||||
val denoise: PhotonDenoiseTuning = PhotonDenoiseTuning.DEFAULT,
|
||||
/** Controls the standalone low-frequency dehaze pipeline. */
|
||||
/** Controls Dehaze + DHA baked into HDRNet's ProfileGainTableMap output. */
|
||||
val dehaze: PhotonDehazeTuning = PhotonDehazeTuning.DEFAULT,
|
||||
) {
|
||||
fun normalized(): PhotonCoreImagingTuning = copy(
|
||||
@@ -345,7 +345,7 @@ data class PhotonSabreLumaTuningNodes(
|
||||
}
|
||||
|
||||
/**
|
||||
* Controls for the standalone low-frequency dehaze pipeline.
|
||||
* Controls for Dehaze + DHA applied to HDRNet output and baked into its PGTM.
|
||||
*
|
||||
* [strength] scales the two estimated atmospheric haze points before curve construction.
|
||||
* [dynamicHighlightStrength] controls how much of the histogram-derived highlight scale is used;
|
||||
@@ -369,19 +369,10 @@ data class PhotonDehazeTuning(
|
||||
|
||||
val isActive: Boolean
|
||||
get() = normalized().let {
|
||||
PROCESSING_ENABLED &&
|
||||
it.enabled && (it.strength > 0f || it.dynamicHighlightStrength > 0f)
|
||||
it.enabled && (it.strength > 0f || it.dynamicHighlightStrength > 0f)
|
||||
}
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* Temporary master gate for the standalone Dehaze stage.
|
||||
*
|
||||
* Keep persisted tuning intact so captures and presets remain forward-compatible, while
|
||||
* every render/metering path observes the same disabled state until the stage is restored.
|
||||
*/
|
||||
const val PROCESSING_ENABLED = false
|
||||
|
||||
val DEFAULT = PhotonDehazeTuning()
|
||||
val DISABLED = PhotonDehazeTuning(enabled = false)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import com.hinnka.mycamera.processor.PhotonDehazeTuning
|
||||
|
||||
/** Native hot path for converting HDRNet's bilateral grid into a dense PGTM gain table. */
|
||||
internal object DngHdrNetProfileGainTableNative {
|
||||
init {
|
||||
@@ -9,6 +11,7 @@ internal object DngHdrNetProfileGainTableNative {
|
||||
fun generateGains(
|
||||
plan: HdrNetProfileGainTablePlan,
|
||||
coefficients: FloatArray,
|
||||
modelInput: FloatArray,
|
||||
guideShifts: FloatArray,
|
||||
guideSlopes: FloatArray,
|
||||
acr3Curve: FloatArray,
|
||||
@@ -17,12 +20,19 @@ internal object DngHdrNetProfileGainTableNative {
|
||||
renderMaxGainBlendThreshold: Float,
|
||||
minTableGain: Float,
|
||||
maxTableGain: Float,
|
||||
dehazeCurve: PhotonDehazeCurveParameters,
|
||||
postExposureGain: Float,
|
||||
): FloatArray? {
|
||||
if (!postExposureGain.isFinite() || postExposureGain <= 0f) return null
|
||||
val outputCount = plan.cellCount.toLong() * plan.pointCount
|
||||
if (outputCount !in 1..Int.MAX_VALUE.toLong()) return null
|
||||
val output = FloatArray(outputCount.toInt())
|
||||
val completed = nativeGenerateGains(
|
||||
coefficients = coefficients,
|
||||
modelInput = modelInput,
|
||||
inputWidth = DngPhotonProfileGainTableGenerator.HDRNET_INPUT_WIDTH,
|
||||
inputHeight = DngPhotonProfileGainTableGenerator.HDRNET_INPUT_HEIGHT,
|
||||
inputChannels = HDRNET_INPUT_CHANNELS,
|
||||
sourceGridWidth = DngPhotonProfileGainTableGenerator.HDRNET_GRID_WIDTH,
|
||||
sourceGridHeight = DngPhotonProfileGainTableGenerator.HDRNET_GRID_HEIGHT,
|
||||
sourceGridDepth = DngPhotonProfileGainTableGenerator.HDRNET_GRID_DEPTH,
|
||||
@@ -41,12 +51,21 @@ internal object DngHdrNetProfileGainTableNative {
|
||||
guideShifts = guideShifts,
|
||||
guideSlopes = guideSlopes,
|
||||
acr3Curve = acr3Curve,
|
||||
dehazeCurve = dehazeCurve.toNativeArray(),
|
||||
postExposureGain = postExposureGain,
|
||||
outputGains = output,
|
||||
)
|
||||
return output.takeIf { completed }
|
||||
}
|
||||
|
||||
fun evaluateDisplayLinearLumaGrid(
|
||||
data class Evaluation(
|
||||
val displayLinearLumas: FloatArray,
|
||||
val dehazeCurve: PhotonDehazeCurveParameters,
|
||||
/** Full 256 x 192 post-Dehaze/DHA p99 maximum RGB channel. */
|
||||
val postDehazeP99Peak: Float,
|
||||
)
|
||||
|
||||
fun evaluateDehazedDisplayLinearLumaGrid(
|
||||
plan: HdrNetProfileGainTablePlan,
|
||||
coefficients: FloatArray,
|
||||
modelInput: FloatArray,
|
||||
@@ -55,13 +74,17 @@ internal object DngHdrNetProfileGainTableNative {
|
||||
guideSlopes: FloatArray,
|
||||
renderMinGain: Float,
|
||||
renderMaxGain: Float,
|
||||
renderMaxGainBlendThreshold: Float,
|
||||
dehazeTuning: PhotonDehazeTuning,
|
||||
outputGridWidth: Int,
|
||||
outputGridHeight: Int,
|
||||
footprintSamplesPerAxis: Int,
|
||||
): FloatArray? {
|
||||
): Evaluation? {
|
||||
val outputCount = outputGridWidth.toLong() * outputGridHeight
|
||||
if (outputCount !in 1..Int.MAX_VALUE.toLong()) return null
|
||||
val output = FloatArray(outputCount.toInt())
|
||||
val curveValues = FloatArray(PhotonDehazeCurveParameters.NATIVE_VALUE_COUNT)
|
||||
val metrics = FloatArray(EVALUATION_METRIC_COUNT)
|
||||
val normalizedTuning = dehazeTuning.normalized()
|
||||
val completed = nativeEvaluateDisplayLinearLumaGrid(
|
||||
coefficients = coefficients,
|
||||
sourceGridWidth = DngPhotonProfileGainTableGenerator.HDRNET_GRID_WIDTH,
|
||||
@@ -74,16 +97,30 @@ internal object DngHdrNetProfileGainTableNative {
|
||||
inputChannels = HDRNET_INPUT_CHANNELS,
|
||||
outputGridWidth = outputGridWidth,
|
||||
outputGridHeight = outputGridHeight,
|
||||
footprintSamplesPerAxis = footprintSamplesPerAxis,
|
||||
hdrRatio = plan.hdrRatio,
|
||||
renderMinGain = renderMinGain,
|
||||
renderMaxGain = renderMaxGain,
|
||||
renderMaxGainBlendThreshold = renderMaxGainBlendThreshold,
|
||||
dehazeEnabled = normalizedTuning.isActive,
|
||||
dehazeStrength = normalizedTuning.strength,
|
||||
dynamicHighlightStrength = normalizedTuning.dynamicHighlightStrength,
|
||||
outputRotation = outputRotation,
|
||||
guideShifts = guideShifts,
|
||||
guideSlopes = guideSlopes,
|
||||
outputLumas = output,
|
||||
outputDehazeCurve = curveValues,
|
||||
outputMetrics = metrics,
|
||||
)
|
||||
if (!completed) return null
|
||||
val curve = PhotonDehazeCurveParameters.fromNativeArray(curveValues) ?: return null
|
||||
val postDehazeP99Peak = metrics[METRIC_POST_DEHAZE_P99_PEAK]
|
||||
.takeIf { it.isFinite() && it in 0f..1f }
|
||||
?: return null
|
||||
return Evaluation(
|
||||
displayLinearLumas = output,
|
||||
dehazeCurve = curve,
|
||||
postDehazeP99Peak = postDehazeP99Peak,
|
||||
)
|
||||
return output.takeIf { completed }
|
||||
}
|
||||
|
||||
private external fun nativeEvaluateDisplayLinearLumaGrid(
|
||||
@@ -98,18 +135,27 @@ internal object DngHdrNetProfileGainTableNative {
|
||||
inputChannels: Int,
|
||||
outputGridWidth: Int,
|
||||
outputGridHeight: Int,
|
||||
footprintSamplesPerAxis: Int,
|
||||
hdrRatio: Float,
|
||||
renderMinGain: Float,
|
||||
renderMaxGain: Float,
|
||||
renderMaxGainBlendThreshold: Float,
|
||||
dehazeEnabled: Boolean,
|
||||
dehazeStrength: Float,
|
||||
dynamicHighlightStrength: Float,
|
||||
outputRotation: Int,
|
||||
guideShifts: FloatArray,
|
||||
guideSlopes: FloatArray,
|
||||
outputLumas: FloatArray,
|
||||
outputDehazeCurve: FloatArray,
|
||||
outputMetrics: FloatArray,
|
||||
): Boolean
|
||||
|
||||
private external fun nativeGenerateGains(
|
||||
coefficients: FloatArray,
|
||||
modelInput: FloatArray,
|
||||
inputWidth: Int,
|
||||
inputHeight: Int,
|
||||
inputChannels: Int,
|
||||
sourceGridWidth: Int,
|
||||
sourceGridHeight: Int,
|
||||
sourceGridDepth: Int,
|
||||
@@ -128,8 +174,12 @@ internal object DngHdrNetProfileGainTableNative {
|
||||
guideShifts: FloatArray,
|
||||
guideSlopes: FloatArray,
|
||||
acr3Curve: FloatArray,
|
||||
dehazeCurve: FloatArray,
|
||||
postExposureGain: Float,
|
||||
outputGains: FloatArray,
|
||||
): Boolean
|
||||
|
||||
private const val HDRNET_INPUT_CHANNELS = 4
|
||||
private const val EVALUATION_METRIC_COUNT = 1
|
||||
private const val METRIC_POST_DEHAZE_P99_PEAK = 0
|
||||
}
|
||||
@@ -1354,6 +1354,8 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
val outputRotation: Int,
|
||||
val hdrRatio: Float,
|
||||
val sourceToShortGain: Float,
|
||||
/** Persisted downstream HDRNet exposure used when regenerating without a viewfinder. */
|
||||
val hdrNetPostExposureEv: Float? = null,
|
||||
val colorCorrectionMatrix: FloatArray,
|
||||
val hueSatMap: DcpHueSatMap?,
|
||||
val hueSatMapSupportsOverrange: Boolean,
|
||||
@@ -1372,6 +1374,7 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
val map: DngProfileGainTableMap,
|
||||
val hdrRatio: Float? = null,
|
||||
val sourceToShortGain: Float? = null,
|
||||
val hdrNetPostExposureEv: Float? = null,
|
||||
)
|
||||
|
||||
private data class GpuPhotonGainCurves(
|
||||
@@ -1379,11 +1382,6 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
val textureId: Int,
|
||||
)
|
||||
|
||||
private data class HdrNetInferenceCandidate(
|
||||
val plan: HdrNetProfileGainTablePlan,
|
||||
val coefficients: FloatArray,
|
||||
)
|
||||
|
||||
private var cellSamplesProgram = 0
|
||||
private val photonPrograms = IntArray(DngPhotonLocalToneMapGpuShaders.Pass.entries.size)
|
||||
private var hdrNetInputProgram = 0
|
||||
@@ -1590,109 +1588,111 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
GLES31.glGetUniformLocation(hdrNetInputProgram, "uWarpCount"),
|
||||
activeWarpParameters.size / 8,
|
||||
)
|
||||
val baseShortGain = basePlan.sourceToShortGain
|
||||
val baseLongGain = baseShortGain * basePlan.hdrRatio
|
||||
val dehazeTuning = input.metadata.coreImagingTuning.dehaze.normalized()
|
||||
val modelInputBuffer = ByteBuffer.allocateDirect(inputFloatCount * Float.SIZE_BYTES)
|
||||
.order(ByteOrder.nativeOrder())
|
||||
val modelOutputBuffer = ByteBuffer.allocateDirect(
|
||||
DngPhotonProfileGainTableGenerator.HDRNET_OUTPUT_FLOAT_COUNT * Float.SIZE_BYTES,
|
||||
).order(ByteOrder.nativeOrder())
|
||||
|
||||
fun planCandidate(shortGain: Float, longGain: Float): HdrNetProfileGainTablePlan? {
|
||||
if (!shortGain.isFinite() || !longGain.isFinite() ||
|
||||
shortGain <= 0f || longGain < shortGain
|
||||
) return null
|
||||
val candidateHdrRatio = longGain / shortGain
|
||||
if (!candidateHdrRatio.isFinite() || candidateHdrRatio < 1f) return null
|
||||
return DngPhotonProfileGainTableGenerator.hdrNetPlan(
|
||||
rendererBaselineExposureEv = input.rendererBaselineExposureEv,
|
||||
hdrRatio = candidateHdrRatio,
|
||||
sourceToShortGain = shortGain,
|
||||
samplingArea = samplingArea,
|
||||
)
|
||||
val plan = basePlan
|
||||
GLES31.glUseProgram(hdrNetInputProgram)
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, bufferIds[0])
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, bufferIds[1])
|
||||
GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + LINEAR_RGB_TEXTURE_UNIT)
|
||||
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, linearRgbTextureId)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(hdrNetInputProgram, "uSourceToShortGain"),
|
||||
plan.sourceToShortGain,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(hdrNetInputProgram, "uHdrRatio"),
|
||||
plan.hdrRatio,
|
||||
)
|
||||
GLES31.glDispatchCompute(
|
||||
GlesComputeWorkGroup.imageGroupCount(
|
||||
DngPhotonProfileGainTableGenerator.HDRNET_INPUT_WIDTH,
|
||||
),
|
||||
GlesComputeWorkGroup.imageGroupCount(
|
||||
DngPhotonProfileGainTableGenerator.HDRNET_INPUT_HEIGHT,
|
||||
),
|
||||
1,
|
||||
)
|
||||
GLES31.glMemoryBarrier(
|
||||
GLES31.GL_SHADER_STORAGE_BARRIER_BIT or GLES31.GL_BUFFER_UPDATE_BARRIER_BIT,
|
||||
)
|
||||
RawGlesProgram.logErrors("prepare HDRNet input")
|
||||
val modelInput = readFloatStorageBuffer(
|
||||
bufferId = bufferIds[0],
|
||||
floatCount = inputFloatCount,
|
||||
label = "HDRNet input",
|
||||
) ?: return null
|
||||
if (modelInput.any { !it.isFinite() }) {
|
||||
PLog.e(TAG, "HDRNet input contains a non-finite value")
|
||||
return null
|
||||
}
|
||||
|
||||
fun runCandidate(
|
||||
shortGain: Float,
|
||||
longGain: Float,
|
||||
): Pair<HdrNetInferenceCandidate, FloatArray>? {
|
||||
val candidatePlan = planCandidate(shortGain, longGain) ?: return null
|
||||
|
||||
GLES31.glUseProgram(hdrNetInputProgram)
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, bufferIds[0])
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, bufferIds[1])
|
||||
GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + LINEAR_RGB_TEXTURE_UNIT)
|
||||
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, linearRgbTextureId)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(hdrNetInputProgram, "uSourceToShortGain"),
|
||||
candidatePlan.sourceToShortGain,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(hdrNetInputProgram, "uHdrRatio"),
|
||||
candidatePlan.hdrRatio,
|
||||
)
|
||||
GLES31.glDispatchCompute(
|
||||
GlesComputeWorkGroup.imageGroupCount(
|
||||
DngPhotonProfileGainTableGenerator.HDRNET_INPUT_WIDTH,
|
||||
),
|
||||
GlesComputeWorkGroup.imageGroupCount(
|
||||
DngPhotonProfileGainTableGenerator.HDRNET_INPUT_HEIGHT,
|
||||
),
|
||||
1,
|
||||
)
|
||||
GLES31.glMemoryBarrier(
|
||||
GLES31.GL_SHADER_STORAGE_BARRIER_BIT or GLES31.GL_BUFFER_UPDATE_BARRIER_BIT,
|
||||
)
|
||||
RawGlesProgram.logErrors("prepare HDRNet input")
|
||||
val inputFloats = readFloatStorageBuffer(
|
||||
bufferId = bufferIds[0],
|
||||
floatCount = inputFloatCount,
|
||||
label = "HDRNet input",
|
||||
) ?: return null
|
||||
if (inputFloats.any { !it.isFinite() }) {
|
||||
PLog.e(TAG, "HDRNet input contains a non-finite value")
|
||||
return null
|
||||
}
|
||||
modelInputBuffer.clear()
|
||||
modelInputBuffer.asFloatBuffer().put(inputFloats)
|
||||
modelInputBuffer.rewind()
|
||||
modelOutputBuffer.clear()
|
||||
interpreter.run(modelInputBuffer, modelOutputBuffer)
|
||||
modelOutputBuffer.rewind()
|
||||
val coefficients = FloatArray(
|
||||
DngPhotonProfileGainTableGenerator.HDRNET_OUTPUT_FLOAT_COUNT,
|
||||
)
|
||||
modelOutputBuffer.asFloatBuffer().get(coefficients)
|
||||
val displayLinearLumaGrid =
|
||||
DngPhotonProfileGainTableGenerator.hdrNetDisplayLinearLumaGrid(
|
||||
plan = candidatePlan,
|
||||
coefficients = coefficients,
|
||||
modelInput = inputFloats,
|
||||
outputRotation = input.outputRotation,
|
||||
)
|
||||
if (displayLinearLumaGrid == null) return null
|
||||
return HdrNetInferenceCandidate(
|
||||
plan = candidatePlan,
|
||||
coefficients = coefficients,
|
||||
) to displayLinearLumaGrid
|
||||
}
|
||||
|
||||
val exposureResult = input.viewfinderReference?.let { reference ->
|
||||
RawLegacyAutoExposureMatcher.solveHdrNetExposure(
|
||||
modelInputBuffer.clear()
|
||||
modelInputBuffer.asFloatBuffer().put(modelInput)
|
||||
modelInputBuffer.rewind()
|
||||
modelOutputBuffer.clear()
|
||||
interpreter.run(modelInputBuffer, modelOutputBuffer)
|
||||
modelOutputBuffer.rewind()
|
||||
val coefficients = FloatArray(
|
||||
DngPhotonProfileGainTableGenerator.HDRNET_OUTPUT_FLOAT_COUNT,
|
||||
)
|
||||
modelOutputBuffer.asFloatBuffer().get(coefficients)
|
||||
val evaluation = DngPhotonProfileGainTableGenerator.evaluateHdrNetDehaze(
|
||||
plan = plan,
|
||||
coefficients = coefficients,
|
||||
modelInput = modelInput,
|
||||
outputRotation = input.outputRotation,
|
||||
dehazeTuning = dehazeTuning,
|
||||
) ?: return null
|
||||
val maximumPostExposureEv = hdrNetPostExposureLimitEv(
|
||||
evaluation.postDehazeP99Peak,
|
||||
)
|
||||
val match = input.viewfinderReference?.let { reference ->
|
||||
RawLegacyAutoExposureMatcher.solveHdrNetPostExposure(
|
||||
referenceFrame = reference,
|
||||
initialShortGain = baseShortGain,
|
||||
initialLongGain = baseLongGain,
|
||||
evaluateCandidate = ::runCandidate,
|
||||
displayLinearLumas = evaluation.displayLinearLumas,
|
||||
maximumExposureEv = maximumPostExposureEv,
|
||||
)
|
||||
}
|
||||
val selectedCandidate = exposureResult
|
||||
?: runCandidate(baseShortGain, baseLongGain)?.first
|
||||
?: return null
|
||||
val plan = selectedCandidate.plan
|
||||
val coefficients = selectedCandidate.coefficients
|
||||
val restoredPostExposureEv = input.hdrNetPostExposureEv
|
||||
?.takeIf(Float::isFinite)
|
||||
?.coerceIn(
|
||||
MeteringSystem.RAW_EXPOSURE_MIN_EV,
|
||||
maximumPostExposureEv,
|
||||
)
|
||||
val postExposureEv = match?.exposureEv ?: restoredPostExposureEv ?: 0f
|
||||
val postExposureSource = when {
|
||||
match != null -> "VIEWFINDER_MATCH"
|
||||
restoredPostExposureEv != null -> "PERSISTED_CAPTURE_MATCH"
|
||||
else -> "NONE"
|
||||
}
|
||||
PLog.i(
|
||||
TAG,
|
||||
"HDRNET_MATCH stage=SELECTED shortGain=${plan.sourceToShortGain} " +
|
||||
"hdrRatio=${plan.hdrRatio} " +
|
||||
"postExposureEv=$postExposureEv " +
|
||||
"postExposureSource=$postExposureSource " +
|
||||
"maximumPostExposureEv=$maximumPostExposureEv " +
|
||||
"matchRate=${match?.matchRate} " +
|
||||
"meanAbsoluteErrorEv=${match?.meanAbsoluteErrorEv} " +
|
||||
"postDehazeP99Peak=${evaluation.postDehazeP99Peak} " +
|
||||
"dehazeActive=${dehazeTuning.isActive} " +
|
||||
"dehazeLow=${evaluation.dehazeCurve.hazePointLow} " +
|
||||
"dehazeHigh=${evaluation.dehazeCurve.hazePointHigh} " +
|
||||
"dhaScale=${evaluation.dehazeCurve.highlightScale} " +
|
||||
"dhaDetected=${evaluation.dehazeCurve.detectedHighlightScale} " +
|
||||
"dehazeSamples=${evaluation.dehazeCurve.sampledPixelCount}",
|
||||
)
|
||||
val map = DngPhotonProfileGainTableGenerator.mapFromHdrNetCoefficients(
|
||||
plan = plan,
|
||||
coefficients = coefficients,
|
||||
modelInput = modelInput,
|
||||
dehazeCurve = evaluation.dehazeCurve,
|
||||
postExposureEv = postExposureEv,
|
||||
) ?: return null
|
||||
val textureId = uploadProfileGainTableTexture(map) ?: return null
|
||||
try {
|
||||
@@ -1705,6 +1705,7 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
map = map,
|
||||
hdrRatio = plan.hdrRatio,
|
||||
sourceToShortGain = plan.sourceToShortGain,
|
||||
hdrNetPostExposureEv = postExposureEv,
|
||||
)
|
||||
} catch (error: Throwable) {
|
||||
PLog.e(TAG, "HDRNet ProfileGainTableMap generation failed", error)
|
||||
@@ -3061,5 +3062,14 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
const val HUE_SAT_TEXTURE_UNIT = 3
|
||||
const val GLES31_MIN_SSBO_BYTES = 16L * 1024L * 1024L
|
||||
const val STREAMING_TILE_CORE_EDGE_PX = 3072
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import com.hinnka.mycamera.processor.PhotonDehazeTuning
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import kotlin.math.ln
|
||||
|
||||
@@ -168,11 +169,17 @@ internal object DngPhotonProfileGainTableGenerator {
|
||||
* DNG can only apply a scalar multiplicative gain, so each spatial cell's affine response is
|
||||
* resampled to 64 x 48 and converted into a 257-point gain curve per cell. The range
|
||||
* coordinate uses MGC's learned 16-segment luma guide from guide_coeffs.pb before trilinear
|
||||
* sampling of the bilateral grid.
|
||||
* 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.
|
||||
*/
|
||||
fun mapFromHdrNetCoefficients(
|
||||
plan: HdrNetProfileGainTablePlan,
|
||||
coefficients: FloatArray,
|
||||
modelInput: FloatArray,
|
||||
dehazeCurve: PhotonDehazeCurveParameters,
|
||||
postExposureEv: Float,
|
||||
): DngProfileGainTableMap? {
|
||||
if (coefficients.size != HDRNET_OUTPUT_FLOAT_COUNT) {
|
||||
PLog.e(
|
||||
@@ -181,9 +188,12 @@ internal object DngPhotonProfileGainTableGenerator {
|
||||
)
|
||||
return null
|
||||
}
|
||||
if (modelInput.size != HDRNET_INPUT_WIDTH * HDRNET_INPUT_HEIGHT * 4) return null
|
||||
if (!postExposureEv.isFinite()) return null
|
||||
val gains = DngHdrNetProfileGainTableNative.generateGains(
|
||||
plan = plan,
|
||||
coefficients = coefficients,
|
||||
modelInput = modelInput,
|
||||
guideShifts = HDRNET_GUIDE_SHIFTS,
|
||||
guideSlopes = HDRNET_GUIDE_SLOPES,
|
||||
acr3Curve = ACR3Curve.samples(),
|
||||
@@ -192,6 +202,8 @@ internal object DngPhotonProfileGainTableGenerator {
|
||||
renderMaxGainBlendThreshold = HDRNET_RENDER_MAX_GAIN_BLEND_THRESHOLD,
|
||||
minTableGain = MIN_TABLE_GAIN,
|
||||
maxTableGain = MAX_TABLE_GAIN,
|
||||
dehazeCurve = dehazeCurve,
|
||||
postExposureGain = DngBaselineExposure.exactGain(postExposureEv),
|
||||
) ?: run {
|
||||
PLog.e(TAG, "Native HDRNet ProfileGainTableMap generation failed")
|
||||
return null
|
||||
@@ -223,22 +235,22 @@ internal object DngPhotonProfileGainTableGenerator {
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluates HDRNet across the complete image on the 8 x 6 matching grid and returns clipped
|
||||
* display-linear Rec.709 luma. This is the same post-EOTF domain built from the classic
|
||||
* matcher's ARGB_8888 candidate and reference images.
|
||||
* Builds Dehaze + DHA from the complete 256 x 192 HDRNet candidate, then evaluates the
|
||||
* composed output on the 8 x 6 display-linear Rec.709 matching grid.
|
||||
*/
|
||||
fun hdrNetDisplayLinearLumaGrid(
|
||||
fun evaluateHdrNetDehaze(
|
||||
plan: HdrNetProfileGainTablePlan,
|
||||
coefficients: FloatArray,
|
||||
modelInput: FloatArray,
|
||||
outputRotation: Int,
|
||||
): FloatArray? {
|
||||
dehazeTuning: PhotonDehazeTuning,
|
||||
): DngHdrNetProfileGainTableNative.Evaluation? {
|
||||
if (coefficients.size != HDRNET_OUTPUT_FLOAT_COUNT) return null
|
||||
val expectedInputCount = HDRNET_INPUT_WIDTH * HDRNET_INPUT_HEIGHT * 4
|
||||
if (modelInput.size != expectedInputCount) return null
|
||||
val rotation = ((outputRotation % 360) + 360) % 360
|
||||
if (rotation != 0 && rotation != 90 && rotation != 180 && rotation != 270) return null
|
||||
return DngHdrNetProfileGainTableNative.evaluateDisplayLinearLumaGrid(
|
||||
return DngHdrNetProfileGainTableNative.evaluateDehazedDisplayLinearLumaGrid(
|
||||
plan = plan,
|
||||
coefficients = coefficients,
|
||||
modelInput = modelInput,
|
||||
@@ -247,14 +259,13 @@ internal object DngPhotonProfileGainTableGenerator {
|
||||
guideSlopes = HDRNET_GUIDE_SLOPES,
|
||||
renderMinGain = HDRNET_RENDER_MIN_GAIN,
|
||||
renderMaxGain = HDRNET_RENDER_MAX_GAIN,
|
||||
renderMaxGainBlendThreshold = HDRNET_RENDER_MAX_GAIN_BLEND_THRESHOLD,
|
||||
dehazeTuning = dehazeTuning,
|
||||
outputGridWidth = HDRNET_MATCH_GRID_WIDTH,
|
||||
outputGridHeight = HDRNET_MATCH_GRID_HEIGHT,
|
||||
footprintSamplesPerAxis = HDRNET_MATCH_FOOTPRINT_SAMPLES_PER_AXIS,
|
||||
)
|
||||
}
|
||||
|
||||
private const val HDRNET_MATCH_FOOTPRINT_SAMPLES_PER_AXIS = 4
|
||||
|
||||
fun plan(
|
||||
width: Int,
|
||||
height: Int,
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import com.hinnka.mycamera.processor.PhotonDehazeTuning
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/** Parameters for the chromaticity-preserving low-frequency dehaze curve. */
|
||||
@@ -28,193 +25,57 @@ internal data class PhotonDehazeCurveParameters(
|
||||
detectedHighlightScale,
|
||||
).all(Float::isFinite),
|
||||
) { "Non-finite Photon dehaze curve" }
|
||||
require(hazePointLow in 0f..1f && hazePointHigh in hazePointLow..1f) {
|
||||
"Invalid Photon dehaze points"
|
||||
}
|
||||
require(
|
||||
highlightScale > 0f && quadraticCoefficient >= 0f &&
|
||||
linearSlope >= 0f && detectedHighlightScale > 0f,
|
||||
) { "Invalid Photon dehaze coefficients" }
|
||||
require(sampledPixelCount > 0) { "Photon dehaze curve has no samples" }
|
||||
}
|
||||
|
||||
fun mappedLuminance(input: Float): Float {
|
||||
val normalizedInput = input.coerceIn(0f, 1f)
|
||||
val scaled = min(normalizedInput * highlightScale, 1f)
|
||||
return if (scaled < hazePointHigh) {
|
||||
val distance = max(scaled - hazePointLow, 0f)
|
||||
distance * distance * quadraticCoefficient
|
||||
} else {
|
||||
shoulderValue + (scaled - hazePointHigh) * linearSlope
|
||||
}.coerceIn(0f, 1f)
|
||||
}
|
||||
|
||||
fun gainForLuminance(input: Float): Float =
|
||||
mappedLuminance(input) / max(input.coerceIn(0f, 1f), MIN_LUMINANCE)
|
||||
fun toNativeArray(): FloatArray = floatArrayOf(
|
||||
hazePointLow,
|
||||
hazePointHigh,
|
||||
highlightScale,
|
||||
quadraticCoefficient,
|
||||
linearSlope,
|
||||
shoulderValue,
|
||||
detectedHighlightScale,
|
||||
sampledPixelCount.toFloat(),
|
||||
)
|
||||
|
||||
companion object {
|
||||
private const val MIN_LUMINANCE = 1e-6f
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whole-image statistics used by [PhotonDehazePipeline].
|
||||
*
|
||||
* The two histograms reproduce the MGC low-frequency DehazeAndDha contracts: the first measures
|
||||
* only the bottom 877 values of summed 12-bit RGB, while the second tracks the brightest channel
|
||||
* plus one eighth of the channel spread. No face mask is available in Photon, which is equivalent
|
||||
* to the original zero-mask path (one vote per sample and no luminance offset).
|
||||
*/
|
||||
internal class PhotonDehazeHistogram {
|
||||
private val hazeHistogram = IntArray(HAZE_HISTOGRAM_SIZE)
|
||||
private val highlightHistogram = IntArray(HIGHLIGHT_HISTOGRAM_SIZE)
|
||||
var sampleCount: Int = 0
|
||||
private set
|
||||
|
||||
fun addLinearRgb(red: Float, green: Float, blue: Float) {
|
||||
if (!red.isFinite() || !green.isFinite() || !blue.isFinite()) return
|
||||
val r = quantize12(red)
|
||||
val g = quantize12(green)
|
||||
val b = quantize12(blue)
|
||||
val minimum = min(r, min(g, b))
|
||||
val maximum = max(r, max(g, b))
|
||||
val hazeBin = (r + g + b).coerceIn(0, HAZE_HISTOGRAM_SIZE - 1)
|
||||
val highlightBin = (maximum + (maximum - minimum) / 8)
|
||||
.coerceIn(0, HIGHLIGHT_HISTOGRAM_SIZE - 1)
|
||||
hazeHistogram[hazeBin] += 1
|
||||
highlightHistogram[highlightBin] += 1
|
||||
sampleCount += 1
|
||||
}
|
||||
|
||||
fun estimateCurve(tuning: PhotonDehazeTuning): PhotonDehazeCurveParameters? {
|
||||
if (sampleCount <= 0) return null
|
||||
val normalizedTuning = tuning.normalized()
|
||||
val cumulativeHaze = cumulative(hazeHistogram)
|
||||
val cumulativeHighlight = cumulative(highlightHistogram)
|
||||
|
||||
val detectedHighlightScale = extractHighlightScale(cumulativeHighlight)
|
||||
val highlightScale = 1f +
|
||||
(detectedHighlightScale - 1f) * normalizedTuning.dynamicHighlightStrength
|
||||
val hazeLevel = estimateHazeLevel(cumulativeHaze)
|
||||
val hazeBase = highlightScale * hazeLevel * HAZE_DAMPING * normalizedTuning.strength
|
||||
val hazePointLow = (HAZE_POINT_LOW_SCALE * hazeBase / SIGNAL_MAX).coerceIn(0f, 1f)
|
||||
val hazePointHigh = (HAZE_POINT_HIGH_SCALE * hazeBase / SIGNAL_MAX)
|
||||
.coerceIn(hazePointLow, 1f)
|
||||
|
||||
val interval = hazePointHigh - hazePointLow
|
||||
val quadraticCoefficient: Float
|
||||
val shoulderValue: Float
|
||||
val linearSlope: Float
|
||||
if (interval > MIN_CURVE_INTERVAL) {
|
||||
quadraticCoefficient = 1f /
|
||||
(interval * interval + 2f * (1f - hazePointHigh) * interval)
|
||||
shoulderValue = interval * interval * quadraticCoefficient
|
||||
linearSlope = if (hazePointHigh < 1f) {
|
||||
(1f - shoulderValue) / (1f - hazePointHigh)
|
||||
} else {
|
||||
0f
|
||||
}
|
||||
} else {
|
||||
// Zero dehaze strength leaves the original linear segment intact while DHA can still
|
||||
// adjust its scale. Avoid materializing the unused infinite quadratic coefficient.
|
||||
quadraticCoefficient = 0f
|
||||
shoulderValue = 0f
|
||||
linearSlope = 1f
|
||||
fun fromNativeArray(values: FloatArray): PhotonDehazeCurveParameters? {
|
||||
if (values.size != NATIVE_VALUE_COUNT || values.any { !it.isFinite() }) return null
|
||||
val sampledPixelCount = values[7].roundToInt()
|
||||
if (sampledPixelCount <= 0) return null
|
||||
return runCatching {
|
||||
PhotonDehazeCurveParameters(
|
||||
hazePointLow = values[0],
|
||||
hazePointHigh = values[1],
|
||||
highlightScale = values[2],
|
||||
quadraticCoefficient = values[3],
|
||||
linearSlope = values[4],
|
||||
shoulderValue = values[5],
|
||||
detectedHighlightScale = values[6],
|
||||
sampledPixelCount = sampledPixelCount,
|
||||
)
|
||||
}.getOrNull()
|
||||
}
|
||||
return PhotonDehazeCurveParameters(
|
||||
hazePointLow = hazePointLow,
|
||||
hazePointHigh = hazePointHigh,
|
||||
highlightScale = highlightScale,
|
||||
quadraticCoefficient = quadraticCoefficient,
|
||||
linearSlope = linearSlope,
|
||||
shoulderValue = shoulderValue,
|
||||
detectedHighlightScale = detectedHighlightScale,
|
||||
sampledPixelCount = sampleCount,
|
||||
|
||||
val IDENTITY = PhotonDehazeCurveParameters(
|
||||
hazePointLow = 0f,
|
||||
hazePointHigh = 0f,
|
||||
highlightScale = 1f,
|
||||
quadraticCoefficient = 0f,
|
||||
linearSlope = 1f,
|
||||
shoulderValue = 0f,
|
||||
detectedHighlightScale = 1f,
|
||||
sampledPixelCount = 1,
|
||||
)
|
||||
}
|
||||
|
||||
private fun estimateHazeLevel(cumulativeHaze: IntArray): Float {
|
||||
var sum = 0f
|
||||
for (index in 0 until HAZE_QUANTILE_SAMPLE_COUNT) {
|
||||
val position = index.toFloat() / (HAZE_QUANTILE_SAMPLE_COUNT - 1).toFloat()
|
||||
val multiplier = HAZE_QUANTILE_LOW +
|
||||
(HAZE_QUANTILE_HIGH - HAZE_QUANTILE_LOW) * position
|
||||
val target = HAZE_QUANTILE * multiplier * sampleCount.toFloat()
|
||||
val summedRgbBin = quantile(cumulativeHaze, target)
|
||||
sum += min(summedRgbBin / 3f, HAZE_LEVEL_LIMIT)
|
||||
}
|
||||
return sum / HAZE_QUANTILE_SAMPLE_COUNT.toFloat()
|
||||
}
|
||||
|
||||
private fun extractHighlightScale(cumulativeHighlight: IntArray): Float {
|
||||
val distanceFromWhite = 1f - HIGHLIGHT_QUANTILE
|
||||
val adaptiveWindowMix = (distanceFromWhite * 5f).coerceIn(0f, 1f)
|
||||
val maximumHalfWindow = HIGHLIGHT_WINDOW_MIN +
|
||||
(HIGHLIGHT_WINDOW_MAX - HIGHLIGHT_WINDOW_MIN) * adaptiveWindowMix
|
||||
val halfWindow = min(distanceFromWhite, maximumHalfWindow)
|
||||
var sum = 0f
|
||||
for (index in 0 until HIGHLIGHT_QUANTILE_SAMPLE_COUNT) {
|
||||
val position = index.toFloat() / (HIGHLIGHT_QUANTILE_SAMPLE_COUNT - 1).toFloat()
|
||||
val quantilePosition =
|
||||
(HIGHLIGHT_QUANTILE - halfWindow) + 2f * halfWindow * position
|
||||
sum += quantile(
|
||||
cumulativeHighlight,
|
||||
quantilePosition * sampleCount.toFloat(),
|
||||
) / SIGNAL_MAX
|
||||
}
|
||||
val meanHighlight = sum / HIGHLIGHT_QUANTILE_SAMPLE_COUNT.toFloat()
|
||||
val rawScale = if (meanHighlight > MIN_HIGHLIGHT_LEVEL) {
|
||||
HIGHLIGHT_TARGET / meanHighlight
|
||||
} else {
|
||||
HIGHLIGHT_SCALE_MAX
|
||||
}
|
||||
return rawScale.coerceIn(HIGHLIGHT_SCALE_MIN, HIGHLIGHT_SCALE_MAX)
|
||||
}
|
||||
|
||||
private fun cumulative(histogram: IntArray): IntArray {
|
||||
val output = IntArray(histogram.size)
|
||||
var sum = 0
|
||||
for (index in histogram.indices) {
|
||||
sum += histogram[index]
|
||||
output[index] = sum
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
private fun quantile(cumulative: IntArray, target: Float): Float {
|
||||
val boundedTarget = target.coerceIn(0f, cumulative.last().toFloat())
|
||||
var low = 0
|
||||
var high = cumulative.lastIndex
|
||||
while (low < high) {
|
||||
val middle = (low + high) ushr 1
|
||||
if (cumulative[middle].toFloat() >= boundedTarget) high = middle else low = middle + 1
|
||||
}
|
||||
val currentIndex = low
|
||||
if (currentIndex == 0) return 0f
|
||||
val previousCount = cumulative[currentIndex - 1].toFloat()
|
||||
val currentCount = cumulative[currentIndex].toFloat()
|
||||
if (currentCount <= previousCount) return currentIndex.toFloat()
|
||||
val fraction = ((boundedTarget - previousCount) / (currentCount - previousCount))
|
||||
.coerceIn(0f, 1f)
|
||||
return currentIndex - 1f + fraction
|
||||
}
|
||||
|
||||
private fun quantize12(value: Float): Int =
|
||||
(value.coerceIn(0f, 1f) * SIGNAL_MAX).roundToInt()
|
||||
|
||||
companion object {
|
||||
private const val SIGNAL_MAX = 4095f
|
||||
private const val HAZE_HISTOGRAM_SIZE = 877
|
||||
private const val HIGHLIGHT_HISTOGRAM_SIZE = 5251
|
||||
private const val HAZE_QUANTILE_SAMPLE_COUNT = 20
|
||||
private const val HIGHLIGHT_QUANTILE_SAMPLE_COUNT = 5
|
||||
private const val HAZE_QUANTILE = 0.001f
|
||||
private const val HAZE_QUANTILE_LOW = 0.1f
|
||||
private const val HAZE_QUANTILE_HIGH = 1.9f
|
||||
private const val HAZE_LEVEL_LIMIT = 172f
|
||||
private const val HAZE_POINT_LOW_SCALE = 0.6f
|
||||
private const val HAZE_POINT_HIGH_SCALE = 1.2f
|
||||
private const val HAZE_DAMPING = 0.98f
|
||||
private const val HIGHLIGHT_QUANTILE = 0.993f
|
||||
private const val HIGHLIGHT_TARGET = 0.88f
|
||||
private const val HIGHLIGHT_WINDOW_MIN = 0.01f
|
||||
private const val HIGHLIGHT_WINDOW_MAX = 0.05f
|
||||
private const val HIGHLIGHT_SCALE_MIN = 0.78f
|
||||
private const val HIGHLIGHT_SCALE_MAX = 1.7f
|
||||
private const val MIN_HIGHLIGHT_LEVEL = 1e-6f
|
||||
private const val MIN_CURVE_INTERVAL = 1e-6f
|
||||
const val NATIVE_VALUE_COUNT = 8
|
||||
}
|
||||
}
|
||||
@@ -1,738 +0,0 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import android.opengl.GLES30
|
||||
import android.opengl.GLES31
|
||||
import com.hinnka.mycamera.processor.GlesComputeWorkGroup
|
||||
import com.hinnka.mycamera.processor.PhotonDehazeTuning
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
/**
|
||||
* GPU-resident low-frequency dehaze pipeline.
|
||||
*
|
||||
* The histogram, curve, and full-resolution application are separate compute programs so mobile
|
||||
* drivers do not compile one large dynamically-branched shader. Pixel and curve data remain on GPU.
|
||||
*/
|
||||
internal class PhotonDehazePipeline {
|
||||
data class Output(val textureId: Int)
|
||||
|
||||
private var histogramProgram = 0
|
||||
private var curveProgram = 0
|
||||
private var applyProgram = 0
|
||||
private var histogramBufferId = 0
|
||||
private var curveBufferId = 0
|
||||
private var capabilitiesValidated = false
|
||||
|
||||
private var histogramSourceLocation = -1
|
||||
private var histogramSourceSizeLocation = -1
|
||||
private var histogramLowSizeLocation = -1
|
||||
private var curveStrengthLocation = -1
|
||||
private var curveDynamicHighlightStrengthLocation = -1
|
||||
private var applySourceLocation = -1
|
||||
private var applySourceSizeLocation = -1
|
||||
|
||||
private val zeroHistogramData = ByteBuffer
|
||||
.allocateDirect(HISTOGRAM_BUFFER_BYTES)
|
||||
.order(ByteOrder.nativeOrder())
|
||||
|
||||
fun initialize(): Boolean {
|
||||
if (!capabilitiesValidated) {
|
||||
if (!validateCapabilities()) return false
|
||||
capabilitiesValidated = true
|
||||
}
|
||||
if (programsReady()) {
|
||||
ensureStorageBuffers()
|
||||
return histogramBufferId != 0 && curveBufferId != 0
|
||||
}
|
||||
|
||||
val startedAtNs = System.nanoTime()
|
||||
if (histogramProgram == 0) {
|
||||
histogramProgram = RawGlesProgram.compileCompute(
|
||||
HISTOGRAM_COMPUTE_SHADER,
|
||||
"photonDehazeHistogram",
|
||||
)
|
||||
}
|
||||
if (curveProgram == 0) {
|
||||
curveProgram = RawGlesProgram.compileCompute(
|
||||
CURVE_COMPUTE_SHADER,
|
||||
"photonDehazeCurve",
|
||||
)
|
||||
}
|
||||
if (applyProgram == 0) {
|
||||
applyProgram = RawGlesProgram.compileCompute(
|
||||
APPLY_COMPUTE_SHADER,
|
||||
"photonDehazeApply",
|
||||
)
|
||||
}
|
||||
if (!programsReady()) return false
|
||||
|
||||
histogramSourceLocation = GLES31.glGetUniformLocation(histogramProgram, "uLinearRgb")
|
||||
histogramSourceSizeLocation = GLES31.glGetUniformLocation(histogramProgram, "uSourceSize")
|
||||
histogramLowSizeLocation =
|
||||
GLES31.glGetUniformLocation(histogramProgram, "uLowFrequencySize")
|
||||
curveStrengthLocation = GLES31.glGetUniformLocation(curveProgram, "uStrength")
|
||||
curveDynamicHighlightStrengthLocation =
|
||||
GLES31.glGetUniformLocation(curveProgram, "uDynamicHighlightStrength")
|
||||
applySourceLocation = GLES31.glGetUniformLocation(applyProgram, "uLinearRgb")
|
||||
applySourceSizeLocation = GLES31.glGetUniformLocation(applyProgram, "uSourceSize")
|
||||
check(
|
||||
histogramSourceLocation >= 0 && histogramSourceSizeLocation >= 0 &&
|
||||
histogramLowSizeLocation >= 0 && curveStrengthLocation >= 0 &&
|
||||
curveDynamicHighlightStrengthLocation >= 0 && applySourceLocation >= 0 &&
|
||||
applySourceSizeLocation >= 0,
|
||||
) { "Photon dehaze compute uniforms are incomplete" }
|
||||
|
||||
ensureStorageBuffers()
|
||||
PLog.d(
|
||||
TAG,
|
||||
"Photon dehaze programs initialized histogramChars=${HISTOGRAM_COMPUTE_SHADER.length} " +
|
||||
"curveChars=${CURVE_COMPUTE_SHADER.length} applyChars=${APPLY_COMPUTE_SHADER.length} " +
|
||||
"tookMs=${(System.nanoTime() - startedAtNs) / 1_000_000L}",
|
||||
)
|
||||
return histogramBufferId != 0 && curveBufferId != 0
|
||||
}
|
||||
|
||||
fun render(
|
||||
sourceTextureId: Int,
|
||||
targetTextureId: Int,
|
||||
width: Int,
|
||||
height: Int,
|
||||
tuning: PhotonDehazeTuning,
|
||||
): Output? = renderWithHistogramSource(
|
||||
histogramSourceTextureId = sourceTextureId,
|
||||
histogramWidth = width,
|
||||
histogramHeight = height,
|
||||
sourceTextureId = sourceTextureId,
|
||||
targetTextureId = targetTextureId,
|
||||
width = width,
|
||||
height = height,
|
||||
tuning = tuning,
|
||||
)
|
||||
|
||||
/**
|
||||
* Builds the adaptive curve from the full-resolution source while applying it to another
|
||||
* texture in the same linear RGB domain. Capture metering uses this to preserve the exact
|
||||
* final-render histogram while evaluating only its small viewfinder-sized image.
|
||||
*/
|
||||
fun renderWithHistogramSource(
|
||||
histogramSourceTextureId: Int,
|
||||
histogramWidth: Int,
|
||||
histogramHeight: Int,
|
||||
sourceTextureId: Int,
|
||||
targetTextureId: Int,
|
||||
width: Int,
|
||||
height: Int,
|
||||
tuning: PhotonDehazeTuning,
|
||||
): Output? {
|
||||
val startedAtNs = System.nanoTime()
|
||||
val normalizedTuning = tuning.normalized()
|
||||
require(normalizedTuning.isActive) { "Photon dehaze render requested while disabled" }
|
||||
require(
|
||||
histogramSourceTextureId != 0 && sourceTextureId != 0 && targetTextureId != 0
|
||||
) {
|
||||
"Photon dehaze requires valid source and destination textures"
|
||||
}
|
||||
require(sourceTextureId != targetTextureId) {
|
||||
"Photon dehaze requires a linear RGB ping-pong destination"
|
||||
}
|
||||
require(
|
||||
histogramWidth > 0 && histogramHeight > 0 && width > 0 && height > 0
|
||||
) { "Invalid Photon dehaze dimensions" }
|
||||
if (!initialize()) return null
|
||||
|
||||
val lowWidth = (histogramWidth + DOWNSAMPLE_FACTOR - 1) / DOWNSAMPLE_FACTOR
|
||||
val lowHeight = (histogramHeight + DOWNSAMPLE_FACTOR - 1) / DOWNSAMPLE_FACTOR
|
||||
resetHistogram()
|
||||
GLES31.glActiveTexture(GLES31.GL_TEXTURE0)
|
||||
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, histogramSourceTextureId)
|
||||
|
||||
// LinearRcd writes through a framebuffer; histogram consumes that texture by sampler.
|
||||
GLES31.glMemoryBarrier(
|
||||
GLES31.GL_FRAMEBUFFER_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT,
|
||||
)
|
||||
GLES31.glUseProgram(histogramProgram)
|
||||
GLES31.glUniform1i(histogramSourceLocation, 0)
|
||||
GLES31.glUniform2i(
|
||||
histogramSourceSizeLocation,
|
||||
histogramWidth,
|
||||
histogramHeight,
|
||||
)
|
||||
GLES31.glUniform2i(histogramLowSizeLocation, lowWidth, lowHeight)
|
||||
GLES31.glBindBufferBase(
|
||||
GLES31.GL_SHADER_STORAGE_BUFFER,
|
||||
HISTOGRAM_BUFFER_BINDING,
|
||||
histogramBufferId,
|
||||
)
|
||||
GLES31.glDispatchCompute(
|
||||
GlesComputeWorkGroup.groupCount(lowWidth, HISTOGRAM_SAMPLES_PER_GROUP),
|
||||
lowHeight,
|
||||
1,
|
||||
)
|
||||
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT)
|
||||
|
||||
GLES31.glUseProgram(curveProgram)
|
||||
GLES31.glUniform1f(curveStrengthLocation, normalizedTuning.strength)
|
||||
GLES31.glUniform1f(
|
||||
curveDynamicHighlightStrengthLocation,
|
||||
normalizedTuning.dynamicHighlightStrength,
|
||||
)
|
||||
GLES31.glBindBufferBase(
|
||||
GLES31.GL_SHADER_STORAGE_BUFFER,
|
||||
HISTOGRAM_BUFFER_BINDING,
|
||||
histogramBufferId,
|
||||
)
|
||||
GLES31.glBindBufferBase(
|
||||
GLES31.GL_SHADER_STORAGE_BUFFER,
|
||||
CURVE_BUFFER_BINDING,
|
||||
curveBufferId,
|
||||
)
|
||||
GLES31.glDispatchCompute(1, 1, 1)
|
||||
GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT)
|
||||
|
||||
GLES31.glUseProgram(applyProgram)
|
||||
GLES31.glActiveTexture(GLES31.GL_TEXTURE0)
|
||||
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, sourceTextureId)
|
||||
GLES31.glUniform1i(applySourceLocation, 0)
|
||||
GLES31.glUniform2i(applySourceSizeLocation, width, height)
|
||||
GLES31.glBindBufferBase(
|
||||
GLES31.GL_SHADER_STORAGE_BUFFER,
|
||||
APPLY_CURVE_BUFFER_BINDING,
|
||||
curveBufferId,
|
||||
)
|
||||
GLES31.glBindImageTexture(
|
||||
OUTPUT_IMAGE_BINDING,
|
||||
targetTextureId,
|
||||
0,
|
||||
false,
|
||||
0,
|
||||
GLES31.GL_WRITE_ONLY,
|
||||
GLES30.GL_RGBA16F,
|
||||
)
|
||||
GLES31.glDispatchCompute(
|
||||
GlesComputeWorkGroup.linearGroupCount(width),
|
||||
height,
|
||||
1,
|
||||
)
|
||||
GLES31.glMemoryBarrier(
|
||||
GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or
|
||||
GLES31.GL_TEXTURE_FETCH_BARRIER_BIT or
|
||||
GLES31.GL_FRAMEBUFFER_BARRIER_BIT,
|
||||
)
|
||||
|
||||
unbindPipelineResources()
|
||||
requireNoGlError("GPU-resident histogram/curve/apply")
|
||||
PLog.i(
|
||||
TAG,
|
||||
"Photon dehaze submitted size=${width}x$height " +
|
||||
"histogram=${histogramWidth}x$histogramHeight " +
|
||||
"low=${lowWidth}x$lowHeight " +
|
||||
"maxSamples=${lowWidth * lowHeight} path=GPU_COMPUTE_BATCHED_HISTOGRAM " +
|
||||
"curveScanBins=${HAZE_HISTOGRAM_SIZE + HIGHLIGHT_HISTOGRAM_SIZE} " +
|
||||
"cpuReadback=false strength=${normalizedTuning.strength} " +
|
||||
"dynamicHighlightStrength=${normalizedTuning.dynamicHighlightStrength} " +
|
||||
"submitMs=${(System.nanoTime() - startedAtNs) / 1_000_000L}",
|
||||
)
|
||||
return Output(targetTextureId)
|
||||
}
|
||||
|
||||
fun release() {
|
||||
if (histogramProgram != 0) GLES31.glDeleteProgram(histogramProgram)
|
||||
if (curveProgram != 0) GLES31.glDeleteProgram(curveProgram)
|
||||
if (applyProgram != 0) GLES31.glDeleteProgram(applyProgram)
|
||||
histogramProgram = 0
|
||||
curveProgram = 0
|
||||
applyProgram = 0
|
||||
val buffers = intArrayOf(histogramBufferId, curveBufferId).filter { it != 0 }.toIntArray()
|
||||
if (buffers.isNotEmpty()) GLES31.glDeleteBuffers(buffers.size, buffers, 0)
|
||||
histogramBufferId = 0
|
||||
curveBufferId = 0
|
||||
histogramSourceLocation = -1
|
||||
histogramSourceSizeLocation = -1
|
||||
histogramLowSizeLocation = -1
|
||||
curveStrengthLocation = -1
|
||||
curveDynamicHighlightStrengthLocation = -1
|
||||
applySourceLocation = -1
|
||||
applySourceSizeLocation = -1
|
||||
capabilitiesValidated = false
|
||||
}
|
||||
|
||||
private fun programsReady(): Boolean =
|
||||
histogramProgram != 0 && curveProgram != 0 && applyProgram != 0
|
||||
|
||||
private fun ensureStorageBuffers() {
|
||||
if (histogramBufferId != 0 && curveBufferId != 0) return
|
||||
val buffers = IntArray(2)
|
||||
GLES31.glGenBuffers(2, buffers, 0)
|
||||
histogramBufferId = buffers[0]
|
||||
curveBufferId = buffers[1]
|
||||
check(histogramBufferId != 0 && curveBufferId != 0) {
|
||||
"Unable to allocate Photon dehaze storage buffers"
|
||||
}
|
||||
|
||||
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, histogramBufferId)
|
||||
zeroHistogramData.clear()
|
||||
GLES31.glBufferData(
|
||||
GLES31.GL_SHADER_STORAGE_BUFFER,
|
||||
HISTOGRAM_BUFFER_BYTES,
|
||||
zeroHistogramData,
|
||||
GLES31.GL_DYNAMIC_DRAW,
|
||||
)
|
||||
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, curveBufferId)
|
||||
GLES31.glBufferData(
|
||||
GLES31.GL_SHADER_STORAGE_BUFFER,
|
||||
CURVE_BUFFER_BYTES,
|
||||
null,
|
||||
GLES31.GL_DYNAMIC_DRAW,
|
||||
)
|
||||
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
|
||||
requireNoGlError("storage buffer allocation")
|
||||
}
|
||||
|
||||
private fun resetHistogram() {
|
||||
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, histogramBufferId)
|
||||
zeroHistogramData.clear()
|
||||
GLES31.glBufferSubData(
|
||||
GLES31.GL_SHADER_STORAGE_BUFFER,
|
||||
0,
|
||||
HISTOGRAM_BUFFER_BYTES,
|
||||
zeroHistogramData,
|
||||
)
|
||||
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
|
||||
GLES31.glMemoryBarrier(
|
||||
GLES31.GL_BUFFER_UPDATE_BARRIER_BIT or GLES31.GL_SHADER_STORAGE_BARRIER_BIT,
|
||||
)
|
||||
}
|
||||
|
||||
private fun unbindPipelineResources() {
|
||||
GLES31.glBindImageTexture(
|
||||
OUTPUT_IMAGE_BINDING,
|
||||
0,
|
||||
0,
|
||||
false,
|
||||
0,
|
||||
GLES31.GL_WRITE_ONLY,
|
||||
GLES30.GL_RGBA16F,
|
||||
)
|
||||
GLES31.glBindBufferBase(
|
||||
GLES31.GL_SHADER_STORAGE_BUFFER,
|
||||
HISTOGRAM_BUFFER_BINDING,
|
||||
0,
|
||||
)
|
||||
GLES31.glBindBufferBase(
|
||||
GLES31.GL_SHADER_STORAGE_BUFFER,
|
||||
CURVE_BUFFER_BINDING,
|
||||
0,
|
||||
)
|
||||
GLES31.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0)
|
||||
GLES31.glActiveTexture(GLES31.GL_TEXTURE0)
|
||||
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0)
|
||||
}
|
||||
|
||||
private fun validateCapabilities(): Boolean {
|
||||
val maxSsboBindings = queryInt(GLES31.GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS)
|
||||
val maxComputeSsboBlocks = queryInt(GLES31.GL_MAX_COMPUTE_SHADER_STORAGE_BLOCKS)
|
||||
val maxSsboBlockSize = queryInt(GLES31.GL_MAX_SHADER_STORAGE_BLOCK_SIZE)
|
||||
val maxComputeImages = queryInt(GLES31.GL_MAX_COMPUTE_IMAGE_UNIFORMS)
|
||||
val maxSharedBytes = queryInt(GLES31.GL_MAX_COMPUTE_SHARED_MEMORY_SIZE)
|
||||
val valid = maxSsboBindings >= 2 &&
|
||||
maxComputeSsboBlocks >= 2 &&
|
||||
maxSsboBlockSize >= HISTOGRAM_BUFFER_BYTES &&
|
||||
maxComputeImages >= 1 &&
|
||||
maxSharedBytes >= SHARED_HISTOGRAM_BYTES
|
||||
if (!valid) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"Photon dehaze GPU capabilities insufficient: ssboBindings=$maxSsboBindings " +
|
||||
"computeSsboBlocks=$maxComputeSsboBlocks ssboBlockBytes=$maxSsboBlockSize " +
|
||||
"computeImages=$maxComputeImages sharedBytes=$maxSharedBytes " +
|
||||
"requiredHistogramBytes=$HISTOGRAM_BUFFER_BYTES " +
|
||||
"requiredSharedBytes=$SHARED_HISTOGRAM_BYTES",
|
||||
)
|
||||
}
|
||||
return valid
|
||||
}
|
||||
|
||||
private fun queryInt(parameter: Int): Int {
|
||||
val value = IntArray(1)
|
||||
GLES31.glGetIntegerv(parameter, value, 0)
|
||||
return value[0]
|
||||
}
|
||||
|
||||
private fun requireNoGlError(operation: String) {
|
||||
val errors = buildList {
|
||||
var error = GLES31.glGetError()
|
||||
while (error != GLES31.GL_NO_ERROR) {
|
||||
add("0x${error.toString(16)}")
|
||||
error = GLES31.glGetError()
|
||||
}
|
||||
}
|
||||
check(errors.isEmpty()) { "Photon dehaze $operation failed: ${errors.joinToString()}" }
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "PhotonDehazePipeline"
|
||||
const val DOWNSAMPLE_FACTOR = 8
|
||||
private const val HAZE_HISTOGRAM_SIZE = 877
|
||||
private const val HIGHLIGHT_HISTOGRAM_SIZE = 5251
|
||||
private const val HISTOGRAM_ELEMENT_COUNT =
|
||||
HAZE_HISTOGRAM_SIZE + HIGHLIGHT_HISTOGRAM_SIZE + 1
|
||||
private const val HISTOGRAM_BUFFER_BYTES = HISTOGRAM_ELEMENT_COUNT * Int.SIZE_BYTES
|
||||
private const val CURVE_VALUE_COUNT = 8
|
||||
private const val CURVE_BUFFER_BYTES = CURVE_VALUE_COUNT * Float.SIZE_BYTES
|
||||
private const val HISTOGRAM_SAMPLES_PER_GROUP = 8
|
||||
private const val SOURCE_PIXELS_PER_SAMPLE = DOWNSAMPLE_FACTOR * DOWNSAMPLE_FACTOR
|
||||
private const val SHARED_HISTOGRAM_BYTES =
|
||||
HISTOGRAM_SAMPLES_PER_GROUP * SOURCE_PIXELS_PER_SAMPLE * 4 * Float.SIZE_BYTES +
|
||||
HISTOGRAM_SAMPLES_PER_GROUP * 3 * Int.SIZE_BYTES
|
||||
private const val HISTOGRAM_BUFFER_BINDING = 0
|
||||
private const val CURVE_BUFFER_BINDING = 1
|
||||
private const val APPLY_CURVE_BUFFER_BINDING = 0
|
||||
private const val OUTPUT_IMAGE_BINDING = 0
|
||||
|
||||
val HISTOGRAM_COMPUTE_SHADER = """
|
||||
#version 310 es
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
precision highp sampler2D;
|
||||
|
||||
layout(local_size_x = 128, local_size_y = 1) in;
|
||||
uniform sampler2D uLinearRgb;
|
||||
uniform ivec2 uSourceSize;
|
||||
uniform ivec2 uLowFrequencySize;
|
||||
|
||||
layout(std430, binding = 0) buffer HistogramBuffer {
|
||||
uint hazeHistogram[$HAZE_HISTOGRAM_SIZE];
|
||||
uint highlightHistogram[$HIGHLIGHT_HISTOGRAM_SIZE];
|
||||
uint sampleCount;
|
||||
} histogram;
|
||||
|
||||
shared vec4 sharedLinearRgb[512];
|
||||
shared uint sharedHazeBins[8];
|
||||
shared uint sharedHighlightBins[8];
|
||||
shared uint sharedValidSamples[8];
|
||||
const float SIGNAL_MAX = 4095.0;
|
||||
|
||||
int quantize12(float value) {
|
||||
return int(floor(clamp(value, 0.0, 1.0) * SIGNAL_MAX + 0.5));
|
||||
}
|
||||
|
||||
void main() {
|
||||
uint lane = gl_LocalInvocationID.x;
|
||||
uint sampleIndex = lane / 16u;
|
||||
uint sampleLane = lane - sampleIndex * 16u;
|
||||
ivec2 lowPosition = ivec2(
|
||||
gl_WorkGroupID.x * 8u + sampleIndex,
|
||||
gl_WorkGroupID.y
|
||||
);
|
||||
bool lowSampleValid = all(lessThan(lowPosition, uLowFrequencySize));
|
||||
for (uint loadIndex = 0u; loadIndex < 4u; ++loadIndex) {
|
||||
uint pixelIndex = sampleLane + loadIndex * 16u;
|
||||
ivec2 localPixel = ivec2(pixelIndex % 8u, pixelIndex / 8u);
|
||||
ivec2 sourcePosition = lowPosition * 8 + localPixel;
|
||||
bool sourceValid = lowSampleValid &&
|
||||
all(lessThan(sourcePosition, uSourceSize));
|
||||
uint sharedIndex = sampleIndex * 64u + pixelIndex;
|
||||
sharedLinearRgb[sharedIndex] = sourceValid
|
||||
? vec4(texelFetch(uLinearRgb, sourcePosition, 0).rgb, 1.0)
|
||||
: vec4(0.0);
|
||||
}
|
||||
barrier();
|
||||
if (sampleLane == 0u) {
|
||||
vec4 sum = vec4(0.0);
|
||||
uint sharedBase = sampleIndex * 64u;
|
||||
for (uint index = 0u; index < 64u; ++index) {
|
||||
sum += sharedLinearRgb[sharedBase + index];
|
||||
}
|
||||
vec3 rgb = sum.w > 0.0 ? sum.rgb / sum.w : vec3(0.0);
|
||||
bool valid = sum.w > 0.0 && !any(isnan(rgb)) && !any(isinf(rgb));
|
||||
sharedValidSamples[sampleIndex] = valid ? 1u : 0u;
|
||||
if (valid) {
|
||||
int r = quantize12(rgb.r);
|
||||
int g = quantize12(rgb.g);
|
||||
int b = quantize12(rgb.b);
|
||||
int minimum = min(r, min(g, b));
|
||||
int maximum = max(r, max(g, b));
|
||||
sharedHazeBins[sampleIndex] = uint(
|
||||
clamp(r + g + b, 0, $HAZE_HISTOGRAM_SIZE - 1)
|
||||
);
|
||||
sharedHighlightBins[sampleIndex] = uint(clamp(
|
||||
maximum + (maximum - minimum) / 8,
|
||||
0,
|
||||
$HIGHLIGHT_HISTOGRAM_SIZE - 1
|
||||
));
|
||||
}
|
||||
}
|
||||
barrier();
|
||||
if (lane != 0u) return;
|
||||
|
||||
uint validCount = 0u;
|
||||
for (uint index = 0u; index < 8u; ++index) {
|
||||
validCount += sharedValidSamples[index];
|
||||
if (sharedValidSamples[index] == 0u) continue;
|
||||
|
||||
uint hazeBin = sharedHazeBins[index];
|
||||
bool firstHaze = true;
|
||||
for (uint previous = 0u; previous < index; ++previous) {
|
||||
if (sharedValidSamples[previous] != 0u &&
|
||||
sharedHazeBins[previous] == hazeBin) firstHaze = false;
|
||||
}
|
||||
if (firstHaze) {
|
||||
uint count = 1u;
|
||||
for (uint next = index + 1u; next < 8u; ++next) {
|
||||
if (sharedValidSamples[next] != 0u &&
|
||||
sharedHazeBins[next] == hazeBin) count += 1u;
|
||||
}
|
||||
atomicAdd(histogram.hazeHistogram[hazeBin], count);
|
||||
}
|
||||
|
||||
uint highlightBin = sharedHighlightBins[index];
|
||||
bool firstHighlight = true;
|
||||
for (uint previous = 0u; previous < index; ++previous) {
|
||||
if (sharedValidSamples[previous] != 0u &&
|
||||
sharedHighlightBins[previous] == highlightBin) firstHighlight = false;
|
||||
}
|
||||
if (firstHighlight) {
|
||||
uint count = 1u;
|
||||
for (uint next = index + 1u; next < 8u; ++next) {
|
||||
if (sharedValidSamples[next] != 0u &&
|
||||
sharedHighlightBins[next] == highlightBin) count += 1u;
|
||||
}
|
||||
atomicAdd(histogram.highlightHistogram[highlightBin], count);
|
||||
}
|
||||
}
|
||||
atomicAdd(histogram.sampleCount, validCount);
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
val CURVE_COMPUTE_SHADER = """
|
||||
#version 310 es
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
|
||||
layout(local_size_x = 128, local_size_y = 1) in;
|
||||
uniform float uStrength;
|
||||
uniform float uDynamicHighlightStrength;
|
||||
|
||||
layout(std430, binding = 0) readonly buffer HistogramBuffer {
|
||||
uint hazeHistogram[$HAZE_HISTOGRAM_SIZE];
|
||||
uint highlightHistogram[$HIGHLIGHT_HISTOGRAM_SIZE];
|
||||
uint sampleCount;
|
||||
} histogram;
|
||||
layout(std430, binding = 1) buffer CurveBuffer {
|
||||
float values[$CURVE_VALUE_COUNT];
|
||||
} curve;
|
||||
|
||||
const float SIGNAL_MAX = 4095.0;
|
||||
const float HAZE_QUANTILE = 0.001;
|
||||
const float HAZE_QUANTILE_LOW = 0.1;
|
||||
const float HAZE_QUANTILE_HIGH = 1.9;
|
||||
const float HAZE_LEVEL_LIMIT = 172.0;
|
||||
const float HAZE_POINT_LOW_SCALE = 0.6;
|
||||
const float HAZE_POINT_HIGH_SCALE = 1.2;
|
||||
const float HAZE_DAMPING = 0.98;
|
||||
const float HIGHLIGHT_QUANTILE = 0.993;
|
||||
const float HIGHLIGHT_TARGET = 0.88;
|
||||
const float HIGHLIGHT_WINDOW_MIN = 0.01;
|
||||
const float HIGHLIGHT_WINDOW_MAX = 0.05;
|
||||
const float HIGHLIGHT_SCALE_MIN = 0.78;
|
||||
const float HIGHLIGHT_SCALE_MAX = 1.7;
|
||||
const float MIN_HIGHLIGHT_LEVEL = 1e-6;
|
||||
const float MIN_CURVE_INTERVAL = 1e-6;
|
||||
|
||||
float interpolateQuantile(int index, float target, uint previous, uint cumulative) {
|
||||
if (index == 0) return 0.0;
|
||||
if (cumulative <= previous) return float(index);
|
||||
float fraction = clamp(
|
||||
(target - float(previous)) / (float(cumulative) - float(previous)),
|
||||
0.0,
|
||||
1.0
|
||||
);
|
||||
return float(index) - 1.0 + fraction;
|
||||
}
|
||||
|
||||
void main() {
|
||||
if (gl_GlobalInvocationID.x != 0u) return;
|
||||
uint total = histogram.sampleCount;
|
||||
if (total == 0u) {
|
||||
curve.values[0] = 0.0;
|
||||
curve.values[1] = 0.0;
|
||||
curve.values[2] = 1.0;
|
||||
curve.values[3] = 0.0;
|
||||
curve.values[4] = 1.0;
|
||||
curve.values[5] = 0.0;
|
||||
curve.values[6] = 1.0;
|
||||
curve.values[7] = 0.0;
|
||||
return;
|
||||
}
|
||||
|
||||
float distanceFromWhite = 1.0 - HIGHLIGHT_QUANTILE;
|
||||
float adaptiveWindowMix = clamp(distanceFromWhite * 5.0, 0.0, 1.0);
|
||||
float maximumHalfWindow = HIGHLIGHT_WINDOW_MIN +
|
||||
(HIGHLIGHT_WINDOW_MAX - HIGHLIGHT_WINDOW_MIN) * adaptiveWindowMix;
|
||||
float halfWindow = min(distanceFromWhite, maximumHalfWindow);
|
||||
int nextHighlight = 0;
|
||||
uint highlightCumulative = 0u;
|
||||
float highlightSum = 0.0;
|
||||
float highlightTarget =
|
||||
(HIGHLIGHT_QUANTILE - halfWindow) * float(total);
|
||||
for (int index = 0;
|
||||
index < $HIGHLIGHT_HISTOGRAM_SIZE && nextHighlight < 5;
|
||||
++index
|
||||
) {
|
||||
uint previous = highlightCumulative;
|
||||
uint binCount = histogram.highlightHistogram[index];
|
||||
highlightCumulative += binCount;
|
||||
while (nextHighlight < 5 &&
|
||||
float(highlightCumulative) >= highlightTarget
|
||||
) {
|
||||
highlightSum += interpolateQuantile(
|
||||
index,
|
||||
highlightTarget,
|
||||
previous,
|
||||
highlightCumulative
|
||||
) / SIGNAL_MAX;
|
||||
nextHighlight += 1;
|
||||
if (nextHighlight < 5) {
|
||||
float position = float(nextHighlight) / 4.0;
|
||||
highlightTarget = (
|
||||
(HIGHLIGHT_QUANTILE - halfWindow) +
|
||||
2.0 * halfWindow * position
|
||||
) * float(total);
|
||||
}
|
||||
}
|
||||
}
|
||||
while (nextHighlight < 5) {
|
||||
highlightSum += float($HIGHLIGHT_HISTOGRAM_SIZE - 1) / SIGNAL_MAX;
|
||||
nextHighlight += 1;
|
||||
}
|
||||
float meanHighlight = highlightSum / 5.0;
|
||||
float rawScale = meanHighlight > MIN_HIGHLIGHT_LEVEL
|
||||
? HIGHLIGHT_TARGET / meanHighlight
|
||||
: HIGHLIGHT_SCALE_MAX;
|
||||
float detectedHighlightScale = clamp(
|
||||
rawScale,
|
||||
HIGHLIGHT_SCALE_MIN,
|
||||
HIGHLIGHT_SCALE_MAX
|
||||
);
|
||||
float highlightScale = 1.0 +
|
||||
(detectedHighlightScale - 1.0) * uDynamicHighlightStrength;
|
||||
|
||||
int nextHaze = 0;
|
||||
uint hazeCumulative = 0u;
|
||||
float hazeSum = 0.0;
|
||||
float hazeTarget = HAZE_QUANTILE * HAZE_QUANTILE_LOW * float(total);
|
||||
for (int index = 0; index < $HAZE_HISTOGRAM_SIZE && nextHaze < 20; ++index) {
|
||||
uint previous = hazeCumulative;
|
||||
uint binCount = histogram.hazeHistogram[index];
|
||||
hazeCumulative += binCount;
|
||||
while (nextHaze < 20 && float(hazeCumulative) >= hazeTarget) {
|
||||
float summedRgbBin = interpolateQuantile(
|
||||
index,
|
||||
hazeTarget,
|
||||
previous,
|
||||
hazeCumulative
|
||||
);
|
||||
hazeSum += min(summedRgbBin / 3.0, HAZE_LEVEL_LIMIT);
|
||||
nextHaze += 1;
|
||||
if (nextHaze < 20) {
|
||||
float position = float(nextHaze) / 19.0;
|
||||
float multiplier = HAZE_QUANTILE_LOW +
|
||||
(HAZE_QUANTILE_HIGH - HAZE_QUANTILE_LOW) * position;
|
||||
hazeTarget = HAZE_QUANTILE * multiplier * float(total);
|
||||
}
|
||||
}
|
||||
}
|
||||
while (nextHaze < 20) {
|
||||
hazeSum += min(
|
||||
float($HAZE_HISTOGRAM_SIZE - 1) / 3.0,
|
||||
HAZE_LEVEL_LIMIT
|
||||
);
|
||||
nextHaze += 1;
|
||||
}
|
||||
float hazeLevel = hazeSum / 20.0;
|
||||
float hazeBase = highlightScale * hazeLevel * HAZE_DAMPING * uStrength;
|
||||
float hazePointLow = clamp(
|
||||
HAZE_POINT_LOW_SCALE * hazeBase / SIGNAL_MAX,
|
||||
0.0,
|
||||
1.0
|
||||
);
|
||||
float hazePointHigh = clamp(
|
||||
HAZE_POINT_HIGH_SCALE * hazeBase / SIGNAL_MAX,
|
||||
hazePointLow,
|
||||
1.0
|
||||
);
|
||||
float interval = hazePointHigh - hazePointLow;
|
||||
float quadraticCoefficient;
|
||||
float shoulderValue;
|
||||
float linearSlope;
|
||||
if (interval > MIN_CURVE_INTERVAL) {
|
||||
quadraticCoefficient = 1.0 /
|
||||
(interval * interval + 2.0 * (1.0 - hazePointHigh) * interval);
|
||||
shoulderValue = interval * interval * quadraticCoefficient;
|
||||
linearSlope = hazePointHigh < 1.0
|
||||
? (1.0 - shoulderValue) / (1.0 - hazePointHigh)
|
||||
: 0.0;
|
||||
} else {
|
||||
quadraticCoefficient = 0.0;
|
||||
shoulderValue = 0.0;
|
||||
linearSlope = 1.0;
|
||||
}
|
||||
curve.values[0] = hazePointLow;
|
||||
curve.values[1] = hazePointHigh;
|
||||
curve.values[2] = highlightScale;
|
||||
curve.values[3] = quadraticCoefficient;
|
||||
curve.values[4] = linearSlope;
|
||||
curve.values[5] = shoulderValue;
|
||||
curve.values[6] = detectedHighlightScale;
|
||||
curve.values[7] = float(total);
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
val APPLY_COMPUTE_SHADER = """
|
||||
#version 310 es
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
precision highp sampler2D;
|
||||
precision highp image2D;
|
||||
|
||||
layout(local_size_x = 128, local_size_y = 1) in;
|
||||
uniform sampler2D uLinearRgb;
|
||||
uniform ivec2 uSourceSize;
|
||||
layout(rgba16f, binding = 0) writeonly uniform highp image2D uOutput;
|
||||
layout(std430, binding = 0) readonly buffer CurveBuffer {
|
||||
float values[$CURVE_VALUE_COUNT];
|
||||
} curve;
|
||||
|
||||
void main() {
|
||||
ivec2 position = ivec2(
|
||||
gl_WorkGroupID.x * 128u + gl_LocalInvocationID.x,
|
||||
gl_WorkGroupID.y
|
||||
);
|
||||
if (any(greaterThanEqual(position, uSourceSize))) return;
|
||||
vec3 rgb = clamp(texelFetch(uLinearRgb, position, 0).rgb, vec3(0.0), vec3(1.0));
|
||||
float hazePointLow = curve.values[0];
|
||||
float hazePointHigh = curve.values[1];
|
||||
float highlightScale = curve.values[2];
|
||||
float quadraticCoefficient = curve.values[3];
|
||||
float linearSlope = curve.values[4];
|
||||
float shoulderValue = curve.values[5];
|
||||
float luminance = (rgb.r + rgb.g + rgb.b) * (1.0 / 3.0);
|
||||
float scaled = min(luminance * highlightScale, 1.0);
|
||||
float mapped;
|
||||
if (scaled < hazePointHigh) {
|
||||
float distance = max(scaled - hazePointLow, 0.0);
|
||||
mapped = distance * distance * quadraticCoefficient;
|
||||
} else {
|
||||
mapped = shoulderValue + (scaled - hazePointHigh) * linearSlope;
|
||||
}
|
||||
float gain = clamp(mapped, 0.0, 1.0) / max(luminance, 1e-6);
|
||||
imageStore(
|
||||
uOutput,
|
||||
position,
|
||||
vec4(clamp(rgb * gain, vec3(0.0), vec3(1.0)), 1.0)
|
||||
);
|
||||
}
|
||||
""".trimIndent()
|
||||
}
|
||||
}
|
||||
@@ -1503,7 +1503,6 @@ class RawDemosaicProcessor {
|
||||
private val linearFloatToUintPass = RawLinearFloatToUintPass()
|
||||
private val warpRectilinearPass = RawWarpRectilinearPass(fullscreenQuad)
|
||||
private val linearRcdPass = RawLinearRcdPass(fullscreenQuad)
|
||||
private val photonDehazePipeline = PhotonDehazePipeline()
|
||||
private val hdrReferencePass = RawHdrReferencePass(engineTonePass)
|
||||
private val meteringDemosaicAlgorithm = RawMeteringDemosaicAlgorithm()
|
||||
private val fastMomentsStatsAlgorithm = RawAEStatsAlgorithm()
|
||||
@@ -1643,6 +1642,7 @@ class RawDemosaicProcessor {
|
||||
val linearColorCorrectionMatrix: FloatArray,
|
||||
val linearCameraWhite: FloatArray,
|
||||
val hueSatMap: DcpHueSatMap?,
|
||||
val deferDcpHueSatUntilAfterPgtm: Boolean,
|
||||
val applyLinearDngBaselineExposure: Boolean,
|
||||
val hasProfileGainTableMap: Boolean,
|
||||
val applyDcpBaselineExposureOffset: Boolean,
|
||||
@@ -1831,6 +1831,7 @@ class RawDemosaicProcessor {
|
||||
forceRegeneratePhotonPgtm: Boolean = false,
|
||||
photonHdrRatio: Float? = null,
|
||||
photonSourceToShortGain: Float? = null,
|
||||
photonHdrNetPostExposureEv: Float? = null,
|
||||
rawCfaCorrectionMode: String? = null,
|
||||
rawBlackBorderCrop: RawBlackBorderCrop = RawBlackBorderCrop(),
|
||||
onMetadata: ((RawMetadata) -> Unit)? = null
|
||||
@@ -1878,6 +1879,7 @@ class RawDemosaicProcessor {
|
||||
forceRegeneratePhotonPgtm = forceRegeneratePhotonPgtm,
|
||||
photonHdrRatio = photonHdrRatio,
|
||||
photonSourceToShortGain = photonSourceToShortGain,
|
||||
photonHdrNetPostExposureEv = photonHdrNetPostExposureEv,
|
||||
rawCfaCorrectionMode = rawCfaCorrectionMode,
|
||||
rawBlackBorderCrop = rawBlackBorderCrop,
|
||||
dngFile = dngFile,
|
||||
@@ -2329,6 +2331,7 @@ class RawDemosaicProcessor {
|
||||
forceRegeneratePhotonPgtm: Boolean = false,
|
||||
photonHdrRatio: Float? = null,
|
||||
photonSourceToShortGain: Float? = null,
|
||||
photonHdrNetPostExposureEv: Float? = null,
|
||||
rawCfaCorrectionMode: String? = null,
|
||||
rawBlackBorderCrop: RawBlackBorderCrop = RawBlackBorderCrop(),
|
||||
dngFile: File? = null,
|
||||
@@ -2577,8 +2580,21 @@ class RawDemosaicProcessor {
|
||||
}
|
||||
val normalizedToneMappingParameters = rawToneMappingParameters.normalized()
|
||||
val photonHdrRequested = normalizedToneMappingParameters.usePhotonHdr
|
||||
val forcePhotonPgtmRegeneration =
|
||||
photonHdrRequested && forceRegeneratePhotonPgtm
|
||||
val hasReusablePhotonPgtm = if (dngFile != null) {
|
||||
embeddedDngProfiles.any { it.isPhotonHdr && it.hasProfileGainTableMap }
|
||||
} else {
|
||||
sourceProfileGainTableMap != null
|
||||
}
|
||||
// Enabling HDRNet is a rendering contract, not merely a preference hint. Imported DNGs
|
||||
// normally have no Photon profile to reuse, so every render entry point (including SDR
|
||||
// and Ultra HDR export) must generate one instead of silently continuing without PGTM.
|
||||
val regeneratePhotonPgtm = photonHdrRequested &&
|
||||
(forceRegeneratePhotonPgtm || !hasReusablePhotonPgtm)
|
||||
val photonPgtmRegenerationTrigger = when {
|
||||
!regeneratePhotonPgtm -> "reuse-embedded"
|
||||
forceRegeneratePhotonPgtm -> "explicit-force"
|
||||
else -> "missing-photon-pgtm"
|
||||
}
|
||||
val useAdobeProfilePipeline = colorEngine == RawRenderingEngine.AdobeCurve
|
||||
val embeddedProfileDecision = EmbeddedDngProfilePolicy.resolve(
|
||||
hasEmbeddedProfile = embeddedDngRenderPlan != null,
|
||||
@@ -2666,10 +2682,8 @@ class RawDemosaicProcessor {
|
||||
"unsupported samplesPerPixel=$actualSamplesPerPixel"
|
||||
borrowedGpuSource != null -> "GPU-resident stacked source"
|
||||
borrowedDemosaicSource != null -> "GPU-resident prepared demosaic"
|
||||
forcePhotonPgtmRegeneration ->
|
||||
regeneratePhotonPgtm ->
|
||||
"HDRNet PGTM regeneration requires continuous linear RGB"
|
||||
actualMetadata.coreImagingTuning.dehaze.isActive ->
|
||||
"Photon dehaze requires one continuous low-frequency image"
|
||||
hasActiveWarp && !(captureProfilePreparationRequested && !captureExposureRequested) ->
|
||||
"DNG WarpRectilinear requires a displacement-aware render source region"
|
||||
colorEngine == RawRenderingEngine.DarktableFilmic ->
|
||||
@@ -2817,7 +2831,7 @@ class RawDemosaicProcessor {
|
||||
!hasDcpSelection &&
|
||||
normalizedToneMappingParameters.profileToneMapMode == RawProfileToneMapMode.Profile
|
||||
val embeddedProfileGainTableMap = when {
|
||||
forcePhotonPgtmRegeneration -> null
|
||||
regeneratePhotonPgtm -> null
|
||||
photonHdrRequested -> photonProfileGainTableMap
|
||||
?: sourceProfileGainTableMap.takeIf { dngFile == null }
|
||||
selectedEmbeddedProfileIsActive -> selectedProfileGainTableMap
|
||||
@@ -2831,7 +2845,8 @@ class RawDemosaicProcessor {
|
||||
"selected=${selectedEmbeddedDngProfile?.profileName ?: "none"} " +
|
||||
"engine=$colorEngine customDcp=$hasDcpSelection photonHdr=$photonHdrRequested " +
|
||||
"pgtmSource=${when {
|
||||
forcePhotonPgtmRegeneration -> "regenerate-hdrnet"
|
||||
regeneratePhotonPgtm ->
|
||||
"regenerate-hdrnet:$photonPgtmRegenerationTrigger"
|
||||
embeddedProfileGainTableMap == null -> "none"
|
||||
photonHdrRequested -> "photon-hdr"
|
||||
else -> "selected-profile"
|
||||
@@ -3321,6 +3336,9 @@ class RawDemosaicProcessor {
|
||||
appendLine("hdrNetFinalShortGain=$outputShortGain")
|
||||
appendLine("hdrNetFinalLongGain=${outputShortGain * outputHdrRatio}")
|
||||
appendLine("hdrNetFinalHdrRatio=$outputHdrRatio")
|
||||
appendLine(
|
||||
"hdrNetPostExposureEv=${output.hdrNetPostExposureEv ?: 0f}",
|
||||
)
|
||||
}.trimEnd()
|
||||
}
|
||||
val captureProfileFailed =
|
||||
@@ -3343,6 +3361,7 @@ class RawDemosaicProcessor {
|
||||
exposureOffsetEv = solvedExposureEv,
|
||||
hdrRatio = selectedCaptureHdrRatio,
|
||||
finalShortGain = selectedCaptureSourceToShortGain,
|
||||
hdrNetPostExposureEv = captureProfileOutput?.hdrNetPostExposureEv,
|
||||
rawSceneExposureSummaryText = captureSummaryText,
|
||||
profileGainTableMap = captureProfileGainTableMap,
|
||||
gpuDemosaicedRawSource = reusableDemosaicSource,
|
||||
@@ -3352,10 +3371,15 @@ class RawDemosaicProcessor {
|
||||
return@withContext null
|
||||
}
|
||||
|
||||
if (forcePhotonPgtmRegeneration) {
|
||||
if (regeneratePhotonPgtm) {
|
||||
val persistedHdrRatio = photonHdrRatio?.takeIf { it.isFinite() && it >= 1f }
|
||||
val persistedSourceToShortGain = photonSourceToShortGain
|
||||
?.takeIf { it.isFinite() && it > 0f }
|
||||
val persistedPostExposureEv = photonHdrNetPostExposureEv
|
||||
?.takeIf {
|
||||
it.isFinite() && it in
|
||||
MeteringSystem.RAW_EXPOSURE_MIN_EV..MeteringSystem.RAW_EXPOSURE_MAX_EV
|
||||
}
|
||||
val usePersistedCaptureAe =
|
||||
persistedHdrRatio != null && persistedSourceToShortGain != null
|
||||
val estimatedExposure = if (usePersistedCaptureAe) {
|
||||
@@ -3381,9 +3405,10 @@ class RawDemosaicProcessor {
|
||||
?.takeIf { it.isFinite() && it >= 1f }
|
||||
val estimatedSourceToShortGain = estimatedExposure?.finalShortGain
|
||||
?.takeIf { it.isFinite() && it > 0f }
|
||||
// Capture-time finalShortGain already includes the full-viewfinder spatial match.
|
||||
// Prefer the persisted pair so PGTM refresh is reproducible without the original
|
||||
// in-memory thumbnail. ML AE is only a fallback for older metadata contracts.
|
||||
// Capture-time short gain and HDR ratio describe the fixed HDRNet inference.
|
||||
// The downstream viewfinder-match exposure is persisted independently so PGTM
|
||||
// refresh can reproduce the composed result without changing model inputs.
|
||||
// ML AE remains a fallback for older metadata contracts.
|
||||
val useEstimatedAe = !usePersistedCaptureAe &&
|
||||
estimatedHdrRatio != null && estimatedSourceToShortGain != null
|
||||
val regenerationHdrRatio = when {
|
||||
@@ -3405,7 +3430,7 @@ class RawDemosaicProcessor {
|
||||
else -> persistedSourceToShortGain ?: 1f
|
||||
}
|
||||
val regenerationAeSource = when {
|
||||
usePersistedCaptureAe -> "PERSISTED_CAPTURE_VIEWFINDER_MATCH"
|
||||
usePersistedCaptureAe -> "PERSISTED_CAPTURE_AE"
|
||||
useEstimatedAe ->
|
||||
"MGC_ML_AE_REFRESH_WITHOUT_VIEWFINDER_TARGET"
|
||||
else -> "LEGACY_RATIO_SHORT_UNITY_FALLBACK"
|
||||
@@ -3415,9 +3440,11 @@ class RawDemosaicProcessor {
|
||||
PLog.i(
|
||||
TAG,
|
||||
"HDRNet PGTM regeneration " +
|
||||
"trigger=$photonPgtmRegenerationTrigger " +
|
||||
"hdrRatio=$regenerationHdrRatio " +
|
||||
"finalShortGain=$regenerationSourceToShortGain " +
|
||||
"finalLongGain=$regenerationLongGain " +
|
||||
"postExposureEv=${persistedPostExposureEv ?: 0f} " +
|
||||
"aeSource=$regenerationAeSource " +
|
||||
"sourceBaselineEv=${actualMetadata.baselineExposure} " +
|
||||
"sourceBaselineGain=${exactDngBaselineExposureGain(actualMetadata)} " +
|
||||
@@ -3443,6 +3470,7 @@ class RawDemosaicProcessor {
|
||||
outputRotation = actualRotation,
|
||||
hdrRatio = regenerationHdrRatio,
|
||||
sourceToShortGain = regenerationSourceToShortGain,
|
||||
hdrNetPostExposureEv = persistedPostExposureEv,
|
||||
colorCorrectionMatrix = linearColorCorrectionMatrix,
|
||||
hueSatMap = activeDcpRenderPlan?.hueSatMap,
|
||||
hueSatMapSupportsOverrange = hueSatMapSupportsOverrange,
|
||||
@@ -3465,10 +3493,19 @@ class RawDemosaicProcessor {
|
||||
"${regeneratedPhotonPgtm.map.mapPointsV}x" +
|
||||
regeneratedPhotonPgtm.map.mapPointsN +
|
||||
" hdrRatio=${regeneratedPhotonPgtm.hdrRatio}" +
|
||||
" finalShortGain=${regeneratedPhotonPgtm.sourceToShortGain}",
|
||||
" finalShortGain=${regeneratedPhotonPgtm.sourceToShortGain}" +
|
||||
" postExposureEv=${regeneratedPhotonPgtm.hdrNetPostExposureEv}",
|
||||
)
|
||||
}
|
||||
|
||||
// Newly generated HDRNet maps contain the downstream Dehaze + DHA curve. The DCP
|
||||
// color map must therefore execute after PGTM; Local Laplacian and ordinary DNG
|
||||
// profile maps retain their existing ordering.
|
||||
val deferDcpHueSatUntilAfterPgtm =
|
||||
photonHdrRequested && hasProfileGainTableMap &&
|
||||
(regeneratePhotonPgtm ||
|
||||
photonHdrRatio?.let { it.isFinite() && it >= 1f } == true)
|
||||
|
||||
// BaselineExposure is source metadata plus an optional classic auto-exposure offset.
|
||||
// Photon HDR never changes it. Rendering only applies explicit edit controls.
|
||||
val effectiveExposureCompensation = rawExposureCompensation
|
||||
@@ -3531,6 +3568,7 @@ class RawDemosaicProcessor {
|
||||
linearColorCorrectionMatrix = linearColorCorrectionMatrix,
|
||||
linearCameraWhite = linearCameraWhite,
|
||||
hueSatMap = activeDcpRenderPlan?.hueSatMap,
|
||||
deferDcpHueSatUntilAfterPgtm = deferDcpHueSatUntilAfterPgtm,
|
||||
applyLinearDngBaselineExposure = applyLinearDngBaselineExposure,
|
||||
hasProfileGainTableMap = hasProfileGainTableMap,
|
||||
applyDcpBaselineExposureOffset = applyDcpBaselineExposureOffset,
|
||||
@@ -3595,7 +3633,6 @@ class RawDemosaicProcessor {
|
||||
// it through ColorCorrectAll's camera-domain inputEV; other linear engines retain
|
||||
// the exact post-matrix 2^EV gain.
|
||||
checkGlError("Before LinearRcdPass")
|
||||
val dehazeTuning = actualMetadata.coreImagingTuning.dehaze.normalized()
|
||||
|
||||
renderLinearRcdPass(
|
||||
metadata = actualMetadata,
|
||||
@@ -3606,10 +3643,10 @@ class RawDemosaicProcessor {
|
||||
rawExposureCompensation = 0f,
|
||||
colorCorrectionMatrix = linearColorCorrectionMatrix,
|
||||
cameraWhite = linearCameraWhite,
|
||||
// MGC ProcessLowFrequency runs DehazeAndDha before ApplyColorMap. Defer the DCP
|
||||
// hue/sat map to a second linear pass only while standalone dehaze is active.
|
||||
// HDRNet's PGTM contains HDRNet -> Dehaze/DHA, so its DCP color map is deferred
|
||||
// to the profile pass. Other paths retain their established linear-pass order.
|
||||
hueSatMap = activeDcpRenderPlan?.hueSatMap
|
||||
?.takeUnless { dehazeTuning.isActive },
|
||||
?.takeUnless { deferDcpHueSatUntilAfterPgtm },
|
||||
applyDngBaselineExposure = applyLinearDngBaselineExposure,
|
||||
clampProfileRgb = clampProfileRgb,
|
||||
hueSatMapSupportsOverrange = hueSatMapSupportsOverrange,
|
||||
@@ -3628,53 +3665,6 @@ class RawDemosaicProcessor {
|
||||
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
|
||||
checkGlError("After LinearRcdPass Swap")
|
||||
if (dehazeTuning.isActive) {
|
||||
checkNotNull(
|
||||
photonDehazePipeline.render(
|
||||
sourceTextureId = demosaicTextureId,
|
||||
targetTextureId = linearOutputTextureId,
|
||||
width = actualWidth,
|
||||
height = actualHeight,
|
||||
tuning = dehazeTuning,
|
||||
),
|
||||
) { "Photon dehaze pipeline failed" }
|
||||
|
||||
val dehazeTempTexture = demosaicTextureId
|
||||
demosaicTextureId = linearOutputTextureId
|
||||
linearOutputTextureId = dehazeTempTexture
|
||||
val dehazeTempFramebuffer = demosaicFramebufferId
|
||||
demosaicFramebufferId = linearOutputFramebufferId
|
||||
linearOutputFramebufferId = dehazeTempFramebuffer
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
|
||||
checkGlError("After PhotonDehazePass Swap")
|
||||
|
||||
activeDcpRenderPlan?.hueSatMap?.takeIf { it.isValid }?.let { hueSatMap ->
|
||||
renderLinearRcdPass(
|
||||
metadata = actualMetadata,
|
||||
sourceTextureId = demosaicTextureId,
|
||||
targetFramebufferId = linearOutputFramebufferId,
|
||||
viewportWidth = actualWidth,
|
||||
viewportHeight = actualHeight,
|
||||
rawExposureCompensation = 0f,
|
||||
colorCorrectionMatrix = identityMatrix3x3(),
|
||||
cameraWhite = floatArrayOf(1f, 1f, 1f),
|
||||
hueSatMap = hueSatMap,
|
||||
applyDngBaselineExposure = false,
|
||||
clampProfileRgb = false,
|
||||
hueSatMapSupportsOverrange = hueSatMapSupportsOverrange,
|
||||
hncsCameraDomainGains = null,
|
||||
label = "PostDehazeColorMapPass",
|
||||
)
|
||||
val colorMapTempTexture = demosaicTextureId
|
||||
demosaicTextureId = linearOutputTextureId
|
||||
linearOutputTextureId = colorMapTempTexture
|
||||
val colorMapTempFramebuffer = demosaicFramebufferId
|
||||
demosaicFramebufferId = linearOutputFramebufferId
|
||||
linearOutputFramebufferId = colorMapTempFramebuffer
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
|
||||
checkGlError("After PostDehazeColorMapPass Swap")
|
||||
}
|
||||
}
|
||||
// LinearRcdPass has consumed the camera-RGB NLM result. The post-CCM pipeline uses
|
||||
// the full-resolution ping-pong textures, so both denoiseprofile textures can go.
|
||||
releaseDenoiseProfileFramebuffers()
|
||||
@@ -3734,7 +3724,7 @@ class RawDemosaicProcessor {
|
||||
metadata = actualMetadata,
|
||||
inputTextureId = combinedInputTexture,
|
||||
dcpRenderPlan = activeDcpRenderPlan,
|
||||
applyDcpHueSatMap = false,
|
||||
applyDcpHueSatMap = deferDcpHueSatUntilAfterPgtm,
|
||||
profileExposureUniforms = combinedProfileExposureUniforms,
|
||||
spectralFilmLut = spektrafilmLut,
|
||||
hncsRenderPlan = hncsRenderPlan,
|
||||
@@ -3769,6 +3759,7 @@ class RawDemosaicProcessor {
|
||||
profileExposureUniforms = combinedProfileExposureUniforms,
|
||||
rawToneMappingParameters = rawToneMappingParameters,
|
||||
applyProfileGainTableMap = hasProfileGainTableMap,
|
||||
applyDcpHueSatMap = deferDcpHueSatUntilAfterPgtm,
|
||||
coordinateInput = if (hasProfileGainTableMap) {
|
||||
RawEngineTonePass.HdrCoordinateInput(
|
||||
textureId = demosaicTextureId,
|
||||
@@ -3896,6 +3887,7 @@ class RawDemosaicProcessor {
|
||||
profileExposureUniforms = profileExposureUniforms,
|
||||
rawToneMappingParameters = rawToneMappingParameters,
|
||||
applyProfileGainTableMap = hasProfileGainTableMap,
|
||||
applyDcpHueSatMap = deferDcpHueSatUntilAfterPgtm,
|
||||
)
|
||||
}
|
||||
renderOutputPass(
|
||||
@@ -4185,7 +4177,8 @@ class RawDemosaicProcessor {
|
||||
rawExposureCompensation = 0f,
|
||||
colorCorrectionMatrix = config.linearColorCorrectionMatrix,
|
||||
cameraWhite = config.linearCameraWhite,
|
||||
hueSatMap = config.hueSatMap,
|
||||
hueSatMap = config.hueSatMap
|
||||
?.takeUnless { config.deferDcpHueSatUntilAfterPgtm },
|
||||
applyDngBaselineExposure = config.applyLinearDngBaselineExposure,
|
||||
clampProfileRgb = config.clampProfileRgb,
|
||||
hueSatMapSupportsOverrange = config.hueSatMapSupportsOverrange,
|
||||
@@ -4204,7 +4197,7 @@ class RawDemosaicProcessor {
|
||||
metadata = config.metadata,
|
||||
inputTextureId = demosaicTextureId,
|
||||
dcpRenderPlan = config.activeDcpRenderPlan,
|
||||
applyDcpHueSatMap = false,
|
||||
applyDcpHueSatMap = config.deferDcpHueSatUntilAfterPgtm,
|
||||
profileExposureUniforms = config.profileExposureUniforms,
|
||||
spectralFilmLut = config.spectralFilmLut,
|
||||
hncsRenderPlan = config.hncsRenderPlan,
|
||||
@@ -4242,6 +4235,7 @@ class RawDemosaicProcessor {
|
||||
profileExposureUniforms = config.profileExposureUniforms,
|
||||
rawToneMappingParameters = config.rawToneMappingParameters,
|
||||
applyProfileGainTableMap = config.hasProfileGainTableMap,
|
||||
applyDcpHueSatMap = config.deferDcpHueSatUntilAfterPgtm,
|
||||
globalOriginX = working.left,
|
||||
globalOriginY = working.top,
|
||||
fullImageWidth = config.fullWidth,
|
||||
@@ -4550,6 +4544,7 @@ class RawDemosaicProcessor {
|
||||
outputRotation: Int,
|
||||
hdrRatio: Float,
|
||||
sourceToShortGain: Float,
|
||||
hdrNetPostExposureEv: Float? = null,
|
||||
colorCorrectionMatrix: FloatArray,
|
||||
hueSatMap: DcpHueSatMap?,
|
||||
hueSatMapSupportsOverrange: Boolean,
|
||||
@@ -4593,6 +4588,7 @@ class RawDemosaicProcessor {
|
||||
outputRotation = outputRotation,
|
||||
hdrRatio = hdrRatio,
|
||||
sourceToShortGain = sourceToShortGain,
|
||||
hdrNetPostExposureEv = hdrNetPostExposureEv,
|
||||
colorCorrectionMatrix = colorCorrectionMatrix,
|
||||
hueSatMap = hueSatMap,
|
||||
hueSatMapSupportsOverrange = hueSatMapSupportsOverrange,
|
||||
@@ -7265,6 +7261,7 @@ class RawDemosaicProcessor {
|
||||
profileExposureUniforms: ProfileExposureUniforms,
|
||||
rawToneMappingParameters: RawToneMappingParameters,
|
||||
applyProfileGainTableMap: Boolean,
|
||||
applyDcpHueSatMap: Boolean = false,
|
||||
coordinateInput: RawEngineTonePass.HdrCoordinateInput? = null,
|
||||
globalOriginX: Int = 0,
|
||||
globalOriginY: Int = 0,
|
||||
@@ -7296,9 +7293,7 @@ class RawDemosaicProcessor {
|
||||
toneMappingParameters = rawToneMappingParameters,
|
||||
profileExposure = profileExposureUniforms,
|
||||
dcpRenderPlan = dcpRenderPlan,
|
||||
// LinearRcdPass has already applied the profile HueSatMap. Adobe still
|
||||
// consumes the selected curve and LookTable through the shared binder.
|
||||
applyDcpHueSatMap = false,
|
||||
applyDcpHueSatMap = applyDcpHueSatMap,
|
||||
spectralFilmLut = spectralFilmLut,
|
||||
hncsRenderPlan = hncsRenderPlan,
|
||||
bindProfileGainTable = { program ->
|
||||
@@ -8826,7 +8821,6 @@ class RawDemosaicProcessor {
|
||||
fastMomentsStatsAlgorithm.release()
|
||||
legacyHighlightHistogramAlgorithm.release()
|
||||
linearRcdPass.release()
|
||||
photonDehazePipeline.release()
|
||||
warpRectilinearPass.release()
|
||||
linearUintToFloatPass.release()
|
||||
linearFloatToUintPass.release()
|
||||
|
||||
@@ -111,8 +111,10 @@ data class RawDngCaptureProfileResult(
|
||||
val exposureOffsetEv: Float?,
|
||||
/** Photon HDR long/short TET ratio; always null for classic auto exposure. */
|
||||
val hdrRatio: Float?,
|
||||
/** Final source/short gain after Photon HDR's capture-viewfinder grid match. */
|
||||
/** Fixed source/short gain used by Photon HDR inference. */
|
||||
val finalShortGain: Float?,
|
||||
/** Viewfinder-match exposure applied after HDRNet + Dehaze/DHA; null for non-HDRNet paths. */
|
||||
val hdrNetPostExposureEv: Float? = null,
|
||||
/** Capture-time MGC AE inputs and results serialized as photon:SummaryText in the DNG XMP. */
|
||||
val rawSceneExposureSummaryText: String? = null,
|
||||
val profileGainTableMap: DngProfileGainTableMap?,
|
||||
@@ -134,19 +136,25 @@ data class RawDngProfilePreparation(
|
||||
val baselineExposureEv: Float,
|
||||
val hdrRatio: Float?,
|
||||
val finalShortGain: Float?,
|
||||
val hdrNetPostExposureEv: Float? = null,
|
||||
val rawSceneExposureSummaryText: String? = null,
|
||||
val profileGainTableMap: DngProfileGainTableMap?,
|
||||
val gpuDemosaicedRawSource: GpuDemosaicedRawSource? = null,
|
||||
)
|
||||
|
||||
/** Process-local capture result persisted with Photon gallery metadata for PGTM regeneration. */
|
||||
internal object RawPhotonHdrRatioMetadata {
|
||||
internal object RawPhotonHdrMetadata {
|
||||
private const val PROPERTY = "photonHdrNetRatio"
|
||||
private const val CONTRACT_PROPERTY = "photonHdrNetRatioContract"
|
||||
private const val CURRENT_CONTRACT = "mgc_fast_moments_v25_portrait_mask_v1"
|
||||
private const val SHORT_GAIN_PROPERTY = "photonHdrNetSourceToShortGain"
|
||||
private const val SHORT_GAIN_CONTRACT_PROPERTY = "photonHdrNetSourceToShortGainContract"
|
||||
private const val CURRENT_SHORT_GAIN_CONTRACT = "mgc_fast_moments_v25_final_short_v1"
|
||||
private const val POST_EXPOSURE_PROPERTY = "photonHdrNetPostExposureEv"
|
||||
private const val POST_EXPOSURE_CONTRACT_PROPERTY =
|
||||
"photonHdrNetPostExposureEvContract"
|
||||
private const val CURRENT_POST_EXPOSURE_CONTRACT =
|
||||
"hdrnet_post_dehaze_viewfinder_v1"
|
||||
|
||||
fun read(properties: Map<String, String>): Float? = properties[PROPERTY]
|
||||
?.toFloatOrNull()
|
||||
@@ -159,10 +167,23 @@ internal object RawPhotonHdrRatioMetadata {
|
||||
?.takeIf { it.isFinite() && it > 0f }
|
||||
}
|
||||
|
||||
fun readPostExposureEv(properties: Map<String, String>): Float? {
|
||||
if (properties[POST_EXPOSURE_CONTRACT_PROPERTY] !=
|
||||
CURRENT_POST_EXPOSURE_CONTRACT
|
||||
) return null
|
||||
return properties[POST_EXPOSURE_PROPERTY]
|
||||
?.toFloatOrNull()
|
||||
?.takeIf {
|
||||
it.isFinite() && it in
|
||||
MeteringSystem.RAW_EXPOSURE_MIN_EV..MeteringSystem.RAW_EXPOSURE_MAX_EV
|
||||
}
|
||||
}
|
||||
|
||||
fun write(
|
||||
properties: Map<String, String>,
|
||||
hdrRatio: Float?,
|
||||
finalShortGain: Float? = null,
|
||||
postExposureEv: Float? = null,
|
||||
): Map<String, String> {
|
||||
val validRatio = hdrRatio?.takeIf { it.isFinite() && it >= 1f } ?: return properties
|
||||
var result = properties + mapOf(
|
||||
@@ -176,6 +197,16 @@ internal object RawPhotonHdrRatioMetadata {
|
||||
SHORT_GAIN_CONTRACT_PROPERTY to CURRENT_SHORT_GAIN_CONTRACT,
|
||||
)
|
||||
}
|
||||
val validPostExposureEv = postExposureEv?.takeIf {
|
||||
it.isFinite() && it in
|
||||
MeteringSystem.RAW_EXPOSURE_MIN_EV..MeteringSystem.RAW_EXPOSURE_MAX_EV
|
||||
}
|
||||
if (validPostExposureEv != null) {
|
||||
result += mapOf(
|
||||
POST_EXPOSURE_PROPERTY to validPostExposureEv.toString(),
|
||||
POST_EXPOSURE_CONTRACT_PROPERTY to CURRENT_POST_EXPOSURE_CONTRACT,
|
||||
)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
|
||||
@@ -4,10 +4,8 @@ import android.graphics.Bitmap
|
||||
import android.graphics.Rect
|
||||
import com.hinnka.mycamera.preview.PortraitMaskSnapshot
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.floor
|
||||
import kotlin.math.max
|
||||
import kotlin.math.pow
|
||||
|
||||
internal data class RawLegacyExposurePreviewFrame(
|
||||
val width: Int,
|
||||
@@ -76,8 +74,8 @@ internal data class RawLegacyHighlightExposureLimit(
|
||||
|
||||
/**
|
||||
* Capture-side viewfinder matching derived from PhotonCamera 1.27.1's spatial solver. Native code
|
||||
* owns reference linearization, robust grid statistics and both exposure solvers. Kotlin only
|
||||
* evaluates the HDRNet candidates requested by native code and retains their inference payloads.
|
||||
* owns reference linearization, robust grid statistics and exposure selection. HDRNet matching
|
||||
* evaluates its completed processing chain once and solves only a downstream scalar exposure.
|
||||
*/
|
||||
internal object RawLegacyAutoExposureMatcher {
|
||||
private const val TAG = "RawLegacyAutoExposureMatcher"
|
||||
@@ -92,10 +90,10 @@ internal object RawLegacyAutoExposureMatcher {
|
||||
val areaFraction: Float,
|
||||
)
|
||||
|
||||
private data class HdrNetInference<T>(
|
||||
val shortEv: Float,
|
||||
val hdrRatioEv: Float,
|
||||
val payload: T,
|
||||
data class HdrNetPostExposureMatch(
|
||||
val exposureEv: Float,
|
||||
val matchRate: Float,
|
||||
val meanAbsoluteErrorEv: Float,
|
||||
)
|
||||
|
||||
fun createRequest(
|
||||
@@ -258,74 +256,53 @@ internal object RawLegacyAutoExposureMatcher {
|
||||
}
|
||||
|
||||
/**
|
||||
* Drives the native two-dimensional HDRNet matcher.
|
||||
*
|
||||
* Native code jointly searches the model's short-EV and HDR-ratio-EV coordinates. Robust
|
||||
* highlight error anchors short exposure, paired p20..p80 dynamic-range error drives HDR
|
||||
* ratio, and their measured cross-response is retained in the damped Jacobian. Selection and
|
||||
* convergence still use the weighted full-grid direct-EV match rate.
|
||||
* 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.
|
||||
*/
|
||||
fun <T> solveHdrNetExposure(
|
||||
fun solveHdrNetPostExposure(
|
||||
referenceFrame: RawLegacyExposurePreviewFrame,
|
||||
initialShortGain: Float,
|
||||
initialLongGain: Float,
|
||||
evaluateCandidate: (shortGain: Float, longGain: Float) -> Pair<T, FloatArray>?,
|
||||
): T? {
|
||||
if (!initialShortGain.isFinite() || !initialLongGain.isFinite() ||
|
||||
initialShortGain <= 0f || initialLongGain < initialShortGain
|
||||
) {
|
||||
return null
|
||||
}
|
||||
val initialHdrRatio = initialLongGain / initialShortGain
|
||||
if (!initialHdrRatio.isFinite() || initialHdrRatio < 1f) return null
|
||||
val maximumHdrRatio = maxOf(
|
||||
initialHdrRatio,
|
||||
RawSceneExposureMath.FAST_MOMENTS_MAX_HDR_RATIO,
|
||||
)
|
||||
displayLinearLumas: FloatArray,
|
||||
maximumExposureEv: Float,
|
||||
): 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
|
||||
) return null
|
||||
val solver = RawLegacyAutoExposureNativeBridge.Solver.create(referenceFrame)
|
||||
?: run {
|
||||
PLog.w(TAG, "Photon HDR matching skipped: viewfinder grid is unreliable")
|
||||
PLog.w(TAG, "HDRNet post-exposure matching skipped: viewfinder grid is unreliable")
|
||||
return null
|
||||
}
|
||||
return solver.use {
|
||||
if (!solver.startHdrNetSolve(initialHdrRatio, maximumHdrRatio)) {
|
||||
return@use null
|
||||
}
|
||||
val inferences = ArrayList<HdrNetInference<T>>()
|
||||
while (true) {
|
||||
val parameters = solver.nextHdrNetParameters() ?: break
|
||||
val shortGain = initialShortGain * 2.0f.pow(parameters.shortEv)
|
||||
val hdrRatio = (initialHdrRatio * 2.0f.pow(parameters.hdrRatioEv))
|
||||
.coerceAtLeast(1f)
|
||||
val longGain = shortGain * hdrRatio
|
||||
if (!shortGain.isFinite() || !longGain.isFinite() ||
|
||||
shortGain <= 0f || longGain < shortGain
|
||||
) {
|
||||
return@use null
|
||||
}
|
||||
val candidate = evaluateCandidate(shortGain, longGain) ?: return@use null
|
||||
if (!solver.submitHdrNetCandidate(
|
||||
parameters = parameters,
|
||||
displayLinearLumas = candidate.second,
|
||||
columns = DngPhotonProfileGainTableGenerator.HDRNET_MATCH_GRID_WIDTH,
|
||||
rows = DngPhotonProfileGainTableGenerator.HDRNET_MATCH_GRID_HEIGHT,
|
||||
)) return@use null
|
||||
inferences += HdrNetInference(
|
||||
shortEv = parameters.shortEv,
|
||||
hdrRatioEv = parameters.hdrRatioEv,
|
||||
payload = candidate.first,
|
||||
solver.solveSingleGridExposure(
|
||||
displayLinearLumas = displayLinearLumas,
|
||||
columns = DngPhotonProfileGainTableGenerator.HDRNET_MATCH_GRID_WIDTH,
|
||||
rows = DngPhotonProfileGainTableGenerator.HDRNET_MATCH_GRID_HEIGHT,
|
||||
minimumExposureEv = MeteringSystem.RAW_EXPOSURE_MIN_EV,
|
||||
maximumExposureEv = minOf(
|
||||
maximumExposureEv,
|
||||
MeteringSystem.RAW_EXPOSURE_MAX_EV,
|
||||
),
|
||||
)?.let { result ->
|
||||
PLog.i(
|
||||
TAG,
|
||||
"HDRNet post-exposure matching result: " +
|
||||
"exposureEv=${result.exposureEv} " +
|
||||
"matchRate=${result.matchRate} " +
|
||||
"meanAbsoluteErrorEv=${result.meanAbsoluteErrorEv}",
|
||||
)
|
||||
HdrNetPostExposureMatch(
|
||||
exposureEv = result.exposureEv,
|
||||
matchRate = result.matchRate,
|
||||
meanAbsoluteErrorEv = result.meanAbsoluteErrorEv,
|
||||
)
|
||||
}
|
||||
val result = solver.hdrNetResult() ?: return@use null
|
||||
val selectedInference = inferences.minByOrNull {
|
||||
abs(it.shortEv - result.shortEv) +
|
||||
abs(it.hdrRatioEv - result.hdrRatioEv)
|
||||
}?.takeIf {
|
||||
abs(it.shortEv - result.shortEv) < HDRNET_PAYLOAD_LOOKUP_TOLERANCE_EV &&
|
||||
abs(it.hdrRatioEv - result.hdrRatioEv) <
|
||||
HDRNET_PAYLOAD_LOOKUP_TOLERANCE_EV
|
||||
} ?: return@use null
|
||||
selectedInference.payload
|
||||
}
|
||||
}
|
||||
|
||||
@@ -378,7 +355,6 @@ internal object RawLegacyAutoExposureMatcher {
|
||||
|
||||
private data class Size(val width: Int, val height: Int)
|
||||
|
||||
private const val HDRNET_PAYLOAD_LOOKUP_TOLERANCE_EV = 0.001f
|
||||
|
||||
private fun resolvePortraitPriority(
|
||||
snapshot: PortraitMaskSnapshot?,
|
||||
|
||||
@@ -6,14 +6,10 @@ internal object RawLegacyAutoExposureNativeBridge {
|
||||
System.loadLibrary("my-native-lib")
|
||||
}
|
||||
|
||||
data class HdrNetParameters(
|
||||
val shortEv: Float,
|
||||
val hdrRatioEv: Float,
|
||||
)
|
||||
|
||||
data class HdrNetResult(
|
||||
val shortEv: Float,
|
||||
val hdrRatioEv: Float,
|
||||
data class SingleExposureResult(
|
||||
val exposureEv: Float,
|
||||
val matchRate: Float,
|
||||
val meanAbsoluteErrorEv: Float,
|
||||
)
|
||||
|
||||
class Solver private constructor(
|
||||
@@ -54,52 +50,38 @@ internal object RawLegacyAutoExposureNativeBridge {
|
||||
)
|
||||
}
|
||||
|
||||
fun startHdrNetSolve(
|
||||
initialHdrRatio: Float,
|
||||
maximumHdrRatio: Float,
|
||||
): Boolean {
|
||||
check(handle != 0L) { "Native exposure solver is closed" }
|
||||
return nativeStartHdrNetSolve(handle, initialHdrRatio, maximumHdrRatio)
|
||||
}
|
||||
|
||||
fun nextHdrNetParameters(): HdrNetParameters? {
|
||||
check(handle != 0L) { "Native exposure solver is closed" }
|
||||
val values = nativeNextHdrNetParameters(handle) ?: return null
|
||||
if (values.size != HDRNET_PARAMETER_VALUE_COUNT) return null
|
||||
return HdrNetParameters(
|
||||
shortEv = values[0],
|
||||
hdrRatioEv = values[1],
|
||||
).takeIf { it.shortEv.isFinite() && it.hdrRatioEv.isFinite() }
|
||||
}
|
||||
|
||||
fun submitHdrNetCandidate(
|
||||
parameters: HdrNetParameters,
|
||||
fun solveSingleGridExposure(
|
||||
displayLinearLumas: FloatArray,
|
||||
columns: Int,
|
||||
rows: Int,
|
||||
): Boolean {
|
||||
minimumExposureEv: Float,
|
||||
maximumExposureEv: Float,
|
||||
): SingleExposureResult? {
|
||||
check(handle != 0L) { "Native exposure solver is closed" }
|
||||
if (columns <= 0 || rows <= 0 || displayLinearLumas.size != columns * rows) {
|
||||
return false
|
||||
if (columns <= 0 || rows <= 0 || displayLinearLumas.size != columns * rows ||
|
||||
!minimumExposureEv.isFinite() || !maximumExposureEv.isFinite() ||
|
||||
minimumExposureEv > maximumExposureEv
|
||||
) {
|
||||
return null
|
||||
}
|
||||
return nativeSubmitHdrNetGridCandidate(
|
||||
val values = nativeSolveSingleGridExposure(
|
||||
handle = handle,
|
||||
shortEv = parameters.shortEv,
|
||||
hdrRatioEv = parameters.hdrRatioEv,
|
||||
candidateDisplayLinearLumas = displayLinearLumas,
|
||||
columns = columns,
|
||||
rows = rows,
|
||||
minimumExposureEv = minimumExposureEv,
|
||||
maximumExposureEv = maximumExposureEv,
|
||||
)
|
||||
}
|
||||
|
||||
fun hdrNetResult(): HdrNetResult? {
|
||||
check(handle != 0L) { "Native exposure solver is closed" }
|
||||
val values = nativeGetHdrNetResult(handle) ?: return null
|
||||
if (values.size != HDRNET_RESULT_VALUE_COUNT) return null
|
||||
return HdrNetResult(
|
||||
shortEv = values[0],
|
||||
hdrRatioEv = values[1],
|
||||
).takeIf { it.shortEv.isFinite() && it.hdrRatioEv.isFinite() }
|
||||
?: return null
|
||||
if (values.size != SINGLE_EXPOSURE_RESULT_VALUE_COUNT) return null
|
||||
return SingleExposureResult(
|
||||
exposureEv = values[0],
|
||||
matchRate = values[1],
|
||||
meanAbsoluteErrorEv = values[2],
|
||||
).takeIf {
|
||||
it.exposureEv.isFinite() && it.matchRate.isFinite() &&
|
||||
it.meanAbsoluteErrorEv.isFinite()
|
||||
}
|
||||
}
|
||||
|
||||
fun configureExposureBounds(minimumEv: Float, maximumEv: Float): Boolean {
|
||||
@@ -157,24 +139,14 @@ internal object RawLegacyAutoExposureNativeBridge {
|
||||
rows: Int,
|
||||
): Boolean
|
||||
|
||||
private external fun nativeStartHdrNetSolve(
|
||||
private external fun nativeSolveSingleGridExposure(
|
||||
handle: Long,
|
||||
initialHdrRatio: Float,
|
||||
maximumHdrRatio: Float,
|
||||
): Boolean
|
||||
|
||||
private external fun nativeNextHdrNetParameters(handle: Long): FloatArray?
|
||||
|
||||
private external fun nativeSubmitHdrNetGridCandidate(
|
||||
handle: Long,
|
||||
shortEv: Float,
|
||||
hdrRatioEv: Float,
|
||||
candidateDisplayLinearLumas: FloatArray,
|
||||
columns: Int,
|
||||
rows: Int,
|
||||
): Boolean
|
||||
|
||||
private external fun nativeGetHdrNetResult(handle: Long): FloatArray?
|
||||
minimumExposureEv: Float,
|
||||
maximumExposureEv: Float,
|
||||
): FloatArray?
|
||||
|
||||
private external fun nativeConfigureExposureBounds(
|
||||
handle: Long,
|
||||
@@ -185,6 +157,5 @@ internal object RawLegacyAutoExposureNativeBridge {
|
||||
private external fun nativeGetResultExposureEv(handle: Long): Float
|
||||
private external fun nativeDestroy(handle: Long)
|
||||
|
||||
private const val HDRNET_PARAMETER_VALUE_COUNT = 2
|
||||
private const val HDRNET_RESULT_VALUE_COUNT = 2
|
||||
private const val SINGLE_EXPOSURE_RESULT_VALUE_COUNT = 3
|
||||
}
|
||||
@@ -94,7 +94,6 @@ fun RawEditPanel(
|
||||
availableLuts: List<LutInfo>,
|
||||
thumbnail: Bitmap?,
|
||||
rawExposureCompensation: Float,
|
||||
rawAdaptiveExposureMode: RawAdaptiveExposureMode,
|
||||
rawHighlightsAdjustment: Float,
|
||||
rawShadowsAdjustment: Float,
|
||||
rawBlackPointCorrection: Float,
|
||||
@@ -113,7 +112,6 @@ fun RawEditPanel(
|
||||
onImportDcp: () -> Unit,
|
||||
onDeleteDcp: (DcpInfo) -> Unit,
|
||||
onRawExposureCompensationChange: (Float) -> Unit,
|
||||
onRawAdaptiveExposureModeChange: (RawAdaptiveExposureMode) -> Unit,
|
||||
onRawHighlightsAdjustmentChange: (Float) -> Unit,
|
||||
onRawShadowsAdjustmentChange: (Float) -> Unit,
|
||||
onRawBlackPointCorrectionChange: (Float) -> Unit,
|
||||
@@ -134,7 +132,9 @@ fun RawEditPanel(
|
||||
onAdjustmentEnd: () -> Unit,
|
||||
onRawExposureCompensationReset: ((Float) -> Unit)? = null,
|
||||
onOpenBaselineLutSheet: (() -> Unit)? = null,
|
||||
showAdaptiveExposureModeSelector: Boolean = true,
|
||||
showAdaptiveExposureControl: Boolean = false,
|
||||
rawAdaptiveExposureMode: RawAdaptiveExposureMode = RawAdaptiveExposureMode.PHOTON_HDR,
|
||||
onRawAdaptiveExposureModeChange: (RawAdaptiveExposureMode) -> Unit = {},
|
||||
showDngMetadataControls: Boolean = false,
|
||||
contentMode: RawEditPanelContentMode = RawEditPanelContentMode.FULL,
|
||||
selectedHncsProfileId: String? = null,
|
||||
@@ -157,15 +157,7 @@ fun RawEditPanel(
|
||||
.padding(vertical = 16.dp),
|
||||
verticalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
if (showAdaptiveExposureModeSelector) {
|
||||
RawAdaptiveExposureModeSetting(
|
||||
mode = rawAdaptiveExposureMode,
|
||||
onModeChange = { mode ->
|
||||
onRawAdaptiveExposureModeChange(mode)
|
||||
onAdjustmentEnd()
|
||||
},
|
||||
)
|
||||
} else {
|
||||
if (showAdaptiveExposureControl) {
|
||||
RawSwitchSettingItem(
|
||||
title = stringResource(R.string.settings_raw_photon_hdr),
|
||||
description = stringResource(R.string.settings_raw_photon_hdr_edit_description),
|
||||
@@ -178,11 +170,10 @@ fun RawEditPanel(
|
||||
RawAdaptiveExposureMode.OFF
|
||||
}
|
||||
)
|
||||
onAdjustmentEnd()
|
||||
},
|
||||
)
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
}
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
RawRenderingEngineSettingsPanel(
|
||||
selectedDcpId = selectedDcpId,
|
||||
@@ -465,33 +456,6 @@ fun RawRenderingEngineSettingsPanel(
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun RawAdaptiveExposureModeSetting(
|
||||
mode: RawAdaptiveExposureMode,
|
||||
onModeChange: (RawAdaptiveExposureMode) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
RawChoiceSetting(
|
||||
title = stringResource(R.string.settings_raw_adaptive_exposure_mode),
|
||||
description = stringResource(R.string.settings_raw_adaptive_exposure_mode_description),
|
||||
levels = listOf(
|
||||
RawAdaptiveExposureMode.PHOTON_HDR.name to
|
||||
stringResource(R.string.settings_raw_adaptive_exposure_mode_photon_hdr),
|
||||
RawAdaptiveExposureMode.LEGACY_AUTO_EXPOSURE.name to
|
||||
stringResource(R.string.settings_raw_adaptive_exposure_mode_legacy),
|
||||
RawAdaptiveExposureMode.OFF.name to
|
||||
stringResource(R.string.settings_raw_adaptive_exposure_mode_off),
|
||||
),
|
||||
currentLevel = mode.name,
|
||||
onLevelSelected = { persistedName ->
|
||||
RawAdaptiveExposureMode.entries
|
||||
.firstOrNull { it.name == persistedName }
|
||||
?.let(onModeChange)
|
||||
},
|
||||
modifier = modifier,
|
||||
)
|
||||
}
|
||||
|
||||
/** Shared RAW DNG metadata correction controls for a lens-specific configuration. */
|
||||
@Composable
|
||||
fun RawDngMetadataCorrectionSettings(
|
||||
|
||||
@@ -600,6 +600,11 @@ fun GalleryEditScreen(
|
||||
return
|
||||
}
|
||||
val currentEditSourcePhoto = editSourcePhoto ?: currentPhoto
|
||||
val currentEditMetadata = currentEditSourcePhoto.metadata ?: viewModel.currentMediaMetadata
|
||||
val currentEditMimeType = currentEditMetadata?.mimeType ?: currentEditSourcePhoto.mimeType
|
||||
val isImportedDng = currentEditMetadata?.isImported == true &&
|
||||
(currentEditMimeType?.contains("dng", ignoreCase = true) == true ||
|
||||
currentEditSourcePhoto.displayName.endsWith(".dng", ignoreCase = true))
|
||||
|
||||
val previewSourceWidth = previewBitmap?.width?.takeIf { it > 0 }
|
||||
?: currentPhoto.width.takeIf { it > 0 }
|
||||
@@ -648,10 +653,13 @@ fun GalleryEditScreen(
|
||||
var pendingRawPreviewRefresh by remember(currentEditSourcePhoto.id) { mutableStateOf(false) }
|
||||
val isRefreshingRawPreview = viewModel.refreshingPhotos.contains(currentEditSourcePhoto.id)
|
||||
|
||||
fun refreshRawPreview(showResultToast: Boolean = false) {
|
||||
fun refreshRawPreview(
|
||||
showResultToast: Boolean = false,
|
||||
forceRegeneratePhotonPgtm: Boolean = forceRegeneratePhotonPgtmOnRefresh,
|
||||
) {
|
||||
viewModel.refreshRawPreview(
|
||||
photo = currentEditSourcePhoto,
|
||||
forceRegeneratePhotonPgtm = forceRegeneratePhotonPgtmOnRefresh,
|
||||
forceRegeneratePhotonPgtm = forceRegeneratePhotonPgtm,
|
||||
) { success ->
|
||||
if (showResultToast) {
|
||||
Toast.makeText(
|
||||
@@ -663,13 +671,19 @@ fun GalleryEditScreen(
|
||||
}
|
||||
}
|
||||
|
||||
fun requestRawPreviewRefresh(showResultToast: Boolean = false) {
|
||||
fun requestRawPreviewRefresh(
|
||||
showResultToast: Boolean = false,
|
||||
forceRegeneratePhotonPgtm: Boolean = forceRegeneratePhotonPgtmOnRefresh,
|
||||
) {
|
||||
if (!isRaw) return
|
||||
if (viewModel.refreshingPhotos.contains(currentEditSourcePhoto.id)) {
|
||||
pendingRawPreviewRefresh = true
|
||||
return
|
||||
}
|
||||
refreshRawPreview(showResultToast)
|
||||
refreshRawPreview(
|
||||
showResultToast = showResultToast,
|
||||
forceRegeneratePhotonPgtm = forceRegeneratePhotonPgtm,
|
||||
)
|
||||
}
|
||||
|
||||
LaunchedEffect(isRefreshingRawPreview, pendingRawPreviewRefresh, currentEditSourcePhoto.id) {
|
||||
@@ -1823,8 +1837,19 @@ fun GalleryEditScreen(
|
||||
if (success) requestRawPreviewRefresh()
|
||||
}
|
||||
},
|
||||
onRawAdaptiveExposureModeChange =
|
||||
viewModel::selectRawAdaptiveExposureModeForEdit,
|
||||
onRawAdaptiveExposureModeChange = { mode ->
|
||||
viewModel.selectRawAdaptiveExposureModeForEdit(mode)
|
||||
viewModel.persistCurrentRawEditMetadata(
|
||||
currentEditSourcePhoto
|
||||
) { success ->
|
||||
if (success) {
|
||||
requestRawPreviewRefresh(
|
||||
forceRegeneratePhotonPgtm =
|
||||
mode.usesPhotonHdr,
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
onRawHighlightsAdjustmentChange = {
|
||||
viewModel.saveRawHighlightsAdjustmentValue(currentEditSourcePhoto, it)
|
||||
},
|
||||
@@ -1898,7 +1923,7 @@ fun GalleryEditScreen(
|
||||
onOpenBaselineLutSheet = {
|
||||
showRawBaselineLutSelectorSheet = true
|
||||
},
|
||||
showAdaptiveExposureModeSelector = false,
|
||||
showAdaptiveExposureControl = isImportedDng,
|
||||
showDngMetadataControls = true,
|
||||
contentMode = RawEditPanelContentMode.FULL,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
|
||||
@@ -385,7 +385,6 @@ fun SettingsScreen(
|
||||
val rawHncsProfileId by viewModel.rawHncsProfileId.collectAsState()
|
||||
val rawHncsFilmCurveMode by viewModel.rawHncsFilmCurveMode.collectAsState()
|
||||
val rawExposureCompensation by viewModel.rawExposureCompensation.collectAsState()
|
||||
val rawAdaptiveExposureMode by viewModel.rawAdaptiveExposureMode.collectAsState()
|
||||
val rawHighlightsAdjustment by viewModel.rawHighlightsAdjustment.collectAsState()
|
||||
val rawShadowsAdjustment by viewModel.rawShadowsAdjustment.collectAsState()
|
||||
val rawMinShutterSpeedNs by viewModel.rawMinShutterSpeedNs.collectAsState()
|
||||
@@ -2024,7 +2023,6 @@ fun SettingsScreen(
|
||||
availableLuts = availableLuts,
|
||||
thumbnail = previewThumbnail,
|
||||
rawExposureCompensation = rawExposureCompensationUi,
|
||||
rawAdaptiveExposureMode = rawAdaptiveExposureMode,
|
||||
rawHighlightsAdjustment = rawHighlightsAdjustmentUi,
|
||||
rawShadowsAdjustment = rawShadowsAdjustmentUi,
|
||||
rawBlackPointCorrection = rawBlackPointCorrectionUi,
|
||||
@@ -2048,11 +2046,6 @@ fun SettingsScreen(
|
||||
onRawExposureCompensationChange = {
|
||||
rawExposureCompensationUi = it
|
||||
},
|
||||
onRawAdaptiveExposureModeChange = { mode ->
|
||||
rawToneMappingParametersUi =
|
||||
rawToneMappingParametersUi.withPhotonHdr(mode.usesPhotonHdr)
|
||||
viewModel.setRawAdaptiveExposureMode(mode)
|
||||
},
|
||||
onRawHighlightsAdjustmentChange = {
|
||||
rawHighlightsAdjustmentUi = it
|
||||
},
|
||||
|
||||
@@ -830,6 +830,7 @@ object RawProcessor {
|
||||
baselineExposureEv = finalBaselineExposureEv,
|
||||
hdrRatio = captureProfile?.hdrRatio,
|
||||
finalShortGain = captureProfile?.finalShortGain,
|
||||
hdrNetPostExposureEv = captureProfile?.hdrNetPostExposureEv,
|
||||
rawSceneExposureSummaryText = captureProfile?.rawSceneExposureSummaryText,
|
||||
profileGainTableMap = preparedProfileGainTableMap,
|
||||
gpuDemosaicedRawSource = captureProfile?.gpuDemosaicedRawSource,
|
||||
|
||||
@@ -69,7 +69,6 @@ import com.hinnka.mycamera.raw.RawProcessingPreferences
|
||||
import com.hinnka.mycamera.raw.RawProfile
|
||||
import com.hinnka.mycamera.raw.RawCfaCorrection
|
||||
import com.hinnka.mycamera.raw.RawCaptureExposureCompensationMetadata
|
||||
import com.hinnka.mycamera.raw.RawAdaptiveExposureMode
|
||||
import com.hinnka.mycamera.raw.RawDemosaicProcessor
|
||||
import com.hinnka.mycamera.raw.RawProfileToneMapMode
|
||||
import com.hinnka.mycamera.raw.RawRenderingEngine
|
||||
@@ -146,11 +145,7 @@ private data class RawSpectralFilmSettings(
|
||||
val tuning: SpectralFilmTuning
|
||||
)
|
||||
|
||||
private fun resolveEffectiveRawAutoExposure(
|
||||
userPrefs: UserPreferences?
|
||||
): Boolean {
|
||||
return userPrefs?.rawAutoExposure ?: true
|
||||
}
|
||||
private fun resolveEffectiveRawAutoExposure(): Boolean = false
|
||||
|
||||
private fun resolveCaptureSharpening(
|
||||
isRawCapture: Boolean,
|
||||
@@ -934,7 +929,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
userPrefs: UserPreferences?
|
||||
): RawToneMappingParameters {
|
||||
val base = userPrefs?.rawToneMappingParameters ?: RawToneMappingParameters.DEFAULT
|
||||
return base.normalized()
|
||||
return base.withPhotonHdr(true)
|
||||
}
|
||||
|
||||
fun savePreset(preset: com.hinnka.mycamera.model.CameraPreset) {
|
||||
@@ -1358,19 +1353,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
val rawExposureCompensation: StateFlow<Float> = userPreferencesRepository.userPreferences
|
||||
.map { it.rawExposureCompensation }
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, 0f)
|
||||
val rawAdaptiveExposureMode: StateFlow<RawAdaptiveExposureMode> =
|
||||
userPreferencesRepository.userPreferences
|
||||
.map { preferences ->
|
||||
RawAdaptiveExposureMode.resolve(
|
||||
usePhotonHdr = preferences.rawToneMappingParameters.usePhotonHdr,
|
||||
useLegacyAutoExposure = preferences.rawAutoExposure,
|
||||
)
|
||||
}
|
||||
.stateIn(
|
||||
viewModelScope,
|
||||
SharingStarted.Eagerly,
|
||||
RawAdaptiveExposureMode.LEGACY_AUTO_EXPOSURE,
|
||||
)
|
||||
val rawHighlightsAdjustment: StateFlow<Float> = userPreferencesRepository.userPreferences
|
||||
.map { it.rawHighlightsAdjustment }
|
||||
.stateIn(viewModelScope, SharingStarted.Eagerly, 0f)
|
||||
@@ -2393,9 +2375,6 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
fun setRawExposureCompensation(value: Float) {
|
||||
viewModelScope.launch { userPreferencesRepository.saveRawExposureCompensation(value) }
|
||||
}
|
||||
fun setRawAdaptiveExposureMode(mode: RawAdaptiveExposureMode) {
|
||||
viewModelScope.launch { userPreferencesRepository.saveRawAdaptiveExposureMode(mode) }
|
||||
}
|
||||
fun setRawHighlightsAdjustment(value: Float) {
|
||||
viewModelScope.launch { userPreferencesRepository.saveRawHighlightsAdjustment(value) }
|
||||
}
|
||||
@@ -2822,9 +2801,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
target = baselineTarget,
|
||||
userPrefs = userPrefs,
|
||||
)
|
||||
val effectiveRawAutoExposure = resolveEffectiveRawAutoExposure(
|
||||
userPrefs = userPrefs,
|
||||
)
|
||||
val effectiveRawAutoExposure = resolveEffectiveRawAutoExposure()
|
||||
|
||||
val spectralFilmSettings = resolveRawSpectralFilmSettings(userPrefs)
|
||||
|
||||
@@ -5278,9 +5255,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
userPrefs = userPrefs,
|
||||
)
|
||||
val baselineMetadata = resolveBaselineMetadata(baselineTarget, userPrefs)
|
||||
val effectiveRawAutoExposure = resolveEffectiveRawAutoExposure(
|
||||
userPrefs = userPrefs,
|
||||
)
|
||||
val effectiveRawAutoExposure = resolveEffectiveRawAutoExposure()
|
||||
val spectralFilmSettings = resolveRawSpectralFilmSettings(userPrefs)
|
||||
val captureExposureBias = state.value.exposureBias
|
||||
val captureExposureCompensationEv = state.value.run {
|
||||
@@ -5447,9 +5422,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
(userPrefs?.mirrorFrontCamera ?: true)
|
||||
val baselineMetadata = resolveBaselineMetadata(BaselineColorCorrectionTarget.JPG, userPrefs)
|
||||
val currentCameraId = cameraController.getCurrentCameraId()
|
||||
val effectiveRawAutoExposure = resolveEffectiveRawAutoExposure(
|
||||
userPrefs = userPrefs,
|
||||
)
|
||||
val effectiveRawAutoExposure = resolveEffectiveRawAutoExposure()
|
||||
val spectralFilmSettings = resolveRawSpectralFilmSettings(userPrefs)
|
||||
val captureInfo = cameraController.rebuildCaptureInfo(
|
||||
result = null,
|
||||
@@ -5720,9 +5693,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
userPrefs = userPrefs,
|
||||
)
|
||||
val baselineMetadata = resolveBaselineMetadata(baselineTarget, userPrefs)
|
||||
val effectiveRawAutoExposure = resolveEffectiveRawAutoExposure(
|
||||
userPrefs = userPrefs,
|
||||
)
|
||||
val effectiveRawAutoExposure = resolveEffectiveRawAutoExposure()
|
||||
val spectralFilmSettings = resolveRawSpectralFilmSettings(userPrefs)
|
||||
val captureExposureBias = state.value.exposureBias
|
||||
val captureExposureCompensationEv = state.value.run {
|
||||
@@ -6152,9 +6123,7 @@ class CameraViewModel(application: Application) : AndroidViewModel(application)
|
||||
userPrefs = userPrefs,
|
||||
)
|
||||
val baselineMetadata = resolveBaselineMetadata(baselineTarget, userPrefs)
|
||||
val effectiveRawAutoExposure = resolveEffectiveRawAutoExposure(
|
||||
userPrefs = userPrefs,
|
||||
)
|
||||
val effectiveRawAutoExposure = resolveEffectiveRawAutoExposure()
|
||||
val spectralFilmSettings = resolveRawSpectralFilmSettings(userPrefs)
|
||||
|
||||
// 创建统一的 PhotoMetadata,包含编辑配置和拍摄信息
|
||||
|
||||
@@ -859,14 +859,8 @@
|
||||
<string name="settings_raw_profile_tone_map_default">預設</string>
|
||||
<string name="settings_raw_profile_tone_map_embedded">內嵌</string>
|
||||
<string name="settings_raw_profile_tone_map_oppo_master">OPPO 大師</string>
|
||||
<string name="settings_raw_photon_hdr">HDRNet模型</string>
|
||||
<string name="settings_raw_photon_hdr_description">在明暗反差較大的場景中保留更多高光與暗部細節,讓畫面亮度過渡更自然。</string>
|
||||
<string name="settings_raw_photon_hdr_edit_description">為目前照片套用 HDRNet模型,保留更多高光與暗部細節。</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode">HDR+ 動態範圍最佳化</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_description">選擇 HDR+ 處理方式:HDRNet模型或局部色調映射。</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_off">關閉</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_photon_hdr">HDRNet模型</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_legacy">局部色調映射</string>
|
||||
<string name="settings_raw_photon_hdr">動態範圍最佳化</string>
|
||||
<string name="settings_raw_photon_hdr_edit_description">為目前匯入的 DNG 套用 HDRNet 動態範圍最佳化。</string>
|
||||
<string name="settings_raw_agx_white_relative_exposure">AgX 白色相對曝光</string>
|
||||
<string name="settings_raw_agx_black_relative_exposure">AgX 黑色相對曝光</string>
|
||||
<string name="settings_raw_agx_shoulder">AgX 肩部</string>
|
||||
|
||||
@@ -877,14 +877,8 @@
|
||||
<string name="settings_raw_profile_tone_map_default">默认</string>
|
||||
<string name="settings_raw_profile_tone_map_embedded">内嵌</string>
|
||||
<string name="settings_raw_profile_tone_map_oppo_master">OPPO 大师</string>
|
||||
<string name="settings_raw_photon_hdr">HDRNet模型</string>
|
||||
<string name="settings_raw_photon_hdr_description">在明暗反差较大的场景中保留更多高光和暗部细节,让画面亮度过渡更自然。</string>
|
||||
<string name="settings_raw_photon_hdr_edit_description">对当前照片应用 HDRNet模型,保留更多高光和暗部细节。</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode">HDR+ 动态范围优化</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_description">选择 HDR+ 处理方式:HDRNet模型或局部色调映射。</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_off">关闭</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_photon_hdr">HDRNet模型</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_legacy">局部色调映射</string>
|
||||
<string name="settings_raw_photon_hdr">动态范围优化</string>
|
||||
<string name="settings_raw_photon_hdr_edit_description">对当前导入的 DNG 应用 HDRNet 动态范围优化。</string>
|
||||
<string name="settings_raw_agx_white_relative_exposure">AgX 白色相对曝光</string>
|
||||
<string name="settings_raw_agx_black_relative_exposure">AgX 黑色相对曝光</string>
|
||||
<string name="settings_raw_agx_shoulder">AgX 肩部</string>
|
||||
|
||||
@@ -859,14 +859,8 @@
|
||||
<string name="settings_raw_profile_tone_map_default">預設</string>
|
||||
<string name="settings_raw_profile_tone_map_embedded">內嵌</string>
|
||||
<string name="settings_raw_profile_tone_map_oppo_master">OPPO 大師</string>
|
||||
<string name="settings_raw_photon_hdr">HDRNet模型</string>
|
||||
<string name="settings_raw_photon_hdr_description">在明暗反差較大的場景中保留更多高光與暗部細節,讓畫面亮度過渡更自然。</string>
|
||||
<string name="settings_raw_photon_hdr_edit_description">為目前照片套用 HDRNet模型,保留更多高光與暗部細節。</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode">HDR+ 動態範圍最佳化</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_description">選擇 HDR+ 處理方式:HDRNet模型或局部色調映射。</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_off">關閉</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_photon_hdr">HDRNet模型</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_legacy">局部色調映射</string>
|
||||
<string name="settings_raw_photon_hdr">動態範圍最佳化</string>
|
||||
<string name="settings_raw_photon_hdr_edit_description">為目前匯入的 DNG 套用 HDRNet 動態範圍最佳化。</string>
|
||||
<string name="settings_raw_agx_white_relative_exposure">AgX 白色相對曝光</string>
|
||||
<string name="settings_raw_agx_black_relative_exposure">AgX 黑色相對曝光</string>
|
||||
<string name="settings_raw_agx_shoulder">AgX 肩部</string>
|
||||
|
||||
@@ -859,14 +859,8 @@
|
||||
<string name="settings_raw_profile_tone_map_default">預設</string>
|
||||
<string name="settings_raw_profile_tone_map_embedded">內嵌</string>
|
||||
<string name="settings_raw_profile_tone_map_oppo_master">OPPO 大師</string>
|
||||
<string name="settings_raw_photon_hdr">HDRNet模型</string>
|
||||
<string name="settings_raw_photon_hdr_description">在明暗反差較大的場景中保留更多高光與暗部細節,讓畫面亮度過渡更自然。</string>
|
||||
<string name="settings_raw_photon_hdr_edit_description">為目前照片套用 HDRNet模型,保留更多高光與暗部細節。</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode">HDR+ 動態範圍最佳化</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_description">選擇 HDR+ 處理方式:HDRNet模型或局部色調映射。</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_off">關閉</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_photon_hdr">HDRNet模型</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_legacy">局部色調映射</string>
|
||||
<string name="settings_raw_photon_hdr">動態範圍最佳化</string>
|
||||
<string name="settings_raw_photon_hdr_edit_description">為目前匯入的 DNG 套用 HDRNet 動態範圍最佳化。</string>
|
||||
<string name="settings_raw_agx_white_relative_exposure">AgX 白色相對曝光</string>
|
||||
<string name="settings_raw_agx_black_relative_exposure">AgX 黑色相對曝光</string>
|
||||
<string name="settings_raw_agx_shoulder">AgX 肩部</string>
|
||||
|
||||
@@ -867,14 +867,8 @@
|
||||
<string name="settings_raw_profile_tone_map_default">Default</string>
|
||||
<string name="settings_raw_profile_tone_map_embedded">Embedded</string>
|
||||
<string name="settings_raw_profile_tone_map_oppo_master">OPPO Master</string>
|
||||
<string name="settings_raw_photon_hdr">HDRNet Model</string>
|
||||
<string name="settings_raw_photon_hdr_description">Preserves more highlight and shadow detail in high-contrast scenes for more natural tonal transitions.</string>
|
||||
<string name="settings_raw_photon_hdr_edit_description">Apply the HDRNet model to this photo to preserve more highlight and shadow detail.</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode">HDR+ Dynamic Range Optimization</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_description">Choose an HDR+ processing method: HDRNet Model or Local Tone Mapping.</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_off">Off</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_photon_hdr">HDRNet Model</string>
|
||||
<string name="settings_raw_adaptive_exposure_mode_legacy">Local Tone Mapping</string>
|
||||
<string name="settings_raw_photon_hdr">Dynamic Range Optimization</string>
|
||||
<string name="settings_raw_photon_hdr_edit_description">Apply HDRNet dynamic range optimization to this imported DNG.</string>
|
||||
<string name="settings_raw_agx_white_relative_exposure">AgX White Relative Exposure</string>
|
||||
<string name="settings_raw_agx_black_relative_exposure">AgX Black Relative Exposure</string>
|
||||
<string name="settings_raw_agx_shoulder">AgX Shoulder</string>
|
||||
|
||||
@@ -99,7 +99,7 @@ class PhotonCoreImagingTuningTest {
|
||||
|
||||
assertEquals(4f, normalized.strength, 0f)
|
||||
assertEquals(0f, normalized.dynamicHighlightStrength, 0f)
|
||||
assertEquals(false, normalized.isActive)
|
||||
assertEquals(true, normalized.isActive)
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -115,7 +115,7 @@ class PhotonCoreImagingTuningTest {
|
||||
assertEquals(true, tuning.dehaze.enabled)
|
||||
assertEquals(1f, tuning.dehaze.strength, 0f)
|
||||
assertEquals(1f, tuning.dehaze.dynamicHighlightStrength, 0f)
|
||||
assertEquals(false, tuning.dehaze.isActive)
|
||||
assertEquals(true, tuning.dehaze.isActive)
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import com.hinnka.mycamera.processor.PhotonDehazeTuning
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assume.assumeNoException
|
||||
@@ -37,23 +38,27 @@ class DngHdrNetViewfinderGridTest {
|
||||
)
|
||||
|
||||
val grids = try {
|
||||
DngPhotonProfileGainTableGenerator.hdrNetDisplayLinearLumaGrid(
|
||||
DngPhotonProfileGainTableGenerator.evaluateHdrNetDehaze(
|
||||
plan = neutralBaselinePlan,
|
||||
coefficients = coefficients,
|
||||
modelInput = modelInput,
|
||||
outputRotation = 0,
|
||||
) to DngPhotonProfileGainTableGenerator.hdrNetDisplayLinearLumaGrid(
|
||||
dehazeTuning = PhotonDehazeTuning.DISABLED,
|
||||
) to DngPhotonProfileGainTableGenerator.evaluateHdrNetDehaze(
|
||||
plan = brightBaselinePlan,
|
||||
coefficients = coefficients,
|
||||
modelInput = modelInput,
|
||||
outputRotation = 270,
|
||||
dehazeTuning = PhotonDehazeTuning.DISABLED,
|
||||
)
|
||||
} catch (error: UnsatisfiedLinkError) {
|
||||
assumeNoException("Android HDRNet JNI is unavailable on this host", error)
|
||||
return
|
||||
}
|
||||
val neutralGrid = checkNotNull(grids.first)
|
||||
val brightBaselineGrid = checkNotNull(grids.second)
|
||||
val neutralEvaluation = checkNotNull(grids.first)
|
||||
val brightBaselineEvaluation = checkNotNull(grids.second)
|
||||
val neutralGrid = neutralEvaluation.displayLinearLumas
|
||||
val brightBaselineGrid = brightBaselineEvaluation.displayLinearLumas
|
||||
|
||||
assertEquals(
|
||||
DngPhotonProfileGainTableGenerator.HDRNET_MATCH_GRID_WIDTH *
|
||||
@@ -62,5 +67,11 @@ class DngHdrNetViewfinderGridTest {
|
||||
)
|
||||
neutralGrid.forEach { assertEquals(0.249999f, it, 2e-6f) }
|
||||
assertArrayEquals(neutralGrid, brightBaselineGrid, 2e-6f)
|
||||
assertEquals(0.249999f, neutralEvaluation.postDehazeP99Peak, 2e-6f)
|
||||
assertEquals(
|
||||
neutralEvaluation.postDehazeP99Peak,
|
||||
brightBaselineEvaluation.postDehazeP99Peak,
|
||||
2e-6f,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,100 +1,80 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import com.hinnka.mycamera.processor.PhotonDehazeTuning
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class PhotonDehazeCurveTest {
|
||||
@Test
|
||||
fun zeroStrengthsProduceIdentityCurve() {
|
||||
val histogram = PhotonDehazeHistogram()
|
||||
repeat(4096) { histogram.addLinearRgb(0.2f, 0.4f, 0.6f) }
|
||||
|
||||
val curve = requireNotNull(
|
||||
histogram.estimateCurve(
|
||||
PhotonDehazeTuning(
|
||||
enabled = true,
|
||||
strength = 0f,
|
||||
dynamicHighlightStrength = 0f,
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
assertEquals(0f, curve.hazePointLow, 0f)
|
||||
assertEquals(0f, curve.hazePointHigh, 0f)
|
||||
assertEquals(1f, curve.highlightScale, 0f)
|
||||
assertEquals(0.37f, curve.mappedLuminance(0.37f), 1e-6f)
|
||||
fun identityCurveLeavesTheCompleteRangeUnchanged() {
|
||||
for (index in 0..1000) {
|
||||
val input = index / 1000f
|
||||
assertEquals(input, mapped(input, PhotonDehazeCurveParameters.IDENTITY), 0f)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dehazeCurveIsFiniteContinuousAndMonotonic() {
|
||||
val histogram = PhotonDehazeHistogram()
|
||||
repeat(10000) { index ->
|
||||
val value = index.toFloat() / 9999f
|
||||
histogram.addLinearRgb(value * 0.8f, value, value * 0.6f)
|
||||
}
|
||||
val curve = requireNotNull(
|
||||
histogram.estimateCurve(
|
||||
PhotonDehazeTuning(
|
||||
enabled = true,
|
||||
strength = 1f,
|
||||
dynamicHighlightStrength = 1f,
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
var previous = curve.mappedLuminance(0f)
|
||||
val curve = testCurve()
|
||||
var previous = mapped(0f, curve)
|
||||
for (index in 1..1000) {
|
||||
val mapped = curve.mappedLuminance(index / 1000f)
|
||||
assertTrue(mapped.isFinite())
|
||||
assertTrue("curve regressed at $index", mapped + 1e-6f >= previous)
|
||||
previous = mapped
|
||||
val output = mapped(index / 1000f, curve)
|
||||
assertTrue(output.isFinite())
|
||||
assertTrue("curve regressed at $index", output + 1e-6f >= previous)
|
||||
previous = output
|
||||
}
|
||||
val below = curve.mappedLuminance((curve.hazePointHigh - 1e-5f).coerceAtLeast(0f))
|
||||
val above = curve.mappedLuminance((curve.hazePointHigh + 1e-5f).coerceAtMost(1f))
|
||||
val joinInput = curve.hazePointHigh / curve.highlightScale
|
||||
val below = mapped((joinInput - 1e-5f).coerceAtLeast(0f), curve)
|
||||
val above = mapped((joinInput + 1e-5f).coerceAtMost(1f), curve)
|
||||
assertTrue(kotlin.math.abs(above - below) < 1e-3f)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dynamicHighlightControlDoesNotChangeDetectedSceneScale() {
|
||||
fun estimate(dynamicStrength: Float): PhotonDehazeCurveParameters {
|
||||
val histogram = PhotonDehazeHistogram()
|
||||
repeat(2048) { histogram.addLinearRgb(0.3f, 0.4f, 0.5f) }
|
||||
return requireNotNull(
|
||||
histogram.estimateCurve(
|
||||
PhotonDehazeTuning(
|
||||
enabled = true,
|
||||
strength = 1f,
|
||||
dynamicHighlightStrength = dynamicStrength,
|
||||
),
|
||||
),
|
||||
)
|
||||
fun nativeCurveContractRoundTripsAndRejectsInvalidPayloads() {
|
||||
val original = testCurve()
|
||||
val restored = requireNotNull(
|
||||
PhotonDehazeCurveParameters.fromNativeArray(original.toNativeArray()),
|
||||
)
|
||||
for (index in 0..100) {
|
||||
val input = index / 100f
|
||||
assertEquals(mapped(input, original), mapped(input, restored), 0f)
|
||||
}
|
||||
|
||||
val disabled = estimate(0f)
|
||||
val enabled = estimate(1f)
|
||||
assertEquals(enabled.detectedHighlightScale, disabled.detectedHighlightScale, 0f)
|
||||
assertEquals(1f, disabled.highlightScale, 0f)
|
||||
assertEquals(enabled.detectedHighlightScale, enabled.highlightScale, 0f)
|
||||
assertNull(PhotonDehazeCurveParameters.fromNativeArray(FloatArray(7)))
|
||||
assertNull(
|
||||
PhotonDehazeCurveParameters.fromNativeArray(
|
||||
original.toNativeArray().also { it[2] = Float.NaN },
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun shaderUsesGpuResidentSharedHistogramAndSharedRgbGain() {
|
||||
val histogram = PhotonDehazePipeline.HISTOGRAM_COMPUTE_SHADER
|
||||
val curve = PhotonDehazePipeline.CURVE_COMPUTE_SHADER
|
||||
val apply = PhotonDehazePipeline.APPLY_COMPUTE_SHADER
|
||||
private fun testCurve(): PhotonDehazeCurveParameters {
|
||||
val hazePointLow = 0.04f
|
||||
val hazePointHigh = 0.08f
|
||||
val interval = hazePointHigh - hazePointLow
|
||||
val quadratic = 1f /
|
||||
(interval * interval + 2f * (1f - hazePointHigh) * interval)
|
||||
val shoulder = interval * interval * quadratic
|
||||
return PhotonDehazeCurveParameters(
|
||||
hazePointLow = hazePointLow,
|
||||
hazePointHigh = hazePointHigh,
|
||||
highlightScale = 1.2f,
|
||||
quadraticCoefficient = quadratic,
|
||||
linearSlope = (1f - shoulder) / (1f - hazePointHigh),
|
||||
shoulderValue = shoulder,
|
||||
detectedHighlightScale = 1.2f,
|
||||
sampledPixelCount = 256 * 192,
|
||||
)
|
||||
}
|
||||
|
||||
assertTrue(histogram.contains("layout(local_size_x = 128, local_size_y = 1)"))
|
||||
assertTrue(histogram.contains("shared vec4 sharedLinearRgb[512]"))
|
||||
assertTrue(histogram.contains("sharedHazeBins[previous] == hazeBin"))
|
||||
assertTrue(histogram.contains("atomicAdd(histogram.hazeHistogram"))
|
||||
assertTrue(histogram.contains("atomicAdd(histogram.highlightHistogram"))
|
||||
assertTrue(curve.contains("index < 5251 && nextHighlight < 5"))
|
||||
assertTrue(curve.contains("index < 877 && nextHaze < 20"))
|
||||
assertTrue(apply.contains("imageStore("))
|
||||
assertTrue(apply.contains("(rgb.r + rgb.g + rgb.b) * (1.0 / 3.0)"))
|
||||
assertTrue(apply.contains("rgb * gain"))
|
||||
assertTrue(!apply.contains("pow("))
|
||||
private fun mapped(input: Float, curve: PhotonDehazeCurveParameters): Float {
|
||||
val scaled = (input.coerceIn(0f, 1f) * curve.highlightScale).coerceAtMost(1f)
|
||||
return if (scaled < curve.hazePointHigh) {
|
||||
val distance = (scaled - curve.hazePointLow).coerceAtLeast(0f)
|
||||
distance * distance * curve.quadraticCoefficient
|
||||
} else {
|
||||
curve.shoulderValue +
|
||||
(scaled - curve.hazePointHigh) * curve.linearSlope
|
||||
}.coerceIn(0f, 1f)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user