feat: Sabre merged noise model and parameter validation
This commit is contained in:
1 parent
a1ef390efd
commit
a377781e9d
18 files changed
+306
-237
No files matched your search
@@ -496,6 +496,17 @@ float DownsamplingEnergy(
|
||||
bool AdvancePyramidCorrelation(
|
||||
float spectrum[128],
|
||||
float* coefficient_scale) {
|
||||
// Zero spectral amplitude represents zero noise energy, which has no
|
||||
// identifiable normalized spectrum. Carry that energy in the coefficients
|
||||
// and use the canonical unit spectrum for subsequent pyramid levels.
|
||||
// In particular, do not divide by zero or invent a positive noise floor.
|
||||
if (std::all_of(spectrum, spectrum + 128, [](float value) {
|
||||
return value == 0.0f;
|
||||
})) {
|
||||
std::fill_n(spectrum, 128, 1.0f);
|
||||
*coefficient_scale = 0.0f;
|
||||
return true;
|
||||
}
|
||||
// MGC's fixed eight-tap filter at 0x6b20e0/0x6b6200.
|
||||
constexpr float filter[8] = {
|
||||
-3.0f / 128.0f,
|
||||
|
||||
@@ -40,7 +40,9 @@ struct SpatialStrengthResult {
|
||||
/**
|
||||
* Reproduces CreateLumaDenoiseNoiseBuffers for one luma noise channel.
|
||||
* correlation is MGC's 128-bin normalized power correlation spectrum. A
|
||||
* single uncorrelated frame is represented by 128 ones.
|
||||
* single uncorrelated frame is represented by 128 ones. A uniformly scaled
|
||||
* spectrum contributes the square of that scale to the separable 2D noise
|
||||
* energy; an all-zero spectrum therefore produces zero noise at every level.
|
||||
*/
|
||||
bool BuildNoiseBuffers(
|
||||
float read_noise,
|
||||
|
||||
@@ -13,9 +13,6 @@
|
||||
namespace {
|
||||
|
||||
constexpr char kTag[] = "PLog_MgcSpatialStrength";
|
||||
constexpr float kIdentityMultiplier = 1.0f;
|
||||
constexpr float kIdentityReadNoise = 0.0f;
|
||||
constexpr float kIdentityShotNoise = 1.0f;
|
||||
|
||||
bool CopyFloatArray(
|
||||
JNIEnv* env,
|
||||
@@ -37,44 +34,6 @@ bool IsValidNoisePair(float read, float shot) {
|
||||
(read > 0.0f || shot > 0.0f);
|
||||
}
|
||||
|
||||
int SanitizeNoiseParameters(
|
||||
int frame_count,
|
||||
std::vector<float>* read,
|
||||
std::vector<float>* shot) {
|
||||
int replacement_count = 0;
|
||||
for (int channel = 0; channel < 3; ++channel) {
|
||||
const int channel_offset = channel * frame_count;
|
||||
float identity_read = kIdentityReadNoise;
|
||||
float identity_shot = kIdentityShotNoise;
|
||||
for (int frame = 0; frame < frame_count; ++frame) {
|
||||
const int index = channel_offset + frame;
|
||||
if (IsValidNoisePair((*read)[index], (*shot)[index])) {
|
||||
identity_read = (*read)[index];
|
||||
identity_shot = (*shot)[index];
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (int frame = 0; frame < frame_count; ++frame) {
|
||||
const int index = channel_offset + frame;
|
||||
if (IsValidNoisePair((*read)[index], (*shot)[index])) continue;
|
||||
(*read)[index] = identity_read;
|
||||
(*shot)[index] = identity_shot;
|
||||
++replacement_count;
|
||||
}
|
||||
}
|
||||
return replacement_count;
|
||||
}
|
||||
|
||||
int SanitizePositiveMultipliers(std::vector<float>* values) {
|
||||
int replacement_count = 0;
|
||||
for (float& value : *values) {
|
||||
if (std::isfinite(value) && value > 0.0f) continue;
|
||||
value = kIdentityMultiplier;
|
||||
++replacement_count;
|
||||
}
|
||||
return replacement_count;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" JNIEXPORT jint JNICALL
|
||||
@@ -178,32 +137,46 @@ Java_com_hinnka_mycamera_processor_MgcSpatialStrengthMapGenerator_nativeCompute(
|
||||
&kernel_sigmas)) {
|
||||
return -1;
|
||||
}
|
||||
const int noise_replacements = SanitizeNoiseParameters(
|
||||
frame_count,
|
||||
&input_read_noise,
|
||||
&input_shot_noise);
|
||||
const int frame_weight_replacements =
|
||||
SanitizePositiveMultipliers(&frame_weights);
|
||||
const int kernel_sigma_replacements =
|
||||
SanitizePositiveMultipliers(&kernel_sigmas);
|
||||
const bool rejected_multiplier_replaced =
|
||||
!std::isfinite(rejected_denoise_multiplier) ||
|
||||
rejected_denoise_multiplier <= 0.0f;
|
||||
if (rejected_multiplier_replaced) {
|
||||
rejected_denoise_multiplier = kIdentityMultiplier;
|
||||
}
|
||||
if (noise_replacements > 0 || frame_weight_replacements > 0 ||
|
||||
kernel_sigma_replacements > 0 || rejected_multiplier_replaced) {
|
||||
// These are the same calibrated parameters used to merge the image. Replacing
|
||||
// an invalid frame/channel with another model would describe different pixels.
|
||||
for (size_t index = 0; index < input_read_noise.size(); ++index) {
|
||||
if (IsValidNoisePair(input_read_noise[index], input_shot_noise[index])) {
|
||||
continue;
|
||||
}
|
||||
__android_log_print(
|
||||
ANDROID_LOG_WARN,
|
||||
ANDROID_LOG_ERROR,
|
||||
kTag,
|
||||
"MGC Spatial strength replaced invalid inputs with identity "
|
||||
"noisePairs=%d frameWeights=%d kernelSigmas=%d "
|
||||
"rejectedMultiplier=%d",
|
||||
noise_replacements,
|
||||
frame_weight_replacements,
|
||||
kernel_sigma_replacements,
|
||||
rejected_multiplier_replaced ? 1 : 0);
|
||||
"MGC Spatial strength rejected noise input channel=%zu frame=%zu "
|
||||
"read=%.6g shot=%.6g",
|
||||
index / frame_count,
|
||||
index % frame_count,
|
||||
input_read_noise[index],
|
||||
input_shot_noise[index]);
|
||||
return -1;
|
||||
}
|
||||
for (int frame = 0; frame < frame_count; ++frame) {
|
||||
if (std::isfinite(frame_weights[frame]) && frame_weights[frame] > 0.0f &&
|
||||
std::isfinite(kernel_sigmas[frame]) && kernel_sigmas[frame] > 0.0f) {
|
||||
continue;
|
||||
}
|
||||
__android_log_print(
|
||||
ANDROID_LOG_ERROR,
|
||||
kTag,
|
||||
"MGC Spatial strength rejected merge input frame=%d "
|
||||
"frameWeight=%.6g kernelSigma=%.6g",
|
||||
frame,
|
||||
frame_weights[frame],
|
||||
kernel_sigmas[frame]);
|
||||
return -1;
|
||||
}
|
||||
if (!std::isfinite(rejected_denoise_multiplier) ||
|
||||
rejected_denoise_multiplier <= 0.0f) {
|
||||
__android_log_print(
|
||||
ANDROID_LOG_ERROR,
|
||||
kTag,
|
||||
"MGC Spatial strength rejected denoise multiplier=%.6g",
|
||||
rejected_denoise_multiplier);
|
||||
return -1;
|
||||
}
|
||||
std::vector<uint16_t> output(static_cast<size_t>(output_values));
|
||||
photon::mgc_denoise::SpatialStrengthResult diagnostics;
|
||||
|
||||
@@ -3440,8 +3440,6 @@ object GalleryManager {
|
||||
mgcDenoiseReadNoise = finalStackResult.mgcDenoiseReadNoise,
|
||||
mgcDenoiseShotNoise = finalStackResult.mgcDenoiseShotNoise,
|
||||
mgcSpatialStrengthMap = finalStackResult.mgcSpatialStrengthMap,
|
||||
mgcSabreNoiseModelScale =
|
||||
finalStackResult.mgcSabreNoiseModelScale,
|
||||
mgcDenoiseTuningSnr = finalStackResult.mgcDenoiseTuningSnr,
|
||||
mgcSharpenAttenuationScale =
|
||||
finalStackResult.mgcSharpenAttenuationScale,
|
||||
@@ -3465,9 +3463,9 @@ object GalleryManager {
|
||||
}
|
||||
val defaultDenoiseModelAvailable = when (defaultDenoiseMode) {
|
||||
MgcSpatialGpuDenoiseMode.SABRE_DEFAULT ->
|
||||
finalStackResult.mgcSabreNoiseModelScale?.let {
|
||||
it.isFinite() && it > 0f
|
||||
} == true
|
||||
finalStackResult.mgcDenoiseCorrelation?.size == 128 &&
|
||||
finalStackResult.mgcDenoiseReadNoise?.size == 3 &&
|
||||
finalStackResult.mgcDenoiseShotNoise?.size == 3
|
||||
MgcSpatialGpuDenoiseMode.SPATIAL_DEFAULT ->
|
||||
MultiFrameConfig.ENABLE_MGC_SPATIAL_DEFAULT_DENOISE &&
|
||||
!finalStackResult.mgcSpatialReferenceOnlyDiagnostic &&
|
||||
@@ -3543,7 +3541,6 @@ object GalleryManager {
|
||||
mgcDenoiseReadNoise = null,
|
||||
mgcDenoiseShotNoise = null,
|
||||
mgcSpatialStrengthMap = null,
|
||||
mgcSabreNoiseModelScale = null,
|
||||
mgcDenoiseTuningSnr = null,
|
||||
)
|
||||
|
||||
|
||||
@@ -646,9 +646,8 @@ internal object GlesMgcRawSabreShaders {
|
||||
|
||||
/**
|
||||
* Reproduces the Q8 `SABRE: Average merge factor` diagnostic at V25 0x34e6964. The original
|
||||
* computes the global mean of `256 / accumulated_green_weight_q8`. This is the measured
|
||||
* coefficient scale Photon can transport for its reimplemented Sabre merge; the diagnostic
|
||||
* itself must not be mistaken for the input of GetMergedNoiseModel.
|
||||
* computes the global mean of `256 / accumulated_green_weight_q8`. This is diagnostic only;
|
||||
* classic Sabre builds its merged NoiseModel from the exposure-normalized frame models.
|
||||
*
|
||||
* Four-by-four reduction keeps the readback small without changing the global average.
|
||||
*/
|
||||
|
||||
@@ -1843,22 +1843,20 @@ internal class GlesMgcRawSpatialStacker(
|
||||
val strengthResolveStartNs = System.nanoTime()
|
||||
val spatialDenoiseEnabled =
|
||||
MultiFrameConfig.ENABLE_MGC_SPATIAL_DEFAULT_DENOISE && !referenceOnly
|
||||
val resolvedSpatialNoiseModel = if (
|
||||
strengthCapture != null && queuedStrengthReadback != null
|
||||
) {
|
||||
resolveSpatialNoiseModel(strengthCapture, queuedStrengthReadback)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val spatialNoiseModel = if (spatialDenoiseEnabled) {
|
||||
resolvedSpatialNoiseModel ?: createIdentitySpatialNoiseModel(
|
||||
referenceCalibration = referenceCalibration,
|
||||
reason = when {
|
||||
strengthCapture == null -> "single-admitted-frame"
|
||||
queuedStrengthReadback == null -> "strength-readback-unavailable"
|
||||
else -> "strength-aot-invalid"
|
||||
},
|
||||
)
|
||||
if (spatialNoiseFrameCount == 1) {
|
||||
createIdentitySpatialNoiseModel(referenceCalibration)
|
||||
} else {
|
||||
val capture = checkNotNull(strengthCapture) {
|
||||
"MGC Spatial multi-frame noise capture is unavailable"
|
||||
}
|
||||
val readback = checkNotNull(queuedStrengthReadback) {
|
||||
"MGC Spatial multi-frame noise readback is unavailable"
|
||||
}
|
||||
checkNotNull(resolveSpatialNoiseModel(capture, readback)) {
|
||||
"MGC Spatial multi-frame AOT noise model failed"
|
||||
}
|
||||
}
|
||||
} else {
|
||||
null
|
||||
}
|
||||
@@ -1924,7 +1922,6 @@ internal class GlesMgcRawSpatialStacker(
|
||||
)
|
||||
}
|
||||
checkGlError("MGC Spatial ${outputMode.name} merge")
|
||||
returned = true
|
||||
// MGC's base-SNR * sqrt(planned frame count) value is only a pre-merge planning
|
||||
// estimate. FinishRaw leaves its explicit SNR override unset and evaluates the
|
||||
// propagated Spatial output NoiseModel instead, after alignment/rejection weights
|
||||
@@ -1939,11 +1936,16 @@ internal class GlesMgcRawSpatialStacker(
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val finishRawDenoiseSnr = propagatedOutputSnr
|
||||
?: MgcSpatialMergeTuning.mergedSnr(
|
||||
val finishRawDenoiseSnr = if (spatialDenoiseEnabled) {
|
||||
checkNotNull(propagatedOutputSnr) {
|
||||
"MGC Spatial output NoiseModel cannot produce a finite SNR"
|
||||
}
|
||||
} else {
|
||||
MgcSpatialMergeTuning.mergedSnr(
|
||||
bayerKernelTuning.referenceSnr,
|
||||
mergedFrames,
|
||||
)
|
||||
}
|
||||
val resultLabel = when {
|
||||
exportedRgbTexture != 0 -> "${gpuLinearRgbStorage.name}_GPU"
|
||||
exportedBayerTexture != 0 -> "BAYER16_GPU"
|
||||
@@ -1971,7 +1973,7 @@ internal class GlesMgcRawSpatialStacker(
|
||||
"total=${(System.nanoTime() - processStartNs) / 1_000_000L}ms",
|
||||
)
|
||||
val rgbOutput = outputMode == MgcSpatialOutputMode.RGB
|
||||
RawStackResult(
|
||||
val result = RawStackResult(
|
||||
fusedBayerBuffer = cpuOutput,
|
||||
width = outputWidth,
|
||||
height = outputHeight,
|
||||
@@ -2018,6 +2020,8 @@ internal class GlesMgcRawSpatialStacker(
|
||||
mgcSpatialReferenceOnlyDiagnostic = referenceOnly,
|
||||
fastMomentsRawStats = fastMomentsRawStats,
|
||||
)
|
||||
returned = true
|
||||
result
|
||||
} catch (error: Exception) {
|
||||
PLog.e(TAG, "MGC Spatial ${outputMode.name} merge failed", error)
|
||||
null
|
||||
@@ -2188,6 +2192,12 @@ internal class GlesMgcRawSpatialStacker(
|
||||
exposureScale = 1f,
|
||||
kernelTuning = kernelTuning,
|
||||
)
|
||||
val noiseFrames = arrayListOf(
|
||||
MgcSabreMergedNoiseModel.Frame(
|
||||
referenceCalibration.cameraRgbReadNoise,
|
||||
referenceCalibration.cameraRgbShotNoise,
|
||||
),
|
||||
)
|
||||
val sabreResolveFinalBlackLevel =
|
||||
sabreResolveBlackLevel(referenceCalibration.blackLevels)
|
||||
PLog.i(
|
||||
@@ -2259,6 +2269,10 @@ internal class GlesMgcRawSpatialStacker(
|
||||
referenceExposure / validExposureProduct(frame.exposureProduct)
|
||||
).toFloat().coerceIn(MIN_EXPOSURE_SCALE, MAX_EXPOSURE_SCALE)
|
||||
val calibration = calibrationForFrame(frame, exposureScale, kernelTuning)
|
||||
noiseFrames += MgcSabreMergedNoiseModel.Frame(
|
||||
calibration.cameraRgbReadNoise,
|
||||
calibration.cameraRgbShotNoise,
|
||||
)
|
||||
uploadRaw(images[index], currentRaw, "Sabre frame $index")
|
||||
renderSabreExtract(currentRaw, currentExtracted, extractedWidth, extractedHeight)
|
||||
val noiseTexture = createSabreNoiseLut(referenceCalibration, calibration)
|
||||
@@ -2355,11 +2369,16 @@ internal class GlesMgcRawSpatialStacker(
|
||||
val sabreAverageMergeFactor = readSabreAverageMergeFactor(
|
||||
accumulatedWeightsGb = accumulatedWeightsGb,
|
||||
)
|
||||
val sabreNoiseModelScale = sabreAverageMergeFactor
|
||||
val mergedNoiseModel = MgcSabreMergedNoiseModel.merge(
|
||||
noiseFrames,
|
||||
kernelTuning.referenceSnr,
|
||||
)
|
||||
PLog.i(
|
||||
SABRE_TAG,
|
||||
"MGC Sabre merged NoiseModel averageMergeFactor=$sabreAverageMergeFactor " +
|
||||
"coefficientScale=$sabreNoiseModelScale",
|
||||
"MGC Sabre merged NoiseModel diagnosticAverageMergeFactor=$sabreAverageMergeFactor " +
|
||||
"snrCorrection=${MgcSabreMergedNoiseModel.snrCorrection(kernelTuning.referenceSnr)} " +
|
||||
"read=${mergedNoiseModel.read.contentToString()} " +
|
||||
"shot=${mergedNoiseModel.shot.contentToString()}",
|
||||
)
|
||||
|
||||
renderSabreDehomogenize(
|
||||
@@ -2571,15 +2590,13 @@ internal class GlesMgcRawSpatialStacker(
|
||||
}
|
||||
}
|
||||
checkGlError("MGC Sabre Resolve/VGN color noise")
|
||||
returned = true
|
||||
// FinishRaw resolves denoise tuning SNR from the merged frame's NoiseModel when no
|
||||
// explicit override is present. Photon represents Sabre's merged model with the
|
||||
// measured Q8 average merge factor. V25's GetMergedNoiseModel branch returns the
|
||||
// model directly and does not apply a second SNR lookup-table reduction. The
|
||||
// separately logged referenceSnr * sqrt(frameCount) value remains only a pre-merge
|
||||
// planning estimate.
|
||||
val finishRawDenoiseSnr = kernelTuning.referenceSnr /
|
||||
sqrt(sabreNoiseModelScale)
|
||||
// Classic Sabre composes exposure-normalized frame models and applies its SNR
|
||||
// correction before FinishRaw estimates SNR from the resulting green coefficients.
|
||||
val finishRawDenoiseSnr = checkNotNull(MgcSpatialMergeTuning.outputNoiseModelSnr(
|
||||
signal = kernelTuning.referenceSignal,
|
||||
greenReadVariance = mergedNoiseModel.read[1],
|
||||
greenShotNoiseFactor = mergedNoiseModel.shot[1],
|
||||
)) { "MGC Sabre merged NoiseModel cannot produce a finite SNR" }
|
||||
PLog.i(
|
||||
SABRE_TAG,
|
||||
"MGC Sabre complete frames=${frames.size} native=${width}x$height " +
|
||||
@@ -2591,7 +2608,7 @@ internal class GlesMgcRawSpatialStacker(
|
||||
"chromaFinal=${chromaResult.finalSubmissionMs}ms " +
|
||||
"total=${elapsedMs(processStartNs)}ms",
|
||||
)
|
||||
RawStackResult(
|
||||
val result = RawStackResult(
|
||||
fusedBayerBuffer = cpuOutput,
|
||||
width = outputWidth,
|
||||
height = outputHeight,
|
||||
@@ -2613,11 +2630,15 @@ internal class GlesMgcRawSpatialStacker(
|
||||
},
|
||||
lensShadingCorrectionApplied = hasLensShading(),
|
||||
mergedFrameCount = frames.size,
|
||||
mgcSabreNoiseModelScale = sabreNoiseModelScale,
|
||||
mgcDenoiseReadNoise = mergedNoiseModel.read,
|
||||
mgcDenoiseShotNoise = mergedNoiseModel.shot,
|
||||
mgcDenoiseCorrelation = mergedNoiseModel.correlation,
|
||||
mgcDenoiseTuningSnr = finishRawDenoiseSnr,
|
||||
mgcSharpenAttenuationScale = sabreResolveParameters.demosaicSharpness,
|
||||
coreImagingTuning = coreImagingTuning,
|
||||
)
|
||||
returned = true
|
||||
result
|
||||
} catch (error: Exception) {
|
||||
completionRecorder.releasePending()
|
||||
PLog.e(SABRE_TAG, "MGC Sabre merge failed", error)
|
||||
@@ -5782,32 +5803,19 @@ internal class GlesMgcRawSpatialStacker(
|
||||
viewportHeight = capture.rejectionHeight,
|
||||
)
|
||||
val noise = spatialNoiseParameters(calibration)
|
||||
var usedIdentity = false
|
||||
for (channel in 0 until 3) {
|
||||
val destination = channel * capture.frameCount + frameIndex
|
||||
capture.inputReadNoise[destination] = noise.read[channel]
|
||||
capture.inputShotNoise[destination] = noise.shot[channel]
|
||||
usedIdentity = usedIdentity ||
|
||||
noise.read[channel] != calibration.cameraRgbReadNoise.getOrElse(channel) { Float.NaN } ||
|
||||
noise.shot[channel] != calibration.cameraRgbShotNoise.getOrElse(channel) { Float.NaN }
|
||||
}
|
||||
check(calibration.globalFrameWeight.isFinite() && calibration.globalFrameWeight > 0f &&
|
||||
calibration.kernelSigma.isFinite() && calibration.kernelSigma > 0f) {
|
||||
"MGC Spatial strength frame=$frameIndex has invalid parameters: " +
|
||||
"weight=${calibration.globalFrameWeight} sigma=${calibration.kernelSigma}"
|
||||
}
|
||||
capture.frameWeights[frameIndex] = calibration.globalFrameWeight
|
||||
.takeIf { it.isFinite() && it > 0f }
|
||||
?: SPATIAL_IDENTITY_MULTIPLIER.also { usedIdentity = true }
|
||||
capture.kernelSigmas[frameIndex] = calibration.kernelSigma
|
||||
.takeIf { it.isFinite() && it > 0f }
|
||||
?: SPATIAL_IDENTITY_MULTIPLIER.also { usedIdentity = true }
|
||||
capture.captured[frameIndex] = true
|
||||
if (usedIdentity) {
|
||||
PLog.w(
|
||||
TAG,
|
||||
"MGC Spatial strength frame=$frameIndex contained invalid parameters; " +
|
||||
"using identity inputs read=${noise.read.contentToString()} " +
|
||||
"shot=${noise.shot.contentToString()} " +
|
||||
"frameWeight=${capture.frameWeights[frameIndex]} " +
|
||||
"kernelSigma=${capture.kernelSigmas[frameIndex]}",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun spatialNoiseParameters(
|
||||
@@ -5821,24 +5829,20 @@ internal class GlesMgcRawSpatialStacker(
|
||||
(read > 0f || shot > 0f)
|
||||
}
|
||||
|
||||
val fallbackChannel = intArrayOf(1, 0, 2).firstOrNull(::validPair)
|
||||
val fallbackRead = fallbackChannel?.let(calibration.cameraRgbReadNoise::get)
|
||||
?: SPATIAL_IDENTITY_READ_NOISE
|
||||
val fallbackShot = fallbackChannel?.let(calibration.cameraRgbShotNoise::get)
|
||||
?: SPATIAL_IDENTITY_SHOT_NOISE
|
||||
check(calibration.cameraRgbReadNoise.size == 3 &&
|
||||
calibration.cameraRgbShotNoise.size == 3 && (0..2).all(::validPair)) {
|
||||
"MGC Spatial has invalid camera RGB noise: " +
|
||||
"read=${calibration.cameraRgbReadNoise.contentToString()} " +
|
||||
"shot=${calibration.cameraRgbShotNoise.contentToString()}"
|
||||
}
|
||||
return SpatialNoiseParameters(
|
||||
read = FloatArray(3) { channel ->
|
||||
if (validPair(channel)) calibration.cameraRgbReadNoise[channel] else fallbackRead
|
||||
},
|
||||
shot = FloatArray(3) { channel ->
|
||||
if (validPair(channel)) calibration.cameraRgbShotNoise[channel] else fallbackShot
|
||||
},
|
||||
read = calibration.cameraRgbReadNoise.copyOf(),
|
||||
shot = calibration.cameraRgbShotNoise.copyOf(),
|
||||
)
|
||||
}
|
||||
|
||||
private fun createIdentitySpatialNoiseModel(
|
||||
referenceCalibration: FrameCalibration,
|
||||
reason: String,
|
||||
): MgcSpatialStrengthMapGenerator.Result {
|
||||
val geometry = mgcSpatialDiagnosticGeometry(
|
||||
outputMode = outputMode,
|
||||
@@ -5846,9 +5850,9 @@ internal class GlesMgcRawSpatialStacker(
|
||||
imageHeight = height,
|
||||
)
|
||||
val noise = spatialNoiseParameters(referenceCalibration)
|
||||
PLog.w(
|
||||
PLog.i(
|
||||
TAG,
|
||||
"MGC Spatial denoise model fallback=identity reason=$reason " +
|
||||
"MGC Spatial single-frame identity noise model " +
|
||||
"strengthQ8=$SPATIAL_IDENTITY_STRENGTH_Q8 " +
|
||||
"read=${noise.read.contentToString()} shot=${noise.shot.contentToString()}",
|
||||
)
|
||||
@@ -9886,8 +9890,6 @@ internal class GlesMgcRawSpatialStacker(
|
||||
const val MAX_WHITE_BALANCE_GAIN = 64f
|
||||
const val MIN_NOISE_VARIANCE = 1e-12f
|
||||
const val SPATIAL_IDENTITY_MULTIPLIER = 1f
|
||||
const val SPATIAL_IDENTITY_READ_NOISE = 0f
|
||||
const val SPATIAL_IDENTITY_SHOT_NOISE = 1f
|
||||
const val SPATIAL_IDENTITY_STRENGTH_Q8 = 256
|
||||
// FilterRejectionMap runtime values read from the original MGC process. The
|
||||
// ClippedGaussian formula and tap center were independently verified against its AOT.
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.hinnka.mycamera.processor
|
||||
|
||||
/** Classic V25 Sabre MergeRaw: 0x344964c -> 0x5f366b4 -> 0x38c8fe0. */
|
||||
internal object MgcSabreMergedNoiseModel {
|
||||
/** Coefficients are in normalized, un-white-balanced camera RGB at reference exposure. */
|
||||
data class Frame(val read: FloatArray, val shot: FloatArray)
|
||||
|
||||
data class Output(val read: FloatArray, val shot: FloatArray, val correlation: FloatArray)
|
||||
|
||||
fun merge(frames: List<Frame>, referenceSnr: Float): Output {
|
||||
require(frames.isNotEmpty())
|
||||
val readSum = DoubleArray(3)
|
||||
val shotSum = DoubleArray(3)
|
||||
var weightSum = 0.0
|
||||
val alternateWeight = 1f / frames.size.toFloat()
|
||||
for ((index, frame) in frames.withIndex()) {
|
||||
require(frame.read.size == 3 && frame.shot.size == 3)
|
||||
require(frame.read.all { it.isFinite() && it >= 0f })
|
||||
require(frame.shot.all { it.isFinite() && it >= 0f })
|
||||
// V25 assigns the residual to the reference, including float rounding.
|
||||
val weight = if (index == 0) {
|
||||
1f - alternateWeight * (frames.size - 1).toFloat()
|
||||
} else alternateWeight
|
||||
val squaredWeight = (weight * weight).toDouble()
|
||||
weightSum += weight.toDouble()
|
||||
for (channel in 0..2) {
|
||||
readSum[channel] += frame.read[channel].toDouble() * squaredWeight
|
||||
shotSum[channel] += frame.shot[channel].toDouble() * squaredWeight
|
||||
}
|
||||
}
|
||||
// The original accumulates in double and normalizes shot by the weighted signal gain.
|
||||
// All frame models were transported to reference exposure, so their signal gains are 1.
|
||||
val samples = 1f / snrCorrection(referenceSnr)
|
||||
val correction = 1f / samples
|
||||
val read = FloatArray(3) { readSum[it].toFloat() * correction }
|
||||
val shot = FloatArray(3) { (shotSum[it] / weightSum).toFloat() * correction }
|
||||
// Physical RAW inputs have unit spectra and no quadratic term. Weighted composition
|
||||
// preserves that spectrum; neither RBF weight statistics nor frame count scales it.
|
||||
return Output(read, shot, FloatArray(128) { 1f })
|
||||
}
|
||||
|
||||
/** Average(1 / d) scales every coefficient by d; it preserves the correlation spectrum. */
|
||||
internal fun snrCorrection(referenceSnr: Float): Float {
|
||||
require(referenceSnr.isFinite() && referenceSnr >= 0f)
|
||||
return when {
|
||||
referenceSnr <= 0.5f -> 0.8f
|
||||
referenceSnr < 4f -> interpolate(referenceSnr, 0.5f, 4f, 0.8f, 1f)
|
||||
referenceSnr < 10f -> interpolate(referenceSnr, 4f, 10f, 1f, 0.7f)
|
||||
else -> 0.7f
|
||||
}
|
||||
}
|
||||
|
||||
private fun interpolate(x: Float, x0: Float, x1: Float, y0: Float, y1: Float): Float {
|
||||
val fraction = (x - x0) / (x1 - x0)
|
||||
return y1 * fraction + y0 * (1f - fraction)
|
||||
}
|
||||
}
|
||||
@@ -94,14 +94,27 @@ internal object MgcSabreNoiseEstimatesLut {
|
||||
return squaredErrorSum / QMC_SAMPLE_COUNT.toFloat()
|
||||
}
|
||||
|
||||
/** Box-Muller sequence from MGC's `TransformNoiseModel`, including its bit-reversed angle. */
|
||||
/** V25 TransformNoiseModel (0x5ee7524): XOR progressively filled high-bit masks. */
|
||||
internal fun qmcAngleBits(index: Int): UInt {
|
||||
require(index >= 0)
|
||||
var remaining = index
|
||||
var mask = 0x80000000u
|
||||
var bits = 0u
|
||||
while (remaining != 0) {
|
||||
if ((remaining and 1) != 0) bits = bits xor mask
|
||||
mask = mask or (mask shr 1)
|
||||
remaining = remaining ushr 1
|
||||
}
|
||||
return bits
|
||||
}
|
||||
|
||||
/** Box-Muller sequence from MGC's `TransformNoiseModel`. */
|
||||
private fun createQmcNormalSamples(): FloatArray {
|
||||
val samples = FloatArray(QMC_SAMPLE_COUNT)
|
||||
for (index in 0 until QMC_PAIR_COUNT) {
|
||||
val radialInput = (index.toFloat() + 0.5f) / QMC_PAIR_COUNT.toFloat()
|
||||
val radius = sqrt((-2f * ln(radialInput.toDouble()).toFloat()).toDouble()).toFloat()
|
||||
val reversed = Integer.reverse(index).toUInt().toLong()
|
||||
val phase = (reversed.toDouble() / UINT32_RANGE).toFloat()
|
||||
val phase = (qmcAngleBits(index).toLong().toDouble() / UINT32_RANGE).toFloat()
|
||||
val angle = (phase.toDouble() * TWO_PI).toFloat()
|
||||
samples[index * 2] = radius * sin(angle.toDouble()).toFloat()
|
||||
samples[index * 2 + 1] = radius * cos(angle.toDouble()).toFloat()
|
||||
|
||||
@@ -16,11 +16,11 @@ internal object MgcSpatialMergeTuning {
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluates the representative SNR of Spatial's propagated output NoiseModel.
|
||||
* Evaluates the representative SNR of the propagated Spatial or Sabre output NoiseModel.
|
||||
*
|
||||
* This mirrors MGC V25 NoiseModel::EstimateSnr for the normalized signal path: use the
|
||||
* green channel (index 1), whose read/shot coefficients already include the actual AOT
|
||||
* alignment/rejection weights and output-exposure transport.
|
||||
* green channel (index 1), whose read/shot coefficients already include the selected
|
||||
* merge branch's model composition and output-exposure transport.
|
||||
*/
|
||||
fun outputNoiseModelSnr(
|
||||
signal: Float,
|
||||
|
||||
@@ -81,7 +81,15 @@ internal object MgcSpatialStrengthMapGenerator {
|
||||
inputReadNoise.size == frameCount * 3 &&
|
||||
inputShotNoise.size == frameCount * 3 &&
|
||||
frameWeights.size == frameCount &&
|
||||
kernelSigmas.size == frameCount
|
||||
kernelSigmas.size == frameCount &&
|
||||
inputReadNoise.indices.all { index ->
|
||||
val read = inputReadNoise[index]
|
||||
val shot = inputShotNoise[index]
|
||||
read.isFinite() && read >= 0f && shot.isFinite() && shot >= 0f &&
|
||||
(read > 0f || shot > 0f)
|
||||
} &&
|
||||
frameWeights.all { it.isFinite() && it > 0f } &&
|
||||
kernelSigmas.all { it.isFinite() && it > 0f }
|
||||
if (!valid) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
|
||||
@@ -117,18 +117,17 @@ data class RawStackResult(
|
||||
val lensShadingCorrectionApplied: Boolean = false,
|
||||
val mergedFrameCount: Int = 1,
|
||||
/**
|
||||
* MGC's normalized 128-bin spatial-merge correlation spectrum.
|
||||
* MGC's normalized 128-bin merged NoiseModel correlation spectrum.
|
||||
*
|
||||
* Null means that the exact propagated model is unavailable and the default Spatial denoise
|
||||
* pass must be bypassed.
|
||||
* Null means the merged model is unavailable; a requested default merge-denoise pass must fail.
|
||||
*/
|
||||
val mgcDenoiseCorrelation: FloatArray? = null,
|
||||
/**
|
||||
* Exact normalized camera-RGB read variance emitted by MGC Spatial.
|
||||
* Normalized camera-RGB read variance emitted by the selected MGC merge branch.
|
||||
*/
|
||||
val mgcDenoiseReadNoise: FloatArray? = null,
|
||||
/**
|
||||
* Exact normalized camera-RGB shot coefficient emitted by MGC Spatial.
|
||||
* Normalized camera-RGB shot coefficient emitted by the selected MGC merge branch.
|
||||
*/
|
||||
val mgcDenoiseShotNoise: FloatArray? = null,
|
||||
/**
|
||||
@@ -136,12 +135,6 @@ data class RawStackResult(
|
||||
* DNG write.
|
||||
*/
|
||||
val mgcSpatialStrengthMap: MgcSpatialStrengthMap? = null,
|
||||
/**
|
||||
* Process-local Sabre NoiseModel coefficient scale measured from accumulated Q8 green merge
|
||||
* weights. V25 does not apply a second reference-SNR lookup-table scale after
|
||||
* GetMergedNoiseModel.
|
||||
*/
|
||||
val mgcSabreNoiseModelScale: Float? = null,
|
||||
/**
|
||||
* Merged output-frame SNR used by MGC FinishRaw to select luma/chroma tuning.
|
||||
* This is the linear signal-domain SNR, not ISO or sensor gain.
|
||||
|
||||
@@ -151,7 +151,11 @@ data class PhotonFusionTuning(
|
||||
val mergeGradientThreshold: Float? = null,
|
||||
/** Normalized green signal used only when reference-frame measurement is unavailable. */
|
||||
val missingReferenceSignal: Float = DEFAULT_MISSING_REFERENCE_SIGNAL,
|
||||
/** Scales the 128-bin correlation spectrum before demosaic/noise-pyramid propagation. */
|
||||
/**
|
||||
* Scales Sabre's 128-bin spectrum before noise-pyramid propagation. The
|
||||
* separable 2D noise energy scales quadratically; zero means zero modeled
|
||||
* noise energy. Spatial preserves its measured spectrum without this override.
|
||||
*/
|
||||
val noiseCorrelationScale: Float = 1f,
|
||||
) {
|
||||
fun normalized(): PhotonFusionTuning = copy(
|
||||
|
||||
@@ -181,26 +181,26 @@ internal object MgcFullResolutionDenoise {
|
||||
)
|
||||
return false
|
||||
}
|
||||
val spatialCorrelation = if (useSpatialModel) {
|
||||
val mergedCorrelation = if (useSpatialModel || useSabreModel) {
|
||||
metadata.mgcDenoiseCorrelation
|
||||
} else null
|
||||
val coreTuning = metadata.coreImagingTuning.normalized()
|
||||
val lumaCorrelation = applyFusionCorrelationScale(
|
||||
correlation = preparedYuvNoiseModel?.lumaCorrelation ?: spatialCorrelation,
|
||||
correlation = preparedYuvNoiseModel?.lumaCorrelation ?: mergedCorrelation,
|
||||
scale = coreTuning.fusion.noiseCorrelationScale,
|
||||
enabled = useSabreModel,
|
||||
)
|
||||
val chromaCorrelation = applyFusionCorrelationScale(
|
||||
correlation = preparedYuvNoiseModel?.chromaCorrelation ?: spatialCorrelation,
|
||||
correlation = preparedYuvNoiseModel?.chromaCorrelation ?: mergedCorrelation,
|
||||
scale = coreTuning.fusion.noiseCorrelationScale,
|
||||
enabled = useSabreModel,
|
||||
)
|
||||
if (useSpatialModel &&
|
||||
if ((useSpatialModel || useSabreModel) &&
|
||||
(!validCorrelation(lumaCorrelation) || !validCorrelation(chromaCorrelation))
|
||||
) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"MGC denoise rejected missing/malformed Spatial Y/C correlation spectrum",
|
||||
"MGC denoise rejected missing/malformed $pass Y/C correlation spectrum",
|
||||
)
|
||||
return false
|
||||
}
|
||||
@@ -225,16 +225,15 @@ internal object MgcFullResolutionDenoise {
|
||||
|
||||
val rgbRead: FloatArray
|
||||
val rgbShot: FloatArray
|
||||
val sabreNoiseModelScale: Float
|
||||
if (useSpatialModel) {
|
||||
if (useSpatialModel || useSabreModel) {
|
||||
rgbRead = metadata.mgcDenoiseReadNoise?.copyOf()
|
||||
?: run {
|
||||
PLog.e(TAG, "MGC denoise rejected missing Spatial read coefficients")
|
||||
PLog.e(TAG, "MGC denoise rejected missing $pass read coefficients")
|
||||
return false
|
||||
}
|
||||
rgbShot = metadata.mgcDenoiseShotNoise?.copyOf()
|
||||
?: run {
|
||||
PLog.e(TAG, "MGC denoise rejected missing Spatial shot coefficients")
|
||||
PLog.e(TAG, "MGC denoise rejected missing $pass shot coefficients")
|
||||
return false
|
||||
}
|
||||
if (!validRgbNoise(rgbRead) || !validRgbNoise(rgbShot) ||
|
||||
@@ -242,38 +241,19 @@ internal object MgcFullResolutionDenoise {
|
||||
) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"MGC denoise rejected malformed Spatial noise coefficients: " +
|
||||
"MGC denoise rejected malformed $pass noise coefficients: " +
|
||||
"read=${rgbRead.contentToString()} shot=${rgbShot.contentToString()}",
|
||||
)
|
||||
return false
|
||||
}
|
||||
sabreNoiseModelScale = 1f
|
||||
} else {
|
||||
val resolvedNoise = resolveUserAdjustmentCameraRgbNoise(metadata)
|
||||
if (resolvedNoise == null) {
|
||||
PLog.w(TAG, "MGC denoise skipped: RAW noise profile is unavailable")
|
||||
return false
|
||||
}
|
||||
sabreNoiseModelScale = if (useSabreModel) {
|
||||
metadata.mgcSabreNoiseModelScale?.takeIf {
|
||||
it.isFinite() && it > 0f
|
||||
} ?: run {
|
||||
PLog.e(TAG, "MGC Sabre denoise rejected missing NoiseModel scale")
|
||||
return false
|
||||
}
|
||||
} else {
|
||||
1f
|
||||
}
|
||||
// V25 GetMergedNoiseModel returns Sabre's merged model directly. Photon transports
|
||||
// the measured Q8 average merge factor and applies it uniformly to the physical
|
||||
// reference read/shot coefficients; there is no additional reference-SNR table.
|
||||
// The physical camera model has no quadratic term.
|
||||
rgbShot = FloatArray(3) { channel ->
|
||||
resolvedNoise.shot[channel] * sabreNoiseModelScale
|
||||
}
|
||||
rgbRead = FloatArray(3) { channel ->
|
||||
resolvedNoise.read[channel] * sabreNoiseModelScale
|
||||
}
|
||||
rgbShot = resolvedNoise.shot
|
||||
rgbRead = resolvedNoise.read
|
||||
}
|
||||
val useLensShadingForStrength =
|
||||
(useSpatialModel || useSabreModel || applyLensShadingToDenoiseStrength) &&
|
||||
@@ -377,7 +357,6 @@ internal object MgcFullResolutionDenoise {
|
||||
"measureMoire=$measureMoireEnabled outputScale=$outputScale " +
|
||||
"rgbShot=${rgbShot.contentToString()} " +
|
||||
"rgbRead=${rgbRead.contentToString()} " +
|
||||
"sabreNoiseModelScale=$sabreNoiseModelScale " +
|
||||
"rgbWb=${rgbWhiteBalance.contentToString()} " +
|
||||
"tuningInterpolation=linear " +
|
||||
"lumaScales=${coreTuning.denoise.lumaStrengthScale} " +
|
||||
|
||||
@@ -226,7 +226,6 @@ class RawDemosaicProcessor {
|
||||
mgcDenoiseReadNoise = baseMetadata?.mgcDenoiseReadNoise,
|
||||
mgcDenoiseShotNoise = baseMetadata?.mgcDenoiseShotNoise,
|
||||
mgcSpatialStrengthMap = baseMetadata?.mgcSpatialStrengthMap,
|
||||
mgcSabreNoiseModelScale = baseMetadata?.mgcSabreNoiseModelScale,
|
||||
mgcDenoiseTuningSnr = baseMetadata?.mgcDenoiseTuningSnr,
|
||||
mgcSharpenAttenuationScale = baseMetadata?.mgcSharpenAttenuationScale,
|
||||
coreImagingTuning = baseMetadata?.coreImagingTuning
|
||||
@@ -1400,7 +1399,6 @@ class RawDemosaicProcessor {
|
||||
"frames=${metadata.frameCount} " +
|
||||
"readNoise=${metadata.mgcDenoiseReadNoise?.contentToString()} " +
|
||||
"shotNoise=${metadata.mgcDenoiseShotNoise?.contentToString()} " +
|
||||
"sabreNoiseModelScale=${metadata.mgcSabreNoiseModelScale} " +
|
||||
"strengthMap=${metadata.mgcSpatialStrengthMap?.let {
|
||||
"${it.width}x${it.height}"
|
||||
} ?: "none"} " +
|
||||
@@ -2522,7 +2520,6 @@ class RawDemosaicProcessor {
|
||||
mgcDenoiseReadNoise = null,
|
||||
mgcDenoiseShotNoise = null,
|
||||
mgcSpatialStrengthMap = null,
|
||||
mgcSabreNoiseModelScale = null,
|
||||
mgcDenoiseTuningSnr = null,
|
||||
mgcSharpenAttenuationScale =
|
||||
processLocalMgcSharpenAttenuationScale,
|
||||
@@ -5960,34 +5957,23 @@ class RawDemosaicProcessor {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Reproduces classic Sabre's MergeRaw metadata branch. V25 calls GetMergedNoiseModel and uses
|
||||
* the returned model directly. Photon transports the measured Q8 average merge factor through
|
||||
* [RawMetadata.mgcSabreNoiseModelScale]; no second reference-SNR lookup-table scale is applied.
|
||||
* Sabre does not expose Spatial correlation data.
|
||||
*/
|
||||
/** Consume the classic Sabre merged model once, without reference-model or frame-count scaling. */
|
||||
private fun sabreOutputNoiseMetadata(metadata: RawMetadata): RawMetadata {
|
||||
val scale = checkNotNull(metadata.mgcSabreNoiseModelScale) {
|
||||
"Sabre NoiseModel coefficient scale is unavailable"
|
||||
}
|
||||
check(scale.isFinite() && scale > 0f) {
|
||||
"Sabre NoiseModel coefficient scale is malformed: $scale"
|
||||
}
|
||||
val rgbNoise = checkNotNull(
|
||||
MgcFullResolutionDenoise.resolveUserAdjustmentCameraRgbNoise(metadata),
|
||||
) { "Sabre physical Bayer noise model is unavailable" }
|
||||
val read = checkNotNull(metadata.mgcDenoiseReadNoise)
|
||||
val shot = checkNotNull(metadata.mgcDenoiseShotNoise)
|
||||
val correlation = checkNotNull(metadata.mgcDenoiseCorrelation)
|
||||
check(read.size == 3 && shot.size == 3 && correlation.size == 128)
|
||||
check(read.all { it.isFinite() && it >= 0f } &&
|
||||
shot.all { it.isFinite() && it >= 0f } &&
|
||||
correlation.all { it.isFinite() && it >= 0f })
|
||||
PLog.i(
|
||||
TAG,
|
||||
"MGC Sabre default denoise noise source=reference-bayer*measured-merge-factor " +
|
||||
"captureFrames=${metadata.frameCount} scale=$scale " +
|
||||
"read=${rgbNoise.read.contentToString()} " +
|
||||
"shot=${rgbNoise.shot.contentToString()}",
|
||||
"MGC Sabre default denoise noise source=classic-merged-model " +
|
||||
"captureFrames=${metadata.frameCount} " +
|
||||
"read=${read.contentToString()} shot=${shot.contentToString()}",
|
||||
)
|
||||
return metadata.copy(
|
||||
frameCount = 1,
|
||||
mgcDenoiseCorrelation = null,
|
||||
mgcDenoiseReadNoise = null,
|
||||
mgcDenoiseShotNoise = null,
|
||||
mgcSpatialStrengthMap = null,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -180,18 +180,16 @@ data class RawMetadata(
|
||||
val sensorPixelArrayHeight: Int = 0,
|
||||
val frameCount: Int = 1,
|
||||
/**
|
||||
* MGC's normalized 128-bin power-correlation spectrum after spatial merge.
|
||||
* MGC's normalized 128-bin power-correlation spectrum after the selected MGC merge branch.
|
||||
* Null means either a single uncorrelated source or an unsupported propagated model.
|
||||
*/
|
||||
val mgcDenoiseCorrelation: FloatArray? = null,
|
||||
/** Exact process-local normalized camera-RGB read variance emitted by MGC Spatial. */
|
||||
/** Process-local normalized camera-RGB read variance emitted by the selected MGC merge branch. */
|
||||
val mgcDenoiseReadNoise: FloatArray? = null,
|
||||
/** Exact process-local normalized camera-RGB shot coefficient emitted by MGC Spatial. */
|
||||
/** Process-local normalized camera-RGB shot coefficient emitted by the selected MGC merge branch. */
|
||||
val mgcDenoiseShotNoise: FloatArray? = null,
|
||||
/** Exact process-local Q8 Spatial variance multiplier; never serialized into DNG. */
|
||||
val mgcSpatialStrengthMap: MgcSpatialStrengthMap? = null,
|
||||
/** Sabre's process-local NoiseModel scale measured from accumulated Q8 green merge weights. */
|
||||
val mgcSabreNoiseModelScale: Float? = null,
|
||||
/** Merged output-frame SNR used by MGC FinishRaw to select luma/chroma tuning. */
|
||||
val mgcDenoiseTuningSnr: Float? = null,
|
||||
/** MGC-derived attenuation applied to Photon's final GLES sharpen strength. */
|
||||
@@ -1219,7 +1217,6 @@ data class RawMetadata(
|
||||
if (!mgcDenoiseShotNoise.contentEquals(other.mgcDenoiseShotNoise)) return false
|
||||
} else if (other.mgcDenoiseShotNoise != null) return false
|
||||
if (mgcSpatialStrengthMap != other.mgcSpatialStrengthMap) return false
|
||||
if (mgcSabreNoiseModelScale != other.mgcSabreNoiseModelScale) return false
|
||||
if (mgcDenoiseTuningSnr != other.mgcDenoiseTuningSnr) return false
|
||||
if (mgcSharpenAttenuationScale != other.mgcSharpenAttenuationScale) return false
|
||||
if (coreImagingTuning != other.coreImagingTuning) return false
|
||||
@@ -1258,7 +1255,6 @@ data class RawMetadata(
|
||||
result = 31 * result + (mgcDenoiseReadNoise?.contentHashCode() ?: 0)
|
||||
result = 31 * result + (mgcDenoiseShotNoise?.contentHashCode() ?: 0)
|
||||
result = 31 * result + (mgcSpatialStrengthMap?.hashCode() ?: 0)
|
||||
result = 31 * result + (mgcSabreNoiseModelScale?.hashCode() ?: 0)
|
||||
result = 31 * result + (mgcDenoiseTuningSnr?.hashCode() ?: 0)
|
||||
result = 31 * result + (mgcSharpenAttenuationScale?.hashCode() ?: 0)
|
||||
result = 31 * result + coreImagingTuning.hashCode()
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.hinnka.mycamera.processor
|
||||
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
|
||||
class MgcSabreMergedNoiseModelTest {
|
||||
@Test
|
||||
fun identicalFramesFollowClassicSnrCurveAndInverseFrameCount() {
|
||||
val frame = MgcSabreMergedNoiseModel.Frame(
|
||||
floatArrayOf(0.001f, 0.002f, 0.003f),
|
||||
floatArrayOf(0.01f, 0.02f, 0.03f),
|
||||
)
|
||||
for ((snr, correction) in listOf(0f to 0.8f, 0.5f to 0.8f,
|
||||
2.25f to 0.9f, 4f to 1f, 7f to 0.85f, 10f to 0.7f, 30f to 0.7f)) {
|
||||
for (count in listOf(1, 2, 3, 8)) {
|
||||
val output = MgcSabreMergedNoiseModel.merge(List(count) { frame }, snr)
|
||||
assertArrayEquals(FloatArray(3) { frame.read[it] * correction / count },
|
||||
output.read, 1e-9f)
|
||||
assertArrayEquals(FloatArray(3) { frame.shot[it] * correction / count },
|
||||
output.shot, 1e-8f)
|
||||
assertArrayEquals(FloatArray(128) { 1f }, output.correlation, 0f)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun heterogeneousExposureNormalizedFramesRetainBothNoiseModels() {
|
||||
// Frame 2 has already been transported by gain=2: read*4, shot*2.
|
||||
// Independent equal-weight averaging yields (model1 + model2)/4 at SNR=4.
|
||||
val output = MgcSabreMergedNoiseModel.merge(listOf(
|
||||
MgcSabreMergedNoiseModel.Frame(
|
||||
floatArrayOf(0.001f, 0.002f, 0.004f),
|
||||
floatArrayOf(0.01f, 0.02f, 0.04f),
|
||||
),
|
||||
MgcSabreMergedNoiseModel.Frame(
|
||||
floatArrayOf(0.008f, 0.024f, 0.032f),
|
||||
floatArrayOf(0.06f, 0.08f, 0.16f),
|
||||
),
|
||||
), 4f)
|
||||
assertArrayEquals(floatArrayOf(0.00225f, 0.0065f, 0.009f), output.read, 1e-9f)
|
||||
assertArrayEquals(floatArrayOf(0.0175f, 0.025f, 0.05f), output.shot, 1e-8f)
|
||||
assertEquals(0.2f / kotlin.math.sqrt(0.0115f),
|
||||
MgcSpatialMergeTuning.outputNoiseModelSnr(0.2f, output.read[1], output.shot[1])!!,
|
||||
1e-6f)
|
||||
}
|
||||
}
|
||||
@@ -18,24 +18,33 @@ class MgcSabreNoiseEstimatesLutTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun qmcTransformMatchesReversedMgcReferenceValues() {
|
||||
fun qmcTransformMatchesV25SequenceReplay() {
|
||||
assertEquals(
|
||||
0.0012591606f,
|
||||
0.00124777935f,
|
||||
MgcSabreNoiseEstimatesLut.sqrtDomainVariance(0f, 0.001f, 0.00001f),
|
||||
1e-8f,
|
||||
)
|
||||
assertEquals(
|
||||
0.00025654092f,
|
||||
0.00025717527f,
|
||||
MgcSabreNoiseEstimatesLut.sqrtDomainVariance(0.5f, 0.001f, 0.00001f),
|
||||
1e-8f,
|
||||
)
|
||||
assertEquals(
|
||||
0.00024920312f,
|
||||
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)
|
||||
@@ -92,7 +101,7 @@ class MgcSabreNoiseEstimatesLutTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun mergedNoiseFactorUsesActualGreenRbfWeightsInQ8Domain() {
|
||||
fun diagnosticMergeFactorUsesActualGreenRbfWeightsInQ8Domain() {
|
||||
val shader = GlesMgcRawSabreShaders.reciprocalGreenWeight4x4
|
||||
|
||||
assertTrue(shader.contains("texelFetch(uAccumulatedWeightsGb, p, 0).r"))
|
||||
|
||||
Reference in new issue
Block a user