feat: Sony embedded lens correction and per-plane WarpRectilinear

This commit is contained in:
zhoubinjia committed 2026-11-10 15:46:19 +08:00
1 parent ce87142df3
commit b8dd6aa0c3
15 files changed
+742 -452

No files matched your search

+1
View File
@@ -332,6 +332,7 @@ add_library(my-native-lib SHARED
fotufilm/fotufilm_jni.cpp
native_runtime.cpp
native-lib.cpp
sony_lens_correction.cpp
spektrafilm/spectral_data.cpp
spektrafilm/spectral_filming.cpp
spektrafilm/spectral_gamut.cpp
+15
View File
@@ -0,0 +1,15 @@
#pragma once
// DNG WarpRectilinear record exchanged with Kotlin through DngRawData.warpRectilinear.
//
// Layout of one record (kDngWarpRectilinearRecordFloats floats):
// for plane in R, G, B: [kr0, kr1, kr2, kr3, kt0, kt1]
// then [centerH, centerV] (normalized to the image bounds)
//
// The DNG SDK reuses the last plane's coefficients for image planes beyond the opcode's plane
// count, so a single-plane opcode is stored with its coefficients replicated to all planes.
constexpr int kDngWarpRectilinearPlanes = 3;
constexpr int kDngWarpRectilinearPlaneCoefficients = 6;
constexpr int kDngWarpRectilinearCenterOffset =
kDngWarpRectilinearPlanes * kDngWarpRectilinearPlaneCoefficients;
constexpr int kDngWarpRectilinearRecordFloats = kDngWarpRectilinearCenterOffset + 2;
+75 -7
View File
@@ -31,6 +31,8 @@
#include "math_utils.h"
#include "fixed_raw_calibration.h"
#include "srgb_color_matrix_policy.h"
#include "dng_warp_rectilinear.h"
#include "sony_lens_correction.h"
#ifndef LOG_TAG
#define LOG_TAG "native-lib"
@@ -2346,6 +2348,7 @@ struct ExifData {
int subjectLocation[4] = {0, 0, 0, 0};
int subjectLocationLen = 0;
int rotation = 0;
SonyLensCorrectionTags sonyLensCorrection;
};
static int sget2(unsigned int ord, LibRaw_abstract_datastream *stream) {
@@ -2674,13 +2677,27 @@ static void parseDngOpcodeList(const std::vector<unsigned char> &data,
} else if (opcodeStage == 3 && id == 1 && payloadSize >= 68) {
const unsigned char *payload = data.data() + offset;
const uint32_t planes = dngOpcodeReadU32(payload);
if (planes == 1 && payloadSize == 68) {
std::vector<float> warp(8);
const uint32_t expectedPayload =
4u + planes * kDngWarpRectilinearPlaneCoefficients * 8u + 16u;
if ((planes == 1 || planes == kDngWarpRectilinearPlanes) &&
payloadSize == expectedPayload) {
std::vector<float> warp(kDngWarpRectilinearRecordFloats);
bool valid = true;
for (int i = 0; i < 8; ++i) {
const double value = dngOpcodeReadDouble(payload + 4 + i * 8);
for (int plane = 0; plane < kDngWarpRectilinearPlanes; ++plane) {
// DNG SDK: planes beyond the opcode's plane count reuse its last plane.
const uint32_t sourcePlane = std::min<uint32_t>(plane, planes - 1);
for (int i = 0; i < kDngWarpRectilinearPlaneCoefficients; ++i) {
const double value = dngOpcodeReadDouble(
payload + 4 + (sourcePlane * kDngWarpRectilinearPlaneCoefficients + i) * 8);
valid = valid && std::isfinite(value);
warp[plane * kDngWarpRectilinearPlaneCoefficients + i] = static_cast<float>(value);
}
}
for (int i = 0; i < 2; ++i) {
const double value = dngOpcodeReadDouble(
payload + 4 + planes * kDngWarpRectilinearPlaneCoefficients * 8 + i * 8);
valid = valid && std::isfinite(value);
warp[i] = static_cast<float>(value);
warp[kDngWarpRectilinearCenterOffset + i] = static_cast<float>(value);
}
if (valid) {
info.warpRectilinear.insert(info.warpRectilinear.end(), warp.begin(), warp.end());
@@ -3031,6 +3048,24 @@ static void exif_callback(void *datap, int tag, int type, int len,
if (count > 0)
ed->hasNoiseProfile = true;
}
} else if ((actual_tag == kSonyLensCorrectionTagDistortion ||
actual_tag == kSonyLensCorrectionTagChromaticAberration ||
actual_tag == kSonyLensCorrectionTagVignetting) &&
(tag >> 20) != 0 && type == 8 && len > 0 && len <= 64) {
// Sony ARW lens correction arrays live in plain TIFF IFDs (SubIFD / SR2SubIFD); the
// (ifd + 1) << 20 marker excludes Panasonic and CR3 callbacks that reuse low tag numbers.
std::vector<int16_t> *target =
actual_tag == kSonyLensCorrectionTagDistortion
? &ed->sonyLensCorrection.distortion
: (actual_tag == kSonyLensCorrectionTagChromaticAberration
? &ed->sonyLensCorrection.chromaticAberration
: &ed->sonyLensCorrection.vignetting);
if (target->empty()) {
target->resize(len);
for (int i = 0; i < len; i++) {
(*target)[i] = static_cast<int16_t>(sget2(ord, stream));
}
}
} else if (actual_tag == 0x9214 ||
actual_tag == 0xA214) { // SubjectLocation / SubjectArea
if (len > 0) {
@@ -3306,6 +3341,39 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
env, RawProcessor, cfaPattern, left, top, exportedLscWidth,
exportedLscHeight, exportedLscGrid);
}
if (!isDngInput &&
RawProcessor.imgdata.idata.maker_index == LIBRAW_CAMERAMAKER_Sony) {
SonyLensCorrection sonyCorrection;
if (decodeSonyLensCorrection(ed.sonyLensCorrection, sonyCorrection)) {
std::vector<float> sonyWarp;
if (buildSonyWarpRectilinear(sonyCorrection, width, height, sonyWarp)) {
dngRawTagInfo.warpRectilinear.insert(dngRawTagInfo.warpRectilinear.end(),
sonyWarp.begin(), sonyWarp.end());
dngRawTagInfo.warpRectilinearFlags.push_back(0);
}
// Vignetting is a CFA-domain gain like DNG GainMap; LinearRaw/sRAW pixels have no
// per-site shading stage in the pipeline.
if (!useLinearRawRgb && exportedLscArray == nullptr) {
std::vector<float> sonyGainMap;
if (buildSonyVignettingGainMap(sonyCorrection, width, height, sonyGainMap,
exportedLscWidth, exportedLscHeight,
exportedLscGrid)) {
exportedLscArray = env->NewFloatArray(static_cast<jsize>(sonyGainMap.size()));
if (exportedLscArray) {
env->SetFloatArrayRegion(exportedLscArray, 0,
static_cast<jsize>(sonyGainMap.size()),
sonyGainMap.data());
}
}
}
} else {
LOGI("Sony lens correction: no usable embedded parameters "
"(dist=%zu ca=%zu vig=%zu)",
ed.sonyLensCorrection.distortion.size(),
ed.sonyLensCorrection.chromaticAberration.size(),
ed.sonyLensCorrection.vignetting.size());
}
}
jfloatArray exportedLscGridArray = nullptr;
if (exportedLscArray) {
exportedLscGridArray = env->NewFloatArray(8);
@@ -3830,9 +3898,9 @@ Java_com_hinnka_mycamera_raw_RawDemosaicProcessor_processDngNative(
jfloatArray warpRectilinearArray = nullptr;
jintArray warpRectilinearFlagsArray = nullptr;
if (!dngRawTagInfo.warpRectilinear.empty() &&
dngRawTagInfo.warpRectilinear.size() % 8 == 0 &&
dngRawTagInfo.warpRectilinear.size() % kDngWarpRectilinearRecordFloats == 0 &&
dngRawTagInfo.warpRectilinearFlags.size() ==
dngRawTagInfo.warpRectilinear.size() / 8) {
dngRawTagInfo.warpRectilinear.size() / kDngWarpRectilinearRecordFloats) {
warpRectilinearArray = env->NewFloatArray(dngRawTagInfo.warpRectilinear.size());
env->SetFloatArrayRegion(warpRectilinearArray, 0,
dngRawTagInfo.warpRectilinear.size(),
+353
View File
@@ -0,0 +1,353 @@
#include "sony_lens_correction.h"
#include <algorithm>
#include <cmath>
#include <functional>
#include "common.h"
#include "dng_warp_rectilinear.h"
namespace {
constexpr int kPolynomialTerms = 4; // DNG WarpRectilinear radial terms in r^2
constexpr int kFitSamples = 2048;
constexpr int kScaleSearchIterations = 32;
constexpr double kMinFrameScale = 0.5; // destination zoom factor search range
constexpr double kMaxFrameScale = 2.0;
constexpr int kFitRefinements = 3;
constexpr int kVignettingMapColumns = 65;
double interpolateLinearSpline(const double *xi, const double *yi, int n, double x) {
if (x <= xi[0]) return yi[0];
for (int i = 1; i < n; ++i) {
if (x <= xi[i]) {
const double t = (x - xi[i - 1]) / (xi[i] - xi[i - 1]);
return yi[i - 1] + t * (yi[i] - yi[i - 1]);
}
}
return yi[n - 1];
}
double evaluatePolynomial(const double coefficients[kPolynomialTerms], double r2) {
return coefficients[0] +
r2 * (coefficients[1] + r2 * (coefficients[2] + r2 * coefficients[3]));
}
struct FrameGeometry {
double width;
double height;
double centerX;
double centerY;
double normRadius;
};
FrameGeometry frameGeometry(int width, int height) {
FrameGeometry geometry{};
geometry.width = width;
geometry.height = height;
// WarpRectilinear center 0.5 / 0.5; the normalization radius is the farthest corner
// distance, which equals the half diagonal used by the Sony splines.
geometry.centerX = 0.5 * width;
geometry.centerY = 0.5 * height;
geometry.normRadius = std::hypot(std::max(geometry.centerX, width - geometry.centerX),
std::max(geometry.centerY, height - geometry.centerY));
return geometry;
}
// ratioAtDestination(r) maps a normalized destination radius to the destination-to-source
// radius ratio. Returns true when every destination pixel center on the frame border lands on a
// source pixel center inside the frame.
bool coversFrame(const FrameGeometry &geometry,
const std::function<double(double)> &ratioAtDestination) {
const double maxX = geometry.width - 1.0;
const double maxY = geometry.height - 1.0;
auto covered = [&](double x, double y) {
const double dx = (x - geometry.centerX) / geometry.normRadius;
const double dy = (y - geometry.centerY) / geometry.normRadius;
const double r = std::min(std::sqrt(dx * dx + dy * dy), 1.0);
const double ratio = ratioAtDestination(r);
if (!std::isfinite(ratio) || ratio <= 0.0) return false;
const double sourceX = geometry.centerX + geometry.normRadius * dx * ratio;
const double sourceY = geometry.centerY + geometry.normRadius * dy * ratio;
return sourceX >= 0.0 && sourceX <= maxX && sourceY >= 0.0 && sourceY <= maxY;
};
const int w = static_cast<int>(geometry.width);
const int h = static_cast<int>(geometry.height);
for (int x = 0; x < w; ++x) {
if (!covered(x, 0.0) || !covered(x, maxY)) return false;
}
for (int y = 1; y < h - 1; ++y) {
if (!covered(0.0, y) || !covered(maxX, y)) return false;
}
return true;
}
// Finds the smallest destination zoom factor k for which ratio(r) = sourceRatio(r / k) / k
// covers the frame in all three planes. Returns a non-positive value when no factor in the
// search range works.
double solveFrameScale(const FrameGeometry &geometry,
const std::function<double(int, double)> &sourceRatio) {
auto coveredAt = [&](double k) {
for (int plane = 0; plane < 3; ++plane) {
if (!coversFrame(geometry, [&](double r) { return sourceRatio(plane, r / k) / k; })) {
return false;
}
}
return true;
};
if (!coveredAt(kMaxFrameScale)) return -1.0;
double lo = kMinFrameScale;
double hi = kMaxFrameScale;
if (coveredAt(lo)) return lo;
for (int i = 0; i < kScaleSearchIterations; ++i) {
const double mid = 0.5 * (lo + hi);
if (coveredAt(mid)) {
hi = mid;
} else {
lo = mid;
}
}
return hi;
}
bool solveLinearSystem(double a[kPolynomialTerms][kPolynomialTerms], double b[kPolynomialTerms],
double x[kPolynomialTerms]) {
for (int col = 0; col < kPolynomialTerms; ++col) {
int pivot = col;
for (int row = col + 1; row < kPolynomialTerms; ++row) {
if (std::abs(a[row][col]) > std::abs(a[pivot][col])) pivot = row;
}
if (std::abs(a[pivot][col]) < 1e-300) return false;
if (pivot != col) {
std::swap(a[pivot], a[col]);
std::swap(b[pivot], b[col]);
}
for (int row = col + 1; row < kPolynomialTerms; ++row) {
const double factor = a[row][col] / a[col][col];
for (int k = col; k < kPolynomialTerms; ++k) a[row][k] -= factor * a[col][k];
b[row] -= factor * b[col];
}
}
for (int row = kPolynomialTerms - 1; row >= 0; --row) {
double sum = b[row];
for (int k = row + 1; k < kPolynomialTerms; ++k) sum -= a[row][k] * x[k];
x[row] = sum / a[row][row];
}
for (int i = 0; i < kPolynomialTerms; ++i) {
if (!std::isfinite(x[i])) return false;
}
return true;
}
// Weighted least squares of the spline ratio by a0 + a1 rho^2 + a2 rho^4 + a3 rho^6 over
// [0, rhoMax]. The weight rho^3 minimizes the mean squared pixel displacement over the image
// area (displacement error ~ rho * ratio error, area element ~ rho drho).
bool fitRadialPolynomial(const SonyLensCorrection &correction, int plane, double rhoMax,
double coefficients[kPolynomialTerms]) {
double normal[kPolynomialTerms][kPolynomialTerms] = {};
double rhs[kPolynomialTerms] = {};
for (int i = 0; i < kFitSamples; ++i) {
const double rho = rhoMax * (i + 0.5) / kFitSamples;
const double rho2 = rho * rho;
const double weight = rho2 * rho;
const double target = correction.planeRatio(plane, rho);
const double basis[kPolynomialTerms] = {1.0, rho2, rho2 * rho2, rho2 * rho2 * rho2};
for (int r = 0; r < kPolynomialTerms; ++r) {
rhs[r] += weight * basis[r] * target;
for (int c = 0; c < kPolynomialTerms; ++c) {
normal[r][c] += weight * basis[r] * basis[c];
}
}
}
return solveLinearSystem(normal, rhs, coefficients);
}
double maxFitDisplacementPixels(const SonyLensCorrection &correction, int plane, double rhoMax,
const double coefficients[kPolynomialTerms],
double normRadius) {
double worst = 0.0;
for (int i = 0; i <= kFitSamples; ++i) {
const double rho = rhoMax * i / kFitSamples;
const double spline = correction.planeRatio(plane, rho);
const double polynomial = evaluatePolynomial(coefficients, rho * rho);
worst = std::max(worst, std::abs(polynomial - spline) * rho * normRadius);
}
return worst;
}
} // namespace
double SonyRadialSpline::evaluate(double radius, double identity) const {
return count > 0 ? interpolateLinearSpline(knots, values, count, radius) : identity;
}
double SonyLensCorrection::planeRatio(int plane, double radius) const {
const double ratio = distortion.evaluate(radius, 1.0);
if (plane == 0) return ratio * caRed.evaluate(radius, 1.0);
if (plane == 2) return ratio * caBlue.evaluate(radius, 1.0);
return ratio;
}
namespace {
// Reads the knot count header. Returns 0 for an absent component, -1 for a malformed one.
int sonyKnotCount(const std::vector<int16_t> &tag, int perKnot) {
if (tag.empty() || tag[0] == 0) return 0;
if (tag[0] < 0 || tag[0] % perKnot != 0) return -1;
const int count = tag[0] / perKnot;
if (count < 2 || count > kSonyLensCorrectionMaxKnots ||
static_cast<int>(tag.size()) < count * perKnot + 1) {
return -1;
}
return count;
}
// Fills spline knots at (i + 0.5) / (n - 1) of the half diagonal with decoded values.
// Returns whether any stored value differs from the identity encoding (0).
template <typename Decode>
bool decodeSpline(const std::vector<int16_t> &tag, int count, int valueOffset,
SonyRadialSpline &spline, Decode decode) {
spline.count = count;
bool nonIdentity = false;
for (int i = 0; i < count; ++i) {
const int16_t raw = tag[valueOffset + i];
spline.knots[i] = (i + 0.5) / (count - 1);
spline.values[i] = decode(raw);
nonIdentity = nonIdentity || raw != 0;
}
if (!nonIdentity) spline.count = 0;
return nonIdentity;
}
} // namespace
bool decodeSonyLensCorrection(const SonyLensCorrectionTags &tags, SonyLensCorrection &out) {
out = SonyLensCorrection{};
const int distortionKnots = sonyKnotCount(tags.distortion, 1);
const int caKnots = sonyKnotCount(tags.chromaticAberration, 2);
const int vignettingKnots = sonyKnotCount(tags.vignetting, 1);
if (distortionKnots < 0 || caKnots < 0 || vignettingKnots < 0) {
LOGW("Sony lens correction: malformed arrays dist=%zu/%d ca=%zu/%d vig=%zu/%d",
tags.distortion.size(), tags.distortion.empty() ? 0 : tags.distortion[0],
tags.chromaticAberration.size(),
tags.chromaticAberration.empty() ? 0 : tags.chromaticAberration[0],
tags.vignetting.size(), tags.vignetting.empty() ? 0 : tags.vignetting[0]);
return false;
}
const bool hasDistortion = decodeSpline(
tags.distortion, distortionKnots, 1, out.distortion,
[](int16_t v) { return v * std::ldexp(1.0, -14) + 1.0; });
auto decodeCa = [](int16_t v) { return v * std::ldexp(1.0, -21) + 1.0; };
const bool hasCaRed =
decodeSpline(tags.chromaticAberration, caKnots, 1, out.caRed, decodeCa);
const bool hasCaBlue =
decodeSpline(tags.chromaticAberration, caKnots, 1 + caKnots, out.caBlue, decodeCa);
// Sony stores vignetting falloff as 2^(0.5 - 2^(v * 2^-13 - 1)); correction divides by it.
out.hasVignetting = decodeSpline(
tags.vignetting, vignettingKnots, 1, out.vignettingGain, [](int16_t v) {
return std::pow(2.0, std::pow(2.0, v * std::ldexp(1.0, -13) - 1.0) - 0.5);
});
out.hasGeometry = hasDistortion || hasCaRed || hasCaBlue;
LOGI("Sony lens correction: knots dist=%d caR=%d caB=%d vig=%d",
out.distortion.count, out.caRed.count, out.caBlue.count, out.vignettingGain.count);
return out.hasGeometry || out.hasVignetting;
}
bool buildSonyWarpRectilinear(const SonyLensCorrection &correction, int width, int height,
std::vector<float> &record) {
record.clear();
if (!correction.hasGeometry || width < 2 || height < 2) return false;
const FrameGeometry geometry = frameGeometry(width, height);
// Frame scale from the splines themselves, then alternate polynomial fits over the radius
// range the scaled destination reaches and re-solve the scale on the fitted polynomials, so
// the coverage guarantee holds for exactly what the GPU evaluates.
double scale = solveFrameScale(geometry, [&](int plane, double rho) {
return correction.planeRatio(plane, rho);
});
if (scale <= 0.0) {
LOGW("Sony lens correction: no frame scale covers the distortion");
return false;
}
double coefficients[3][kPolynomialTerms] = {};
for (int refinement = 0; refinement < kFitRefinements; ++refinement) {
const double rhoMax = 1.0 / scale;
for (int plane = 0; plane < 3; ++plane) {
if (!fitRadialPolynomial(correction, plane, rhoMax, coefficients[plane])) {
LOGW("Sony lens correction: polynomial fit failed for plane %d", plane);
return false;
}
}
scale = solveFrameScale(geometry, [&](int plane, double rho) {
return evaluatePolynomial(coefficients[plane], rho * rho);
});
if (scale <= 0.0) {
LOGW("Sony lens correction: fitted polynomial cannot cover the frame");
return false;
}
}
record.assign(kDngWarpRectilinearRecordFloats, 0.0f);
const double rhoMax = 1.0 / scale;
for (int plane = 0; plane < 3; ++plane) {
// ratio(r) = P(r / k) / k => coefficient i scales by k^-(2i + 1).
double factor = 1.0 / scale;
float *planeRecord = record.data() + plane * kDngWarpRectilinearPlaneCoefficients;
for (int term = 0; term < kPolynomialTerms; ++term) {
planeRecord[term] = static_cast<float>(coefficients[plane][term] * factor);
factor /= scale * scale;
}
LOGI("Sony lens correction: plane=%d kr=[%.8f, %.8f, %.8f, %.8f] fitErrMax=%.3fpx",
plane, planeRecord[0], planeRecord[1], planeRecord[2], planeRecord[3],
maxFitDisplacementPixels(correction, plane, rhoMax, coefficients[plane],
geometry.normRadius));
}
record[kDngWarpRectilinearCenterOffset] = 0.5f;
record[kDngWarpRectilinearCenterOffset + 1] = 0.5f;
LOGI("Sony lens correction: warp knots dist=%d ca=%d frameScale=%.5f size=%dx%d",
correction.distortion.count, correction.caRed.count, 1.0 / scale, width, height);
return true;
}
bool buildSonyVignettingGainMap(const SonyLensCorrection &correction, int width, int height,
std::vector<float> &packed, int &mapWidth, int &mapHeight,
float grid[8]) {
packed.clear();
mapWidth = 0;
mapHeight = 0;
if (!correction.hasVignetting || width < 2 || height < 2) return false;
const int columns = kVignettingMapColumns;
const int rows = std::max(2, static_cast<int>(std::lround(
(columns - 1) * static_cast<double>(height) / width)) + 1);
const FrameGeometry geometry = frameGeometry(width, height);
packed.resize(static_cast<size_t>(columns) * rows * 4);
for (int row = 0; row < rows; ++row) {
// GainMap points sit at normalized positions origin + index * spacing over the bounds.
const double y = height * static_cast<double>(row) / (rows - 1);
for (int column = 0; column < columns; ++column) {
const double x = width * static_cast<double>(column) / (columns - 1);
const double r = std::hypot(x - geometry.centerX, y - geometry.centerY) /
geometry.normRadius;
const float gain = static_cast<float>(correction.vignettingGain.evaluate(r, 1.0));
float *point = packed.data() + (static_cast<size_t>(row) * columns + column) * 4;
point[0] = point[1] = point[2] = point[3] = gain;
}
}
mapWidth = columns;
mapHeight = rows;
grid[0] = 0.0f;
grid[1] = 0.0f;
grid[2] = 1.0f / (columns - 1);
grid[3] = 1.0f / (rows - 1);
grid[4] = 0.0f;
grid[5] = 0.0f;
grid[6] = static_cast<float>(width);
grid[7] = static_cast<float>(height);
LOGI("Sony lens correction: vignetting map %dx%d centerGain=%.4f cornerGain=%.4f",
columns, rows, packed[(static_cast<size_t>(rows / 2) * columns + columns / 2) * 4],
packed[0]);
return true;
}
+62
View File
@@ -0,0 +1,62 @@
#pragma once
#include <cstdint>
#include <vector>
// Sony in-camera lens correction parameters stored in ARW TIFF IFDs:
// 0x7032 VignettingCorrParams, 0x7035 ChromaticAberrationCorrParams,
// 0x7037 DistortionCorrParams.
// Each array starts with its knot count (CA stores 2 * knots: red then blue); a zero count means
// the body has no data for that component (e.g. third-party lenses without profiles). Knots are
// uniformly spaced over the radius normalized by the half diagonal around the image center and
// are interpolated with a linear spline (darktable / RawTherapee embedded-metadata semantics).
struct SonyLensCorrectionTags {
std::vector<int16_t> distortion;
std::vector<int16_t> chromaticAberration;
std::vector<int16_t> vignetting;
};
constexpr int kSonyLensCorrectionTagVignetting = 0x7032;
constexpr int kSonyLensCorrectionTagChromaticAberration = 0x7035;
constexpr int kSonyLensCorrectionTagDistortion = 0x7037;
constexpr int kSonyLensCorrectionMaxKnots = 16;
struct SonyRadialSpline {
int count = 0; // 0: component absent (identity)
double knots[kSonyLensCorrectionMaxKnots] = {};
double values[kSonyLensCorrectionMaxKnots] = {};
double evaluate(double radius, double identity) const;
};
struct SonyLensCorrection {
// Destination-to-source radius ratio from distortion.
SonyRadialSpline distortion;
// Destination-to-source radius ratio of red / blue relative to green (lateral CA).
SonyRadialSpline caRed;
SonyRadialSpline caBlue;
// Multiplicative gain that removes vignetting at the source radius.
SonyRadialSpline vignettingGain;
bool hasGeometry = false;
bool hasVignetting = false;
// Combined destination-to-source ratio for plane 0..2 (R, G, B).
double planeRatio(int plane, double radius) const;
};
// Validates and decodes each tag array independently. Returns false when no component carries a
// correction.
bool decodeSonyLensCorrection(const SonyLensCorrectionTags &tags, SonyLensCorrection &out);
// Builds one DNG WarpRectilinear record (see dng_warp_rectilinear.h) whose per-plane radial
// polynomials reproduce the Sony splines. The frame scale is folded into the polynomials so the
// whole width x height destination is covered by source pixels in every plane.
bool buildSonyWarpRectilinear(const SonyLensCorrection &correction, int width, int height,
std::vector<float> &record);
// Builds a DNG GainMap-style vignetting table packed as RGGB-ordered float4 per grid point
// (all four CFA channels carry the same radial gain). grid receives
// [originH, originV, spacingH, spacingV, boundsLeft, boundsTop, boundsRight, boundsBottom].
bool buildSonyVignettingGainMap(const SonyLensCorrection &correction, int width, int height,
std::vector<float> &packed, int &mapWidth, int &mapHeight,
float grid[8]);
@@ -1522,12 +1522,15 @@ internal class DngPhotonProfileGainTableAlgorithm {
val interpreter = ensureHdrNetInterpreter(input.context) ?: return null
val activeWarpParameters = ArrayList<Float>()
input.warpRectilinear
?.takeIf { it.isNotEmpty() && it.size % 8 == 0 }
?.takeIf { it.isNotEmpty() && it.size % DngWarpRectilinear.RECORD_SIZE == 0 }
?.let { warps ->
for (offset in warps.indices step 8) {
val parameters = warps.copyOfRange(offset, offset + 8)
for (offset in warps.indices step DngWarpRectilinear.RECORD_SIZE) {
val parameters =
warps.copyOfRange(offset, offset + DngWarpRectilinear.RECORD_SIZE)
if (input.isNoOpWarp(parameters)) continue
parameters.forEach(activeWarpParameters::add)
// Statistics sample one value per position: use the reference plane.
DngWarpRectilinear.referencePlaneParameters(parameters)
.forEach(activeWarpParameters::add)
}
}
val inputFloatCount = DngPhotonProfileGainTableGenerator.HDRNET_INPUT_WIDTH *
@@ -1621,7 +1624,7 @@ internal class DngPhotonProfileGainTableAlgorithm {
)
GLES31.glUniform1i(
GLES31.glGetUniformLocation(hdrNetInputProgram, "uWarpCount"),
activeWarpParameters.size / 8,
activeWarpParameters.size / DngWarpRectilinear.SINGLE_PLANE_SIZE,
)
val dehazeTuning = PhotonCoreImagingTuning.dehaze.normalized()
val modelInputBuffer = ByteBuffer.allocateDirect(inputByteCount)
@@ -1860,12 +1863,15 @@ internal class DngPhotonProfileGainTableAlgorithm {
if (gridWidth <= 0 || gridHeight <= 0) return null
val activeWarpParameters = ArrayList<Float>()
warpRectilinear
?.takeIf { it.isNotEmpty() && it.size % 8 == 0 }
?.takeIf { it.isNotEmpty() && it.size % DngWarpRectilinear.RECORD_SIZE == 0 }
?.let { warps ->
for (offset in warps.indices step 8) {
val parameters = warps.copyOfRange(offset, offset + 8)
for (offset in warps.indices step DngWarpRectilinear.RECORD_SIZE) {
val parameters =
warps.copyOfRange(offset, offset + DngWarpRectilinear.RECORD_SIZE)
if (input.isNoOpWarp(parameters)) continue
parameters.forEach { activeWarpParameters += it }
// Statistics sample one value per position: use the reference plane.
DngWarpRectilinear.referencePlaneParameters(parameters)
.forEach { activeWarpParameters += it }
}
}
@@ -1997,7 +2003,7 @@ internal class DngPhotonProfileGainTableAlgorithm {
)
GLES31.glUniform1i(
GLES31.glGetUniformLocation(cellSamplesProgram, "uWarpCount"),
activeWarpParameters.size / 8,
activeWarpParameters.size / DngWarpRectilinear.SINGLE_PLANE_SIZE,
)
val safeColorCorrectionMatrix = colorCorrectionMatrix.takeIf { matrix ->
matrix.size >= 9 && matrix.take(9).all { it.isFinite() }
@@ -22,7 +22,7 @@ import java.nio.ByteBuffer
* @param whitePointXy DNG SDK/LibRaw 相机矩阵与当前 CameraNeutral 解出的白点 xy
* @param rotation 旋转角度 (0, 90, 180, 270)
* @param shadowScale DNG ShadowScale,用于 Adobe DefaultBlackRender Auto 的暗部黑点计算
* @param lensShadingMap Lens Shading Map (LSC) 增益表,null表示无LSC数据
* @param lensShadingMap Lens Shading Map (LSC) 增益表(DNG GainMap 或 Sony ARW 内嵌暗角校正),null表示无LSC数据
* @param lensShadingMapWidth LSC 表宽度
* @param lensShadingMapHeight LSC 表高度
* @param lensShadingMapGrid DNG GainMap 参数
@@ -61,7 +61,11 @@ data class DngRawData @Keep constructor(
val activeArray: IntArray?, // [left, top, right, bottom]
val defaultCrop: IntArray?, // [left, top, right, bottom] relative to rawData
val noiseProfile: FloatArray?, // NoiseProfile [S1, O1, S2, O2, ...]
val warpRectilinear: FloatArray?, // repeated [k0, k1, k2, k3, t0, t1, centerH, centerV]
/**
* Repeated DngWarpRectilinear.RECORD_SIZE records: per R/G/B plane [kr0..kr3, kt0, kt1],
* then [centerH, centerV]. Sources: DNG OpcodeList3 or Sony ARW embedded lens correction.
*/
val warpRectilinear: FloatArray?,
val warpRectilinearFlags: IntArray?, // one DNG opcode flags value per warp
val embeddedPreview: Bitmap? = null,
/** Embedded source calibration only; null when neither ColorMatrix nor ForwardMatrix is present. */
@@ -13,6 +13,84 @@ import kotlin.math.sqrt
internal object DngWarpRectilinear {
const val OPTIONAL_FLAG = 1
/** Image planes carried by every record: R, G, B. */
const val PLANES = 3
/** Radial kr0..kr3 followed by tangential kt0, kt1. */
const val PLANE_COEFFICIENTS = 6
/** Offset of [centerH, centerV] inside a record. */
const val CENTER_OFFSET = PLANES * PLANE_COEFFICIENTS
/**
* One opcode record: per-plane coefficients for R, G, B, then the normalized center.
* Single-plane DNG opcodes are replicated to all planes (DNG SDK reuses the last plane).
*/
const val RECORD_SIZE = CENTER_OFFSET + 2
/** Plane whose geometry represents the image for luminance-only sampling. */
const val REFERENCE_PLANE = 1
/** dng_opcode_BaseWarpRectilinear::IsNOP: identity radial and zero tangential terms. */
fun isNoOp(parameters: FloatArray): Boolean {
if (parameters.size != RECORD_SIZE) return false
for (plane in 0 until PLANES) {
val offset = plane * PLANE_COEFFICIENTS
if (parameters[offset] != 1f) return false
for (index in 1 until PLANE_COEFFICIENTS) {
if (parameters[offset + index] != 0f) return false
}
}
return true
}
/** Floats per single-plane geometry: [kr0..kr3, kt0, kt1, centerH, centerV]. */
const val SINGLE_PLANE_SIZE = PLANE_COEFFICIENTS + 2
/**
* Expands a single-plane opcode ([SINGLE_PLANE_SIZE] floats) into a record by replicating
* its coefficients to every plane, as the DNG SDK does for images with more planes.
*/
fun recordFromSinglePlane(singlePlane: FloatArray): FloatArray {
require(singlePlane.size == SINGLE_PLANE_SIZE) {
"Single-plane WarpRectilinear size ${singlePlane.size}"
}
return FloatArray(RECORD_SIZE).also { record ->
for (plane in 0 until PLANES) {
singlePlane.copyInto(record, plane * PLANE_COEFFICIENTS, 0, PLANE_COEFFICIENTS)
}
record[CENTER_OFFSET] = singlePlane[PLANE_COEFFICIENTS]
record[CENTER_OFFSET + 1] = singlePlane[PLANE_COEFFICIENTS + 1]
}
}
/**
* Single-plane geometry of [REFERENCE_PLANE], for consumers that sample one luminance-like
* value per position (statistics, metering) rather than resampling each color plane.
*/
fun referencePlaneParameters(parameters: FloatArray): FloatArray {
require(parameters.size == RECORD_SIZE) { "WarpRectilinear record size ${parameters.size}" }
val offset = REFERENCE_PLANE * PLANE_COEFFICIENTS
return FloatArray(SINGLE_PLANE_SIZE).also { out ->
parameters.copyInto(out, 0, offset, offset + PLANE_COEFFICIENTS)
out[PLANE_COEFFICIENTS] = parameters[CENTER_OFFSET]
out[PLANE_COEFFICIENTS + 1] = parameters[CENTER_OFFSET + 1]
}
}
/** Whether all planes share one geometry, so a single sample serves every channel. */
fun planesShareGeometry(parameters: FloatArray): Boolean {
if (parameters.size != RECORD_SIZE) return false
for (plane in 1 until PLANES) {
for (index in 0 until PLANE_COEFFICIENTS) {
if (parameters[plane * PLANE_COEFFICIENTS + index] != parameters[index]) {
return false
}
}
}
return true
}
enum class Rejection {
NONE,
MALFORMED_OR_UNSAFE,
@@ -61,7 +139,7 @@ internal object DngWarpRectilinear {
right: Int,
bottom: Int,
): Boolean {
if (parameters.size != 8 || width <= 1 || height <= 1 ||
if (parameters.size != RECORD_SIZE || width <= 1 || height <= 1 ||
left < 0 || top < 0 || right > width || bottom > height ||
left >= right || top >= bottom
) {
@@ -69,13 +147,25 @@ internal object DngWarpRectilinear {
}
fun covered(x: Int, y: Int): Boolean {
val source = mapDestinationToSource(parameters, width, height, x.toFloat(), y.toFloat())
?: return false
// AOSP DngCreator accepts coordinates inside the continuous image rectangle
// [0,width) x [0,height). Values above the last pixel center by less than one pixel
// are handled by the resampler without creating a multi-pixel repeated border.
return source.first >= -1e-3f && source.first < width.toFloat() &&
source.second >= -1e-3f && source.second < height.toFloat()
for (plane in 0 until PLANES) {
val source = mapDestinationToSource(
parameters,
plane,
width,
height,
x.toFloat(),
y.toFloat(),
) ?: return false
// AOSP DngCreator accepts coordinates inside the continuous image rectangle
// [0,width) x [0,height). Values above the last pixel center by less than one
// pixel are handled by the resampler without a multi-pixel repeated border.
if (source.first < -1e-3f || source.first >= width.toFloat() ||
source.second < -1e-3f || source.second >= height.toFloat()
) {
return false
}
}
return true
}
val lastX = right - 1
@@ -90,30 +180,35 @@ internal object DngWarpRectilinear {
}
private fun isNumericallySafe(parameters: FloatArray, width: Int, height: Int): Boolean {
if (parameters.size != 8 || parameters.any { !it.isFinite() } ||
if (parameters.size != RECORD_SIZE || parameters.any { !it.isFinite() } ||
width <= 1 || height <= 1
) {
return false
}
if (parameters[6] !in 0f..1f || parameters[7] !in 0f..1f) return false
if (parameters[CENTER_OFFSET] !in 0f..1f || parameters[CENTER_OFFSET + 1] !in 0f..1f) {
return false
}
for (gridY in 0..16) {
for (gridX in 0..16) {
val destinationX = (width - 1) * gridX / 16f
val destinationY = (height - 1) * gridY / 16f
val source = mapDestinationToSource(
parameters,
width,
height,
destinationX,
destinationY,
) ?: return false
val limitX = width * 4f
val limitY = height * 4f
if (source.first !in -limitX..limitX * 2f ||
source.second !in -limitY..limitY * 2f
) {
return false
for (plane in 0 until PLANES) {
for (gridY in 0..16) {
for (gridX in 0..16) {
val destinationX = (width - 1) * gridX / 16f
val destinationY = (height - 1) * gridY / 16f
val source = mapDestinationToSource(
parameters,
plane,
width,
height,
destinationX,
destinationY,
) ?: return false
val limitX = width * 4f
val limitY = height * 4f
if (source.first !in -limitX..limitX * 2f ||
source.second !in -limitY..limitY * 2f
) {
return false
}
}
}
}
@@ -122,26 +217,28 @@ internal object DngWarpRectilinear {
private fun mapDestinationToSource(
parameters: FloatArray,
plane: Int,
width: Int,
height: Int,
destinationX: Float,
destinationY: Float,
): Pair<Float, Float>? {
val centerX = parameters[6] * width
val centerY = parameters[7] * height
val centerX = parameters[CENTER_OFFSET] * width
val centerY = parameters[CENTER_OFFSET + 1] * height
val p = plane * PLANE_COEFFICIENTS
val farX = max(centerX, width - centerX)
val farY = max(centerY, height - centerY)
val normRadius = sqrt(farX * farX + farY * farY).coerceAtLeast(1f)
val dx = (destinationX - centerX) / normRadius
val dy = (destinationY - centerY) / normRadius
val r2 = (dx * dx + dy * dy).coerceAtMost(1f)
val ratio = parameters[0] + parameters[1] * r2 +
parameters[2] * r2 * r2 + parameters[3] * r2 * r2 * r2
val ratio = parameters[p] + parameters[p + 1] * r2 +
parameters[p + 2] * r2 * r2 + parameters[p + 3] * r2 * r2 * r2
if (!ratio.isFinite() || ratio <= 0f) return null
val tangentX = parameters[5] * (r2 + 2f * dx * dx) +
2f * parameters[4] * dx * dy
val tangentY = parameters[4] * (r2 + 2f * dy * dy) +
2f * parameters[5] * dx * dy
val tangentX = parameters[p + 5] * (r2 + 2f * dx * dx) +
2f * parameters[p + 4] * dx * dy
val tangentY = parameters[p + 4] * (r2 + 2f * dy * dy) +
2f * parameters[p + 5] * dx * dy
val sourceX = centerX + normRadius * (dx * ratio + tangentX)
val sourceY = centerY + normRadius * (dy * ratio + tangentY)
return if (sourceX.isFinite() && sourceY.isFinite()) {
@@ -2440,7 +2440,7 @@ class RawDemosaicProcessor {
"RAW_CROP_TRACE stage=DNG_READ raw=${dngRawData.width}x${dngRawData.height} " +
"activeArray=${dngRawData.activeArray?.contentToString()} " +
"defaultCrop=${dngRawData.defaultCrop?.contentToString()} " +
"warpCount=${dngRawData.warpRectilinear?.size?.div(8) ?: 0} " +
"warpCount=${dngRawData.warpRectilinear?.size?.div(DngWarpRectilinear.RECORD_SIZE) ?: 0} " +
"warpFlags=${dngRawData.warpRectilinearFlags?.contentToString()}"
)
embeddedDngJpegPreview = dngRawData.embeddedPreview
@@ -3302,8 +3302,9 @@ class RawDemosaicProcessor {
}
?.let { warps ->
var appliedWarpCount = 0
for (offset in warps.indices step 8) {
val parameters = warps.copyOfRange(offset, offset + 8)
for (offset in warps.indices step DngWarpRectilinear.RECORD_SIZE) {
val parameters =
warps.copyOfRange(offset, offset + DngWarpRectilinear.RECORD_SIZE)
// dng_opcode_BaseWarpRectilinear::IsNOP skips an identity radial
// transform with zero tangential terms. Preserve that Stage 3 behavior.
if (isNoOpWarpRectilinear(parameters)) {
@@ -3327,7 +3328,7 @@ class RawDemosaicProcessor {
linearOutputFramebufferId = tempFbo
appliedWarpCount++
}
PLog.d(TAG, "Applied $appliedWarpCount/${warps.size / 8} DNG WarpRectilinear opcode(s) before color conversion")
PLog.d(TAG, "Applied $appliedWarpCount/${warps.size / DngWarpRectilinear.RECORD_SIZE} DNG WarpRectilinear opcode(s) before color conversion")
}
}
@@ -5559,10 +5560,8 @@ class RawDemosaicProcessor {
) != null
}
private fun isNoOpWarpRectilinear(parameters: FloatArray): Boolean {
if (parameters.size != 8) return false
return parameters[0] == 1f && (1..5).all { index -> parameters[index] == 0f }
}
private fun isNoOpWarpRectilinear(parameters: FloatArray): Boolean =
DngWarpRectilinear.isNoOp(parameters)
private fun filterApplicableWarpRectilinear(
warps: FloatArray?,
@@ -5572,11 +5571,11 @@ class RawDemosaicProcessor {
outputSourceBounds: Rect,
): FloatArray? {
if (warps == null || warps.isEmpty()) return null
if (warps.size % 8 != 0) {
if (warps.size % DngWarpRectilinear.RECORD_SIZE != 0) {
PLog.w(TAG, "Ignoring malformed DNG WarpRectilinear array size=${warps.size}")
return null
}
val opcodeCount = warps.size / 8
val opcodeCount = warps.size / DngWarpRectilinear.RECORD_SIZE
if (flags != null && flags.size != opcodeCount) {
PLog.w(
TAG,
@@ -5586,8 +5585,8 @@ class RawDemosaicProcessor {
val applicable = ArrayList<Float>(warps.size)
for (opcodeIndex in 0 until opcodeCount) {
val offset = opcodeIndex * 8
val parameters = warps.copyOfRange(offset, offset + 8)
val offset = opcodeIndex * DngWarpRectilinear.RECORD_SIZE
val parameters = warps.copyOfRange(offset, offset + DngWarpRectilinear.RECORD_SIZE)
if (isNoOpWarpRectilinear(parameters)) {
PLog.d(TAG, "Skipping no-op DNG WarpRectilinear")
continue
@@ -2,7 +2,11 @@ package com.hinnka.mycamera.raw
import android.opengl.GLES30
/** Applies one DNG WarpRectilinear opcode with the DNG bicubic sampling contract. */
/**
* Applies one DNG WarpRectilinear record ([DngWarpRectilinear.RECORD_SIZE] floats) with the DNG
* bicubic sampling contract. Each RGB plane is resampled with its own geometry, which is how
* lateral chromatic aberration is corrected; alpha follows the reference (green) plane.
*/
internal class RawWarpRectilinearPass(
private val quad: RawFullscreenQuad,
) {
@@ -38,22 +42,34 @@ internal class RawWarpRectilinearPass(
input.width.toFloat(),
input.height.toFloat(),
)
GLES30.glUniform4f(
val radial = FloatArray(DngWarpRectilinear.PLANES * 4)
val tangential = FloatArray(DngWarpRectilinear.PLANES * 2)
for (plane in 0 until DngWarpRectilinear.PLANES) {
val offset = plane * DngWarpRectilinear.PLANE_COEFFICIENTS
for (index in 0 until 4) radial[plane * 4 + index] = input.parameters[offset + index]
tangential[plane * 2] = input.parameters[offset + 4]
tangential[plane * 2 + 1] = input.parameters[offset + 5]
}
GLES30.glUniform4fv(
GLES30.glGetUniformLocation(activeProgram, "uRadial"),
input.parameters[0],
input.parameters[1],
input.parameters[2],
input.parameters[3],
DngWarpRectilinear.PLANES,
radial,
0,
)
GLES30.glUniform2f(
GLES30.glUniform2fv(
GLES30.glGetUniformLocation(activeProgram, "uTangential"),
input.parameters[4],
input.parameters[5],
DngWarpRectilinear.PLANES,
tangential,
0,
)
GLES30.glUniform2f(
GLES30.glGetUniformLocation(activeProgram, "uCenter"),
input.parameters[6],
input.parameters[7],
input.parameters[DngWarpRectilinear.CENTER_OFFSET],
input.parameters[DngWarpRectilinear.CENTER_OFFSET + 1],
)
GLES30.glUniform1i(
GLES30.glGetUniformLocation(activeProgram, "uSharedGeometry"),
if (DngWarpRectilinear.planesShareGeometry(input.parameters)) 1 else 0,
)
quad.draw(activeProgram)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
@@ -75,7 +91,7 @@ internal class RawWarpRectilinearPass(
}
companion object {
private const val PARAMETER_COUNT = 8
private const val PARAMETER_COUNT = DngWarpRectilinear.RECORD_SIZE
val FRAGMENT_SHADER = """
#version 300 es
@@ -87,9 +103,10 @@ internal class RawWarpRectilinearPass(
uniform sampler2D uSourceTexture;
uniform vec2 uImageSize;
uniform vec4 uRadial;
uniform vec2 uTangential;
uniform vec4 uRadial[3];
uniform vec2 uTangential[3];
uniform vec2 uCenter;
uniform int uSharedGeometry;
float bicubicWeight(float x) {
const float A = -0.75;
@@ -118,24 +135,35 @@ internal class RawWarpRectilinearPass(
return total / max(totalWeight, 1e-8);
}
void main() {
vec2 centerPx = uCenter * uImageSize;
vec2 dstPx = gl_FragCoord.xy - vec2(0.5);
vec2 diff = dstPx - centerPx;
vec2 farthest = max(centerPx, uImageSize - centerPx);
float normRadius = max(length(farthest), 1.0);
vec2 normalized = diff / normRadius;
vec2 sourcePixelForPlane(int plane, vec2 centerPx, float normRadius, vec2 normalized) {
vec4 radial = uRadial[plane];
vec2 tangential = uTangential[plane];
float r2 = min(dot(normalized, normalized), 1.0);
float ratio = uRadial.x + uRadial.y * r2 +
uRadial.z * r2 * r2 + uRadial.w * r2 * r2 * r2;
float ratio = radial.x + radial.y * r2 +
radial.z * r2 * r2 + radial.w * r2 * r2 * r2;
float dh = normalized.x;
float dv = normalized.y;
vec2 tangent = vec2(
uTangential.y * (r2 + 2.0 * dh * dh) + 2.0 * uTangential.x * dh * dv,
uTangential.x * (r2 + 2.0 * dv * dv) + 2.0 * uTangential.y * dh * dv
tangential.y * (r2 + 2.0 * dh * dh) + 2.0 * tangential.x * dh * dv,
tangential.x * (r2 + 2.0 * dv * dv) + 2.0 * tangential.y * dh * dv
);
vec2 srcPx = centerPx + normRadius * (normalized * ratio + tangent);
fragColor = sampleDngBicubic(srcPx);
return centerPx + normRadius * (normalized * ratio + tangent);
}
void main() {
vec2 centerPx = uCenter * uImageSize;
vec2 dstPx = gl_FragCoord.xy - vec2(0.5);
vec2 farthest = max(centerPx, uImageSize - centerPx);
float normRadius = max(length(farthest), 1.0);
vec2 normalized = (dstPx - centerPx) / normRadius;
vec4 green = sampleDngBicubic(sourcePixelForPlane(1, centerPx, normRadius, normalized));
if (uSharedGeometry != 0) {
fragColor = green;
return;
}
float red = sampleDngBicubic(sourcePixelForPlane(0, centerPx, normRadius, normalized)).r;
float blue = sampleDngBicubic(sourcePixelForPlane(2, centerPx, normRadius, normalized)).b;
fragColor = vec4(red, green.g, blue, green.a);
}
""".trimIndent()
}
@@ -1348,13 +1348,15 @@ object SuperResolutionDngWriter {
}
val centerH = (dngCx / geometry.sourceWidth).toDouble().coerceIn(0.0, 1.0)
val centerV = (dngCy / geometry.sourceHeight).toDouble().coerceIn(0.0, 1.0)
val parameters = FloatArray(8) { index ->
when {
index < 6 -> coefficients[index].toFloat()
index == 6 -> centerH.toFloat()
else -> centerV.toFloat()
}
}
val parameters = DngWarpRectilinear.recordFromSinglePlane(
FloatArray(DngWarpRectilinear.SINGLE_PLANE_SIZE) { index ->
when {
index < 6 -> coefficients[index].toFloat()
index == 6 -> centerH.toFloat()
else -> centerV.toFloat()
}
},
)
val cropRight = (geometry.defaultCropLeft + geometry.defaultCropWidth).roundToInt()
val cropBottom = (geometry.defaultCropTop + geometry.defaultCropHeight).roundToInt()
if (!DngWarpRectilinear.hasSourceCoverage(
@@ -1,111 +0,0 @@
package com.hinnka.mycamera.processor
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class MgcSabreNoiseEstimatesLutTest {
@Test
fun zeroLinearNoiseProducesZeroSqrtDomainNoise() {
for (index in 0 until MgcSabreNoiseEstimatesLut.WIDTH) {
val signal = index.toFloat() / (MgcSabreNoiseEstimatesLut.WIDTH - 1).toFloat()
assertEquals(
0f,
MgcSabreNoiseEstimatesLut.sqrtDomainVariance(signal, 0f, 0f),
0f,
)
}
}
@Test
fun qmcTransformMatchesV25SequenceReplay() {
assertEquals(
0.00124777935f,
MgcSabreNoiseEstimatesLut.sqrtDomainVariance(0f, 0.001f, 0.00001f),
1e-8f,
)
assertEquals(
0.00025717527f,
MgcSabreNoiseEstimatesLut.sqrtDomainVariance(0.5f, 0.001f, 0.00001f),
1e-8f,
)
assertEquals(
0.00024950321f,
MgcSabreNoiseEstimatesLut.sqrtDomainVariance(1f, 0.001f, 0.00001f),
1e-8f,
)
}
@Test
fun qmcAnglesFollowV25FilledMaskRecurrence() {
val expected = longArrayOf(0, 0x80000000, 0xc0000000, 0x40000000,
0xe0000000, 0x60000000, 0x20000000, 0xa0000000)
expected.forEachIndexed { index, bits ->
assertEquals(bits, MgcSabreNoiseEstimatesLut.qmcAngleBits(index).toLong())
}
}
@Test
fun lutKeepsReferenceAndCurrentRowsAndAveragesGreenVariance() {
val referenceShot = floatArrayOf(0.01f, 0.02f, 0.04f, 0.08f)
val referenceRead = floatArrayOf(0.001f, 0.002f, 0.004f, 0.008f)
val currentShot = floatArrayOf(0.03f, 0.05f, 0.07f, 0.09f)
val currentRead = floatArrayOf(0.003f, 0.005f, 0.007f, 0.009f)
val lut = MgcSabreNoiseEstimatesLut.create(
referenceShot,
referenceRead,
currentShot,
currentRead,
)
val x = MgcSabreNoiseEstimatesLut.WIDTH - 1
val referenceOffset = x * MgcSabreNoiseEstimatesLut.CHANNELS
val currentOffset = (MgcSabreNoiseEstimatesLut.WIDTH + x) *
MgcSabreNoiseEstimatesLut.CHANNELS
assertEquals(
MgcSabreNoiseEstimatesLut.sqrtDomainVariance(1f, referenceShot[0], referenceRead[0]),
lut[referenceOffset],
1e-7f,
)
val referenceGreenVarianceSum =
MgcSabreNoiseEstimatesLut.sqrtDomainVariance(
1f,
referenceShot[1],
referenceRead[1],
) + MgcSabreNoiseEstimatesLut.sqrtDomainVariance(
1f,
referenceShot[2],
referenceRead[2],
)
val expectedReferenceGreen = 0.25f * referenceGreenVarianceSum
assertEquals(expectedReferenceGreen, lut[referenceOffset + 1], 1e-7f)
assertEquals(
MgcSabreNoiseEstimatesLut.sqrtDomainVariance(1f, currentShot[3], currentRead[3]),
lut[currentOffset + 2],
1e-7f,
)
assertEquals(0f, lut[referenceOffset + 3], 0f)
assertEquals(0f, lut[currentOffset + 3], 0f)
assertTrue(lut[referenceOffset] != lut[currentOffset])
}
@Test
fun bayerSabreGuideUsesSqrtColorSpaceBeforeTensorConstruction() {
val shader = GlesMgcRawSabreShaders.guideAndCovariance
val sqrtTransform = "rggb = sqrt(max(vec4(0.0), rggb));"
val greenTensorInput = "green0[index] = rggb"
assertTrue(shader.contains(sqrtTransform))
assertTrue(shader.indexOf(sqrtTransform) < shader.indexOf(greenTensorInput))
}
@Test
fun diagnosticMergeFactorUsesActualGreenRbfWeightsInQ8Domain() {
val shader = GlesMgcRawSabreShaders.reciprocalGreenWeight4x4
assertTrue(shader.contains("texelFetch(uAccumulatedWeightsGb, p, 0).r"))
assertTrue(shader.contains("floor(weight * 256.0 + 0.5)"))
assertTrue(shader.contains("reciprocalSum += 256.0 / weightQ8"))
}
}
@@ -6,7 +6,7 @@ import org.junit.Assert.assertTrue
import org.junit.Test
class DngWarpRectilinearTest {
private val malformedPhotonSample = floatArrayOf(
private val malformedPhotonSample = DngWarpRectilinear.recordFromSinglePlane(floatArrayOf(
1f,
0.016676925f,
0.001357187f,
@@ -15,7 +15,7 @@ class DngWarpRectilinearTest {
0f,
0.5009297f,
0.5010741f,
)
))
@Test
fun optionalWarpThatMapsDefaultCropOutsideRawIsSkipped() {
@@ -38,7 +38,11 @@ class DngWarpRectilinearTest {
@Test
fun normalizedRadialOffsetKeepsFullDefaultCropInsideSource() {
val normalized = malformedPhotonSample.copyOf().also { it[0] = 0.984f }
val normalized = malformedPhotonSample.copyOf().also { record ->
for (plane in 0 until DngWarpRectilinear.PLANES) {
record[plane * DngWarpRectilinear.PLANE_COEFFICIENTS] = 0.984f
}
}
assertTrue(
DngWarpRectilinear.hasSourceCoverage(
@@ -1,181 +0,0 @@
package com.hinnka.mycamera.raw
import com.hinnka.mycamera.data.UserPreferences
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import kotlin.math.max
import kotlin.math.pow
import kotlin.math.sqrt
class RawNoiseProfileSelectionTest {
@Test
fun unconfiguredLensesUseSystemProfileWithUnityCaptureStrength() {
val preferences = UserPreferences()
assertEquals(RawNoiseProfileManager.SYSTEM_PROFILE_ID,
preferences.rawNoiseProfileIdForLens("rear_main"))
assertEquals(RawNoiseProfileManager.SYSTEM_PROFILE_ID,
preferences.rawNoiseProfileIdForLens("rear_isz"))
assertEquals(1f, RawDenoiseDefaults.RAW_MAX_LUMA_STRENGTH, 0f)
assertEquals(1f, RawDenoiseDefaults.RAW_MAX_CHROMA_STRENGTH, 0f)
}
@Test
fun userPreferencesResolveUnifiedAndPerLensNoiseProfiles() {
val preferences = UserPreferences(
rawNoiseProfileId = "unified",
rawNoiseProfileIdsByLens = mapOf("rear_tele" to "tele_override"),
)
assertEquals("unified", preferences.rawNoiseProfileIdForLens("rear_main"))
assertEquals("tele_override", preferences.rawNoiseProfileIdForLens("rear_tele"))
assertEquals("unified", preferences.rawNoiseProfileIdForLens(null))
}
@Test
fun camera2ProfileAveragesTheTwoGreenChannels() {
val profile = floatArrayOf(
1f, 10f,
2f, 20f,
4f, 40f,
8f, 80f,
)
assertArrayEquals(
floatArrayOf(3f, 30f),
RawMetadata.greenNoiseProfile(
profile,
RawMetadata.CFA_RGGB,
RawNoiseProfileLayout.CAMERA2_CFA,
),
0f
)
assertArrayEquals(
floatArrayOf(4.5f, 45f),
RawMetadata.greenNoiseProfile(
profile,
RawMetadata.CFA_GRBG,
RawNoiseProfileLayout.CAMERA2_CFA,
),
0f
)
}
@Test
fun threePlaneDngProfileUsesGreenAndIgnoresNativePadding() {
val profile = floatArrayOf(
1f, 10f,
2f, 20f,
8f, 80f,
0f, 0f,
)
assertArrayEquals(
floatArrayOf(2f, 20f),
RawMetadata.greenNoiseProfile(
profile,
RawMetadata.CFA_RGGB,
RawNoiseProfileLayout.DNG_RGB,
),
0f
)
}
@Test
fun camera2ProfileSelectsRedAndBlueFromCfaPositionOrder() {
val profile = floatArrayOf(
1f, 10f,
2f, 20f,
4f, 40f,
8f, 80f,
)
assertArrayEquals(
floatArrayOf(1f, 10f, 8f, 80f),
RawMetadata.redBlueNoiseProfile(
profile,
RawMetadata.CFA_RGGB,
RawNoiseProfileLayout.CAMERA2_CFA,
),
0f
)
assertArrayEquals(
floatArrayOf(2f, 20f, 4f, 40f),
RawMetadata.redBlueNoiseProfile(
profile,
RawMetadata.CFA_GRBG,
RawNoiseProfileLayout.CAMERA2_CFA,
),
0f
)
assertArrayEquals(
floatArrayOf(4f, 40f, 2f, 20f),
RawMetadata.redBlueNoiseProfile(
profile,
RawMetadata.CFA_GBRG,
RawNoiseProfileLayout.CAMERA2_CFA,
),
0f
)
assertArrayEquals(
floatArrayOf(8f, 80f, 1f, 10f),
RawMetadata.redBlueNoiseProfile(
profile,
RawMetadata.CFA_BGGR,
RawNoiseProfileLayout.CAMERA2_CFA,
),
0f
)
}
@Test
fun threePlaneDngProfileSelectsRedAndBlueAndIgnoresPadding() {
val profile = floatArrayOf(
1f, 10f,
2f, 20f,
8f, 80f,
0f, 0f,
)
assertArrayEquals(
floatArrayOf(1f, 10f, 8f, 80f),
RawMetadata.redBlueNoiseProfile(
profile,
RawMetadata.CFA_BGGR,
RawNoiseProfileLayout.DNG_RGB,
),
0f
)
}
@Test
fun canonicalCalibratedProfileKeepsRGrGbBOrderForEveryCfaLayout() {
val profile = floatArrayOf(
1f, 10f,
2f, 20f,
4f, 40f,
8f, 80f,
)
assertArrayEquals(
floatArrayOf(3f, 30f),
RawMetadata.greenNoiseProfile(
profile,
RawMetadata.CFA_BGGR,
RawNoiseProfileLayout.CANONICAL_BAYER,
),
0f,
)
assertArrayEquals(
floatArrayOf(1f, 10f, 8f, 80f),
RawMetadata.redBlueNoiseProfile(
profile,
RawMetadata.CFA_GBRG,
RawNoiseProfileLayout.CANONICAL_BAYER,
),
0f,
)
}
}
@@ -1,57 +0,0 @@
package com.hinnka.mycamera.viewmodel
import com.hinnka.mycamera.data.UserPreferences
import com.hinnka.mycamera.raw.RawDenoiseDefaults
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class CaptureDenoiseStrengthsTest {
@Test
fun singleRawStartsEditableAtRawMaxDefaults() {
val resolved = resolveCaptureDenoiseStrengths(
isRawCapture = true,
isMergedCapture = false,
userPrefs = null,
)
assertEquals(RawDenoiseDefaults.RAW_MAX_LUMA_STRENGTH, resolved.editableLuma, 0f)
assertEquals(RawDenoiseDefaults.RAW_MAX_CHROMA_STRENGTH, resolved.editableChroma, 0f)
assertNull(resolved.bakedLuma)
assertNull(resolved.bakedChroma)
}
@Test
fun rawMaxDefaultsAreBakedAndGalleryAdjustmentStartsAtZero() {
val resolved = resolveCaptureDenoiseStrengths(
isRawCapture = true,
isMergedCapture = true,
userPrefs = UserPreferences(
rawMaxNoiseReduction = 1.4f,
rawMaxChromaNoiseReduction = 1.6f,
),
)
assertEquals(0f, resolved.editableLuma, 0f)
assertEquals(0f, resolved.editableChroma, 0f)
assertEquals(1.4f, resolved.bakedLuma ?: -1f, 0f)
assertEquals(1.6f, resolved.bakedChroma ?: -1f, 0f)
}
@Test
fun nonRawCaptureDoesNotInheritRawDenoise() {
val resolved = resolveCaptureDenoiseStrengths(
isRawCapture = false,
isMergedCapture = false,
userPrefs = UserPreferences(
rawMaxNoiseReduction = 1f,
rawMaxChromaNoiseReduction = 1f,
),
)
assertEquals(0f, resolved.editableLuma, 0f)
assertEquals(0f, resolved.editableChroma, 0f)
assertNull(resolved.bakedLuma)
assertNull(resolved.bakedChroma)
}
}