feat: photon hdr viewfinder match
This commit is contained in:
1 parent
b6595a06f3
commit
9a79adf77d
12 files changed
+1050
-676
No files matched your search
@@ -12,6 +12,12 @@ namespace {
|
||||
|
||||
constexpr char kLogTag[] = "PLog_DngHdrNetPgtm";
|
||||
constexpr float kHdrNetGainEpsilon = 1.0e-6f;
|
||||
constexpr float kHdrNetLumaRed = 0.298828125f;
|
||||
constexpr float kHdrNetLumaGreen = 0.5869140625f;
|
||||
constexpr float kHdrNetLumaBlue = 0.1142578125f;
|
||||
constexpr float kDisplayLumaRed = 0.2126f;
|
||||
constexpr float kDisplayLumaGreen = 0.7152f;
|
||||
constexpr float kDisplayLumaBlue = 0.0722f;
|
||||
|
||||
struct AxisSample {
|
||||
int lower;
|
||||
@@ -65,6 +71,45 @@ AxisSample MakeAxisSample(int output_index, int output_size, int source_size) {
|
||||
};
|
||||
}
|
||||
|
||||
AxisSample MakeNormalizedAxisSample(float coordinate, int source_size) {
|
||||
const float source_position =
|
||||
std::clamp(coordinate, 0.0f, 1.0f) * source_size - 0.5f;
|
||||
const float source_floor = std::floor(source_position);
|
||||
const int lower_unclamped = static_cast<int>(source_floor);
|
||||
return {
|
||||
std::clamp(lower_unclamped, 0, source_size - 1),
|
||||
std::clamp(lower_unclamped + 1, 0, source_size - 1),
|
||||
source_position - source_floor,
|
||||
};
|
||||
}
|
||||
|
||||
struct RgbSample {
|
||||
float red;
|
||||
float green;
|
||||
float blue;
|
||||
};
|
||||
|
||||
RgbSample SampleModelRgb(const float* model_input, int input_width,
|
||||
int input_channels, const AxisSample& sample_x,
|
||||
const AxisSample& sample_y) {
|
||||
const auto channel_at = [&](int x, int y, int channel) {
|
||||
return model_input[
|
||||
(static_cast<size_t>(y) * input_width + x) * input_channels + channel];
|
||||
};
|
||||
const auto sample_channel = [&](int channel) {
|
||||
const float top =
|
||||
Lerp(channel_at(sample_x.lower, sample_y.lower, channel),
|
||||
channel_at(sample_x.upper, sample_y.lower, channel),
|
||||
sample_x.amount);
|
||||
const float bottom =
|
||||
Lerp(channel_at(sample_x.lower, sample_y.upper, channel),
|
||||
channel_at(sample_x.upper, sample_y.upper, channel),
|
||||
sample_x.amount);
|
||||
return Lerp(top, bottom, sample_y.amount);
|
||||
};
|
||||
return {sample_channel(0), sample_channel(1), sample_channel(2)};
|
||||
}
|
||||
|
||||
float SampleCoefficient(const float* coefficients, int source_width,
|
||||
int source_depth, int coefficient_count,
|
||||
const AxisSample& sample_x,
|
||||
@@ -159,6 +204,164 @@ bool IsValidAcrCurve(const float* curve, int count) {
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" JNIEXPORT jboolean JNICALL
|
||||
Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeEvaluateDisplayLinearLumaGrid(
|
||||
JNIEnv* env, jobject, jfloatArray coefficients_array,
|
||||
jint source_grid_width, jint source_grid_height, jint source_grid_depth,
|
||||
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,
|
||||
jfloatArray guide_shifts_array, jfloatArray guide_slopes_array,
|
||||
jfloatArray output_lumas_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 ||
|
||||
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 ||
|
||||
(output_rotation != 0 && output_rotation != 90 &&
|
||||
output_rotation != 180 && output_rotation != 270)) {
|
||||
LogError("Rejected invalid HDRNet display-grid parameters");
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
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 output_values =
|
||||
static_cast<int64_t>(output_grid_width) * output_grid_height;
|
||||
const int guide_count = env->GetArrayLength(guide_shifts_array);
|
||||
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 ||
|
||||
env->GetArrayLength(output_lumas_array) != output_values) {
|
||||
LogError("Rejected mismatched HDRNet display-grid 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 output_lumas(env, output_lumas_array);
|
||||
if (coefficients.data() == nullptr || model_input.data() == nullptr ||
|
||||
guide_shifts.data() == nullptr || guide_slopes.data() == nullptr ||
|
||||
output_lumas.data() == nullptr) {
|
||||
LogError("Unable to acquire HDRNet display-grid arrays");
|
||||
return JNI_FALSE;
|
||||
}
|
||||
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)) {
|
||||
LogError("Rejected non-finite HDRNet display-grid input");
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
const int output_count = static_cast<int>(output_values);
|
||||
const int footprint_sample_count =
|
||||
footprint_samples_per_axis * footprint_samples_per_axis;
|
||||
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;
|
||||
double luma_sum = 0.0;
|
||||
for (int sample_y = 0; sample_y < footprint_samples_per_axis; ++sample_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) {
|
||||
const float output_u =
|
||||
(grid_x + (sample_x + 0.5f) / footprint_samples_per_axis) /
|
||||
output_grid_width;
|
||||
const float gl_v = 1.0f - output_v_top;
|
||||
float source_u = output_u;
|
||||
float source_v = gl_v;
|
||||
if (output_rotation == 90) {
|
||||
source_u = gl_v;
|
||||
source_v = 1.0f - output_u;
|
||||
} else if (output_rotation == 180) {
|
||||
source_u = 1.0f - output_u;
|
||||
source_v = 1.0f - gl_v;
|
||||
} else if (output_rotation == 270) {
|
||||
source_u = 1.0f - gl_v;
|
||||
source_v = output_u;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
output_lumas.data()[cell] =
|
||||
static_cast<float>(luma_sum / footprint_sample_count);
|
||||
}
|
||||
if (!output_valid.load(std::memory_order_relaxed) ||
|
||||
!IsFiniteArray(output_lumas.data(), static_cast<int>(output_values))) {
|
||||
LogError("HDRNet display-linear grid evaluation produced a non-finite value");
|
||||
return JNI_FALSE;
|
||||
}
|
||||
output_lumas.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,
|
||||
|
||||
@@ -27,11 +27,13 @@ constexpr int kMinimumReliableCellCount = 32;
|
||||
constexpr float kMinimumReferenceWeightSum = 16.0f;
|
||||
constexpr float kHuberDeltaEv = 0.25f;
|
||||
constexpr float kMaximumAbsoluteLog2Residual = 4.0f;
|
||||
constexpr float kMinimumLumaDeltaEv = 0.01f;
|
||||
constexpr float kMinimumCandidateStepEv = 0.01f;
|
||||
constexpr float kMinimumInitialStepEv = 0.25f;
|
||||
constexpr float kMaximumInitialStepEv = 2.0f;
|
||||
constexpr int kMaximumSampleCount = 16;
|
||||
constexpr float kRobustCorrectionToleranceEv = 0.025f;
|
||||
constexpr float kMinimumUsefulResponseSlope = 0.05f;
|
||||
constexpr int kMaximumSampleCount = 6;
|
||||
constexpr int kMinimumModelConvergenceSampleCount = 2;
|
||||
constexpr float kHighConfidenceMatchRate = 0.85f;
|
||||
constexpr float kMatchRateTrendEpsilon = 0.002f;
|
||||
constexpr float kScoreEqualityEpsilon = 0.000001f;
|
||||
@@ -40,7 +42,7 @@ constexpr float kSrgbLinearScale = 12.92f;
|
||||
constexpr float kSrgbTransferA = 0.055f;
|
||||
constexpr float kSrgbTransferGamma = 2.4f;
|
||||
constexpr float kDisplayLinearLumaFloor = 1.0f / (255.0f * 12.92f);
|
||||
constexpr int kNativeResultSize = 15;
|
||||
constexpr int kNativeResultSize = 16;
|
||||
|
||||
float SrgbToLinear(float value) {
|
||||
const float clamped = std::clamp(value, 0.0f, 1.0f);
|
||||
@@ -166,6 +168,40 @@ float WeightedMedian(std::vector<WeightedValue>* values, float weight_sum) {
|
||||
return values->back().value;
|
||||
}
|
||||
|
||||
float RobustExposureCorrection(
|
||||
const std::vector<WeightedValue>& residuals,
|
||||
float weight_sum) {
|
||||
if (residuals.empty() || !(weight_sum > 0.0f)) {
|
||||
return std::numeric_limits<float>::quiet_NaN();
|
||||
}
|
||||
// This is the zero of the derivative of the same Huber loss used by IsBetter().
|
||||
// Predicting this correction keeps candidate generation and final selection aligned.
|
||||
const auto huber_score = [&](float correction_ev) {
|
||||
double score = 0.0;
|
||||
for (const WeightedValue& residual : residuals) {
|
||||
score += residual.weight * std::clamp(
|
||||
residual.value + correction_ev,
|
||||
-kHuberDeltaEv,
|
||||
kHuberDeltaEv);
|
||||
}
|
||||
return score;
|
||||
};
|
||||
|
||||
float lower = -kMaximumAbsoluteLog2Residual;
|
||||
float upper = kMaximumAbsoluteLog2Residual;
|
||||
if (huber_score(lower) >= 0.0) return lower;
|
||||
if (huber_score(upper) <= 0.0) return upper;
|
||||
for (int iteration = 0; iteration < 24; ++iteration) {
|
||||
const float midpoint = (lower + upper) * 0.5f;
|
||||
if (huber_score(midpoint) > 0.0) {
|
||||
upper = midpoint;
|
||||
} else {
|
||||
lower = midpoint;
|
||||
}
|
||||
}
|
||||
return (lower + upper) * 0.5f;
|
||||
}
|
||||
|
||||
struct MatchResult {
|
||||
int matched_cell_count = 0;
|
||||
int valid_cell_count = 0;
|
||||
@@ -174,6 +210,8 @@ struct MatchResult {
|
||||
float mean_absolute_log2_ratio = std::numeric_limits<float>::infinity();
|
||||
float median_log2_ratio = std::numeric_limits<float>::quiet_NaN();
|
||||
float robust_log2_loss = std::numeric_limits<float>::infinity();
|
||||
float recommended_exposure_correction_ev =
|
||||
std::numeric_limits<float>::quiet_NaN();
|
||||
float reference_weight_sum = 0.0f;
|
||||
};
|
||||
|
||||
@@ -210,10 +248,7 @@ public:
|
||||
}
|
||||
if (samples_.empty()) return IssueCandidate(0.0f);
|
||||
|
||||
const Sample& best = BestSample();
|
||||
if (best.match.match_rate >= kHighConfidenceMatchRate &&
|
||||
std::isfinite(best.match.median_log2_ratio) &&
|
||||
std::abs(best.match.median_log2_ratio) <= kMinimumLumaDeltaEv) {
|
||||
if (HasConverged()) {
|
||||
finished_ = true;
|
||||
return std::nullopt;
|
||||
}
|
||||
@@ -231,20 +266,64 @@ public:
|
||||
const jint* pixels,
|
||||
int width,
|
||||
int height) {
|
||||
if (!pending_exposure_ev_.has_value() ||
|
||||
std::abs(*pending_exposure_ev_ - exposure_ev) > kMinimumCandidateStepEv * 0.1f ||
|
||||
if (!IsExpectedCandidate(exposure_ev) ||
|
||||
width != width_ || height != height_) {
|
||||
return false;
|
||||
}
|
||||
MatchResult match;
|
||||
if (!Evaluate(pixels, width, height, &match)) return false;
|
||||
samples_.push_back(Sample{exposure_ev, match});
|
||||
pending_exposure_ev_.reset();
|
||||
return CommitCandidate(exposure_ev, match);
|
||||
}
|
||||
|
||||
bool SubmitCandidate(
|
||||
float exposure_ev,
|
||||
const float* display_linear_lumas,
|
||||
int columns,
|
||||
int rows) {
|
||||
if (!IsExpectedCandidate(exposure_ev) || display_linear_lumas == nullptr ||
|
||||
columns != kGridColumns || rows != kGridRows) {
|
||||
return false;
|
||||
}
|
||||
MatchResult match;
|
||||
if (!EvaluateGridLumas(
|
||||
display_linear_lumas,
|
||||
columns * rows,
|
||||
&match)) {
|
||||
return false;
|
||||
}
|
||||
return CommitCandidate(exposure_ev, match);
|
||||
}
|
||||
|
||||
bool ConfigureExposureBounds(float minimum_ev, float maximum_ev) {
|
||||
if (!std::isfinite(minimum_ev) || !std::isfinite(maximum_ev) ||
|
||||
pending_exposure_ev_.has_value()) {
|
||||
return false;
|
||||
}
|
||||
const float safe_minimum = std::clamp(minimum_ev, kMinExposureEv, kMaxExposureEv);
|
||||
const float safe_maximum = std::clamp(maximum_ev, kMinExposureEv, kMaxExposureEv);
|
||||
if (safe_minimum > safe_maximum || safe_minimum > 0.0f || safe_maximum < 0.0f) {
|
||||
return false;
|
||||
}
|
||||
minimum_exposure_ev_ = safe_minimum;
|
||||
maximum_exposure_ev_ = safe_maximum;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool HasResult() const { return !samples_.empty(); }
|
||||
|
||||
bool HasConverged() const {
|
||||
if (!HasResult()) return false;
|
||||
const MatchResult& match = LastSample().match;
|
||||
if (!std::isfinite(match.recommended_exposure_correction_ev) ||
|
||||
std::abs(match.recommended_exposure_correction_ev) >
|
||||
kRobustCorrectionToleranceEv) {
|
||||
return false;
|
||||
}
|
||||
return static_cast<int>(samples_.size()) >=
|
||||
kMinimumModelConvergenceSampleCount ||
|
||||
match.match_rate >= kHighConfidenceMatchRate;
|
||||
}
|
||||
|
||||
const Sample& BestSample() const {
|
||||
return *std::max_element(
|
||||
samples_.begin(),
|
||||
@@ -258,6 +337,18 @@ public:
|
||||
int ExcludedHighlightCellCount() const { return excluded_highlight_cell_count_; }
|
||||
|
||||
private:
|
||||
bool IsExpectedCandidate(float exposure_ev) const {
|
||||
return pending_exposure_ev_.has_value() && std::isfinite(exposure_ev) &&
|
||||
std::abs(*pending_exposure_ev_ - exposure_ev) <=
|
||||
kMinimumCandidateStepEv * 0.1f;
|
||||
}
|
||||
|
||||
bool CommitCandidate(float exposure_ev, const MatchResult& match) {
|
||||
samples_.push_back(Sample{exposure_ev, match});
|
||||
pending_exposure_ev_.reset();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Initialize(const jint* pixels, int width, int height) {
|
||||
if (!BuildGridLumas(pixels, width, height, &reference_grid_lumas_)) {
|
||||
return false;
|
||||
@@ -298,6 +389,20 @@ private:
|
||||
if (!BuildGridLumas(pixels, width, height, &candidate_grid_lumas)) {
|
||||
return false;
|
||||
}
|
||||
return EvaluateGridLumas(
|
||||
candidate_grid_lumas.data(),
|
||||
static_cast<int>(candidate_grid_lumas.size()),
|
||||
output);
|
||||
}
|
||||
|
||||
bool EvaluateGridLumas(
|
||||
const float* candidate_grid_lumas,
|
||||
int candidate_count,
|
||||
MatchResult* output) const {
|
||||
if (candidate_grid_lumas == nullptr || output == nullptr ||
|
||||
candidate_count != kGridCellCount) {
|
||||
return false;
|
||||
}
|
||||
const int valid_count = static_cast<int>(eligible_cell_indices_.size());
|
||||
std::vector<WeightedValue> log2_ratios(static_cast<size_t>(valid_count));
|
||||
int matched_count = 0;
|
||||
@@ -348,11 +453,15 @@ private:
|
||||
static_cast<float>(compared_weight_sum));
|
||||
output->robust_log2_loss =
|
||||
static_cast<float>(robust_log2_loss_sum / compared_weight_sum);
|
||||
output->recommended_exposure_correction_ev = RobustExposureCorrection(
|
||||
log2_ratios,
|
||||
static_cast<float>(compared_weight_sum));
|
||||
output->reference_weight_sum = static_cast<float>(compared_weight_sum);
|
||||
return std::isfinite(output->match_rate) &&
|
||||
std::isfinite(output->mean_absolute_log2_ratio) &&
|
||||
std::isfinite(output->median_log2_ratio) &&
|
||||
std::isfinite(output->robust_log2_loss) &&
|
||||
std::isfinite(output->recommended_exposure_correction_ev) &&
|
||||
std::isfinite(output->reference_weight_sum);
|
||||
}
|
||||
|
||||
@@ -381,7 +490,8 @@ private:
|
||||
}
|
||||
|
||||
std::optional<float> IssueCandidate(float exposure_ev) {
|
||||
const float safe_ev = std::clamp(exposure_ev, kMinExposureEv, kMaxExposureEv);
|
||||
const float safe_ev =
|
||||
std::clamp(exposure_ev, minimum_exposure_ev_, maximum_exposure_ev_);
|
||||
if (IsAlreadySampled(safe_ev)) return std::nullopt;
|
||||
pending_exposure_ev_ = safe_ev;
|
||||
return pending_exposure_ev_;
|
||||
@@ -398,7 +508,8 @@ private:
|
||||
float acquisition_score,
|
||||
std::vector<Candidate>* candidates) const {
|
||||
if (!std::isfinite(exposure_ev) || !std::isfinite(acquisition_score)) return;
|
||||
const float safe_ev = std::clamp(exposure_ev, kMinExposureEv, kMaxExposureEv);
|
||||
const float safe_ev =
|
||||
std::clamp(exposure_ev, minimum_exposure_ev_, maximum_exposure_ev_);
|
||||
if (IsAlreadySampled(safe_ev)) return;
|
||||
auto duplicate = std::find_if(candidates->begin(), candidates->end(), [&](const Candidate& c) {
|
||||
return std::abs(c.exposure_ev - safe_ev) < kMinimumCandidateStepEv;
|
||||
@@ -413,16 +524,23 @@ private:
|
||||
std::optional<float> SelectNextCandidate() const {
|
||||
std::vector<Candidate> candidates;
|
||||
const Sample& best = BestSample();
|
||||
const Sample& last = LastSample();
|
||||
|
||||
for (const Sample& sample : samples_) {
|
||||
if (!std::isfinite(sample.match.median_log2_ratio)) continue;
|
||||
const float correction =
|
||||
sample.match.recommended_exposure_correction_ev;
|
||||
if (!std::isfinite(correction)) continue;
|
||||
const float predicted_correction = samples_.size() == 1
|
||||
? std::clamp(
|
||||
correction,
|
||||
-kMaximumInitialStepEv,
|
||||
kMaximumInitialStepEv)
|
||||
: correction;
|
||||
const float predicted_ev =
|
||||
sample.exposure_ev - sample.match.median_log2_ratio;
|
||||
const float prediction_distance =
|
||||
std::abs(predicted_ev - sample.exposure_ev);
|
||||
const float score =
|
||||
0.40f + sample.match.match_rate * 0.45f +
|
||||
std::min(prediction_distance, 1.0f) * 0.05f;
|
||||
sample.exposure_ev + predicted_correction;
|
||||
const float score = 2.0f +
|
||||
(sample.exposure_ev == last.exposure_ev ? 0.5f : 0.0f) +
|
||||
0.1f / (0.05f + std::abs(correction));
|
||||
AddCandidate(predicted_ev, score, &candidates);
|
||||
}
|
||||
|
||||
@@ -441,92 +559,62 @@ private:
|
||||
const Sample& upper = *sorted_samples[index + 1];
|
||||
const float width = upper.exposure_ev - lower.exposure_ev;
|
||||
if (width < kMinimumCandidateStepEv * 2.0f) continue;
|
||||
const bool crosses_luma_target =
|
||||
std::isfinite(lower.match.median_log2_ratio) &&
|
||||
std::isfinite(upper.match.median_log2_ratio) &&
|
||||
((lower.match.median_log2_ratio <= 0.0f &&
|
||||
upper.match.median_log2_ratio >= 0.0f) ||
|
||||
(lower.match.median_log2_ratio >= 0.0f &&
|
||||
upper.match.median_log2_ratio <= 0.0f));
|
||||
float candidate_ev;
|
||||
if (crosses_luma_target &&
|
||||
std::abs(upper.match.median_log2_ratio -
|
||||
lower.match.median_log2_ratio) > 0.0001f) {
|
||||
candidate_ev = lower.exposure_ev -
|
||||
lower.match.median_log2_ratio * width /
|
||||
(upper.match.median_log2_ratio -
|
||||
lower.match.median_log2_ratio);
|
||||
const float margin = width * 0.15f;
|
||||
const float lower_correction =
|
||||
lower.match.recommended_exposure_correction_ev;
|
||||
const float upper_correction =
|
||||
upper.match.recommended_exposure_correction_ev;
|
||||
if (!std::isfinite(lower_correction) ||
|
||||
!std::isfinite(upper_correction)) {
|
||||
continue;
|
||||
}
|
||||
const float response_slope =
|
||||
(upper_correction - lower_correction) / width;
|
||||
if (!(response_slope < -kMinimumUsefulResponseSlope)) continue;
|
||||
// Calibrate the next step from the measured exposure response instead of assuming
|
||||
// that an input EV change always produces an identical output-luma EV change.
|
||||
float candidate_ev =
|
||||
lower.exposure_ev - lower_correction / response_slope;
|
||||
const bool brackets_optimum =
|
||||
(lower_correction >= 0.0f && upper_correction <= 0.0f) ||
|
||||
(lower_correction <= 0.0f && upper_correction >= 0.0f);
|
||||
if (brackets_optimum) {
|
||||
candidate_ev = std::clamp(
|
||||
candidate_ev,
|
||||
lower.exposure_ev + margin,
|
||||
upper.exposure_ev - margin);
|
||||
} else if (lower.match.match_rate > upper.match.match_rate) {
|
||||
candidate_ev = lower.exposure_ev + width * 0.382f;
|
||||
} else if (upper.match.match_rate > lower.match.match_rate) {
|
||||
candidate_ev = lower.exposure_ev + width * 0.618f;
|
||||
lower.exposure_ev,
|
||||
upper.exposure_ev);
|
||||
} else {
|
||||
candidate_ev = (lower.exposure_ev + upper.exposure_ev) * 0.5f;
|
||||
candidate_ev = std::clamp(
|
||||
candidate_ev,
|
||||
lower.exposure_ev - width,
|
||||
upper.exposure_ev + width);
|
||||
}
|
||||
const float endpoint_rate =
|
||||
std::max(lower.match.match_rate, upper.match.match_rate);
|
||||
const float rate_gradient =
|
||||
std::abs(lower.match.match_rate - upper.match.match_rate);
|
||||
const float acquisition = endpoint_rate +
|
||||
std::min(width, 1.0f) * 0.20f +
|
||||
rate_gradient * 0.35f +
|
||||
(crosses_luma_target ? 0.10f : 0.0f);
|
||||
const float acquisition =
|
||||
(brackets_optimum ? 4.0f : 3.0f) +
|
||||
0.1f / (0.05f +
|
||||
std::min(std::abs(lower_correction),
|
||||
std::abs(upper_correction)));
|
||||
AddCandidate(candidate_ev, acquisition, &candidates);
|
||||
}
|
||||
|
||||
if (sorted_samples.size() == 1) {
|
||||
const Sample& sample = *sorted_samples.front();
|
||||
float direction = -sample.match.median_log2_ratio;
|
||||
if (!std::isfinite(direction) || std::abs(direction) <= kMinimumLumaDeltaEv) {
|
||||
direction = 1.0f;
|
||||
}
|
||||
const float step = std::clamp(
|
||||
std::abs(direction),
|
||||
kMinimumInitialStepEv,
|
||||
kMaximumInitialStepEv);
|
||||
AddCandidate(
|
||||
sample.exposure_ev + std::copysign(step, direction),
|
||||
1.0f,
|
||||
&candidates);
|
||||
} else {
|
||||
const Sample& left = *sorted_samples.front();
|
||||
const Sample& left_neighbor = *sorted_samples[1];
|
||||
const float left_improvement =
|
||||
left.match.match_rate - left_neighbor.match.match_rate;
|
||||
if (left_improvement > kMatchRateTrendEpsilon ||
|
||||
(std::isfinite(left.match.median_log2_ratio) &&
|
||||
left.match.median_log2_ratio > kMinimumLumaDeltaEv)) {
|
||||
float direction = sample.match.recommended_exposure_correction_ev;
|
||||
const bool needs_validation_probe = !std::isfinite(direction) ||
|
||||
std::abs(direction) <= kRobustCorrectionToleranceEv;
|
||||
if (needs_validation_probe) {
|
||||
if (!std::isfinite(direction) || direction == 0.0f) {
|
||||
direction = -sample.match.median_log2_ratio;
|
||||
}
|
||||
if (!std::isfinite(direction) || direction == 0.0f) {
|
||||
direction = -kMinimumInitialStepEv;
|
||||
}
|
||||
const float step = std::clamp(
|
||||
left_neighbor.exposure_ev - left.exposure_ev,
|
||||
std::abs(direction),
|
||||
kMinimumInitialStepEv,
|
||||
1.0f);
|
||||
kMaximumInitialStepEv);
|
||||
AddCandidate(
|
||||
left.exposure_ev - step,
|
||||
left.match.match_rate + 0.30f +
|
||||
std::max(left_improvement, 0.0f),
|
||||
&candidates);
|
||||
}
|
||||
|
||||
const Sample& right = *sorted_samples.back();
|
||||
const Sample& right_neighbor = *sorted_samples[sorted_samples.size() - 2];
|
||||
const float right_improvement =
|
||||
right.match.match_rate - right_neighbor.match.match_rate;
|
||||
if (right_improvement > kMatchRateTrendEpsilon ||
|
||||
(std::isfinite(right.match.median_log2_ratio) &&
|
||||
right.match.median_log2_ratio < -kMinimumLumaDeltaEv)) {
|
||||
const float step = std::clamp(
|
||||
right.exposure_ev - right_neighbor.exposure_ev,
|
||||
kMinimumInitialStepEv,
|
||||
1.0f);
|
||||
AddCandidate(
|
||||
right.exposure_ev + step,
|
||||
right.match.match_rate + 0.30f +
|
||||
std::max(right_improvement, 0.0f),
|
||||
sample.exposure_ev + std::copysign(step, direction),
|
||||
5.0f,
|
||||
&candidates);
|
||||
}
|
||||
}
|
||||
@@ -551,6 +639,8 @@ private:
|
||||
int excluded_shadow_cell_count_ = 0;
|
||||
int excluded_highlight_cell_count_ = 0;
|
||||
float reference_weight_sum_ = 0.0f;
|
||||
float minimum_exposure_ev_ = kMinExposureEv;
|
||||
float maximum_exposure_ev_ = kMaxExposureEv;
|
||||
bool finished_ = false;
|
||||
std::optional<float> pending_exposure_ev_;
|
||||
std::vector<float> reference_grid_lumas_;
|
||||
@@ -574,9 +664,10 @@ jfloatArray CreateSampleArray(JNIEnv* env, const Sample& sample) {
|
||||
sample.match.median_log2_ratio,
|
||||
sample.match.robust_log2_loss,
|
||||
sample.match.reference_weight_sum,
|
||||
sample.match.recommended_exposure_correction_ev,
|
||||
};
|
||||
jfloatArray result = env->NewFloatArray(9);
|
||||
if (result != nullptr) env->SetFloatArrayRegion(result, 0, 9, values);
|
||||
jfloatArray result = env->NewFloatArray(10);
|
||||
if (result != nullptr) env->SetFloatArrayRegion(result, 0, 10, values);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -646,6 +737,61 @@ Java_com_hinnka_mycamera_raw_RawLegacyAutoExposureNativeBridge_nativeSubmitCandi
|
||||
return submitted ? JNI_TRUE : JNI_FALSE;
|
||||
}
|
||||
|
||||
extern "C" JNIEXPORT jboolean JNICALL
|
||||
Java_com_hinnka_mycamera_raw_RawLegacyAutoExposureNativeBridge_nativeSubmitGridCandidate(
|
||||
JNIEnv* env,
|
||||
jobject,
|
||||
jlong handle,
|
||||
jfloat exposure_ev,
|
||||
jfloatArray candidate_display_linear_lumas,
|
||||
jint columns,
|
||||
jint rows) {
|
||||
ExposureSolver* solver = FromHandle(handle);
|
||||
if (solver == nullptr || candidate_display_linear_lumas == nullptr ||
|
||||
columns != kGridColumns || rows != kGridRows ||
|
||||
env->GetArrayLength(candidate_display_linear_lumas) != kGridCellCount) {
|
||||
return JNI_FALSE;
|
||||
}
|
||||
jfloat* lumas =
|
||||
env->GetFloatArrayElements(candidate_display_linear_lumas, nullptr);
|
||||
if (lumas == nullptr) return JNI_FALSE;
|
||||
bool submitted = false;
|
||||
try {
|
||||
submitted = solver->SubmitCandidate(
|
||||
exposure_ev,
|
||||
lumas,
|
||||
columns,
|
||||
rows);
|
||||
} catch (const std::bad_alloc&) {
|
||||
submitted = false;
|
||||
}
|
||||
env->ReleaseFloatArrayElements(candidate_display_linear_lumas, lumas, JNI_ABORT);
|
||||
return submitted ? JNI_TRUE : JNI_FALSE;
|
||||
}
|
||||
|
||||
extern "C" JNIEXPORT jboolean JNICALL
|
||||
Java_com_hinnka_mycamera_raw_RawLegacyAutoExposureNativeBridge_nativeConfigureExposureBounds(
|
||||
JNIEnv*,
|
||||
jobject,
|
||||
jlong handle,
|
||||
jfloat minimum_ev,
|
||||
jfloat maximum_ev) {
|
||||
ExposureSolver* solver = FromHandle(handle);
|
||||
if (solver == nullptr) return JNI_FALSE;
|
||||
return solver->ConfigureExposureBounds(minimum_ev, maximum_ev)
|
||||
? JNI_TRUE
|
||||
: JNI_FALSE;
|
||||
}
|
||||
|
||||
extern "C" JNIEXPORT jboolean JNICALL
|
||||
Java_com_hinnka_mycamera_raw_RawLegacyAutoExposureNativeBridge_nativeHasConverged(
|
||||
JNIEnv*,
|
||||
jobject,
|
||||
jlong handle) {
|
||||
ExposureSolver* solver = FromHandle(handle);
|
||||
return solver != nullptr && solver->HasConverged() ? JNI_TRUE : JNI_FALSE;
|
||||
}
|
||||
|
||||
extern "C" JNIEXPORT jfloatArray JNICALL
|
||||
Java_com_hinnka_mycamera_raw_RawLegacyAutoExposureNativeBridge_nativeGetLastSample(
|
||||
JNIEnv* env,
|
||||
@@ -674,6 +820,7 @@ Java_com_hinnka_mycamera_raw_RawLegacyAutoExposureNativeBridge_nativeGetResult(
|
||||
best.match.median_log2_ratio,
|
||||
best.match.robust_log2_loss,
|
||||
best.match.reference_weight_sum,
|
||||
best.match.recommended_exposure_correction_ev,
|
||||
static_cast<float>(solver->SampleCount()),
|
||||
static_cast<float>(solver->ExcludedShadowCellCount()),
|
||||
static_cast<float>(solver->ExcludedHighlightCellCount()),
|
||||
|
||||
@@ -51,6 +51,68 @@ internal object DngHdrNetProfileGainTableNative {
|
||||
return output.takeIf { completed }
|
||||
}
|
||||
|
||||
fun evaluateDisplayLinearLumaGrid(
|
||||
plan: HdrNetProfileGainTablePlan,
|
||||
coefficients: FloatArray,
|
||||
modelInput: FloatArray,
|
||||
outputRotation: Int,
|
||||
guideShifts: FloatArray,
|
||||
guideSlopes: FloatArray,
|
||||
renderMinGain: Float,
|
||||
renderMaxGain: Float,
|
||||
outputGridWidth: Int,
|
||||
outputGridHeight: Int,
|
||||
footprintSamplesPerAxis: Int,
|
||||
): FloatArray? {
|
||||
val outputCount = outputGridWidth.toLong() * outputGridHeight
|
||||
if (outputCount !in 1..Int.MAX_VALUE.toLong()) return null
|
||||
val output = FloatArray(outputCount.toInt())
|
||||
val completed = nativeEvaluateDisplayLinearLumaGrid(
|
||||
coefficients = coefficients,
|
||||
sourceGridWidth = DngPhotonProfileGainTableGenerator.HDRNET_GRID_WIDTH,
|
||||
sourceGridHeight = DngPhotonProfileGainTableGenerator.HDRNET_GRID_HEIGHT,
|
||||
sourceGridDepth = DngPhotonProfileGainTableGenerator.HDRNET_GRID_DEPTH,
|
||||
coefficientCount = DngPhotonProfileGainTableGenerator.HDRNET_COEFFICIENT_COUNT,
|
||||
modelInput = modelInput,
|
||||
inputWidth = DngPhotonProfileGainTableGenerator.HDRNET_INPUT_WIDTH,
|
||||
inputHeight = DngPhotonProfileGainTableGenerator.HDRNET_INPUT_HEIGHT,
|
||||
inputChannels = HDRNET_INPUT_CHANNELS,
|
||||
outputGridWidth = outputGridWidth,
|
||||
outputGridHeight = outputGridHeight,
|
||||
footprintSamplesPerAxis = footprintSamplesPerAxis,
|
||||
hdrRatio = plan.hdrRatio,
|
||||
renderMinGain = renderMinGain,
|
||||
renderMaxGain = renderMaxGain,
|
||||
outputRotation = outputRotation,
|
||||
guideShifts = guideShifts,
|
||||
guideSlopes = guideSlopes,
|
||||
outputLumas = output,
|
||||
)
|
||||
return output.takeIf { completed }
|
||||
}
|
||||
|
||||
private external fun nativeEvaluateDisplayLinearLumaGrid(
|
||||
coefficients: FloatArray,
|
||||
sourceGridWidth: Int,
|
||||
sourceGridHeight: Int,
|
||||
sourceGridDepth: Int,
|
||||
coefficientCount: Int,
|
||||
modelInput: FloatArray,
|
||||
inputWidth: Int,
|
||||
inputHeight: Int,
|
||||
inputChannels: Int,
|
||||
outputGridWidth: Int,
|
||||
outputGridHeight: Int,
|
||||
footprintSamplesPerAxis: Int,
|
||||
hdrRatio: Float,
|
||||
renderMinGain: Float,
|
||||
renderMaxGain: Float,
|
||||
outputRotation: Int,
|
||||
guideShifts: FloatArray,
|
||||
guideSlopes: FloatArray,
|
||||
outputLumas: FloatArray,
|
||||
): Boolean
|
||||
|
||||
private external fun nativeGenerateGains(
|
||||
coefficients: FloatArray,
|
||||
sourceGridWidth: Int,
|
||||
@@ -77,4 +139,6 @@ internal object DngHdrNetProfileGainTableNative {
|
||||
diagnosticMode: Int,
|
||||
outputGains: FloatArray,
|
||||
): Boolean
|
||||
|
||||
private const val HDRNET_INPUT_CHANNELS = 4
|
||||
}
|
||||
@@ -1045,7 +1045,8 @@ internal object DngPhotonProfileGainTableInputShader {
|
||||
// The demosaic texture is un-white-balanced camera RGB. The render-stage
|
||||
// camera-to-working matrix includes the selected camera white, matching
|
||||
// MGC's uCcm contract without applying WB a second time.
|
||||
// BaselineExposure is the display/middle-gray target, not an HDRNet input.
|
||||
// BaselineExposure remains DNG render metadata. It is neither an HDRNet input
|
||||
// nor the viewfinder-matching target.
|
||||
vec3 cameraRgb = storedCameraRgb * uSourceToShortGain;
|
||||
// MGC clamps only positive overrange before box downsampling. Negative
|
||||
// samples remain in the average and are clamped by the final box pass.
|
||||
@@ -1388,10 +1389,12 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
val samplesPerPixel: Int,
|
||||
val metadata: RawMetadata,
|
||||
val statsBounds: Rect?,
|
||||
/** DNG BaselineExposure used only by the robust exposure target and final DNG render. */
|
||||
val sourceBaselineExposureEv: Float,
|
||||
/** Total BaselineExposure used by DNG ProfileGainTableMap lookup. */
|
||||
val rendererBaselineExposureEv: Float,
|
||||
/** Complete capture-time viewfinder target; null when regenerating without capture state. */
|
||||
val viewfinderReference: RawLegacyExposurePreviewFrame?,
|
||||
/** Rotation that maps the sensor/model grid into [viewfinderReference] orientation. */
|
||||
val outputRotation: Int,
|
||||
val hdrRatio: Float,
|
||||
val sourceToShortGain: Float,
|
||||
val colorCorrectionMatrix: FloatArray,
|
||||
@@ -1412,8 +1415,8 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
val map: DngProfileGainTableMap,
|
||||
val hdrRatio: Float? = null,
|
||||
val sourceToShortGain: Float? = null,
|
||||
val hdrNetExposureAdjustmentEv: Float,
|
||||
val hdrNetExposureTargetEv: Float? = null,
|
||||
val hdrNetShortExposureAdjustmentEv: Float,
|
||||
val hdrNetLongExposureAdjustmentEv: Float,
|
||||
val hdrNetExposureEvaluation: RawHdrNetExposureEvaluation? = null,
|
||||
)
|
||||
|
||||
@@ -1425,7 +1428,8 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
private data class HdrNetInferenceCandidate(
|
||||
val plan: HdrNetProfileGainTablePlan,
|
||||
val coefficients: FloatArray,
|
||||
val adjustmentEv: Float,
|
||||
val shortAdjustmentEv: Float,
|
||||
val longAdjustmentEv: Float,
|
||||
)
|
||||
|
||||
private var cellSamplesProgram = 0
|
||||
@@ -1472,7 +1476,8 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
Mode.LOCAL_LAPLACIAN -> generateLocalLaplacian(input)?.let { map ->
|
||||
Output(
|
||||
map = map,
|
||||
hdrNetExposureAdjustmentEv = 0f,
|
||||
hdrNetShortExposureAdjustmentEv = 0f,
|
||||
hdrNetLongExposureAdjustmentEv = 0f,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1532,7 +1537,6 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
val basePlan = DngPhotonProfileGainTableGenerator.hdrNetPlan(
|
||||
sourceWidth = width,
|
||||
sourceHeight = height,
|
||||
sourceBaselineExposureEv = input.sourceBaselineExposureEv,
|
||||
rendererBaselineExposureEv = input.rendererBaselineExposureEv,
|
||||
hdrRatio = input.hdrRatio,
|
||||
sourceToShortGain = input.sourceToShortGain,
|
||||
@@ -1644,35 +1648,42 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
)
|
||||
val baseShortGain = basePlan.sourceToShortGain
|
||||
val baseLongGain = baseShortGain * basePlan.hdrRatio
|
||||
val exposureTargetEv = input.sourceBaselineExposureEv
|
||||
var totalInputNs = 0L
|
||||
var totalInferenceNs = 0L
|
||||
var baseCandidate: HdrNetInferenceCandidate? = null
|
||||
var exposureSourceLumaByCell: FloatArray? = null
|
||||
var totalMatchGridNs = 0L
|
||||
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 runCandidate(adjustmentEv: Float): Pair<HdrNetInferenceCandidate, FloatArray>? {
|
||||
// This solve moves the overall exposure anchor. Dynamic range remains the ML AE
|
||||
// result, so short and long must receive the same gain on every candidate.
|
||||
val adjustmentGain = 2.0f.pow(adjustmentEv)
|
||||
val shortGain = baseShortGain * adjustmentGain
|
||||
val longGain = baseLongGain * adjustmentGain
|
||||
if (!shortGain.isFinite() || shortGain <= 0f ||
|
||||
!longGain.isFinite() || longGain < shortGain
|
||||
) {
|
||||
return null
|
||||
}
|
||||
val candidatePlan = DngPhotonProfileGainTableGenerator.hdrNetPlan(
|
||||
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(
|
||||
sourceWidth = width,
|
||||
sourceHeight = height,
|
||||
sourceBaselineExposureEv = input.sourceBaselineExposureEv,
|
||||
rendererBaselineExposureEv = input.rendererBaselineExposureEv,
|
||||
hdrRatio = basePlan.hdrRatio,
|
||||
hdrRatio = candidateHdrRatio,
|
||||
sourceToShortGain = shortGain,
|
||||
diagnosticBand = DngPgtmDiagnostic.activeBandForSource(
|
||||
"$TAG HDRNet capture",
|
||||
),
|
||||
samplingArea = samplingArea,
|
||||
) ?: return null
|
||||
)
|
||||
}
|
||||
|
||||
fun exposureAdjustmentEv(gain: Float, baseGain: Float): Float =
|
||||
(ln((gain / baseGain).toDouble()) / ln(2.0)).toFloat()
|
||||
|
||||
fun runCandidate(
|
||||
shortGain: Float,
|
||||
longGain: Float,
|
||||
): Pair<HdrNetInferenceCandidate, FloatArray>? {
|
||||
val candidatePlan = planCandidate(shortGain, longGain) ?: return null
|
||||
|
||||
val inputStartNs = System.nanoTime()
|
||||
GLES31.glUseProgram(hdrNetInputProgram)
|
||||
@@ -1717,52 +1728,55 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
colorCorrectionMatrix = safeColorCorrectionMatrix,
|
||||
values = inputFloats,
|
||||
)
|
||||
val candidateSourceLumaByCell = exposureSourceLumaByCell
|
||||
?: DngPhotonProfileGainTableGenerator.hdrNetExposureSourceLumaByCell(
|
||||
plan = candidatePlan,
|
||||
modelInput = inputFloats,
|
||||
)?.also { exposureSourceLumaByCell = it }
|
||||
?: return null
|
||||
|
||||
val modelInput = ByteBuffer.allocateDirect(inputFloats.size * Float.SIZE_BYTES)
|
||||
.order(ByteOrder.nativeOrder())
|
||||
modelInput.asFloatBuffer().put(inputFloats)
|
||||
modelInput.rewind()
|
||||
val modelOutput = ByteBuffer.allocateDirect(
|
||||
DngPhotonProfileGainTableGenerator.HDRNET_OUTPUT_FLOAT_COUNT * Float.SIZE_BYTES,
|
||||
).order(ByteOrder.nativeOrder())
|
||||
modelInputBuffer.clear()
|
||||
modelInputBuffer.asFloatBuffer().put(inputFloats)
|
||||
modelInputBuffer.rewind()
|
||||
modelOutputBuffer.clear()
|
||||
val inferenceStartNs = System.nanoTime()
|
||||
interpreter.run(modelInput, modelOutput)
|
||||
interpreter.run(modelInputBuffer, modelOutputBuffer)
|
||||
totalInferenceNs += System.nanoTime() - inferenceStartNs
|
||||
modelOutput.rewind()
|
||||
modelOutputBuffer.rewind()
|
||||
val coefficients = FloatArray(
|
||||
DngPhotonProfileGainTableGenerator.HDRNET_OUTPUT_FLOAT_COUNT,
|
||||
)
|
||||
modelOutput.asFloatBuffer().get(coefficients)
|
||||
modelOutputBuffer.asFloatBuffer().get(coefficients)
|
||||
logHdrNetOutputContract(coefficients, candidatePlan.hdrRatio)
|
||||
val effectiveExposureEvs =
|
||||
DngPhotonProfileGainTableGenerator.hdrNetEffectiveExposureEvs(
|
||||
val matchGridStartNs = System.nanoTime()
|
||||
val displayLinearLumaGrid =
|
||||
DngPhotonProfileGainTableGenerator.hdrNetDisplayLinearLumaGrid(
|
||||
plan = candidatePlan,
|
||||
coefficients = coefficients,
|
||||
sourceLumaByCell = candidateSourceLumaByCell,
|
||||
) ?: return null
|
||||
modelInput = inputFloats,
|
||||
outputRotation = input.outputRotation,
|
||||
)
|
||||
val matchGridNs = System.nanoTime() - matchGridStartNs
|
||||
totalMatchGridNs += matchGridNs
|
||||
PLog.d(
|
||||
TAG,
|
||||
"HDRNet viewfinder grid: shortGain=$shortGain longGain=$longGain " +
|
||||
"hdrRatio=${candidatePlan.hdrRatio} " +
|
||||
"gridMs=${matchGridNs / 1_000_000f}",
|
||||
)
|
||||
if (displayLinearLumaGrid == null) return null
|
||||
return HdrNetInferenceCandidate(
|
||||
plan = candidatePlan,
|
||||
coefficients = coefficients,
|
||||
adjustmentEv = adjustmentEv,
|
||||
).also { candidate ->
|
||||
if (abs(adjustmentEv) < 1e-6f) baseCandidate = candidate
|
||||
} to effectiveExposureEvs
|
||||
shortAdjustmentEv = exposureAdjustmentEv(shortGain, baseShortGain),
|
||||
longAdjustmentEv = exposureAdjustmentEv(longGain, baseLongGain),
|
||||
) to displayLinearLumaGrid
|
||||
}
|
||||
|
||||
val exposureResult = RawLegacyAutoExposureMatcher.solveHdrNetExposure(
|
||||
targetExposureEv = exposureTargetEv,
|
||||
maxAdjustmentEv = HDRNET_EXPOSURE_MAX_ADJUSTMENT_EV,
|
||||
evaluateCandidate = ::runCandidate,
|
||||
)
|
||||
val exposureResult = input.viewfinderReference?.let { reference ->
|
||||
RawLegacyAutoExposureMatcher.solveHdrNetExposure(
|
||||
referenceFrame = reference,
|
||||
initialShortGain = baseShortGain,
|
||||
initialLongGain = baseLongGain,
|
||||
evaluateCandidate = ::runCandidate,
|
||||
)
|
||||
}
|
||||
val selectedCandidate = exposureResult?.payload
|
||||
?: baseCandidate
|
||||
?: runCandidate(0f)?.first
|
||||
?: runCandidate(baseShortGain, baseLongGain)?.first
|
||||
?: return null
|
||||
val plan = selectedCandidate.plan
|
||||
val coefficients = selectedCandidate.coefficients
|
||||
@@ -1781,14 +1795,6 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
throw error
|
||||
}
|
||||
val totalReadyNs = System.nanoTime()
|
||||
val retainedSourceLumas = exposureSourceLumaByCell
|
||||
?.filter { it.isFinite() }
|
||||
?.sorted()
|
||||
.orEmpty()
|
||||
val sourceLumaMedian = retainedSourceLumas.takeIf { it.isNotEmpty() }?.let {
|
||||
val upper = it.size / 2
|
||||
if (it.size % 2 == 0) (it[upper - 1] + it[upper]) * 0.5f else it[upper]
|
||||
}
|
||||
PLog.d(
|
||||
TAG,
|
||||
"HDRNet PGTM ready: input=${DngPhotonProfileGainTableGenerator.HDRNET_INPUT_WIDTH}x" +
|
||||
@@ -1798,7 +1804,6 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
"${DngPhotonProfileGainTableGenerator.HDRNET_GRID_DEPTH} " +
|
||||
"pgtmGrid=${plan.grid.mapPointsH}x${plan.grid.mapPointsV} " +
|
||||
"hdrRatio=${plan.hdrRatio} " +
|
||||
"baselineTargetGain=${plan.sourceBaselineGain} " +
|
||||
"rendererBaselineGain=${plan.rendererBaselineGain} " +
|
||||
"sourceToShortGain=${plan.sourceToShortGain} " +
|
||||
"hdrNetTotalInputGain=${plan.hdrNetInputScale} " +
|
||||
@@ -1812,32 +1817,45 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
"modelInputAux=MIN_REC601_LUMA_X_HDR_RATIO_12 " +
|
||||
"hdrRatioDomain=MODEL_AUX_AND_POST_INFERENCE_COEFFICIENT_UNROLL " +
|
||||
"baselineAppliedToHdrNetInput=false " +
|
||||
"baselineRole=ROBUST_EXPOSURE_TARGET_AND_DNG_RENDER_ONLY " +
|
||||
"baselineAppliedToViewfinderMatch=false " +
|
||||
"baselineRole=DNG_RENDER_COORDINATE_ONLY " +
|
||||
"mapInputDomain=RAW_X_FINAL_SHORT_GAIN " +
|
||||
"pgtmBaselineCancelledFromInputCoordinate=true " +
|
||||
"exposureSolve=${exposureResult != null} " +
|
||||
"exposureMetric=ROBUST_LOG2_ACR3_INVERSE_H_OVER_ACTUAL_SOURCE_LUMA " +
|
||||
"exposureSourceDomain=MODEL_RGB_16X12_CENTRAL_LUMA_POPULATION " +
|
||||
"exposureSourceSamples=${retainedSourceLumas.size} " +
|
||||
"exposureSourceLumaMin=${retainedSourceLumas.firstOrNull()} " +
|
||||
"exposureSourceLumaMedian=$sourceLumaMedian " +
|
||||
"exposureSourceLumaMax=${retainedSourceLumas.lastOrNull()} " +
|
||||
"exposureTargetEv=$exposureTargetEv " +
|
||||
"exposureTargetGain=${basePlan.sourceBaselineGain} " +
|
||||
"exposureAdjustmentMode=COMMON_SHORT_LONG_GAIN " +
|
||||
"exposureMetric=SHARED_CLASSIC_NATIVE_SOLVER " +
|
||||
"exposureCandidateDomain=DISPLAY_LINEAR_REC709_LUMA_GRID " +
|
||||
"exposureReferenceDomain=DISPLAY_LINEAR_REC709_LUMA_GRID " +
|
||||
"exposureSpatialWeight=CLASSIC_REFERENCE_ENDPOINT_RELIABILITY " +
|
||||
"exposureTarget=FULL_CAPTURE_VIEWFINDER_THUMBNAIL " +
|
||||
"exposureReferenceAvailable=${input.viewfinderReference != null} " +
|
||||
"exposureOutputRotation=${input.outputRotation} " +
|
||||
"exposureAdjustmentMode=CLASSIC_NATIVE_SEARCH_SHORT_ONLY_BOUNDS " +
|
||||
"exposureConvergenceCondition=SHARED_ROBUST_CORRECTION " +
|
||||
"exposureBaseShortGain=$baseShortGain " +
|
||||
"exposureBaseLongGain=$baseLongGain " +
|
||||
"exposureBaseHdrRatio=${basePlan.hdrRatio} " +
|
||||
"exposureAdjustmentEv=${selectedCandidate.adjustmentEv} " +
|
||||
"exposureShortAdjustmentEv=${selectedCandidate.shortAdjustmentEv} " +
|
||||
"exposureLongAdjustmentEv=${selectedCandidate.longAdjustmentEv} " +
|
||||
"exposureFinalShortGain=${plan.sourceToShortGain} " +
|
||||
"exposureFinalLongGain=${plan.sourceToShortGain * plan.hdrRatio} " +
|
||||
"exposureFinalHdrRatio=${plan.hdrRatio} " +
|
||||
"exposureHdrRatioInvariantError=${plan.hdrRatio - basePlan.hdrRatio} " +
|
||||
"exposureMedianErrorEv=" +
|
||||
"${exposureResult?.evaluation?.medianExposureErrorEv} " +
|
||||
"exposureScore=${exposureResult?.evaluation?.score} " +
|
||||
"exposureMedianLog2Ratio=" +
|
||||
"${exposureResult?.evaluation?.medianLog2Ratio} " +
|
||||
"exposureRobustLog2Loss=" +
|
||||
"${exposureResult?.evaluation?.robustLog2Loss} " +
|
||||
"exposureMeanAbsoluteLog2Ratio=" +
|
||||
"${exposureResult?.evaluation?.meanAbsoluteLog2Ratio} " +
|
||||
"exposureMatchRate=${exposureResult?.evaluation?.matchRate} " +
|
||||
"exposureRecommendedCorrectionEv=" +
|
||||
"${exposureResult?.evaluation?.recommendedExposureCorrectionEv} " +
|
||||
"exposureConverged=${exposureResult?.evaluation?.converged} " +
|
||||
"exposureCandidateCount=" +
|
||||
"${exposureResult?.evaluation?.evaluatedCandidateCount} " +
|
||||
"stage3Source=${width}x$height linearRgbBounds=$hdrNetSourceBounds " +
|
||||
"processingBounds=$stage3Bounds samplingArea=$samplingArea " +
|
||||
"inputMs=${totalInputNs / 1_000_000f} " +
|
||||
"inferenceMs=${totalInferenceNs / 1_000_000f} " +
|
||||
"matchGridMs=${totalMatchGridNs / 1_000_000f} " +
|
||||
"pgtmMs=${(pgtmReadyNs - pgtmStartNs) / 1_000_000f} " +
|
||||
"totalMs=${(totalReadyNs - totalStartNs) / 1_000_000f}",
|
||||
)
|
||||
@@ -1845,8 +1863,8 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
map = map,
|
||||
hdrRatio = plan.hdrRatio,
|
||||
sourceToShortGain = plan.sourceToShortGain,
|
||||
hdrNetExposureAdjustmentEv = selectedCandidate.adjustmentEv,
|
||||
hdrNetExposureTargetEv = exposureTargetEv,
|
||||
hdrNetShortExposureAdjustmentEv = selectedCandidate.shortAdjustmentEv,
|
||||
hdrNetLongExposureAdjustmentEv = selectedCandidate.longAdjustmentEv,
|
||||
hdrNetExposureEvaluation = exposureResult?.evaluation,
|
||||
)
|
||||
} catch (error: Throwable) {
|
||||
@@ -3405,8 +3423,8 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
"whiteBalanceDomain=BAKED_IN_COLOR_CORRECTION_MATRIX " +
|
||||
"modelInputChannels=R_G_B_LONG_LUMA " +
|
||||
"modelInputFinalClamp=UPPER_ONE_ONLY_NEGATIVE_PRESERVED hueSat=false " +
|
||||
"baselineTargetGain=${plan.sourceBaselineGain} " +
|
||||
"baselineAppliedToModelInput=false " +
|
||||
"baselineAppliedToViewfinderMatch=false " +
|
||||
"rendererBaselineGain=${plan.rendererBaselineGain} " +
|
||||
"sourceToShort=${plan.sourceToShortGain} " +
|
||||
"hdrRatio=${plan.hdrRatio} mapWeights=${plan.mapInputWeights.contentToString()} " +
|
||||
@@ -3512,7 +3530,6 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
private companion object {
|
||||
const val TAG = "PhotonPGTM"
|
||||
const val HDRNET_MODEL_ASSET = "mgc_hdrnet/hdrnet_coefficients.tflite"
|
||||
const val HDRNET_EXPOSURE_MAX_ADJUSTMENT_EV = 4f
|
||||
const val LINEAR_RGB_TEXTURE_UNIT = 0
|
||||
const val RAW_TEXTURE_UNIT = 0
|
||||
const val LENS_SHADING_TEXTURE_UNIT = 1
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import kotlin.math.floor
|
||||
import kotlin.math.ln
|
||||
|
||||
/** Builds a DNG ProfileGainTableMap2 from MGC HDRNet's bilateral affine coefficient grid. */
|
||||
@@ -109,15 +108,14 @@ internal object DngPhotonProfileGainTableGenerator {
|
||||
* Plans a 64 x 48 PGTM grid resampled from MGC HDRNet's fixed 16 x 12 coefficient grid.
|
||||
*
|
||||
* HDRNet runs in the final-short-exposure linear domain: `RAW * sourceToShortGain`.
|
||||
* BaselineExposure supplies only the robust global-exposure target and final DNG exposure; it
|
||||
* is not part of the model tensor. A conforming renderer folds its total BaselineExposure into
|
||||
* the ProfileGainTableMap N coordinate, so the stored weights cancel that renderer gain and
|
||||
* reconstruct the same `RAW * sourceToShortGain` coordinate used to build the table.
|
||||
* A conforming renderer folds its total BaselineExposure into the ProfileGainTableMap N
|
||||
* coordinate, so the stored weights cancel that renderer gain and reconstruct the same
|
||||
* `RAW * sourceToShortGain` coordinate used to build the table. BaselineExposure has no role
|
||||
* in HDRNet inference or viewfinder matching.
|
||||
*/
|
||||
fun hdrNetPlan(
|
||||
sourceWidth: Int,
|
||||
sourceHeight: Int,
|
||||
sourceBaselineExposureEv: Float,
|
||||
rendererBaselineExposureEv: Float,
|
||||
hdrRatio: Float,
|
||||
sourceToShortGain: Float,
|
||||
@@ -125,18 +123,14 @@ internal object DngPhotonProfileGainTableGenerator {
|
||||
samplingArea: PhotonPgtmSamplingArea = PhotonPgtmSamplingArea.FULL,
|
||||
): HdrNetProfileGainTablePlan? {
|
||||
if (sourceWidth <= 0 || sourceHeight <= 0 ||
|
||||
!sourceBaselineExposureEv.isFinite() ||
|
||||
!rendererBaselineExposureEv.isFinite() ||
|
||||
!hdrRatio.isFinite() || hdrRatio <= 0f ||
|
||||
!sourceToShortGain.isFinite() || sourceToShortGain <= 0f
|
||||
) {
|
||||
return null
|
||||
}
|
||||
val sourceBaselineGain = DngBaselineExposure.exactGain(sourceBaselineExposureEv)
|
||||
val rendererBaselineGain = DngBaselineExposure.exactGain(rendererBaselineExposureEv)
|
||||
if (!sourceBaselineGain.isFinite() || sourceBaselineGain <= 0f ||
|
||||
!rendererBaselineGain.isFinite() || rendererBaselineGain <= 0f
|
||||
) {
|
||||
if (!rendererBaselineGain.isFinite() || rendererBaselineGain <= 0f) {
|
||||
return null
|
||||
}
|
||||
// Adobe evaluates MapInputWeights after applying TotalBaselineExposure (including any
|
||||
@@ -161,7 +155,6 @@ internal object DngPhotonProfileGainTableGenerator {
|
||||
pointCount = TABLE_POINTS,
|
||||
mapInputWeights = mapInputWeights,
|
||||
gamma = 1f,
|
||||
sourceBaselineGain = sourceBaselineGain,
|
||||
rendererBaselineGain = rendererBaselineGain,
|
||||
sourceToShortGain = sourceToShortGain,
|
||||
// The native MGC path builds the long-exposure guide from a ratio of at least one.
|
||||
@@ -232,176 +225,37 @@ internal object DngPhotonProfileGainTableGenerator {
|
||||
}
|
||||
|
||||
/**
|
||||
* Reduces the actual 256 x 192 HDRNet RGB tensor to one reliable source-luma sample for each
|
||||
* 16 x 12 affine-grid cell. The tensor is already in final-short space, so division by the
|
||||
* candidate short gain restores the common source domain used by BaselineExposure.
|
||||
*
|
||||
* Endpoint and clipped samples do not represent global exposure. After rejecting those
|
||||
* samples, the central source-luma population is retained so large highlight or deep-shadow
|
||||
* regions cannot dominate the exposure anchor merely through their local HDR gain.
|
||||
* Evaluates HDRNet on the complete 64 x 48 PGTM spatial 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.
|
||||
*/
|
||||
fun hdrNetExposureSourceLumaByCell(
|
||||
plan: HdrNetProfileGainTablePlan,
|
||||
modelInput: FloatArray,
|
||||
): FloatArray? {
|
||||
val expectedCount = HDRNET_INPUT_WIDTH * HDRNET_INPUT_HEIGHT * 4
|
||||
if (modelInput.size != expectedCount) return null
|
||||
if (HDRNET_INPUT_WIDTH % HDRNET_GRID_WIDTH != 0 ||
|
||||
HDRNET_INPUT_HEIGHT % HDRNET_GRID_HEIGHT != 0
|
||||
) {
|
||||
return null
|
||||
}
|
||||
val cellWidth = HDRNET_INPUT_WIDTH / HDRNET_GRID_WIDTH
|
||||
val cellHeight = HDRNET_INPUT_HEIGHT / HDRNET_GRID_HEIGHT
|
||||
val cellPixelCount = cellWidth * cellHeight
|
||||
val minimumValidPixels = (cellPixelCount * HDRNET_EXPOSURE_MIN_VALID_PIXEL_FRACTION)
|
||||
.toInt()
|
||||
.coerceAtLeast(1)
|
||||
val pixelLumas = FloatArray(cellPixelCount)
|
||||
val sourceLumaByCell = FloatArray(HDRNET_GRID_WIDTH * HDRNET_GRID_HEIGHT) { Float.NaN }
|
||||
for (cellY in 0 until HDRNET_GRID_HEIGHT) {
|
||||
for (cellX in 0 until HDRNET_GRID_WIDTH) {
|
||||
var validPixelCount = 0
|
||||
val startX = cellX * cellWidth
|
||||
val startY = cellY * cellHeight
|
||||
for (pixelY in startY until startY + cellHeight) {
|
||||
for (pixelX in startX until startX + cellWidth) {
|
||||
val offset = (pixelY * HDRNET_INPUT_WIDTH + pixelX) * 4
|
||||
val red = modelInput[offset]
|
||||
val green = modelInput[offset + 1]
|
||||
val blue = modelInput[offset + 2]
|
||||
if (!red.isFinite() || !green.isFinite() || !blue.isFinite() ||
|
||||
maxOf(red, green, blue) >= HDRNET_EXPOSURE_INPUT_CLIP
|
||||
) {
|
||||
continue
|
||||
}
|
||||
val shortLuma = red * HDRNET_LUMA_RED +
|
||||
green * HDRNET_LUMA_GREEN + blue * HDRNET_LUMA_BLUE
|
||||
val sourceLuma = shortLuma / plan.hdrNetInputScale
|
||||
if (!sourceLuma.isFinite() || sourceLuma <= HDRNET_EXPOSURE_SOURCE_FLOOR) {
|
||||
continue
|
||||
}
|
||||
pixelLumas[validPixelCount++] = sourceLuma
|
||||
}
|
||||
}
|
||||
if (validPixelCount < minimumValidPixels) continue
|
||||
pixelLumas.sort(0, validPixelCount)
|
||||
sourceLumaByCell[cellY * HDRNET_GRID_WIDTH + cellX] =
|
||||
median(pixelLumas, validPixelCount)
|
||||
}
|
||||
}
|
||||
|
||||
val validCellLumas = sourceLumaByCell.filter { it.isFinite() }.toFloatArray()
|
||||
if (validCellLumas.size < HDRNET_EXPOSURE_MIN_VALID_CELL_COUNT) return null
|
||||
validCellLumas.sort()
|
||||
val lowerLuma = percentile(validCellLumas, HDRNET_EXPOSURE_LOWER_PERCENTILE)
|
||||
val upperLuma = percentile(validCellLumas, HDRNET_EXPOSURE_UPPER_PERCENTILE)
|
||||
var retainedCellCount = 0
|
||||
for (index in sourceLumaByCell.indices) {
|
||||
val sourceLuma = sourceLumaByCell[index]
|
||||
if (!sourceLuma.isFinite() || sourceLuma < lowerLuma || sourceLuma > upperLuma) {
|
||||
sourceLumaByCell[index] = Float.NaN
|
||||
} else {
|
||||
retainedCellCount++
|
||||
}
|
||||
}
|
||||
return sourceLumaByCell.takeIf {
|
||||
retainedCellCount >= HDRNET_EXPOSURE_MIN_VALID_CELL_COUNT
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluates HDRNet at the actual source luma of every retained spatial cell and returns its
|
||||
* equivalent pre-tone exposure in stops: `log2(ACR3^-1(H) / sourceLuma)`. This deliberately
|
||||
* measures the robust global exposure produced by HDRNet while leaving its local spatial and
|
||||
* range-dependent shaping intact.
|
||||
*/
|
||||
fun hdrNetEffectiveExposureEvs(
|
||||
fun hdrNetDisplayLinearLumaGrid(
|
||||
plan: HdrNetProfileGainTablePlan,
|
||||
coefficients: FloatArray,
|
||||
sourceLumaByCell: FloatArray,
|
||||
modelInput: FloatArray,
|
||||
outputRotation: Int,
|
||||
): FloatArray? {
|
||||
if (coefficients.size != HDRNET_OUTPUT_FLOAT_COUNT) return null
|
||||
if (sourceLumaByCell.size != HDRNET_GRID_WIDTH * HDRNET_GRID_HEIGHT) return null
|
||||
val output = FloatArray(sourceLumaByCell.count { it.isFinite() })
|
||||
var outputCount = 0
|
||||
fun coefficient(x: Int, y: Int, depth: Int, component: Int): Float {
|
||||
val index = (((y * HDRNET_GRID_WIDTH + x) * HDRNET_GRID_DEPTH + depth) *
|
||||
HDRNET_COEFFICIENT_COUNT) + component
|
||||
return coefficients[index]
|
||||
}
|
||||
for (y in 0 until HDRNET_GRID_HEIGHT) {
|
||||
for (x in 0 until HDRNET_GRID_WIDTH) {
|
||||
val sourceLuma = sourceLumaByCell[y * HDRNET_GRID_WIDTH + x]
|
||||
if (!sourceLuma.isFinite()) continue
|
||||
val shortIntensity = (sourceLuma * plan.hdrNetInputScale).coerceIn(0f, 1f)
|
||||
val guide = hdrNetGuide(shortIntensity)
|
||||
val rangePosition = guide * HDRNET_GRID_DEPTH - 0.5f
|
||||
val rangeFloor = floor(rangePosition).toInt()
|
||||
val lowerRange = rangeFloor.coerceIn(0, HDRNET_GRID_DEPTH - 1)
|
||||
val upperRange = (rangeFloor + 1).coerceIn(0, HDRNET_GRID_DEPTH - 1)
|
||||
val rangeAmount = rangePosition - floor(rangePosition)
|
||||
val rawScale = lerp(
|
||||
coefficient(x, y, lowerRange, component = 0),
|
||||
coefficient(x, y, upperRange, component = 0),
|
||||
rangeAmount,
|
||||
)
|
||||
val bias = lerp(
|
||||
coefficient(x, y, lowerRange, component = 1),
|
||||
coefficient(x, y, upperRange, component = 1),
|
||||
rangeAmount,
|
||||
)
|
||||
val scale = rawScale * (plan.hdrRatio - 1f) + 1f
|
||||
val predictedLuma = scale * shortIntensity + bias
|
||||
if (!predictedLuma.isFinite()) return null
|
||||
val renderGain = (
|
||||
predictedLuma / (shortIntensity + HDRNET_GAIN_EPSILON)
|
||||
).coerceIn(HDRNET_RENDER_MIN_GAIN, HDRNET_RENDER_MAX_GAIN)
|
||||
val hdrNetOutputLuma = (shortIntensity * renderGain).coerceIn(0f, 1f)
|
||||
val preCurveLuma = ACR3Curve.inputForOutput(hdrNetOutputLuma)
|
||||
if (!preCurveLuma.isFinite() || preCurveLuma <= HDRNET_GAIN_EPSILON) continue
|
||||
val exposureEv = (
|
||||
ln((preCurveLuma / sourceLuma).toDouble()) / LN_2
|
||||
).toFloat()
|
||||
if (!exposureEv.isFinite()) return null
|
||||
output[outputCount++] = exposureEv
|
||||
}
|
||||
}
|
||||
return output.copyOf(outputCount).takeIf {
|
||||
outputCount >= HDRNET_EXPOSURE_MIN_VALID_CELL_COUNT
|
||||
}
|
||||
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(
|
||||
plan = plan,
|
||||
coefficients = coefficients,
|
||||
modelInput = modelInput,
|
||||
outputRotation = rotation,
|
||||
guideShifts = HDRNET_GUIDE_SHIFTS,
|
||||
guideSlopes = HDRNET_GUIDE_SLOPES,
|
||||
renderMinGain = HDRNET_RENDER_MIN_GAIN,
|
||||
renderMaxGain = HDRNET_RENDER_MAX_GAIN,
|
||||
outputGridWidth = HDRNET_PGTM_GRID_WIDTH,
|
||||
outputGridHeight = HDRNET_PGTM_GRID_HEIGHT,
|
||||
footprintSamplesPerAxis = HDRNET_MATCH_FOOTPRINT_SAMPLES_PER_AXIS,
|
||||
)
|
||||
}
|
||||
|
||||
private fun median(sortedValues: FloatArray, count: Int): Float {
|
||||
val upper = count / 2
|
||||
return if (count % 2 == 0) {
|
||||
(sortedValues[upper - 1] + sortedValues[upper]) * 0.5f
|
||||
} else {
|
||||
sortedValues[upper]
|
||||
}
|
||||
}
|
||||
|
||||
private fun percentile(sortedValues: FloatArray, fraction: Float): Float {
|
||||
val position = fraction.coerceIn(0f, 1f) * sortedValues.lastIndex
|
||||
val lower = floor(position).toInt()
|
||||
val upper = (lower + 1).coerceAtMost(sortedValues.lastIndex)
|
||||
return lerp(sortedValues[lower], sortedValues[upper], position - lower)
|
||||
}
|
||||
|
||||
private fun lerp(first: Float, second: Float, amount: Float): Float =
|
||||
first + (second - first) * amount
|
||||
|
||||
private const val HDRNET_GAIN_EPSILON = 1e-6f
|
||||
private const val HDRNET_LUMA_RED = 0.298828125f
|
||||
private const val HDRNET_LUMA_GREEN = 0.5869140625f
|
||||
private const val HDRNET_LUMA_BLUE = 0.1142578125f
|
||||
private const val HDRNET_EXPOSURE_INPUT_CLIP = 0.98f
|
||||
private const val HDRNET_EXPOSURE_SOURCE_FLOOR = 1f / 1024f
|
||||
private const val HDRNET_EXPOSURE_MIN_VALID_PIXEL_FRACTION = 0.5f
|
||||
private const val HDRNET_EXPOSURE_LOWER_PERCENTILE = 0.2f
|
||||
private const val HDRNET_EXPOSURE_UPPER_PERCENTILE = 0.8f
|
||||
private const val HDRNET_EXPOSURE_MIN_VALID_CELL_COUNT = 24
|
||||
private val LN_2 = ln(2.0)
|
||||
private const val HDRNET_MATCH_FOOTPRINT_SAMPLES_PER_AXIS = 4
|
||||
|
||||
fun plan(
|
||||
width: Int,
|
||||
@@ -597,8 +451,6 @@ internal data class HdrNetProfileGainTablePlan(
|
||||
val pointCount: Int,
|
||||
val mapInputWeights: FloatArray,
|
||||
val gamma: Float,
|
||||
/** BaselineExposure gain used only to define the robust global-exposure target. */
|
||||
val sourceBaselineGain: Float,
|
||||
/** Total gain a conforming DNG renderer folds into the MapInputWeights coordinate. */
|
||||
val rendererBaselineGain: Float,
|
||||
/** Gain from source RAW to the candidate final-short exposure used by HDRNet. */
|
||||
@@ -612,7 +464,6 @@ internal data class HdrNetProfileGainTablePlan(
|
||||
require(pointCount > 1)
|
||||
require(mapInputWeights.size == 5 && mapInputWeights.all { it.isFinite() })
|
||||
require(gamma.isFinite() && gamma in 0.125f..8f)
|
||||
require(sourceBaselineGain.isFinite() && sourceBaselineGain > 0f)
|
||||
require(rendererBaselineGain.isFinite() && rendererBaselineGain > 0f)
|
||||
require(sourceToShortGain.isFinite() && sourceToShortGain > 0f)
|
||||
require(hdrRatio.isFinite() && hdrRatio >= 1f)
|
||||
|
||||
@@ -3,11 +3,11 @@ package com.hinnka.mycamera.raw
|
||||
/**
|
||||
* The mutually exclusive capture/development modes for adaptive RAW exposure handling.
|
||||
*
|
||||
* [OFF] leaves both paths disabled. [PHOTON_HDR] writes the legacy AE result into
|
||||
* BaselineExposure, then runs ML AE plus HDRNet using that value as its reproducible exposure
|
||||
* anchor. [LEGACY_AUTO_EXPOSURE] writes the same legacy AE result and generates the historical
|
||||
* Local Laplacian profile gain table. Both enabled modes therefore combine automatic metering
|
||||
* with HDR mapping; only the mapping implementation differs.
|
||||
* [OFF] leaves both paths disabled. [PHOTON_HDR] runs ML AE plus HDRNet and spatially matches the
|
||||
* HDRNet result to the complete capture-time viewfinder thumbnail. [LEGACY_AUTO_EXPOSURE] writes
|
||||
* its scalar viewfinder-matched exposure into BaselineExposure and generates the historical Local
|
||||
* Laplacian profile gain table. Both enabled modes combine automatic metering with HDR mapping;
|
||||
* only the target representation and mapping implementation differ.
|
||||
*/
|
||||
enum class RawAdaptiveExposureMode(val persistedValue: String) {
|
||||
OFF("OFF"),
|
||||
|
||||
@@ -3099,20 +3099,21 @@ class RawDemosaicProcessor {
|
||||
val captureUsesLocalLaplacian =
|
||||
sceneExposureRequest == null && legacyAutoExposureRequest != null
|
||||
val solvedExposureEv = legacyAutoExposureRequest
|
||||
?.takeIf { captureUsesLocalLaplacian }
|
||||
?.let { request ->
|
||||
renderLegacyAutoExposureRequest(
|
||||
request = request,
|
||||
metadata = actualMetadata,
|
||||
sourceTextureId = demosaicTextureId,
|
||||
colorCorrectionMatrix = linearColorCorrectionMatrix,
|
||||
cameraWhite = linearCameraWhite,
|
||||
dcpRenderPlan = activeDcpRenderPlan,
|
||||
rawBlackPointCorrection = rawBlackPointCorrection,
|
||||
rawWhitePointCorrection = rawWhitePointCorrection,
|
||||
outputSourceBounds = outputSourceBounds,
|
||||
outputRotation = actualRotation,
|
||||
)
|
||||
}
|
||||
renderLegacyAutoExposureRequest(
|
||||
request = request,
|
||||
metadata = actualMetadata,
|
||||
sourceTextureId = demosaicTextureId,
|
||||
colorCorrectionMatrix = linearColorCorrectionMatrix,
|
||||
cameraWhite = linearCameraWhite,
|
||||
dcpRenderPlan = activeDcpRenderPlan,
|
||||
rawBlackPointCorrection = rawBlackPointCorrection,
|
||||
rawWhitePointCorrection = rawWhitePointCorrection,
|
||||
outputSourceBounds = outputSourceBounds,
|
||||
outputRotation = actualRotation,
|
||||
)
|
||||
}
|
||||
val processingBounds = captureProfileStatsBounds ?: outputSourceBounds
|
||||
val solvedSceneExposure = sceneExposureRequest?.let { request ->
|
||||
renderSceneExposureRequest(
|
||||
@@ -3162,39 +3163,38 @@ class RawDemosaicProcessor {
|
||||
?.takeIf { it.isFinite() && it > 0f }
|
||||
val captureProfileOutput = when {
|
||||
capturePhotonPgtmRequested && captureUsesHdrNet &&
|
||||
solvedExposureEv != null && captureHdrRatio != null &&
|
||||
legacyAutoExposureRequest != null && captureHdrRatio != null &&
|
||||
captureSourceToShortGain != null -> {
|
||||
generateProfileGainTableMapOnGpu(
|
||||
mode = DngPhotonProfileGainTableAlgorithm.Mode.HDR_NET,
|
||||
context = context.applicationContext,
|
||||
linearRgbTextureId = demosaicTextureId,
|
||||
rawTextureId = rawTextureId,
|
||||
streamingRawData = tiledRawData,
|
||||
streamingRowStride = actualRowStride,
|
||||
width = actualWidth,
|
||||
height = actualHeight,
|
||||
linearRgbTextureWidth = demosaicWidth,
|
||||
linearRgbTextureHeight = demosaicHeight,
|
||||
samplesPerPixel = actualSamplesPerPixel,
|
||||
metadata = actualMetadata.copy(profileGainTableMap = null),
|
||||
statsBounds = captureProfileStatsBounds,
|
||||
// Legacy AE owns the reproducible display-exposure anchor written into
|
||||
// BaselineExposure. ML AE supplies only HDRNet's short/long relationship.
|
||||
sourceBaselineExposureEv = finalBaselineExposureEv,
|
||||
rendererBaselineExposureEv = finalBaselineExposureEv +
|
||||
dcpBaselineExposureOffsetOrZero(activeDcpRenderPlan),
|
||||
// HDRNet's ratio describes capture exposure, not the DCP profile's
|
||||
// independent BaselineExposureOffset rendering adjustment.
|
||||
hdrRatio = captureHdrRatio,
|
||||
sourceToShortGain = captureSourceToShortGain,
|
||||
colorCorrectionMatrix = linearColorCorrectionMatrix,
|
||||
hueSatMap = activeDcpRenderPlan?.hueSatMap,
|
||||
hueSatMapSupportsOverrange = hueSatMapSupportsOverrange,
|
||||
// The continuous linear RGB texture has already received active Stage 3
|
||||
// geometry immediately above. Applying the warp again in HDRNet would
|
||||
// compare a different field of view with the viewfinder thumbnail.
|
||||
warpRectilinear = null,
|
||||
)
|
||||
mode = DngPhotonProfileGainTableAlgorithm.Mode.HDR_NET,
|
||||
context = context.applicationContext,
|
||||
linearRgbTextureId = demosaicTextureId,
|
||||
rawTextureId = rawTextureId,
|
||||
streamingRawData = tiledRawData,
|
||||
streamingRowStride = actualRowStride,
|
||||
width = actualWidth,
|
||||
height = actualHeight,
|
||||
linearRgbTextureWidth = demosaicWidth,
|
||||
linearRgbTextureHeight = demosaicHeight,
|
||||
samplesPerPixel = actualSamplesPerPixel,
|
||||
metadata = actualMetadata.copy(profileGainTableMap = null),
|
||||
statsBounds = processingBounds,
|
||||
rendererBaselineExposureEv = finalBaselineExposureEv +
|
||||
dcpBaselineExposureOffsetOrZero(activeDcpRenderPlan),
|
||||
viewfinderReference = legacyAutoExposureRequest.referenceFrame,
|
||||
outputRotation = actualRotation,
|
||||
// HDRNet's ratio describes capture exposure, not the DCP profile's
|
||||
// independent BaselineExposureOffset rendering adjustment.
|
||||
hdrRatio = captureHdrRatio,
|
||||
sourceToShortGain = captureSourceToShortGain,
|
||||
colorCorrectionMatrix = linearColorCorrectionMatrix,
|
||||
hueSatMap = activeDcpRenderPlan?.hueSatMap,
|
||||
hueSatMapSupportsOverrange = hueSatMapSupportsOverrange,
|
||||
// The continuous linear RGB texture has already received active Stage 3
|
||||
// geometry immediately above. Applying the warp again in HDRNet would
|
||||
// compare a different field of view with the viewfinder thumbnail.
|
||||
warpRectilinear = null,
|
||||
)
|
||||
}
|
||||
capturePhotonPgtmRequested && captureUsesLocalLaplacian &&
|
||||
solvedExposureEv != null -> {
|
||||
@@ -3211,10 +3211,11 @@ class RawDemosaicProcessor {
|
||||
linearRgbTextureHeight = demosaicHeight,
|
||||
samplesPerPixel = actualSamplesPerPixel,
|
||||
metadata = actualMetadata.copy(profileGainTableMap = null),
|
||||
statsBounds = captureProfileStatsBounds,
|
||||
sourceBaselineExposureEv = finalBaselineExposureEv,
|
||||
statsBounds = processingBounds,
|
||||
rendererBaselineExposureEv = finalBaselineExposureEv +
|
||||
dcpBaselineExposureOffsetOrZero(activeDcpRenderPlan),
|
||||
viewfinderReference = null,
|
||||
outputRotation = actualRotation,
|
||||
hdrRatio = 1f,
|
||||
sourceToShortGain = 1f,
|
||||
colorCorrectionMatrix = linearColorCorrectionMatrix,
|
||||
@@ -3225,15 +3226,15 @@ class RawDemosaicProcessor {
|
||||
}
|
||||
else -> {
|
||||
if (capturePhotonPgtmRequested) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
PLog.e(
|
||||
TAG,
|
||||
if (captureUsesHdrNet) {
|
||||
"HDRNet PGTM unavailable: legacy BaselineExposure, ML AE " +
|
||||
"HDRNet PGTM unavailable: complete viewfinder target, ML AE " +
|
||||
"HDR ratio, or final-short gain is missing"
|
||||
} else {
|
||||
"Local Laplacian PGTM unavailable: legacy AE result is missing"
|
||||
},
|
||||
)
|
||||
)
|
||||
}
|
||||
null
|
||||
}
|
||||
@@ -3249,33 +3250,40 @@ class RawDemosaicProcessor {
|
||||
buildString {
|
||||
append(summary.trimEnd())
|
||||
appendLine()
|
||||
appendLine("legacyBaselineExposureOffsetEv=$solvedExposureEv")
|
||||
appendLine("hdrNetBaselineExposureEv=$finalBaselineExposureEv")
|
||||
appendLine("hdrNetExposureTarget=FULL_CAPTURE_VIEWFINDER_THUMBNAIL")
|
||||
appendLine("hdrNetExposureGrid=64x48_SHARED_CLASSIC_NATIVE_SOLVER")
|
||||
appendLine(
|
||||
"hdrNetBaselineExposureGain=" +
|
||||
DngBaselineExposure.exactGain(finalBaselineExposureEv),
|
||||
"hdrNetShortExposureAdjustmentEv=" +
|
||||
output.hdrNetShortExposureAdjustmentEv,
|
||||
)
|
||||
appendLine(
|
||||
"hdrNetExposureAdjustmentEv=${output.hdrNetExposureAdjustmentEv}",
|
||||
)
|
||||
appendLine(
|
||||
"hdrNetExposureTargetEv=" + output.hdrNetExposureTargetEv,
|
||||
"hdrNetLongExposureAdjustmentEv=" +
|
||||
output.hdrNetLongExposureAdjustmentEv,
|
||||
)
|
||||
appendLine("hdrNetFinalShortGain=$outputShortGain")
|
||||
appendLine("hdrNetFinalLongGain=${outputShortGain * outputHdrRatio}")
|
||||
appendLine("hdrNetFinalHdrRatio=$outputHdrRatio")
|
||||
output.hdrNetExposureEvaluation?.let { evaluation ->
|
||||
appendLine(
|
||||
"hdrNetExposureMatchedSpatialSamples=" +
|
||||
"${evaluation.matchedSpatialSampleCount}/" +
|
||||
evaluation.spatialSampleCount,
|
||||
"hdrNetExposureMedianLog2Ratio=${evaluation.medianLog2Ratio}",
|
||||
)
|
||||
appendLine("hdrNetExposureSpatialMatchRate=${evaluation.matchRate}")
|
||||
appendLine(
|
||||
"hdrNetExposureMedianErrorEv=" +
|
||||
evaluation.medianExposureErrorEv,
|
||||
"hdrNetExposureRobustLog2Loss=${evaluation.robustLog2Loss}",
|
||||
)
|
||||
appendLine(
|
||||
"hdrNetExposureMeanAbsoluteLog2Ratio=" +
|
||||
evaluation.meanAbsoluteLog2Ratio,
|
||||
)
|
||||
appendLine("hdrNetExposureMatchRate=${evaluation.matchRate}")
|
||||
appendLine(
|
||||
"hdrNetExposureRecommendedCorrectionEv=" +
|
||||
evaluation.recommendedExposureCorrectionEv,
|
||||
)
|
||||
appendLine("hdrNetExposureConverged=${evaluation.converged}")
|
||||
appendLine(
|
||||
"hdrNetExposureCandidateCount=" +
|
||||
evaluation.evaluatedCandidateCount,
|
||||
)
|
||||
appendLine("hdrNetExposureMatchScore=${evaluation.score}")
|
||||
}
|
||||
}.trimEnd()
|
||||
}
|
||||
@@ -3312,31 +3320,40 @@ class RawDemosaicProcessor {
|
||||
val persistedHdrRatio = photonHdrRatio?.takeIf { it.isFinite() && it >= 1f }
|
||||
val persistedSourceToShortGain = photonSourceToShortGain
|
||||
?.takeIf { it.isFinite() && it > 0f }
|
||||
val estimatedExposure = renderSceneExposureRequest(
|
||||
request = RawSceneExposureMatcher.createRequest(
|
||||
context = context,
|
||||
val usePersistedCaptureAe =
|
||||
persistedHdrRatio != null && persistedSourceToShortGain != null
|
||||
val estimatedExposure = if (usePersistedCaptureAe) {
|
||||
null
|
||||
} else {
|
||||
renderSceneExposureRequest(
|
||||
request = RawSceneExposureMatcher.createRequest(
|
||||
context = context,
|
||||
metadata = actualMetadata,
|
||||
),
|
||||
metadata = actualMetadata,
|
||||
),
|
||||
metadata = actualMetadata,
|
||||
sourceTextureId = demosaicTextureId,
|
||||
rawTextureIdForStats = rawTextureId,
|
||||
rawSamplesPerPixel = actualSamplesPerPixel,
|
||||
colorCorrectionMatrix = linearColorCorrectionMatrix,
|
||||
profileToLinearSrgbTransform = profileToLinearSrgbTransform,
|
||||
outputSourceBounds = outputSourceBounds,
|
||||
stackCompletionTimeline = borrowedGpuSource?.stackCompletionTimeline,
|
||||
restoreSourceBaselineExposure = false,
|
||||
)
|
||||
sourceTextureId = demosaicTextureId,
|
||||
rawTextureIdForStats = rawTextureId,
|
||||
rawSamplesPerPixel = actualSamplesPerPixel,
|
||||
colorCorrectionMatrix = linearColorCorrectionMatrix,
|
||||
profileToLinearSrgbTransform = profileToLinearSrgbTransform,
|
||||
outputSourceBounds = outputSourceBounds,
|
||||
stackCompletionTimeline = borrowedGpuSource?.stackCompletionTimeline,
|
||||
restoreSourceBaselineExposure = false,
|
||||
)
|
||||
}
|
||||
val estimatedHdrRatio = estimatedExposure?.hdrRatio
|
||||
?.takeIf { it.isFinite() && it >= 1f }
|
||||
val estimatedSourceToShortGain = estimatedExposure?.finalShortGain
|
||||
?.takeIf { it.isFinite() && it > 0f }
|
||||
val useEstimatedAe =
|
||||
// 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.
|
||||
val useEstimatedAe = !usePersistedCaptureAe &&
|
||||
estimatedHdrRatio != null && estimatedSourceToShortGain != null
|
||||
val regenerationHdrRatio = if (useEstimatedAe) {
|
||||
estimatedHdrRatio
|
||||
} else {
|
||||
persistedHdrRatio
|
||||
val regenerationHdrRatio = when {
|
||||
usePersistedCaptureAe -> persistedHdrRatio
|
||||
useEstimatedAe -> estimatedHdrRatio
|
||||
else -> persistedHdrRatio
|
||||
}
|
||||
if (regenerationHdrRatio == null) {
|
||||
PLog.e(
|
||||
@@ -3346,15 +3363,15 @@ class RawDemosaicProcessor {
|
||||
)
|
||||
return@withContext null
|
||||
}
|
||||
val regenerationSourceToShortGain = if (useEstimatedAe) {
|
||||
checkNotNull(estimatedSourceToShortGain)
|
||||
} else {
|
||||
persistedSourceToShortGain ?: 1f
|
||||
val regenerationSourceToShortGain = when {
|
||||
usePersistedCaptureAe -> checkNotNull(persistedSourceToShortGain)
|
||||
useEstimatedAe -> checkNotNull(estimatedSourceToShortGain)
|
||||
else -> persistedSourceToShortGain ?: 1f
|
||||
}
|
||||
val regenerationAeSource = when {
|
||||
useEstimatedAe -> "MGC_ML_AE_REFRESH"
|
||||
persistedHdrRatio != null && persistedSourceToShortGain != null ->
|
||||
"PERSISTED_CAPTURE_AE_FALLBACK"
|
||||
usePersistedCaptureAe -> "PERSISTED_CAPTURE_VIEWFINDER_MATCH"
|
||||
useEstimatedAe ->
|
||||
"MGC_ML_AE_REFRESH_WITHOUT_VIEWFINDER_TARGET"
|
||||
else -> "LEGACY_RATIO_SHORT_UNITY_FALLBACK"
|
||||
}
|
||||
val regenerationLongGain =
|
||||
@@ -3384,9 +3401,10 @@ class RawDemosaicProcessor {
|
||||
samplesPerPixel = actualSamplesPerPixel,
|
||||
metadata = actualMetadata.copy(profileGainTableMap = null),
|
||||
statsBounds = outputSourceBounds,
|
||||
sourceBaselineExposureEv = actualMetadata.baselineExposure,
|
||||
rendererBaselineExposureEv = actualMetadata.baselineExposure +
|
||||
dcpBaselineExposureOffsetOrZero(activeDcpRenderPlan),
|
||||
viewfinderReference = null,
|
||||
outputRotation = actualRotation,
|
||||
hdrRatio = regenerationHdrRatio,
|
||||
sourceToShortGain = regenerationSourceToShortGain,
|
||||
colorCorrectionMatrix = linearColorCorrectionMatrix,
|
||||
@@ -3412,8 +3430,10 @@ class RawDemosaicProcessor {
|
||||
regeneratedPhotonPgtm.map.mapPointsN +
|
||||
" hdrRatio=${regeneratedPhotonPgtm.hdrRatio}" +
|
||||
" finalShortGain=${regeneratedPhotonPgtm.sourceToShortGain}" +
|
||||
" exposureAdjustmentEv=" +
|
||||
regeneratedPhotonPgtm.hdrNetExposureAdjustmentEv,
|
||||
" shortExposureAdjustmentEv=" +
|
||||
regeneratedPhotonPgtm.hdrNetShortExposureAdjustmentEv +
|
||||
" longExposureAdjustmentEv=" +
|
||||
regeneratedPhotonPgtm.hdrNetLongExposureAdjustmentEv,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -4483,8 +4503,9 @@ class RawDemosaicProcessor {
|
||||
samplesPerPixel: Int,
|
||||
metadata: RawMetadata,
|
||||
statsBounds: Rect?,
|
||||
sourceBaselineExposureEv: Float,
|
||||
rendererBaselineExposureEv: Float,
|
||||
viewfinderReference: RawLegacyExposurePreviewFrame?,
|
||||
outputRotation: Int,
|
||||
hdrRatio: Float,
|
||||
sourceToShortGain: Float,
|
||||
colorCorrectionMatrix: FloatArray,
|
||||
@@ -4525,8 +4546,9 @@ class RawDemosaicProcessor {
|
||||
samplesPerPixel = samplesPerPixel,
|
||||
metadata = metadata,
|
||||
statsBounds = statsBounds,
|
||||
sourceBaselineExposureEv = sourceBaselineExposureEv,
|
||||
rendererBaselineExposureEv = rendererBaselineExposureEv,
|
||||
viewfinderReference = viewfinderReference,
|
||||
outputRotation = outputRotation,
|
||||
hdrRatio = hdrRatio,
|
||||
sourceToShortGain = sourceToShortGain,
|
||||
colorCorrectionMatrix = colorCorrectionMatrix,
|
||||
|
||||
@@ -107,11 +107,11 @@ data class GpuDemosaicedRawSource(
|
||||
)
|
||||
|
||||
data class RawDngCaptureProfileResult(
|
||||
/** Legacy auto-exposure EV relative to the source baseline; used by classic AE and Photon HDR. */
|
||||
/** Legacy auto-exposure EV relative to the source baseline; null for Photon HDR. */
|
||||
val exposureOffsetEv: Float?,
|
||||
/** Photon HDR long/short TET ratio; always null for classic auto exposure. */
|
||||
val hdrRatio: Float?,
|
||||
/** Capture-time source/final-short TET quotient consumed by HDRNet input normalization. */
|
||||
/** Final source/short gain after Photon HDR's capture-viewfinder grid match. */
|
||||
val finalShortGain: Float?,
|
||||
/** Capture-time MGC AE inputs and results serialized as photon:SummaryText in the DNG XMP. */
|
||||
val rawSceneExposureSummaryText: String? = null,
|
||||
|
||||
@@ -3,7 +3,9 @@ package com.hinnka.mycamera.raw
|
||||
import android.graphics.Bitmap
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.ln
|
||||
import kotlin.math.max
|
||||
import kotlin.math.pow
|
||||
|
||||
internal data class RawLegacyExposurePreviewFrame(
|
||||
val width: Int,
|
||||
@@ -14,29 +16,32 @@ internal data class RawLegacyExposurePreviewFrame(
|
||||
internal data class RawLegacyAutoExposureRequest(
|
||||
val width: Int,
|
||||
val height: Int,
|
||||
/** Complete capture-time viewfinder image retained for Photon HDR spatial matching. */
|
||||
val referenceFrame: RawLegacyExposurePreviewFrame,
|
||||
val solve: ((Float) -> RawLegacyExposurePreviewFrame?) -> Float?,
|
||||
)
|
||||
|
||||
internal data class RawHdrNetExposureEvaluation(
|
||||
val matchedSpatialSampleCount: Int,
|
||||
val spatialSampleCount: Int,
|
||||
val medianLog2Ratio: Float,
|
||||
val robustLog2Loss: Float,
|
||||
val meanAbsoluteLog2Ratio: Float,
|
||||
val matchRate: Float,
|
||||
val medianExposureErrorEv: Float,
|
||||
val meanAbsoluteExposureErrorEv: Float,
|
||||
val robustExposureLoss: Float,
|
||||
val score: Float,
|
||||
val recommendedExposureCorrectionEv: Float,
|
||||
val evaluatedCandidateCount: Int,
|
||||
val converged: Boolean,
|
||||
)
|
||||
|
||||
internal data class RawHdrNetExposureCandidate<T>(
|
||||
val adjustmentEv: Float,
|
||||
val shortGain: Float,
|
||||
val longGain: Float,
|
||||
val payload: T,
|
||||
val evaluation: RawHdrNetExposureEvaluation,
|
||||
)
|
||||
|
||||
/**
|
||||
* Classic capture-side auto exposure derived from the adaptive spatial grid matcher in
|
||||
* PhotonCamera 1.27.1. The RAW renderer supplies default-curve preview candidates while native
|
||||
* code owns endpoint reliability weighting, robust scoring, adaptive search and final selection.
|
||||
* Capture-side viewfinder matching derived from PhotonCamera 1.27.1's spatial solver. Native code
|
||||
* owns reference linearization and reliable-grid statistics. Classic HDR retains adaptive search;
|
||||
* Photon HDR uses the same robust grid residual statistics while solving only its short gain.
|
||||
*/
|
||||
internal object RawLegacyAutoExposureMatcher {
|
||||
private const val TAG = "RawLegacyAutoExposureMatcher"
|
||||
@@ -46,6 +51,17 @@ internal object RawLegacyAutoExposureMatcher {
|
||||
val frame: RawLegacyExposurePreviewFrame,
|
||||
)
|
||||
|
||||
private enum class HdrNetSolveDirection {
|
||||
LOWER_SHORT,
|
||||
RAISE_SHORT,
|
||||
}
|
||||
|
||||
private data class HdrNetProbe<T>(
|
||||
val adjustmentEv: Float,
|
||||
val shortGain: Float,
|
||||
val payload: T,
|
||||
)
|
||||
|
||||
fun createRequest(
|
||||
capturePreviewThumbnail: Bitmap?,
|
||||
): RawLegacyAutoExposureRequest? {
|
||||
@@ -53,12 +69,13 @@ internal object RawLegacyAutoExposureMatcher {
|
||||
buildReference(it)
|
||||
}
|
||||
if (capturePreviewThumbnail != null && reference == null) {
|
||||
PLog.w(TAG, "Classic auto exposure skipped: capture preview is unavailable")
|
||||
PLog.w(TAG, "Viewfinder matching skipped: capture preview is unavailable")
|
||||
}
|
||||
return reference?.let {
|
||||
RawLegacyAutoExposureRequest(
|
||||
width = it.frame.width,
|
||||
height = it.frame.height,
|
||||
referenceFrame = it.frame,
|
||||
solve = { renderSample -> solve(it, renderSample) },
|
||||
)
|
||||
}
|
||||
@@ -83,197 +100,134 @@ internal object RawLegacyAutoExposureMatcher {
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches the one-dimensional Photon exposure bracket without rendering a PGTM candidate.
|
||||
* Each EV candidate applies one common gain to short and long, preserving the ML AE HDR ratio.
|
||||
* [evaluateCandidate] returns the spatial effective exposure of the actual image in stops:
|
||||
* `log2(ACR3^-1(H) / sourceLuma)`. Its robust center is matched directly to the legacy
|
||||
* BaselineExposure EV, so local HDR shaping does not turn a synthetic 18% gray into a second
|
||||
* global exposure target.
|
||||
* Matches Photon HDR directly against the complete capture-time viewfinder image.
|
||||
*
|
||||
* The HDRNet candidate and classic ARGB image are both converted to display-linear Rec.709
|
||||
* luma grids before entering the same native solver. Search, convergence, weighting and final
|
||||
* selection therefore have one implementation. HDRNet only constrains the native exposure-EV
|
||||
* search to one side of zero and maps that EV exclusively to short while long remains fixed.
|
||||
*/
|
||||
fun <T> solveHdrNetExposure(
|
||||
targetExposureEv: Float,
|
||||
maxAdjustmentEv: Float,
|
||||
evaluateCandidate: (Float) -> Pair<T, FloatArray>?,
|
||||
referenceFrame: RawLegacyExposurePreviewFrame,
|
||||
initialShortGain: Float,
|
||||
initialLongGain: Float,
|
||||
evaluateCandidate: (shortGain: Float, longGain: Float) -> Pair<T, FloatArray>?,
|
||||
): RawHdrNetExposureCandidate<T>? {
|
||||
if (!targetExposureEv.isFinite()) return null
|
||||
val limit = maxAdjustmentEv.takeIf { it.isFinite() && it > MIN_SEARCH_STEP_EV }
|
||||
?.coerceAtMost(MAX_SEARCH_RANGE_EV)
|
||||
?: 0f
|
||||
val samples = ArrayList<RawHdrNetExposureCandidate<T>>(MAX_HDRNET_SAMPLE_COUNT)
|
||||
var nextEv = 0f
|
||||
var searchMinimumEv = -limit
|
||||
var searchMaximumEv = limit
|
||||
while (samples.size < MAX_HDRNET_SAMPLE_COUNT) {
|
||||
val candidate = evaluateCandidate(nextEv) ?: break
|
||||
val evaluation = evaluateHdrNetExposure(targetExposureEv, candidate.second) ?: break
|
||||
val sample = RawHdrNetExposureCandidate(
|
||||
adjustmentEv = nextEv,
|
||||
payload = candidate.first,
|
||||
evaluation = evaluation,
|
||||
)
|
||||
samples += sample
|
||||
PLog.d(
|
||||
TAG,
|
||||
"HDRNet exposure sample: adjustmentEv=$nextEv " +
|
||||
"matchedSpatialSamples=${evaluation.matchedSpatialSampleCount}/" +
|
||||
"${evaluation.spatialSampleCount} " +
|
||||
"targetExposureEv=$targetExposureEv " +
|
||||
"medianExposureErrorEv=${evaluation.medianExposureErrorEv} " +
|
||||
"meanAbsoluteExposureErrorEv=${evaluation.meanAbsoluteExposureErrorEv} " +
|
||||
"robustExposureLoss=${evaluation.robustExposureLoss} " +
|
||||
"matchRate=${evaluation.matchRate} " +
|
||||
"score=${evaluation.score}",
|
||||
)
|
||||
if (limit == 0f ||
|
||||
abs(evaluation.medianExposureErrorEv) <= CONVERGED_RESIDUAL_EV
|
||||
) {
|
||||
break
|
||||
}
|
||||
if (samples.size == 1) {
|
||||
// Lock the search direction from the first response. The controlled variable is
|
||||
// one common exposure EV, so this restriction never changes the short/long ratio.
|
||||
if (evaluation.medianExposureErrorEv > 0f) {
|
||||
searchMaximumEv = 0f
|
||||
} else {
|
||||
searchMinimumEv = 0f
|
||||
}
|
||||
}
|
||||
val proposed = nextHdrNetAdjustment(
|
||||
samples = samples,
|
||||
minimumEv = searchMinimumEv,
|
||||
maximumEv = searchMaximumEv,
|
||||
) ?: break
|
||||
if (samples.any { abs(it.adjustmentEv - proposed) < MIN_SEARCH_STEP_EV }) break
|
||||
nextEv = proposed
|
||||
}
|
||||
val best = samples.minWithOrNull(
|
||||
compareBy<RawHdrNetExposureCandidate<T>> { it.evaluation.robustExposureLoss }
|
||||
.thenBy { it.evaluation.meanAbsoluteExposureErrorEv }
|
||||
.thenByDescending { it.evaluation.matchRate }
|
||||
.thenBy { abs(it.adjustmentEv) },
|
||||
) ?: return null
|
||||
PLog.i(
|
||||
TAG,
|
||||
"HDRNet exposure result: adjustmentEv=${best.adjustmentEv} " +
|
||||
"matchedSpatialSamples=${best.evaluation.matchedSpatialSampleCount}/" +
|
||||
"${best.evaluation.spatialSampleCount} " +
|
||||
"targetExposureEv=$targetExposureEv " +
|
||||
"medianExposureErrorEv=${best.evaluation.medianExposureErrorEv} " +
|
||||
"meanAbsoluteExposureErrorEv=${best.evaluation.meanAbsoluteExposureErrorEv} " +
|
||||
"robustExposureLoss=${best.evaluation.robustExposureLoss} " +
|
||||
"matchRate=${best.evaluation.matchRate} " +
|
||||
"score=${best.evaluation.score} sampleCount=${samples.size}",
|
||||
)
|
||||
return best
|
||||
}
|
||||
|
||||
private fun evaluateHdrNetExposure(
|
||||
targetExposureEv: Float,
|
||||
candidateExposureEvs: FloatArray,
|
||||
): RawHdrNetExposureEvaluation? {
|
||||
if (candidateExposureEvs.isEmpty() || candidateExposureEvs.any { !it.isFinite() }) {
|
||||
if (!initialShortGain.isFinite() || !initialLongGain.isFinite() ||
|
||||
initialShortGain <= 0f || initialLongGain < initialShortGain
|
||||
) {
|
||||
return null
|
||||
}
|
||||
val residualHistogram = FloatArray(RESIDUAL_HISTOGRAM_BINS)
|
||||
var matchedSpatialSampleCount = 0
|
||||
var absoluteResidualSum = 0.0
|
||||
var robustLossSum = 0.0
|
||||
for (candidateExposureEv in candidateExposureEvs) {
|
||||
val residual = (candidateExposureEv - targetExposureEv)
|
||||
.coerceIn(-MAX_RESIDUAL_EV, MAX_RESIDUAL_EV)
|
||||
val absoluteResidual = abs(residual)
|
||||
val matched = absoluteResidual <= MATCH_RESIDUAL_EV
|
||||
if (matched) matchedSpatialSampleCount++
|
||||
absoluteResidualSum += absoluteResidual
|
||||
robustLossSum += huberLoss(residual)
|
||||
val histogramPosition = ((residual + MAX_RESIDUAL_EV) /
|
||||
(2f * MAX_RESIDUAL_EV) * (RESIDUAL_HISTOGRAM_BINS - 1))
|
||||
.toInt()
|
||||
.coerceIn(0, RESIDUAL_HISTOGRAM_BINS - 1)
|
||||
residualHistogram[histogramPosition] += 1f
|
||||
}
|
||||
val medianTarget = candidateExposureEvs.size * 0.5
|
||||
var cumulative = 0.0
|
||||
var medianBin = 0
|
||||
for (bin in residualHistogram.indices) {
|
||||
cumulative += residualHistogram[bin]
|
||||
if (cumulative >= medianTarget) {
|
||||
medianBin = bin
|
||||
break
|
||||
val solver = RawLegacyAutoExposureNativeBridge.Solver.create(referenceFrame)
|
||||
?: run {
|
||||
PLog.w(TAG, "Photon HDR matching skipped: viewfinder grid is unreliable")
|
||||
return null
|
||||
}
|
||||
}
|
||||
val medianResidual = -MAX_RESIDUAL_EV +
|
||||
(medianBin + 0.5f) * (2f * MAX_RESIDUAL_EV / RESIDUAL_HISTOGRAM_BINS)
|
||||
val meanAbsoluteResidual = (absoluteResidualSum / candidateExposureEvs.size).toFloat()
|
||||
val robustLoss = (robustLossSum / candidateExposureEvs.size).toFloat()
|
||||
val matchRate = matchedSpatialSampleCount.toFloat() / candidateExposureEvs.size
|
||||
return RawHdrNetExposureEvaluation(
|
||||
matchedSpatialSampleCount = matchedSpatialSampleCount,
|
||||
spatialSampleCount = candidateExposureEvs.size,
|
||||
matchRate = matchRate,
|
||||
medianExposureErrorEv = medianResidual,
|
||||
meanAbsoluteExposureErrorEv = meanAbsoluteResidual,
|
||||
robustExposureLoss = robustLoss,
|
||||
score = 1f / (1f + robustLoss),
|
||||
)
|
||||
}
|
||||
|
||||
private fun <T> nextHdrNetAdjustment(
|
||||
samples: List<RawHdrNetExposureCandidate<T>>,
|
||||
minimumEv: Float,
|
||||
maximumEv: Float,
|
||||
): Float? {
|
||||
val sorted = samples.sortedBy { it.adjustmentEv }
|
||||
var narrowestBracket: Pair<RawHdrNetExposureCandidate<T>, RawHdrNetExposureCandidate<T>>? =
|
||||
null
|
||||
for (index in 0 until sorted.lastIndex) {
|
||||
val lower = sorted[index]
|
||||
val upper = sorted[index + 1]
|
||||
if (lower.evaluation.medianExposureErrorEv *
|
||||
upper.evaluation.medianExposureErrorEv > 0f
|
||||
) {
|
||||
continue
|
||||
return solver.use {
|
||||
val probes = ArrayList<HdrNetProbe<T>>()
|
||||
var solveDirection: HdrNetSolveDirection? = null
|
||||
while (true) {
|
||||
val adjustmentEv = solver.nextExposureEv() ?: break
|
||||
val adjustedShortGain = initialShortGain * 2.0f.pow(adjustmentEv)
|
||||
if (!adjustedShortGain.isFinite() || adjustedShortGain <= 0f) break
|
||||
val shortGain = minOf(adjustedShortGain, initialLongGain)
|
||||
val probeStartNs = System.nanoTime()
|
||||
val candidate = evaluateCandidate(shortGain, initialLongGain) ?: break
|
||||
val candidateReadyNs = System.nanoTime()
|
||||
if (!solver.submitCandidate(
|
||||
exposureEv = adjustmentEv,
|
||||
displayLinearLumas = candidate.second,
|
||||
columns = DngPhotonProfileGainTableGenerator.HDRNET_PGTM_GRID_WIDTH,
|
||||
rows = DngPhotonProfileGainTableGenerator.HDRNET_PGTM_GRID_HEIGHT,
|
||||
)
|
||||
) {
|
||||
return null
|
||||
}
|
||||
val sample = solver.lastSample() ?: return null
|
||||
probes += HdrNetProbe(
|
||||
adjustmentEv = adjustmentEv,
|
||||
shortGain = shortGain,
|
||||
payload = candidate.first,
|
||||
)
|
||||
if (solveDirection == null) {
|
||||
val direction = when {
|
||||
sample.recommendedExposureCorrectionEv < 0f ->
|
||||
HdrNetSolveDirection.LOWER_SHORT
|
||||
sample.recommendedExposureCorrectionEv > 0f ->
|
||||
HdrNetSolveDirection.RAISE_SHORT
|
||||
sample.medianLog2Ratio >= 0f -> HdrNetSolveDirection.LOWER_SHORT
|
||||
else -> HdrNetSolveDirection.RAISE_SHORT
|
||||
}
|
||||
solveDirection = direction
|
||||
val maximumRaiseEv = log2Ratio(initialLongGain, initialShortGain)
|
||||
.coerceAtLeast(0f)
|
||||
val boundsConfigured = when (direction) {
|
||||
HdrNetSolveDirection.LOWER_SHORT ->
|
||||
solver.configureExposureBounds(-Float.MAX_VALUE, 0f)
|
||||
HdrNetSolveDirection.RAISE_SHORT ->
|
||||
solver.configureExposureBounds(0f, maximumRaiseEv)
|
||||
}
|
||||
if (!boundsConfigured) return null
|
||||
}
|
||||
val probeReadyNs = System.nanoTime()
|
||||
PLog.d(
|
||||
TAG,
|
||||
"HDRNet viewfinder probe: index=${probes.size} " +
|
||||
"adjustmentAxis=${if (adjustmentEv == 0f) "BASE" else "SHORT"} " +
|
||||
"adjustmentEv=$adjustmentEv " +
|
||||
"shortGain=$shortGain longGain=$initialLongGain " +
|
||||
"hdrRatio=${initialLongGain / shortGain} " +
|
||||
"solveDirection=$solveDirection " +
|
||||
"matchedCells=${sample.matchedCellCount}/${sample.validCellCount} " +
|
||||
"medianLog2Ratio=${sample.medianLog2Ratio} " +
|
||||
"robustLog2Loss=${sample.robustLog2Loss} " +
|
||||
"meanAbsoluteLog2Ratio=${sample.meanAbsoluteLog2Ratio} " +
|
||||
"matchRate=${sample.matchRate} " +
|
||||
"recommendedExposureCorrectionEv=" +
|
||||
"${sample.recommendedExposureCorrectionEv} " +
|
||||
"candidateMs=${(candidateReadyNs - probeStartNs) / 1_000_000f} " +
|
||||
"matchStatsMs=${(probeReadyNs - candidateReadyNs) / 1_000_000f} " +
|
||||
"totalMs=${(probeReadyNs - probeStartNs) / 1_000_000f}",
|
||||
)
|
||||
}
|
||||
val currentWidth = upper.adjustmentEv - lower.adjustmentEv
|
||||
val selectedWidth = narrowestBracket?.let { it.second.adjustmentEv - it.first.adjustmentEv }
|
||||
if (selectedWidth == null || currentWidth < selectedWidth) {
|
||||
narrowestBracket = lower to upper
|
||||
}
|
||||
}
|
||||
narrowestBracket?.let { (lower, upper) ->
|
||||
val lowerResidual = lower.evaluation.medianExposureErrorEv
|
||||
val upperResidual = upper.evaluation.medianExposureErrorEv
|
||||
val width = upper.adjustmentEv - lower.adjustmentEv
|
||||
val denominator = upperResidual - lowerResidual
|
||||
val secant = if (abs(denominator) > 1e-4f) {
|
||||
lower.adjustmentEv - lowerResidual * width / denominator
|
||||
} else {
|
||||
(lower.adjustmentEv + upper.adjustmentEv) * 0.5f
|
||||
}
|
||||
val margin = minOf(width * 0.15f, 0.05f)
|
||||
return secant.coerceIn(
|
||||
lower.adjustmentEv + margin,
|
||||
upper.adjustmentEv - margin,
|
||||
).coerceIn(minimumEv, maximumEv)
|
||||
}
|
||||
val anchor = samples.minWithOrNull(
|
||||
compareBy<RawHdrNetExposureCandidate<T>> {
|
||||
abs(it.evaluation.medianExposureErrorEv)
|
||||
}.thenBy { it.evaluation.robustExposureLoss },
|
||||
) ?: return null
|
||||
val residual = anchor.evaluation.medianExposureErrorEv
|
||||
if (!residual.isFinite() || abs(residual) <= CONVERGED_RESIDUAL_EV) return null
|
||||
val stepMagnitude = abs(residual).coerceIn(MIN_DIRECTIONAL_STEP_EV, MAX_DIRECTIONAL_STEP_EV)
|
||||
return (anchor.adjustmentEv - kotlin.math.sign(residual) * stepMagnitude)
|
||||
.coerceIn(minimumEv, maximumEv)
|
||||
}
|
||||
|
||||
private fun huberLoss(residualEv: Float): Float {
|
||||
val absolute = abs(residualEv)
|
||||
return if (absolute <= HUBER_DELTA_EV) {
|
||||
0.5f * absolute * absolute / HUBER_DELTA_EV
|
||||
} else {
|
||||
absolute - 0.5f * HUBER_DELTA_EV
|
||||
val result = solver.result() ?: return@use null
|
||||
val selectedProbe = probes.minByOrNull {
|
||||
abs(it.adjustmentEv - result.best.exposureEv)
|
||||
}?.takeIf {
|
||||
abs(it.adjustmentEv - result.best.exposureEv) < HDRNET_PROBE_LOOKUP_TOLERANCE_EV
|
||||
} ?: return@use null
|
||||
val selected = RawHdrNetExposureCandidate(
|
||||
shortGain = selectedProbe.shortGain,
|
||||
longGain = initialLongGain,
|
||||
payload = selectedProbe.payload,
|
||||
evaluation = RawHdrNetExposureEvaluation(
|
||||
medianLog2Ratio = result.best.medianLog2Ratio,
|
||||
robustLog2Loss = result.best.robustLog2Loss,
|
||||
meanAbsoluteLog2Ratio = result.best.meanAbsoluteLog2Ratio,
|
||||
matchRate = result.best.matchRate,
|
||||
recommendedExposureCorrectionEv =
|
||||
result.best.recommendedExposureCorrectionEv,
|
||||
evaluatedCandidateCount = result.evaluatedSampleCount,
|
||||
converged = solver.hasConverged(),
|
||||
),
|
||||
)
|
||||
PLog.i(
|
||||
TAG,
|
||||
"HDRNet viewfinder result: shortGain=${selected.shortGain} " +
|
||||
"longGain=${selected.longGain} " +
|
||||
"hdrRatio=${selected.longGain / selected.shortGain} " +
|
||||
"solveDirection=$solveDirection " +
|
||||
"medianLog2Ratio=${selected.evaluation.medianLog2Ratio} " +
|
||||
"robustLog2Loss=${selected.evaluation.robustLog2Loss} " +
|
||||
"meanAbsoluteLog2Ratio=${selected.evaluation.meanAbsoluteLog2Ratio} " +
|
||||
"matchRate=${selected.evaluation.matchRate} " +
|
||||
"recommendedExposureCorrectionEv=" +
|
||||
"${selected.evaluation.recommendedExposureCorrectionEv} " +
|
||||
"converged=${selected.evaluation.converged} " +
|
||||
"candidateCount=${selected.evaluation.evaluatedCandidateCount} " +
|
||||
"convergenceCondition=SHARED_ROBUST_CORRECTION",
|
||||
)
|
||||
selected
|
||||
}
|
||||
}
|
||||
|
||||
@@ -303,6 +257,8 @@ internal object RawLegacyAutoExposureMatcher {
|
||||
"meanAbsoluteLog2Ratio=${sample.meanAbsoluteLog2Ratio} " +
|
||||
"medianLog2Ratio=${sample.medianLog2Ratio} " +
|
||||
"robustLog2Loss=${sample.robustLog2Loss} " +
|
||||
"recommendedExposureCorrectionEv=" +
|
||||
"${sample.recommendedExposureCorrectionEv} " +
|
||||
"referenceWeightSum=${sample.referenceWeightSum}",
|
||||
)
|
||||
}
|
||||
@@ -316,6 +272,8 @@ internal object RawLegacyAutoExposureMatcher {
|
||||
"meanAbsoluteLog2Ratio=${result.best.meanAbsoluteLog2Ratio} " +
|
||||
"medianLog2Ratio=${result.best.medianLog2Ratio} " +
|
||||
"robustLog2Loss=${result.best.robustLog2Loss} " +
|
||||
"recommendedExposureCorrectionEv=" +
|
||||
"${result.best.recommendedExposureCorrectionEv} " +
|
||||
"referenceWeightSum=${result.best.referenceWeightSum} " +
|
||||
"sampleCount=${result.evaluatedSampleCount} " +
|
||||
"excludedShadowCells=${result.excludedShadowCellCount} " +
|
||||
@@ -330,16 +288,10 @@ internal object RawLegacyAutoExposureMatcher {
|
||||
|
||||
private data class Size(val width: Int, val height: Int)
|
||||
|
||||
private const val MATCH_RESIDUAL_EV = 0.13750352f
|
||||
private const val HUBER_DELTA_EV = 0.25f
|
||||
private const val MAX_RESIDUAL_EV = 4f
|
||||
private const val RESIDUAL_HISTOGRAM_BINS = 512
|
||||
private const val CONVERGED_RESIDUAL_EV = 0.03f
|
||||
private const val MIN_SEARCH_STEP_EV = 0.02f
|
||||
private const val MIN_DIRECTIONAL_STEP_EV = 0.125f
|
||||
private const val MAX_DIRECTIONAL_STEP_EV = 1f
|
||||
private const val MAX_SEARCH_RANGE_EV = 4f
|
||||
private const val MAX_HDRNET_SAMPLE_COUNT = 8
|
||||
private const val HDRNET_PROBE_LOOKUP_TOLERANCE_EV = 0.001f
|
||||
|
||||
private fun log2Ratio(value: Float, reference: Float): Float =
|
||||
(ln((value / reference).toDouble()) / ln(2.0)).toFloat()
|
||||
|
||||
private fun longEdgeSize(sourceWidth: Int, sourceHeight: Int, maxLongEdge: Int): Size {
|
||||
val longEdge = minOf(max(sourceWidth, sourceHeight), maxLongEdge.coerceAtLeast(1))
|
||||
|
||||
@@ -18,6 +18,7 @@ internal object RawLegacyAutoExposureNativeBridge {
|
||||
val medianLog2Ratio: Float,
|
||||
val robustLog2Loss: Float,
|
||||
val referenceWeightSum: Float,
|
||||
val recommendedExposureCorrectionEv: Float,
|
||||
)
|
||||
|
||||
data class Result(
|
||||
@@ -49,6 +50,35 @@ internal object RawLegacyAutoExposureNativeBridge {
|
||||
)
|
||||
}
|
||||
|
||||
fun submitCandidate(
|
||||
exposureEv: Float,
|
||||
displayLinearLumas: FloatArray,
|
||||
columns: Int,
|
||||
rows: Int,
|
||||
): Boolean {
|
||||
check(handle != 0L) { "Native exposure solver is closed" }
|
||||
if (columns <= 0 || rows <= 0 || displayLinearLumas.size != columns * rows) {
|
||||
return false
|
||||
}
|
||||
return nativeSubmitGridCandidate(
|
||||
handle = handle,
|
||||
exposureEv = exposureEv,
|
||||
candidateDisplayLinearLumas = displayLinearLumas,
|
||||
columns = columns,
|
||||
rows = rows,
|
||||
)
|
||||
}
|
||||
|
||||
fun configureExposureBounds(minimumEv: Float, maximumEv: Float): Boolean {
|
||||
check(handle != 0L) { "Native exposure solver is closed" }
|
||||
return nativeConfigureExposureBounds(handle, minimumEv, maximumEv)
|
||||
}
|
||||
|
||||
fun hasConverged(): Boolean {
|
||||
check(handle != 0L) { "Native exposure solver is closed" }
|
||||
return nativeHasConverged(handle)
|
||||
}
|
||||
|
||||
fun lastSample(): Sample? {
|
||||
check(handle != 0L) { "Native exposure solver is closed" }
|
||||
return nativeGetLastSample(handle)?.toSample()
|
||||
@@ -60,12 +90,12 @@ internal object RawLegacyAutoExposureNativeBridge {
|
||||
if (values.size != RESULT_VALUE_COUNT) return null
|
||||
return Result(
|
||||
best = values.toSample() ?: return null,
|
||||
evaluatedSampleCount = values[9].roundToInt(),
|
||||
excludedShadowCellCount = values[10].roundToInt(),
|
||||
excludedHighlightCellCount = values[11].roundToInt(),
|
||||
shadowWeightZeroLinear = values[12],
|
||||
highlightWeightZeroLinear = values[13],
|
||||
huberDeltaEv = values[14],
|
||||
evaluatedSampleCount = values[10].roundToInt(),
|
||||
excludedShadowCellCount = values[11].roundToInt(),
|
||||
excludedHighlightCellCount = values[12].roundToInt(),
|
||||
shadowWeightZeroLinear = values[13],
|
||||
highlightWeightZeroLinear = values[14],
|
||||
huberDeltaEv = values[15],
|
||||
)
|
||||
}
|
||||
|
||||
@@ -100,6 +130,7 @@ internal object RawLegacyAutoExposureNativeBridge {
|
||||
medianLog2Ratio = this[6],
|
||||
robustLog2Loss = this[7],
|
||||
referenceWeightSum = this[8],
|
||||
recommendedExposureCorrectionEv = this[9],
|
||||
)
|
||||
}
|
||||
|
||||
@@ -119,10 +150,26 @@ internal object RawLegacyAutoExposureNativeBridge {
|
||||
height: Int,
|
||||
): Boolean
|
||||
|
||||
private external fun nativeSubmitGridCandidate(
|
||||
handle: Long,
|
||||
exposureEv: Float,
|
||||
candidateDisplayLinearLumas: FloatArray,
|
||||
columns: Int,
|
||||
rows: Int,
|
||||
): Boolean
|
||||
|
||||
private external fun nativeConfigureExposureBounds(
|
||||
handle: Long,
|
||||
minimumEv: Float,
|
||||
maximumEv: Float,
|
||||
): Boolean
|
||||
|
||||
private external fun nativeHasConverged(handle: Long): Boolean
|
||||
|
||||
private external fun nativeGetLastSample(handle: Long): FloatArray?
|
||||
private external fun nativeGetResult(handle: Long): FloatArray?
|
||||
private external fun nativeDestroy(handle: Long)
|
||||
|
||||
private const val SAMPLE_VALUE_COUNT = 9
|
||||
private const val RESULT_VALUE_COUNT = 15
|
||||
private const val SAMPLE_VALUE_COUNT = 10
|
||||
private const val RESULT_VALUE_COUNT = 16
|
||||
}
|
||||
@@ -842,7 +842,8 @@ object RawProcessor {
|
||||
"sourceBaselineEv=$sourceBaselineExposureEv " +
|
||||
"sourceBaselineGain=${DngBaselineExposure.exactGain(sourceBaselineExposureEv)} " +
|
||||
"legacyExposureOffsetEv=$legacyExposureOffsetEv " +
|
||||
"baselineExposureSource=SOURCE_PLUS_LEGACY_AE " +
|
||||
"baselineExposureSource=" +
|
||||
"${if (legacyExposureOffsetEv != null) "SOURCE_PLUS_LEGACY_AE" else "SOURCE_METADATA"} " +
|
||||
"finalBaselineEv=${finalProfile.baselineExposureEv} " +
|
||||
"finalBaselineGain=${DngBaselineExposure.exactGain(finalProfile.baselineExposureEv)} " +
|
||||
"pgtm=${finalProfile.profileGainTableMap != null} " +
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assume.assumeNoException
|
||||
import org.junit.Test
|
||||
|
||||
class DngHdrNetViewfinderGridTest {
|
||||
@Test
|
||||
fun displayLinearGridMatchesClassicDomainAndIgnoresRendererBaseline() {
|
||||
val modelInput = FloatArray(
|
||||
DngPhotonProfileGainTableGenerator.HDRNET_INPUT_WIDTH *
|
||||
DngPhotonProfileGainTableGenerator.HDRNET_INPUT_HEIGHT * 4,
|
||||
)
|
||||
for (offset in modelInput.indices step 4) {
|
||||
modelInput[offset] = 0.25f
|
||||
modelInput[offset + 1] = 0.25f
|
||||
modelInput[offset + 2] = 0.25f
|
||||
modelInput[offset + 3] = 0.5f
|
||||
}
|
||||
val coefficients = FloatArray(
|
||||
DngPhotonProfileGainTableGenerator.HDRNET_OUTPUT_FLOAT_COUNT,
|
||||
)
|
||||
val neutralBaselinePlan = checkNotNull(
|
||||
DngPhotonProfileGainTableGenerator.hdrNetPlan(
|
||||
sourceWidth = 4_032,
|
||||
sourceHeight = 3_024,
|
||||
rendererBaselineExposureEv = 0f,
|
||||
hdrRatio = 2f,
|
||||
sourceToShortGain = 1f,
|
||||
),
|
||||
)
|
||||
val brightBaselinePlan = checkNotNull(
|
||||
DngPhotonProfileGainTableGenerator.hdrNetPlan(
|
||||
sourceWidth = 4_032,
|
||||
sourceHeight = 3_024,
|
||||
rendererBaselineExposureEv = 3f,
|
||||
hdrRatio = 2f,
|
||||
sourceToShortGain = 1f,
|
||||
),
|
||||
)
|
||||
|
||||
val grids = try {
|
||||
DngPhotonProfileGainTableGenerator.hdrNetDisplayLinearLumaGrid(
|
||||
plan = neutralBaselinePlan,
|
||||
coefficients = coefficients,
|
||||
modelInput = modelInput,
|
||||
outputRotation = 0,
|
||||
) to DngPhotonProfileGainTableGenerator.hdrNetDisplayLinearLumaGrid(
|
||||
plan = brightBaselinePlan,
|
||||
coefficients = coefficients,
|
||||
modelInput = modelInput,
|
||||
outputRotation = 270,
|
||||
)
|
||||
} catch (error: UnsatisfiedLinkError) {
|
||||
assumeNoException("Android HDRNet JNI is unavailable on this host", error)
|
||||
return
|
||||
}
|
||||
val neutralGrid = checkNotNull(grids.first)
|
||||
val brightBaselineGrid = checkNotNull(grids.second)
|
||||
|
||||
assertEquals(
|
||||
DngPhotonProfileGainTableGenerator.HDRNET_PGTM_GRID_WIDTH *
|
||||
DngPhotonProfileGainTableGenerator.HDRNET_PGTM_GRID_HEIGHT,
|
||||
neutralGrid.size,
|
||||
)
|
||||
neutralGrid.forEach { assertEquals(0.249999f, it, 2e-6f) }
|
||||
assertArrayEquals(neutralGrid, brightBaselineGrid, 2e-6f)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user