feat: raw noise propagation optimize
This commit is contained in:
1 parent
62927db382
commit
45f25560cf
7 files changed
+1329
-614
No files matched your search
@@ -0,0 +1,252 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import android.opengl.GLES30
|
||||
import android.opengl.GLES31
|
||||
import com.hinnka.mycamera.processor.GlesComputeWorkGroup
|
||||
|
||||
/** Generates the shared synthetic Bayer noise field directly in the calibration RAW texture. */
|
||||
internal class DemosaicNoiseAtlasGenerator {
|
||||
private var program = 0
|
||||
|
||||
fun initialize(): Boolean = getOrCreateProgram() != 0
|
||||
|
||||
fun generate(
|
||||
targetTextureId: Int,
|
||||
cfaPattern: Int,
|
||||
calculationWb: FloatArray,
|
||||
inputRead: FloatArray,
|
||||
inputShot: FloatArray,
|
||||
referenceSignals: FloatArray,
|
||||
readOnlySlot: Int,
|
||||
sampleSize: Int,
|
||||
): Boolean {
|
||||
require(targetTextureId != 0)
|
||||
require(calculationWb.size == 3)
|
||||
require(inputRead.size == 3)
|
||||
require(inputShot.size == 3)
|
||||
require(referenceSignals.size == SAMPLE_COUNT)
|
||||
require(readOnlySlot in referenceSignals.indices)
|
||||
require(sampleSize > 0)
|
||||
|
||||
val activeProgram = getOrCreateProgram()
|
||||
if (activeProgram == 0) return false
|
||||
|
||||
GLES31.glUseProgram(activeProgram)
|
||||
GLES31.glBindImageTexture(
|
||||
0,
|
||||
targetTextureId,
|
||||
0,
|
||||
false,
|
||||
0,
|
||||
GLES31.GL_WRITE_ONLY,
|
||||
GLES30.GL_RGBA16UI,
|
||||
)
|
||||
try {
|
||||
GLES31.glUniform1i(
|
||||
GLES31.glGetUniformLocation(activeProgram, "uCfaPattern"),
|
||||
cfaPattern,
|
||||
)
|
||||
GLES31.glUniform3fv(
|
||||
GLES31.glGetUniformLocation(activeProgram, "uCalculationWb"),
|
||||
1,
|
||||
calculationWb,
|
||||
0,
|
||||
)
|
||||
GLES31.glUniform3fv(
|
||||
GLES31.glGetUniformLocation(activeProgram, "uInputRead"),
|
||||
1,
|
||||
inputRead,
|
||||
0,
|
||||
)
|
||||
GLES31.glUniform3fv(
|
||||
GLES31.glGetUniformLocation(activeProgram, "uInputShot"),
|
||||
1,
|
||||
inputShot,
|
||||
0,
|
||||
)
|
||||
GLES31.glUniform4fv(
|
||||
GLES31.glGetUniformLocation(activeProgram, "uReferenceSignals"),
|
||||
1,
|
||||
referenceSignals,
|
||||
0,
|
||||
)
|
||||
GLES31.glUniform1i(
|
||||
GLES31.glGetUniformLocation(activeProgram, "uReadOnlySlot"),
|
||||
readOnlySlot,
|
||||
)
|
||||
GLES31.glUniform1i(
|
||||
GLES31.glGetUniformLocation(activeProgram, "uSampleSize"),
|
||||
sampleSize,
|
||||
)
|
||||
GLES31.glDispatchCompute(
|
||||
GlesComputeWorkGroup.imageGroupCount((sampleSize + 1) / 2),
|
||||
GlesComputeWorkGroup.imageGroupCount(sampleSize),
|
||||
1,
|
||||
)
|
||||
GLES31.glMemoryBarrier(
|
||||
GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or
|
||||
GLES31.GL_TEXTURE_FETCH_BARRIER_BIT,
|
||||
)
|
||||
val error = GLES31.glGetError()
|
||||
check(error == GLES31.GL_NO_ERROR) {
|
||||
"Synthetic demosaic noise atlas generation failed with GL error " +
|
||||
"0x${error.toString(16)}"
|
||||
}
|
||||
return true
|
||||
} finally {
|
||||
GLES31.glBindImageTexture(
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
false,
|
||||
0,
|
||||
GLES31.GL_WRITE_ONLY,
|
||||
GLES30.GL_RGBA16UI,
|
||||
)
|
||||
GLES31.glUseProgram(0)
|
||||
}
|
||||
}
|
||||
|
||||
fun release() {
|
||||
if (program != 0) {
|
||||
GLES31.glDeleteProgram(program)
|
||||
program = 0
|
||||
}
|
||||
}
|
||||
|
||||
private fun getOrCreateProgram(): Int {
|
||||
if (program == 0) {
|
||||
program = RawGlesProgram.compileCompute(COMPUTE_SHADER, "DemosaicNoiseAtlas")
|
||||
}
|
||||
return program
|
||||
}
|
||||
|
||||
private companion object {
|
||||
private const val SAMPLE_COUNT = 4
|
||||
|
||||
private val COMPUTE_SHADER = """
|
||||
#version 310 es
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
precision highp uimage2D;
|
||||
|
||||
layout(local_size_x = 8, local_size_y = 8) in;
|
||||
layout(rgba16ui, binding = 0) writeonly uniform highp uimage2D uOutput;
|
||||
|
||||
uniform int uCfaPattern;
|
||||
uniform vec3 uCalculationWb;
|
||||
uniform vec3 uInputRead;
|
||||
uniform vec3 uInputShot;
|
||||
uniform vec4 uReferenceSignals;
|
||||
uniform int uReadOnlySlot;
|
||||
uniform int uSampleSize;
|
||||
|
||||
uint hashBits(uint value) {
|
||||
value ^= value >> 16;
|
||||
value *= 0x7feb352du;
|
||||
value ^= value >> 15;
|
||||
value *= 0x846ca68bu;
|
||||
value ^= value >> 16;
|
||||
return value;
|
||||
}
|
||||
|
||||
float uniformOpen01(uint value) {
|
||||
return (float(hashBits(value) & 0x007fffffu) + 0.5) / 8388608.0;
|
||||
}
|
||||
|
||||
vec2 standardNormalPair(ivec2 pairPosition) {
|
||||
int pairsPerRow = (uSampleSize + 1) / 2;
|
||||
uint pairIndex = uint(pairPosition.y * pairsPerRow + pairPosition.x);
|
||||
float first = uniformOpen01(pairIndex * 2u + 0x68bc21ebu);
|
||||
float second = uniformOpen01(pairIndex * 2u + 0x02e5be93u);
|
||||
float radius = sqrt(-2.0 * log(first));
|
||||
float angle = 6.283185307179586 * second;
|
||||
return radius * vec2(cos(angle), sin(angle));
|
||||
}
|
||||
|
||||
int expandedBlockSize(int cfaPattern) {
|
||||
if (cfaPattern >= 8 && cfaPattern <= 11) return 4;
|
||||
if (cfaPattern >= 4 && cfaPattern <= 7) return 2;
|
||||
return 1;
|
||||
}
|
||||
|
||||
int baseBayerPattern(int cfaPattern) {
|
||||
if (cfaPattern >= 8 && cfaPattern <= 11) return cfaPattern - 8;
|
||||
if (cfaPattern >= 4 && cfaPattern <= 7) return cfaPattern - 4;
|
||||
return clamp(cfaPattern, 0, 3);
|
||||
}
|
||||
|
||||
int bayerChannelIndex(int cfaPattern, int xParity, int yParity) {
|
||||
if (cfaPattern == 1) {
|
||||
if (yParity == 0 && xParity == 0) return 1;
|
||||
if (yParity == 0 && xParity == 1) return 0;
|
||||
if (yParity == 1 && xParity == 0) return 3;
|
||||
return 2;
|
||||
}
|
||||
if (cfaPattern == 2) {
|
||||
if (yParity == 0 && xParity == 0) return 2;
|
||||
if (yParity == 0 && xParity == 1) return 3;
|
||||
if (yParity == 1 && xParity == 0) return 0;
|
||||
return 1;
|
||||
}
|
||||
if (cfaPattern == 3) {
|
||||
if (yParity == 0 && xParity == 0) return 3;
|
||||
if (yParity == 0 && xParity == 1) return 2;
|
||||
if (yParity == 1 && xParity == 0) return 1;
|
||||
return 0;
|
||||
}
|
||||
if (yParity == 0 && xParity == 0) return 0;
|
||||
if (yParity == 0 && xParity == 1) return 1;
|
||||
if (yParity == 1 && xParity == 0) return 2;
|
||||
return 3;
|
||||
}
|
||||
|
||||
int rgbChannelForPixel(ivec2 position) {
|
||||
int blockSize = expandedBlockSize(uCfaPattern);
|
||||
int bayerChannel = bayerChannelIndex(
|
||||
baseBayerPattern(uCfaPattern),
|
||||
(position.x / blockSize) & 1,
|
||||
(position.y / blockSize) & 1
|
||||
);
|
||||
if (bayerChannel == 0) return 0;
|
||||
if (bayerChannel == 3) return 2;
|
||||
return 1;
|
||||
}
|
||||
|
||||
void writeSamples(ivec2 position, float gaussian) {
|
||||
int channel = rgbChannelForPixel(position);
|
||||
float wb = max(uCalculationWb[channel], 1e-6);
|
||||
vec4 rawSignals = uReferenceSignals / wb;
|
||||
vec4 variances =
|
||||
vec4(uInputRead[channel]) + uInputShot[channel] * rawSignals;
|
||||
variances[uReadOnlySlot] = uInputRead[channel];
|
||||
vec4 noisy = clamp(
|
||||
rawSignals + sqrt(max(variances, vec4(0.0))) * gaussian,
|
||||
0.0,
|
||||
1.0
|
||||
);
|
||||
for (int slot = 0; slot < 4; ++slot) {
|
||||
uint quantized = uint(floor(noisy[slot] * 65535.0 + 0.5));
|
||||
imageStore(
|
||||
uOutput,
|
||||
position + ivec2(slot * uSampleSize, 0),
|
||||
uvec4(quantized, 0u, 0u, 1u)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
ivec2 pairPosition = ivec2(gl_GlobalInvocationID.xy);
|
||||
ivec2 firstPosition = ivec2(pairPosition.x * 2, pairPosition.y);
|
||||
if (any(greaterThanEqual(firstPosition, ivec2(uSampleSize)))) return;
|
||||
|
||||
vec2 gaussian = standardNormalPair(pairPosition);
|
||||
writeSamples(firstPosition, gaussian.x);
|
||||
ivec2 secondPosition = firstPosition + ivec2(1, 0);
|
||||
if (secondPosition.x < uSampleSize) {
|
||||
writeSamples(secondPosition, gaussian.y);
|
||||
}
|
||||
}
|
||||
""".trimIndent()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,904 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import android.opengl.GLES30
|
||||
import android.opengl.GLES31
|
||||
import android.util.Half
|
||||
import com.hinnka.mycamera.utils.LargeDirectBuffer
|
||||
import com.hinnka.mycamera.utils.PLog
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import kotlin.math.PI
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.sin
|
||||
|
||||
internal typealias DemosaicNoiseTransfer = MgcFullResolutionDenoise.PreparedYuvNoiseModel
|
||||
|
||||
internal data class DemosaicNoiseRenderRequest(
|
||||
val metadata: RawMetadata,
|
||||
val rawTextureId: Int,
|
||||
val linearOutputTextureId: Int,
|
||||
val outputTextureId: Int,
|
||||
val width: Int,
|
||||
val height: Int,
|
||||
)
|
||||
|
||||
/** Computes the legacy half-bin luma/chroma spectrum in O(N log N) instead of direct O(N²). */
|
||||
internal object DemosaicNoiseSpectrum {
|
||||
const val SIZE = 128
|
||||
|
||||
fun propagatedCorrelation(
|
||||
residuals: Array<FloatArray>,
|
||||
channels: IntArray,
|
||||
inputCorrelation: FloatArray,
|
||||
): FloatArray? {
|
||||
if (inputCorrelation.size != SIZE) return null
|
||||
val demosaicPower = halfBinDirectionalPower(residuals, channels)
|
||||
val demosaicPowerMean = demosaicPower.average()
|
||||
if (!demosaicPowerMean.isFinite() || demosaicPowerMean <= 0.0) return null
|
||||
val composed = DoubleArray(SIZE) { index ->
|
||||
inputCorrelation[index].toDouble() *
|
||||
(demosaicPower[index] / demosaicPowerMean)
|
||||
}
|
||||
val compositionMean = composed.average()
|
||||
if (!compositionMean.isFinite() || compositionMean <= 0.0) return null
|
||||
return FloatArray(SIZE) { index ->
|
||||
(composed[index] / compositionMean).toFloat()
|
||||
}.takeIf { spectrum -> spectrum.all { it.isFinite() && it >= 0f } }
|
||||
}
|
||||
|
||||
internal fun halfBinDirectionalPower(
|
||||
residuals: Array<FloatArray>,
|
||||
channels: IntArray,
|
||||
): DoubleArray {
|
||||
require(channels.all { it in residuals.indices })
|
||||
require(channels.all { residuals[it].size == SIZE * SIZE })
|
||||
val power = DoubleArray(SIZE)
|
||||
val real = DoubleArray(SIZE)
|
||||
val imaginary = DoubleArray(SIZE)
|
||||
for (channel in channels) {
|
||||
val residual = residuals[channel]
|
||||
for (line in 0 until SIZE) {
|
||||
fillShiftedLine(
|
||||
residual = residual,
|
||||
line = line,
|
||||
vertical = false,
|
||||
real = real,
|
||||
imaginary = imaginary,
|
||||
)
|
||||
forwardFft(real, imaginary)
|
||||
accumulateMappedPower(real, imaginary, power)
|
||||
|
||||
fillShiftedLine(
|
||||
residual = residual,
|
||||
line = line,
|
||||
vertical = true,
|
||||
real = real,
|
||||
imaginary = imaginary,
|
||||
)
|
||||
forwardFft(real, imaginary)
|
||||
accumulateMappedPower(real, imaginary, power)
|
||||
}
|
||||
}
|
||||
val normalization = 2.0 * SIZE * SIZE
|
||||
for (bin in power.indices) power[bin] /= normalization
|
||||
return power
|
||||
}
|
||||
|
||||
private fun fillShiftedLine(
|
||||
residual: FloatArray,
|
||||
line: Int,
|
||||
vertical: Boolean,
|
||||
real: DoubleArray,
|
||||
imaginary: DoubleArray,
|
||||
) {
|
||||
for (position in 0 until SIZE) {
|
||||
val value = if (vertical) {
|
||||
residual[position * SIZE + line]
|
||||
} else {
|
||||
residual[line * SIZE + position]
|
||||
}.toDouble()
|
||||
real[position] = value * HALF_BIN_SHIFT_COSINE[position]
|
||||
imaginary[position] = value * HALF_BIN_SHIFT_SINE[position]
|
||||
}
|
||||
}
|
||||
|
||||
private fun accumulateMappedPower(
|
||||
real: DoubleArray,
|
||||
imaginary: DoubleArray,
|
||||
power: DoubleArray,
|
||||
) {
|
||||
for (bin in 0 until SIZE) {
|
||||
// The legacy frequency is 2π(bin + 0.5)/N - π. Premultiplication supplies the
|
||||
// half-bin shift; this rotation maps the centered legacy order to FFT order.
|
||||
val fftIndex = (bin + SIZE / 2) and (SIZE - 1)
|
||||
power[bin] +=
|
||||
real[fftIndex] * real[fftIndex] +
|
||||
imaginary[fftIndex] * imaginary[fftIndex]
|
||||
}
|
||||
}
|
||||
|
||||
private fun forwardFft(real: DoubleArray, imaginary: DoubleArray) {
|
||||
var reversed = 0
|
||||
for (index in 1 until SIZE) {
|
||||
var bit = SIZE shr 1
|
||||
while (reversed and bit != 0) {
|
||||
reversed = reversed xor bit
|
||||
bit = bit shr 1
|
||||
}
|
||||
reversed = reversed xor bit
|
||||
if (index < reversed) {
|
||||
val realSwap = real[index]
|
||||
real[index] = real[reversed]
|
||||
real[reversed] = realSwap
|
||||
val imaginarySwap = imaginary[index]
|
||||
imaginary[index] = imaginary[reversed]
|
||||
imaginary[reversed] = imaginarySwap
|
||||
}
|
||||
}
|
||||
|
||||
var length = 2
|
||||
while (length <= SIZE) {
|
||||
val halfLength = length / 2
|
||||
val twiddleStep = SIZE / length
|
||||
var block = 0
|
||||
while (block < SIZE) {
|
||||
for (offset in 0 until halfLength) {
|
||||
val twiddleIndex = offset * twiddleStep
|
||||
val twiddleReal = FFT_COSINE[twiddleIndex]
|
||||
val twiddleImaginary = FFT_SINE[twiddleIndex]
|
||||
val evenIndex = block + offset
|
||||
val oddIndex = evenIndex + halfLength
|
||||
val oddReal =
|
||||
real[oddIndex] * twiddleReal -
|
||||
imaginary[oddIndex] * twiddleImaginary
|
||||
val oddImaginary =
|
||||
real[oddIndex] * twiddleImaginary +
|
||||
imaginary[oddIndex] * twiddleReal
|
||||
val evenReal = real[evenIndex]
|
||||
val evenImaginary = imaginary[evenIndex]
|
||||
real[evenIndex] = evenReal + oddReal
|
||||
imaginary[evenIndex] = evenImaginary + oddImaginary
|
||||
real[oddIndex] = evenReal - oddReal
|
||||
imaginary[oddIndex] = evenImaginary - oddImaginary
|
||||
}
|
||||
block += length
|
||||
}
|
||||
length = length shl 1
|
||||
}
|
||||
}
|
||||
|
||||
private val HALF_BIN_SHIFT_COSINE =
|
||||
DoubleArray(SIZE) { position -> cos(-PI * position / SIZE) }
|
||||
private val HALF_BIN_SHIFT_SINE =
|
||||
DoubleArray(SIZE) { position -> sin(-PI * position / SIZE) }
|
||||
private val FFT_COSINE =
|
||||
DoubleArray(SIZE / 2) { index -> cos(-2.0 * PI * index / SIZE) }
|
||||
private val FFT_SINE =
|
||||
DoubleArray(SIZE / 2) { index -> sin(-2.0 * PI * index / SIZE) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Measures how the active demosaic pipeline propagates physical Bayer noise into MGC's YUV
|
||||
* domain. The calibrator owns the synthetic fields, GL calibration resources, model fitting and
|
||||
* cache; [RawDemosaicProcessor] only supplies pipeline initialization and one demosaic dispatch.
|
||||
*/
|
||||
internal class DemosaicNoisePropagationCalibrator(
|
||||
private val initializePipeline: (cfaPattern: Int) -> Boolean,
|
||||
private val renderDemosaic: (DemosaicNoiseRenderRequest) -> Unit,
|
||||
) {
|
||||
private data class NoiseSample(
|
||||
val referenceSignal: Float,
|
||||
val workingLumaMean: Float,
|
||||
val normalizedYuvVariance: FloatArray,
|
||||
val lumaCorrelation: FloatArray?,
|
||||
val chromaCorrelation: FloatArray?,
|
||||
)
|
||||
|
||||
private data class CacheKey(
|
||||
val cfaPattern: Int,
|
||||
val normalizedRgbReadBits: List<Int>,
|
||||
val normalizedRgbShotBits: List<Int>,
|
||||
val inputCorrelationBits: List<Int>,
|
||||
val calculationWbBits: List<Int>,
|
||||
)
|
||||
|
||||
private enum class NoiseComponent {
|
||||
TOTAL,
|
||||
READ_ONLY,
|
||||
}
|
||||
|
||||
private data class NoiseSampleSpec(
|
||||
val referenceSignal: Float,
|
||||
val component: NoiseComponent,
|
||||
val includeCorrelation: Boolean,
|
||||
)
|
||||
|
||||
private data class GlRenderTiming(
|
||||
val atlasGenerationSubmitMs: Long,
|
||||
val demosaicMs: Long,
|
||||
val readbackMs: Long,
|
||||
)
|
||||
|
||||
private class AnalysisWorkspace {
|
||||
val workingRgb = Array(3) { FloatArray(ANALYSIS_PIXELS) }
|
||||
val yuvResidual = Array(3) { FloatArray(ANALYSIS_PIXELS) }
|
||||
}
|
||||
|
||||
private inner class GlCalibrationSession {
|
||||
private val textures = IntArray(3)
|
||||
private val framebuffers = IntArray(1)
|
||||
private val savedPackAlignment = glInteger(GLES30.GL_PACK_ALIGNMENT)
|
||||
private val savedFramebuffer = glInteger(GLES30.GL_FRAMEBUFFER_BINDING)
|
||||
private val savedPixelPackBuffer = glInteger(GLES30.GL_PIXEL_PACK_BUFFER_BINDING)
|
||||
private val savedActiveTexture = glInteger(GLES30.GL_ACTIVE_TEXTURE)
|
||||
private val savedTextureBinding = glInteger(GLES30.GL_TEXTURE_BINDING_2D)
|
||||
private var released = false
|
||||
val allocationMs: Long
|
||||
|
||||
private val rawTextureId: Int
|
||||
get() = textures[0]
|
||||
private val outputTextureId: Int
|
||||
get() = textures[1]
|
||||
private val linearOutputTextureId: Int
|
||||
get() = textures[2]
|
||||
private val framebufferId: Int
|
||||
get() = framebuffers[0]
|
||||
|
||||
init {
|
||||
val startNs = System.nanoTime()
|
||||
try {
|
||||
GLES30.glGenTextures(textures.size, textures, 0)
|
||||
check(textures.all { it != 0 }) {
|
||||
"Unable to allocate noise calibration textures"
|
||||
}
|
||||
|
||||
configureTexture(
|
||||
textureId = rawTextureId,
|
||||
// GLES 3.1 guarantees RGBA16UI image store. Demosaic samplers consume .r,
|
||||
// so calibration does not need a format-conversion pass back to R16UI.
|
||||
internalFormat = GLES30.GL_RGBA16UI,
|
||||
)
|
||||
configureTexture(
|
||||
textureId = outputTextureId,
|
||||
internalFormat = GLES30.GL_RGBA16F,
|
||||
)
|
||||
configureTexture(
|
||||
textureId = linearOutputTextureId,
|
||||
internalFormat = GLES30.GL_RGBA16F,
|
||||
)
|
||||
|
||||
GLES30.glGenFramebuffers(1, framebuffers, 0)
|
||||
check(framebufferId != 0) {
|
||||
"Unable to allocate noise calibration framebuffer"
|
||||
}
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebufferId)
|
||||
GLES30.glFramebufferTexture2D(
|
||||
GLES30.GL_FRAMEBUFFER,
|
||||
GLES30.GL_COLOR_ATTACHMENT0,
|
||||
GLES30.GL_TEXTURE_2D,
|
||||
outputTextureId,
|
||||
0,
|
||||
)
|
||||
check(
|
||||
GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER) ==
|
||||
GLES30.GL_FRAMEBUFFER_COMPLETE,
|
||||
) {
|
||||
"Noise calibration framebuffer is incomplete"
|
||||
}
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
|
||||
checkGlError("resource allocation")
|
||||
allocationMs = elapsedMs(startNs)
|
||||
} catch (error: Throwable) {
|
||||
release()
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
fun render(
|
||||
metadata: RawMetadata,
|
||||
calculationWb: FloatArray,
|
||||
inputRead: FloatArray,
|
||||
inputShot: FloatArray,
|
||||
rgbaOutput: ByteBuffer,
|
||||
): GlRenderTiming {
|
||||
val atlasGenerationStartNs = System.nanoTime()
|
||||
check(
|
||||
atlasGenerator.generate(
|
||||
targetTextureId = rawTextureId,
|
||||
cfaPattern = metadata.cfaPattern,
|
||||
calculationWb = calculationWb,
|
||||
inputRead = inputRead,
|
||||
inputShot = inputShot,
|
||||
referenceSignals = REFERENCE_SIGNALS,
|
||||
readOnlySlot = READ_ONLY_SLOT,
|
||||
sampleSize = CALIBRATION_SIZE,
|
||||
),
|
||||
) {
|
||||
"Unable to generate synthetic demosaic noise atlas"
|
||||
}
|
||||
val atlasGenerationSubmitMs = elapsedMs(atlasGenerationStartNs)
|
||||
|
||||
val demosaicStartNs = System.nanoTime()
|
||||
renderDemosaic(
|
||||
DemosaicNoiseRenderRequest(
|
||||
metadata = metadata,
|
||||
rawTextureId = rawTextureId,
|
||||
linearOutputTextureId = linearOutputTextureId,
|
||||
outputTextureId = outputTextureId,
|
||||
width = ATLAS_WIDTH,
|
||||
height = ATLAS_HEIGHT,
|
||||
),
|
||||
)
|
||||
val demosaicMs = elapsedMs(demosaicStartNs)
|
||||
|
||||
val readbackStartNs = System.nanoTime()
|
||||
GLES31.glMemoryBarrier(
|
||||
GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or
|
||||
GLES31.GL_FRAMEBUFFER_BARRIER_BIT,
|
||||
)
|
||||
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, framebufferId)
|
||||
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 8)
|
||||
rgbaOutput.clear()
|
||||
GLES30.glReadPixels(
|
||||
0,
|
||||
0,
|
||||
ATLAS_WIDTH,
|
||||
ATLAS_HEIGHT,
|
||||
GLES30.GL_RGBA,
|
||||
GLES30.GL_HALF_FLOAT,
|
||||
rgbaOutput,
|
||||
)
|
||||
checkGlError("readback")
|
||||
return GlRenderTiming(
|
||||
atlasGenerationSubmitMs = atlasGenerationSubmitMs,
|
||||
demosaicMs = demosaicMs,
|
||||
readbackMs = elapsedMs(readbackStartNs),
|
||||
)
|
||||
}
|
||||
|
||||
fun release() {
|
||||
if (released) return
|
||||
released = true
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
|
||||
GLES30.glDeleteFramebuffers(framebuffers.size, framebuffers, 0)
|
||||
GLES30.glDeleteTextures(textures.size, textures, 0)
|
||||
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, savedPackAlignment)
|
||||
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, savedPixelPackBuffer)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, savedFramebuffer)
|
||||
GLES30.glActiveTexture(savedActiveTexture)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, savedTextureBinding)
|
||||
}
|
||||
|
||||
private fun configureTexture(textureId: Int, internalFormat: Int) {
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textureId)
|
||||
GLES30.glTexStorage2D(
|
||||
GLES30.GL_TEXTURE_2D,
|
||||
1,
|
||||
internalFormat,
|
||||
ATLAS_WIDTH,
|
||||
ATLAS_HEIGHT,
|
||||
)
|
||||
GLES30.glTexParameteri(
|
||||
GLES30.GL_TEXTURE_2D,
|
||||
GLES30.GL_TEXTURE_MIN_FILTER,
|
||||
GLES30.GL_NEAREST,
|
||||
)
|
||||
GLES30.glTexParameteri(
|
||||
GLES30.GL_TEXTURE_2D,
|
||||
GLES30.GL_TEXTURE_MAG_FILTER,
|
||||
GLES30.GL_NEAREST,
|
||||
)
|
||||
GLES30.glTexParameteri(
|
||||
GLES30.GL_TEXTURE_2D,
|
||||
GLES30.GL_TEXTURE_WRAP_S,
|
||||
GLES30.GL_CLAMP_TO_EDGE,
|
||||
)
|
||||
GLES30.glTexParameteri(
|
||||
GLES30.GL_TEXTURE_2D,
|
||||
GLES30.GL_TEXTURE_WRAP_T,
|
||||
GLES30.GL_CLAMP_TO_EDGE,
|
||||
)
|
||||
}
|
||||
|
||||
private fun glInteger(parameter: Int): Int {
|
||||
val value = IntArray(1)
|
||||
GLES30.glGetIntegerv(parameter, value, 0)
|
||||
return value[0]
|
||||
}
|
||||
}
|
||||
|
||||
private val atlasGenerator = DemosaicNoiseAtlasGenerator()
|
||||
private var cachedKey: CacheKey? = null
|
||||
private var cachedTransfer: DemosaicNoiseTransfer? = null
|
||||
|
||||
fun release() {
|
||||
atlasGenerator.release()
|
||||
cachedKey = null
|
||||
cachedTransfer = null
|
||||
}
|
||||
|
||||
fun prepareUserAdjustment(
|
||||
metadata: RawMetadata,
|
||||
calculationWb4: FloatArray,
|
||||
): DemosaicNoiseTransfer? {
|
||||
val rgbNoise = MgcFullResolutionDenoise.resolveUserAdjustmentCameraRgbNoise(metadata)
|
||||
?: return null
|
||||
val propagationMetadata = metadata.copy(
|
||||
frameCount = 1,
|
||||
mgcDenoiseReadNoise = rgbNoise.read,
|
||||
mgcDenoiseShotNoise = rgbNoise.shot,
|
||||
mgcDenoiseCorrelation = FloatArray(SPECTRUM_BINS) { 1f },
|
||||
mgcSpatialStrengthMap = null,
|
||||
)
|
||||
return measure(propagationMetadata, calculationWb4)?.also { transfer ->
|
||||
PLog.i(
|
||||
TAG,
|
||||
"MGC USER_ADJUSTMENT noise propagation ready " +
|
||||
"pipeline=${pipelineLabel(metadata.cfaPattern)} " +
|
||||
"lumaCorrelation=${transfer.lumaCorrelation.minOrNull()}.." +
|
||||
"${transfer.lumaCorrelation.maxOrNull()}/${transfer.lumaCorrelation.average()} " +
|
||||
"chromaCorrelation=${transfer.chromaCorrelation.minOrNull()}.." +
|
||||
"${transfer.chromaCorrelation.maxOrNull()}/" +
|
||||
transfer.chromaCorrelation.average(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun measure(
|
||||
metadata: RawMetadata,
|
||||
calculationWb4: FloatArray,
|
||||
): DemosaicNoiseTransfer? {
|
||||
val inputRead = metadata.mgcDenoiseReadNoise
|
||||
val inputShot = metadata.mgcDenoiseShotNoise
|
||||
val inputCorrelation = metadata.mgcDenoiseCorrelation
|
||||
if (inputRead?.size != 3 || inputShot?.size != 3 ||
|
||||
inputCorrelation?.size != SPECTRUM_BINS ||
|
||||
inputRead.any { !it.isFinite() || it < 0f } ||
|
||||
inputShot.any { !it.isFinite() || it < 0f } ||
|
||||
inputCorrelation.any { !it.isFinite() || it < 0f }
|
||||
) {
|
||||
return null
|
||||
}
|
||||
val calculationWb = floatArrayOf(
|
||||
calculationWb4.getOrElse(0) { 1f },
|
||||
1f,
|
||||
calculationWb4.getOrElse(3) { 1f },
|
||||
)
|
||||
val cacheKey = CacheKey(
|
||||
cfaPattern = metadata.cfaPattern,
|
||||
normalizedRgbReadBits = inputRead.map(Float::toBits),
|
||||
normalizedRgbShotBits = inputShot.map(Float::toBits),
|
||||
inputCorrelationBits = inputCorrelation.map(Float::toBits),
|
||||
calculationWbBits = calculationWb.map(Float::toBits),
|
||||
)
|
||||
if (cacheKey == cachedKey) {
|
||||
PLog.i(TAG, "Demosaic noise propagation cache hit pipeline=${pipelineLabel(metadata.cfaPattern)}")
|
||||
return cachedTransfer
|
||||
}
|
||||
|
||||
val totalStartNs = System.nanoTime()
|
||||
return try {
|
||||
val pipelineInitStartNs = System.nanoTime()
|
||||
check(initializePipeline(metadata.cfaPattern)) {
|
||||
"Unable to initialize ${pipelineLabel(metadata.cfaPattern)} noise propagation programs"
|
||||
}
|
||||
check(atlasGenerator.initialize()) {
|
||||
"Unable to initialize synthetic demosaic noise atlas generator"
|
||||
}
|
||||
val pipelineInitMs = elapsedMs(pipelineInitStartNs)
|
||||
val calibrationMetadata = metadata.copy(
|
||||
width = ATLAS_WIDTH,
|
||||
height = ATLAS_HEIGHT,
|
||||
// The supplied coefficients already describe the merged output frame.
|
||||
frameCount = 1,
|
||||
blackLevel = FloatArray(4),
|
||||
whiteLevel = 65535f,
|
||||
lensShadingMap = null,
|
||||
lensShadingMapWidth = 0,
|
||||
lensShadingMapHeight = 0,
|
||||
lensShadingMapGrid = null,
|
||||
channelNoiseProfile = floatArrayOf(
|
||||
inputShot[0], inputRead[0],
|
||||
inputShot[1], inputRead[1],
|
||||
inputShot[2], inputRead[2],
|
||||
),
|
||||
noiseProfileLayout = RawNoiseProfileLayout.DNG_RGB,
|
||||
)
|
||||
measureUncached(
|
||||
metadata = calibrationMetadata,
|
||||
calculationWb = calculationWb,
|
||||
inputRead = inputRead,
|
||||
inputShot = inputShot,
|
||||
inputCorrelation = inputCorrelation,
|
||||
pipelineInitMs = pipelineInitMs,
|
||||
totalStartNs = totalStartNs,
|
||||
)?.also { transfer ->
|
||||
cachedKey = cacheKey
|
||||
cachedTransfer = transfer
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"${pipelineLabel(metadata.cfaPattern)} noise propagation failed",
|
||||
error,
|
||||
)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
private fun measureUncached(
|
||||
metadata: RawMetadata,
|
||||
calculationWb: FloatArray,
|
||||
inputRead: FloatArray,
|
||||
inputShot: FloatArray,
|
||||
inputCorrelation: FloatArray,
|
||||
pipelineInitMs: Long,
|
||||
totalStartNs: Long,
|
||||
): DemosaicNoiseTransfer? {
|
||||
val cpuSetupStartNs = System.nanoTime()
|
||||
val calibrationPixels = ATLAS_WIDTH * ATLAS_HEIGHT
|
||||
val rgba = LargeDirectBuffer.allocate(
|
||||
calibrationPixels.toLong() * 4 * Short.SIZE_BYTES,
|
||||
"Demosaic noise propagation RGBA16F atlas",
|
||||
)?.order(ByteOrder.nativeOrder()) ?: return null
|
||||
val workspace = AnalysisWorkspace()
|
||||
val cpuSetupMs = elapsedMs(cpuSetupStartNs)
|
||||
val session = try {
|
||||
GlCalibrationSession()
|
||||
} catch (error: Throwable) {
|
||||
LargeDirectBuffer.free(rgba)
|
||||
throw error
|
||||
}
|
||||
|
||||
val samples = ArrayList<NoiseSample>(SAMPLE_SPECS.size - 1)
|
||||
var readSample: NoiseSample? = null
|
||||
var renderTiming = GlRenderTiming(
|
||||
atlasGenerationSubmitMs = 0L,
|
||||
demosaicMs = 0L,
|
||||
readbackMs = 0L,
|
||||
)
|
||||
var totalAnalysisMs = 0L
|
||||
var totalCorrelationMs = 0L
|
||||
val resourceReleaseStartNs: Long
|
||||
try {
|
||||
renderTiming = session.render(
|
||||
metadata = metadata,
|
||||
calculationWb = calculationWb,
|
||||
inputRead = inputRead,
|
||||
inputShot = inputShot,
|
||||
rgbaOutput = rgba,
|
||||
)
|
||||
|
||||
SAMPLE_SPECS.forEachIndexed { slotIndex, spec ->
|
||||
val analysisStartNs = System.nanoTime()
|
||||
val analysis = analyzeOutput(
|
||||
rgba = rgba,
|
||||
atlasSlot = slotIndex,
|
||||
calculationWb = calculationWb,
|
||||
spec = spec,
|
||||
inputRead = inputRead,
|
||||
inputShot = inputShot,
|
||||
workspace = workspace,
|
||||
preserveResidual = spec.includeCorrelation,
|
||||
) ?: return null
|
||||
val analysisMs = elapsedMs(analysisStartNs)
|
||||
|
||||
val correlationStartNs = System.nanoTime()
|
||||
val lumaCorrelation = if (spec.includeCorrelation) {
|
||||
DemosaicNoiseSpectrum.propagatedCorrelation(
|
||||
residuals = workspace.yuvResidual,
|
||||
channels = intArrayOf(0),
|
||||
inputCorrelation = inputCorrelation,
|
||||
) ?: return null
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val chromaCorrelation = if (spec.includeCorrelation) {
|
||||
DemosaicNoiseSpectrum.propagatedCorrelation(
|
||||
residuals = workspace.yuvResidual,
|
||||
channels = intArrayOf(1, 2),
|
||||
inputCorrelation = inputCorrelation,
|
||||
) ?: return null
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val correlationMs = elapsedMs(correlationStartNs)
|
||||
totalAnalysisMs += analysisMs
|
||||
totalCorrelationMs += correlationMs
|
||||
|
||||
val sample = NoiseSample(
|
||||
referenceSignal = spec.referenceSignal,
|
||||
workingLumaMean = analysis.workingLumaMean,
|
||||
normalizedYuvVariance = analysis.normalizedYuvVariance,
|
||||
lumaCorrelation = lumaCorrelation,
|
||||
chromaCorrelation = chromaCorrelation,
|
||||
)
|
||||
if (spec.component == NoiseComponent.READ_ONLY) {
|
||||
readSample = sample
|
||||
} else {
|
||||
samples += sample
|
||||
}
|
||||
PLog.i(
|
||||
TAG,
|
||||
"Demosaic noise propagation sample " +
|
||||
"pipeline=${pipelineLabel(metadata.cfaPattern)} atlasSlot=$slotIndex " +
|
||||
"component=${spec.component} reference=${spec.referenceSignal} " +
|
||||
"correlation=${spec.includeCorrelation} " +
|
||||
"workingLumaMean=${analysis.workingLumaMean} " +
|
||||
"normalizedYuvVariance=${analysis.normalizedYuvVariance.contentToString()} " +
|
||||
"outputToTheoreticalInputVarianceRatio=" +
|
||||
"${analysis.outputToTheoreticalInputVarianceRatio.contentToString()} " +
|
||||
"analysisMs=$analysisMs correlationMs=$correlationMs",
|
||||
)
|
||||
}
|
||||
} finally {
|
||||
resourceReleaseStartNs = System.nanoTime()
|
||||
session.release()
|
||||
LargeDirectBuffer.free(rgba)
|
||||
}
|
||||
val resourceReleaseMs = elapsedMs(resourceReleaseStartNs)
|
||||
val referenceSample = samples.first { it.referenceSignal == REFERENCE_SIGNAL }
|
||||
val lumaCorrelation = checkNotNull(referenceSample.lumaCorrelation)
|
||||
val chromaCorrelation = checkNotNull(referenceSample.chromaCorrelation)
|
||||
val fitStartNs = System.nanoTime()
|
||||
val transfer = fitTransfer(
|
||||
samples = samples,
|
||||
readSample = checkNotNull(readSample),
|
||||
lumaCorrelation = lumaCorrelation,
|
||||
chromaCorrelation = chromaCorrelation,
|
||||
) ?: return null
|
||||
val fitMs = elapsedMs(fitStartNs)
|
||||
PLog.i(
|
||||
TAG,
|
||||
"Demosaic noise calibration timing " +
|
||||
"pipeline=${pipelineLabel(metadata.cfaPattern)} " +
|
||||
"totalMs=${elapsedMs(totalStartNs)} programInitMs=$pipelineInitMs " +
|
||||
"cpuSetupMs=$cpuSetupMs resourceAllocMs=${session.allocationMs} " +
|
||||
"atlas=${ATLAS_WIDTH}x$ATLAS_HEIGHT " +
|
||||
"atlasGenerationSubmitMs=${renderTiming.atlasGenerationSubmitMs} " +
|
||||
"demosaicMs=${renderTiming.demosaicMs} " +
|
||||
"readbackMs=${renderTiming.readbackMs} analysisMs=$totalAnalysisMs " +
|
||||
"correlationMs=$totalCorrelationMs fitMs=$fitMs " +
|
||||
"resourceReleaseMs=$resourceReleaseMs",
|
||||
)
|
||||
return transfer
|
||||
}
|
||||
|
||||
private data class OutputAnalysis(
|
||||
val workingLumaMean: Float,
|
||||
val normalizedYuvVariance: FloatArray,
|
||||
val outputToTheoreticalInputVarianceRatio: FloatArray,
|
||||
)
|
||||
|
||||
private fun analyzeOutput(
|
||||
rgba: ByteBuffer,
|
||||
atlasSlot: Int,
|
||||
calculationWb: FloatArray,
|
||||
spec: NoiseSampleSpec,
|
||||
inputRead: FloatArray,
|
||||
inputShot: FloatArray,
|
||||
workspace: AnalysisWorkspace,
|
||||
preserveResidual: Boolean,
|
||||
): OutputAnalysis? {
|
||||
val mean = DoubleArray(3)
|
||||
var sampleIndex = 0
|
||||
for (y in 0 until ANALYSIS_SIZE) {
|
||||
val sourceY = ANALYSIS_ORIGIN + y
|
||||
for (x in 0 until ANALYSIS_SIZE) {
|
||||
val sourceX = atlasSlot * CALIBRATION_SIZE + ANALYSIS_ORIGIN + x
|
||||
val pixelOffset =
|
||||
(sourceY * ATLAS_WIDTH + sourceX) * 4 * Short.SIZE_BYTES
|
||||
for (channel in 0 until 3) {
|
||||
val value = Half.toFloat(
|
||||
rgba.getShort(pixelOffset + channel * Short.SIZE_BYTES),
|
||||
) * calculationWb[channel]
|
||||
workspace.workingRgb[channel][sampleIndex] = value
|
||||
mean[channel] += value
|
||||
}
|
||||
sampleIndex++
|
||||
}
|
||||
}
|
||||
for (channel in 0 until 3) mean[channel] /= ANALYSIS_PIXELS.toDouble()
|
||||
var workingLumaMean = 0.0
|
||||
for (channel in 0 until 3) {
|
||||
workingLumaMean += RGB_TO_YUV[channel] * mean[channel]
|
||||
}
|
||||
|
||||
val outputVariance = DoubleArray(3)
|
||||
val yuvVariance = DoubleArray(3)
|
||||
for (index in 0 until ANALYSIS_PIXELS) {
|
||||
val red = workspace.workingRgb[0][index] - mean[0].toFloat()
|
||||
val green = workspace.workingRgb[1][index] - mean[1].toFloat()
|
||||
val blue = workspace.workingRgb[2][index] - mean[2].toFloat()
|
||||
outputVariance[0] += red * red
|
||||
outputVariance[1] += green * green
|
||||
outputVariance[2] += blue * blue
|
||||
for (outputChannel in 0 until 3) {
|
||||
val offset = outputChannel * 3
|
||||
val residual =
|
||||
RGB_TO_YUV[offset] * red +
|
||||
RGB_TO_YUV[offset + 1] * green +
|
||||
RGB_TO_YUV[offset + 2] * blue
|
||||
yuvVariance[outputChannel] += residual * residual
|
||||
if (preserveResidual) workspace.yuvResidual[outputChannel][index] = residual
|
||||
}
|
||||
}
|
||||
val outputToTheoreticalInputVarianceRatio = FloatArray(3)
|
||||
for (channel in 0 until 3) {
|
||||
outputVariance[channel] /= ANALYSIS_PIXELS.toDouble()
|
||||
val wb = calculationWb[channel].coerceAtLeast(1e-6f).toDouble()
|
||||
val rawSignal = spec.referenceSignal.toDouble() / wb
|
||||
val rawVariance = when (spec.component) {
|
||||
NoiseComponent.TOTAL ->
|
||||
inputRead[channel].toDouble() + inputShot[channel] * rawSignal
|
||||
NoiseComponent.READ_ONLY -> inputRead[channel].toDouble()
|
||||
}
|
||||
val theoreticalWorkingVariance = rawVariance * wb * wb
|
||||
if (!theoreticalWorkingVariance.isFinite() || theoreticalWorkingVariance <= 0.0 ||
|
||||
!outputVariance[channel].isFinite() || outputVariance[channel] <= 0.0
|
||||
) {
|
||||
return null
|
||||
}
|
||||
outputToTheoreticalInputVarianceRatio[channel] =
|
||||
(outputVariance[channel] / theoreticalWorkingVariance).toFloat()
|
||||
}
|
||||
val normalizedYuvVariance = FloatArray(3) { channel ->
|
||||
(yuvVariance[channel] / ANALYSIS_PIXELS.toDouble()).toFloat()
|
||||
}
|
||||
if (!workingLumaMean.isFinite() || workingLumaMean <= 0.0 ||
|
||||
normalizedYuvVariance.any { !it.isFinite() || it <= 0f }
|
||||
) {
|
||||
return null
|
||||
}
|
||||
return OutputAnalysis(
|
||||
workingLumaMean = workingLumaMean.toFloat(),
|
||||
normalizedYuvVariance = normalizedYuvVariance,
|
||||
outputToTheoreticalInputVarianceRatio = outputToTheoreticalInputVarianceRatio,
|
||||
)
|
||||
}
|
||||
|
||||
private fun fitTransfer(
|
||||
samples: List<NoiseSample>,
|
||||
readSample: NoiseSample,
|
||||
lumaCorrelation: FloatArray,
|
||||
chromaCorrelation: FloatArray,
|
||||
): DemosaicNoiseTransfer? {
|
||||
val fittedRead = readSample.normalizedYuvVariance.copyOf()
|
||||
val fittedShot = FloatArray(3)
|
||||
val fittedQuadratic = FloatArray(3)
|
||||
val fitTerms = Array(3) { "none" }
|
||||
val relativeFitError = FloatArray(3)
|
||||
val signals = samples.map { it.workingLumaMean.toDouble() }.toDoubleArray()
|
||||
for (channel in 0 until 3) {
|
||||
val variances = samples
|
||||
.map { it.normalizedYuvVariance[channel].toDouble() }
|
||||
.toDoubleArray()
|
||||
val fit = fitNonNegativeNoisePolynomial(
|
||||
signals,
|
||||
variances,
|
||||
fixedRead = fittedRead[channel].toDouble(),
|
||||
) ?: return null
|
||||
fittedShot[channel] = fit.shot.toFloat()
|
||||
fittedQuadratic[channel] = fit.quadratic.toFloat()
|
||||
fitTerms[channel] = buildList {
|
||||
if (fit.read > 0.0) add("read")
|
||||
if (fit.shot > 0.0) add("shot")
|
||||
if (fit.quadratic > 0.0) add("quadratic")
|
||||
}.joinToString("+").ifEmpty { "zero" }
|
||||
relativeFitError[channel] = samples.maxOf { sample ->
|
||||
val measured = sample.normalizedYuvVariance[channel].toDouble()
|
||||
val signal = sample.workingLumaMean.toDouble()
|
||||
val predicted = fit.read + fit.shot * signal + fit.quadratic * signal * signal
|
||||
(abs(predicted - measured) / measured.coerceAtLeast(1e-12)).toFloat()
|
||||
}
|
||||
}
|
||||
|
||||
val chromaEnvelopeSignals = DoubleArray(samples.size * 2) { signals[it / 2] }
|
||||
val chromaRequiredSignalVariance = DoubleArray(samples.size * 2) { index ->
|
||||
val sampleIndex = index / 2
|
||||
val channel = 1 + index % 2
|
||||
(samples[sampleIndex].normalizedYuvVariance[channel] - fittedRead[channel])
|
||||
.toDouble()
|
||||
.coerceAtLeast(0.0)
|
||||
}
|
||||
val sharedChromaFit = fitNonUnderestimatingSignalNoisePolynomial(
|
||||
chromaEnvelopeSignals,
|
||||
chromaRequiredSignalVariance,
|
||||
) ?: return null
|
||||
|
||||
val normalizedRead = FloatArray(3) { fittedRead[it] * 4f }
|
||||
val normalizedLumaShot = fittedShot[0] * 2f
|
||||
val normalizedLumaQuadratic = fittedQuadratic[0]
|
||||
val normalizedChromaShot = (sharedChromaFit.shot * 2.0).toFloat()
|
||||
val normalizedChromaQuadratic = sharedChromaFit.quadratic.toFloat()
|
||||
if (normalizedRead.any { !it.isFinite() || it < 0f } ||
|
||||
!normalizedLumaShot.isFinite() || normalizedLumaShot < 0f ||
|
||||
!normalizedLumaQuadratic.isFinite() || normalizedLumaQuadratic < 0f ||
|
||||
!normalizedChromaShot.isFinite() || normalizedChromaShot < 0f ||
|
||||
!normalizedChromaQuadratic.isFinite() || normalizedChromaQuadratic < 0f
|
||||
) {
|
||||
return null
|
||||
}
|
||||
PLog.i(
|
||||
TAG,
|
||||
"Demosaic YUV noise model complete " +
|
||||
"signals=${samples.map(NoiseSample::workingLumaMean)} " +
|
||||
"variance=${samples.map { it.normalizedYuvVariance.contentToString() }} " +
|
||||
"readOnlySignal=${readSample.workingLumaMean} " +
|
||||
"readOnlyVariance=${readSample.normalizedYuvVariance.contentToString()} " +
|
||||
"fitTerms=${fitTerms.contentToString()} " +
|
||||
"fitRead=${fittedRead.contentToString()} " +
|
||||
"fitShot=${fittedShot.contentToString()} " +
|
||||
"fitQuadratic=${fittedQuadratic.contentToString()} " +
|
||||
"fitMaxRelativeError=${relativeFitError.contentToString()} " +
|
||||
"sharedChromaShot=${sharedChromaFit.shot} " +
|
||||
"sharedChromaQuadratic=${sharedChromaFit.quadratic} " +
|
||||
"scale2Read=${normalizedRead.contentToString()} " +
|
||||
"scale2LumaShot=$normalizedLumaShot " +
|
||||
"scale2LumaQuadratic=$normalizedLumaQuadratic " +
|
||||
"scale2ChromaShot=$normalizedChromaShot " +
|
||||
"scale2ChromaQuadratic=$normalizedChromaQuadratic",
|
||||
)
|
||||
return DemosaicNoiseTransfer(
|
||||
normalizedRead = normalizedRead,
|
||||
normalizedLumaShot = normalizedLumaShot,
|
||||
normalizedLumaQuadratic = normalizedLumaQuadratic,
|
||||
normalizedChromaShot = normalizedChromaShot,
|
||||
normalizedChromaQuadratic = normalizedChromaQuadratic,
|
||||
lumaCorrelation = lumaCorrelation,
|
||||
chromaCorrelation = chromaCorrelation,
|
||||
)
|
||||
}
|
||||
|
||||
private fun checkGlError(operation: String) {
|
||||
val error = GLES30.glGetError()
|
||||
check(error == GLES30.GL_NO_ERROR) {
|
||||
"Demosaic noise calibration $operation failed with GL error 0x${error.toString(16)}"
|
||||
}
|
||||
}
|
||||
|
||||
private fun pipelineLabel(cfaPattern: Int): String =
|
||||
if (RawMetadata.isQuadBayer(cfaPattern)) "QUAD_BAYER" else "STANDARD_BAYER_VGN"
|
||||
|
||||
private fun elapsedMs(startNs: Long): Long =
|
||||
(System.nanoTime() - startNs) / 1_000_000L
|
||||
|
||||
private companion object {
|
||||
private const val TAG = "DemosaicNoiseCalibrator"
|
||||
private const val CALIBRATION_SIZE = 256
|
||||
private const val ATLAS_HEIGHT = CALIBRATION_SIZE
|
||||
private const val ANALYSIS_SIZE = 128
|
||||
private const val ANALYSIS_ORIGIN = (CALIBRATION_SIZE - ANALYSIS_SIZE) / 2
|
||||
private const val ANALYSIS_PIXELS = ANALYSIS_SIZE * ANALYSIS_SIZE
|
||||
private const val SPECTRUM_BINS = 128
|
||||
private const val REFERENCE_SIGNAL = 0.18f
|
||||
private val SAMPLE_SPECS = arrayOf(
|
||||
NoiseSampleSpec(0.04f, NoiseComponent.TOTAL, includeCorrelation = false),
|
||||
NoiseSampleSpec(REFERENCE_SIGNAL, NoiseComponent.TOTAL, includeCorrelation = true),
|
||||
NoiseSampleSpec(0.50f, NoiseComponent.TOTAL, includeCorrelation = false),
|
||||
NoiseSampleSpec(REFERENCE_SIGNAL, NoiseComponent.READ_ONLY, includeCorrelation = false),
|
||||
)
|
||||
private val REFERENCE_SIGNALS =
|
||||
FloatArray(SAMPLE_SPECS.size) { SAMPLE_SPECS[it].referenceSignal }
|
||||
private val READ_ONLY_SLOT =
|
||||
SAMPLE_SPECS.indexOfFirst { it.component == NoiseComponent.READ_ONLY }
|
||||
private val ATLAS_WIDTH = CALIBRATION_SIZE * SAMPLE_SPECS.size
|
||||
|
||||
// Must remain bit-exact with mgc_full_resolution_denoise_jni.cpp.
|
||||
private val RGB_TO_YUV = floatArrayOf(
|
||||
0.2125999927520752f,
|
||||
0.7152000069618225f,
|
||||
0.07219959795475006f,
|
||||
-0.16245023906230927f,
|
||||
-0.5464943051338196f,
|
||||
0.7089447379112244f,
|
||||
0.9999967217445374f,
|
||||
-0.9083024859428406f,
|
||||
-0.09169333428144455f,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,6 @@ import android.opengl.EGLDisplay
|
||||
import android.opengl.EGLSurface
|
||||
import android.opengl.GLES30
|
||||
import android.opengl.GLES31
|
||||
import android.util.Half
|
||||
import android.util.Log
|
||||
import androidx.core.graphics.createBitmap
|
||||
import com.hinnka.mycamera.camera.AspectRatio
|
||||
@@ -56,18 +55,13 @@ import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
import java.util.Locale
|
||||
import java.util.concurrent.Executors
|
||||
import kotlin.math.PI
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.ceil
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.exp
|
||||
import kotlin.math.floor
|
||||
import kotlin.math.ln
|
||||
import kotlin.math.max
|
||||
import kotlin.math.min
|
||||
import kotlin.math.pow
|
||||
import kotlin.math.roundToInt
|
||||
import kotlin.math.sin
|
||||
import kotlin.math.sqrt
|
||||
import android.opengl.Matrix as GlMatrix
|
||||
|
||||
@@ -93,28 +87,6 @@ internal enum class MgcSpatialGpuDenoiseMode {
|
||||
BYPASS_DEFAULT_DENOISE,
|
||||
}
|
||||
|
||||
private typealias DemosaicNoiseTransfer = MgcFullResolutionDenoise.PreparedYuvNoiseModel
|
||||
|
||||
private data class DemosaicNoiseSample(
|
||||
val referenceSignal: Float,
|
||||
val workingLumaMean: Float,
|
||||
val normalizedYuvVariance: FloatArray,
|
||||
val lumaCorrelation: FloatArray,
|
||||
val chromaCorrelation: FloatArray,
|
||||
)
|
||||
|
||||
private data class DemosaicNoiseTransferCacheKey(
|
||||
val cfaPattern: Int,
|
||||
val normalizedRgbReadBits: List<Int>,
|
||||
val normalizedRgbShotBits: List<Int>,
|
||||
val calculationWbBits: List<Int>,
|
||||
)
|
||||
|
||||
private enum class DemosaicNoiseComponent {
|
||||
TOTAL,
|
||||
READ_ONLY,
|
||||
}
|
||||
|
||||
/**
|
||||
* RAW 图像解马赛克处理器
|
||||
*
|
||||
@@ -282,31 +254,10 @@ class RawDemosaicProcessor {
|
||||
private const val LINEAR_RAW_RGB_EXPANSION_ROWS = 128
|
||||
private const val RCD_HIGHLIGHT_RECONSTRUCTION_MIN_WB_GAIN = 1e-3f
|
||||
private const val RCD_HIGHLIGHT_RECONSTRUCTION_MAX_WB_GAIN = 64.0f
|
||||
// The calibration field contains a 128x128 analysis core plus enough support for
|
||||
// VGN's 20-pixel halo and the complete color-noise IIR chain on every side.
|
||||
private const val VGN_NOISE_CALIBRATION_SIZE = 256
|
||||
private const val VGN_NOISE_ANALYSIS_SIZE = 128
|
||||
private const val VGN_NOISE_ANALYSIS_ORIGIN =
|
||||
(VGN_NOISE_CALIBRATION_SIZE - VGN_NOISE_ANALYSIS_SIZE) / 2
|
||||
private const val VGN_NOISE_SPECTRUM_BINS = 128
|
||||
private const val VGN_NOISE_REFERENCE_SIGNAL = 0.18f
|
||||
private const val MGC_SIGNAL_LINEAR_HISTOGRAM_BITS = 10
|
||||
private const val MGC_SIGNAL_LINEAR_HISTOGRAM_BINS =
|
||||
1 shl MGC_SIGNAL_LINEAR_HISTOGRAM_BITS
|
||||
private const val MGC_SIGNAL_ROW_STEP = 8
|
||||
private val VGN_NOISE_MODEL_SIGNALS = floatArrayOf(0.04f, 0.18f, 0.50f)
|
||||
// Must remain bit-exact with mgc_full_resolution_denoise_jni.cpp.
|
||||
private val MGC_DENOISE_RGB_TO_YUV = floatArrayOf(
|
||||
0.2125999927520752f,
|
||||
0.7152000069618225f,
|
||||
0.07219959795475006f,
|
||||
-0.16245023906230927f,
|
||||
-0.5464943051338196f,
|
||||
0.7089447379112244f,
|
||||
0.9999967217445374f,
|
||||
-0.9083024859428406f,
|
||||
-0.09169333428144455f,
|
||||
)
|
||||
private const val RAW_TILE_MAX_CORE_EDGE_PX = 3072
|
||||
private const val RAW_PREWARM_CORE_EDGE_PX = 2048
|
||||
// Phocus GetStripMargin(50) returns 60 pixels for gradient/color-noise interpolation.
|
||||
@@ -1132,7 +1083,10 @@ class RawDemosaicProcessor {
|
||||
}
|
||||
if (applyDefaultDenoise) {
|
||||
demosaicNoiseTransfer = checkNotNull(
|
||||
measureDemosaicNoiseTransfer(quadMetadata),
|
||||
demosaicNoisePropagationCalibrator.measure(
|
||||
quadMetadata,
|
||||
demosaicCalculationWbGains(quadMetadata),
|
||||
),
|
||||
) { "Unable to propagate Spatial noise through Quad Bayer demosaic" }
|
||||
}
|
||||
runQuadBayerDemosaic(
|
||||
@@ -1156,7 +1110,10 @@ class RawDemosaicProcessor {
|
||||
}
|
||||
if (applyDefaultDenoise) {
|
||||
demosaicNoiseTransfer = checkNotNull(
|
||||
measureDemosaicNoiseTransfer(vgnMetadata),
|
||||
demosaicNoisePropagationCalibrator.measure(
|
||||
vgnMetadata,
|
||||
demosaicCalculationWbGains(vgnMetadata),
|
||||
),
|
||||
) { "Unable to propagate Spatial noise through VGN" }
|
||||
}
|
||||
runStandardBayerVgnDemosaic(
|
||||
@@ -1210,7 +1167,10 @@ class RawDemosaicProcessor {
|
||||
}
|
||||
if (applyDefaultDenoise) {
|
||||
demosaicNoiseTransfer = checkNotNull(
|
||||
measureDemosaicNoiseTransfer(quadMetadata),
|
||||
demosaicNoisePropagationCalibrator.measure(
|
||||
quadMetadata,
|
||||
demosaicCalculationWbGains(quadMetadata),
|
||||
),
|
||||
) { "Unable to propagate Spatial noise through Quad Bayer demosaic" }
|
||||
}
|
||||
runQuadBayerDemosaic(
|
||||
@@ -1243,7 +1203,10 @@ class RawDemosaicProcessor {
|
||||
}
|
||||
if (applyDefaultDenoise) {
|
||||
demosaicNoiseTransfer = checkNotNull(
|
||||
measureDemosaicNoiseTransfer(vgnMetadata),
|
||||
demosaicNoisePropagationCalibrator.measure(
|
||||
vgnMetadata,
|
||||
demosaicCalculationWbGains(vgnMetadata),
|
||||
),
|
||||
) { "Unable to propagate Spatial noise through VGN" }
|
||||
}
|
||||
runStandardBayerVgnDemosaic(
|
||||
@@ -1562,6 +1525,37 @@ class RawDemosaicProcessor {
|
||||
private val meteringDemosaicAlgorithm = RawMeteringDemosaicAlgorithm()
|
||||
private val quadBayerDemosaicAlgorithm = QuadBayerDemosaicAlgorithm()
|
||||
private val vgnDemosaicAlgorithm = VgnDemosaicAlgorithm()
|
||||
private val demosaicNoisePropagationCalibrator = DemosaicNoisePropagationCalibrator(
|
||||
initializePipeline = { cfaPattern ->
|
||||
if (RawMetadata.isQuadBayer(cfaPattern)) {
|
||||
ensureQuadBayerPrograms()
|
||||
} else {
|
||||
ensureVgnPrograms()
|
||||
}
|
||||
},
|
||||
renderDemosaic = { request ->
|
||||
if (RawMetadata.isQuadBayer(request.metadata.cfaPattern)) {
|
||||
runQuadBayerDemosaic(
|
||||
metadata = request.metadata,
|
||||
width = request.width,
|
||||
height = request.height,
|
||||
highlightReconstructionEnabled = false,
|
||||
rawInputTextureId = request.rawTextureId,
|
||||
outputTargetTextureId = request.outputTextureId,
|
||||
)
|
||||
} else {
|
||||
runStandardBayerVgnDemosaic(
|
||||
metadata = request.metadata,
|
||||
width = request.width,
|
||||
height = request.height,
|
||||
highlightReconstructionEnabled = false,
|
||||
rawInputTextureId = request.rawTextureId,
|
||||
linearOutputTargetTextureId = request.linearOutputTextureId,
|
||||
outputTargetTextureId = request.outputTextureId,
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
private var rawTextureId = 0
|
||||
private var rawTileTextureWidth = 0
|
||||
@@ -1612,8 +1606,6 @@ class RawDemosaicProcessor {
|
||||
private var readbackPboSize = 0
|
||||
private var readbackBuffer: ByteBuffer? = null
|
||||
private var readbackBufferSize = 0
|
||||
private var userAdjustmentNoiseTransferCacheKey: DemosaicNoiseTransferCacheKey? = null
|
||||
private var userAdjustmentNoiseTransferCacheValue: DemosaicNoiseTransfer? = null
|
||||
|
||||
// denoiseprofile 中间纹理: ping-pong (RGBA16F)
|
||||
private var gfTexId = intArrayOf(0, 0)
|
||||
@@ -2964,7 +2956,10 @@ class RawDemosaicProcessor {
|
||||
val rawDomainHighlightReconstructionEnabled = true
|
||||
if (!captureProfilePreparationRequested && userAdjustmentDenoiseEnabled) {
|
||||
userAdjustmentNoiseTransfer =
|
||||
prepareUserAdjustmentNoiseTransfer(actualMetadata)
|
||||
demosaicNoisePropagationCalibrator.prepareUserAdjustment(
|
||||
actualMetadata,
|
||||
demosaicCalculationWbGains(actualMetadata),
|
||||
)
|
||||
}
|
||||
PLog.i(
|
||||
TAG,
|
||||
@@ -3605,10 +3600,19 @@ class RawDemosaicProcessor {
|
||||
|
||||
var completed = false
|
||||
var userAdjustmentNoiseTransfer: DemosaicNoiseTransfer? = null
|
||||
var userAdjustmentNoiseTransferPrepared = false
|
||||
val userAdjustmentDenoiseEnabled =
|
||||
(config.denoiseValue ?: 0f) > 0f || (config.chromaDenoiseValue ?: 0f) > 0f
|
||||
try {
|
||||
if (userAdjustmentDenoiseEnabled && config.samplesPerPixel == 1) {
|
||||
// The calibration atlas runs once. Do not retain its 1024x256 intermediates in
|
||||
// the full-size tile pool for the remainder of this render.
|
||||
vgnDemosaicAlgorithm.setTileTexturePoolingEnabled(false)
|
||||
userAdjustmentNoiseTransfer =
|
||||
demosaicNoisePropagationCalibrator.prepareUserAdjustment(
|
||||
config.metadata,
|
||||
demosaicCalculationWbGains(config.metadata),
|
||||
)
|
||||
}
|
||||
vgnDemosaicAlgorithm.setTileTexturePoolingEnabled(true)
|
||||
setupOutputFramebuffer(maximumOutputWidth, maximumOutputHeight)
|
||||
|
||||
@@ -3625,13 +3629,6 @@ class RawDemosaicProcessor {
|
||||
samplesPerPixel = config.samplesPerPixel,
|
||||
)
|
||||
setupFullResFramebuffer(workWidth, workHeight)
|
||||
if (!userAdjustmentNoiseTransferPrepared &&
|
||||
userAdjustmentDenoiseEnabled && config.samplesPerPixel == 1
|
||||
) {
|
||||
userAdjustmentNoiseTransfer =
|
||||
prepareUserAdjustmentNoiseTransfer(config.metadata)
|
||||
userAdjustmentNoiseTransferPrepared = true
|
||||
}
|
||||
|
||||
when {
|
||||
config.samplesPerPixel in 3..4 -> {
|
||||
@@ -4632,7 +4629,11 @@ class RawDemosaicProcessor {
|
||||
"luma=$lumaEnabled($lumaStrength) " +
|
||||
"chroma=$chromaEnabled($chromaStrength) " +
|
||||
"noiseTransfer=${demosaicNoiseTransfer?.let {
|
||||
demosaicNoisePipelineLabel(metadata.cfaPattern)
|
||||
if (RawMetadata.isQuadBayer(metadata.cfaPattern)) {
|
||||
"QUAD_BAYER"
|
||||
} else {
|
||||
"STANDARD_BAYER_VGN"
|
||||
}
|
||||
} ?: "identity"} " +
|
||||
"lscStrength=${lensShadingLogString(metadata)} " +
|
||||
"readbackMs=${(nativeStartNs - readbackStartNs) / 1_000_000L} " +
|
||||
@@ -5403,543 +5404,6 @@ class RawDemosaicProcessor {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the physical single-frame model consumed by USER_ADJUSTMENT after demosaic.
|
||||
* Sensor samples start with an identity power spectrum; the measured demosaic transfer
|
||||
* supplies the Y/Cb/Cr coefficients and separate luma/chroma correlations seen by the
|
||||
* full-resolution denoiser.
|
||||
*/
|
||||
private fun prepareUserAdjustmentNoiseTransfer(
|
||||
metadata: RawMetadata,
|
||||
): DemosaicNoiseTransfer? {
|
||||
val rgbNoise = MgcFullResolutionDenoise.resolveUserAdjustmentCameraRgbNoise(metadata)
|
||||
?: return null
|
||||
val calculationWb = demosaicCalculationWbGains(metadata)
|
||||
val cacheKey = DemosaicNoiseTransferCacheKey(
|
||||
cfaPattern = metadata.cfaPattern,
|
||||
normalizedRgbReadBits = rgbNoise.read.map { it.toBits() },
|
||||
normalizedRgbShotBits = rgbNoise.shot.map { it.toBits() },
|
||||
calculationWbBits = calculationWb.map { it.toBits() },
|
||||
)
|
||||
if (cacheKey == userAdjustmentNoiseTransferCacheKey) {
|
||||
return userAdjustmentNoiseTransferCacheValue
|
||||
}
|
||||
val propagationMetadata = metadata.copy(
|
||||
frameCount = 1,
|
||||
mgcDenoiseReadNoise = rgbNoise.read,
|
||||
mgcDenoiseShotNoise = rgbNoise.shot,
|
||||
mgcDenoiseCorrelation = FloatArray(VGN_NOISE_SPECTRUM_BINS) { 1f },
|
||||
mgcSpatialStrengthMap = null,
|
||||
)
|
||||
val transfer = measureDemosaicNoiseTransfer(propagationMetadata)
|
||||
if (transfer != null) {
|
||||
userAdjustmentNoiseTransferCacheKey = cacheKey
|
||||
userAdjustmentNoiseTransferCacheValue = transfer
|
||||
PLog.i(
|
||||
TAG,
|
||||
"MGC USER_ADJUSTMENT noise propagation ready " +
|
||||
"pipeline=${demosaicNoisePipelineLabel(metadata.cfaPattern)} " +
|
||||
"lumaCorrelation=${transfer.lumaCorrelation.minOrNull()}.." +
|
||||
"${transfer.lumaCorrelation.maxOrNull()}/" +
|
||||
"${transfer.lumaCorrelation.average()} " +
|
||||
"chromaCorrelation=${transfer.chromaCorrelation.minOrNull()}.." +
|
||||
"${transfer.chromaCorrelation.maxOrNull()}/" +
|
||||
transfer.chromaCorrelation.average(),
|
||||
)
|
||||
}
|
||||
return transfer
|
||||
}
|
||||
|
||||
/**
|
||||
* Measures the small-signal noise transfer of the exact demosaic pipeline used for this
|
||||
* capture. Standard Bayer runs VGN; expanded Bayer runs the Quad Bayer compute chain.
|
||||
*
|
||||
* Neutral flat fields at several signal levels are populated with independent Bayer noise
|
||||
* using the input noise model and the current calculation WB. Their exact demosaic outputs are
|
||||
* transformed to MGC YUV before fitting
|
||||
* variance = read + shot * luma + quadratic * luma^2. The quadratic term is required because
|
||||
* VGN's content-adaptive interpolation makes chroma variance visibly convex with signal.
|
||||
* The reference field also supplies separate luma and combined-chroma one-dimensional power
|
||||
* correlation spectra composed with the input spectrum.
|
||||
*/
|
||||
private fun measureDemosaicNoiseTransfer(
|
||||
metadata: RawMetadata,
|
||||
): DemosaicNoiseTransfer? {
|
||||
val samples = VGN_NOISE_MODEL_SIGNALS.map { referenceSignal ->
|
||||
measureDemosaicNoiseSample(
|
||||
metadata,
|
||||
referenceSignal,
|
||||
DemosaicNoiseComponent.TOTAL,
|
||||
) ?: return null
|
||||
}
|
||||
val referenceSample = samples.minBy { sample ->
|
||||
abs(sample.referenceSignal - VGN_NOISE_REFERENCE_SIGNAL)
|
||||
}
|
||||
// ChromaDenoisePyramidComplete retains separate Y/Cb/Cr read tables, but its generated
|
||||
// ABI accepts one shared shot/quadratic curve for Cb and Cr. Measure the constant terms
|
||||
// directly, then fit the tightest shared chroma curve that never underestimates either
|
||||
// chroma channel at a calibration signal.
|
||||
val readSample = measureDemosaicNoiseSample(
|
||||
metadata,
|
||||
VGN_NOISE_REFERENCE_SIGNAL,
|
||||
DemosaicNoiseComponent.READ_ONLY,
|
||||
) ?: return null
|
||||
val fittedRead = readSample.normalizedYuvVariance.copyOf()
|
||||
val fittedShot = FloatArray(3)
|
||||
val fittedQuadratic = FloatArray(3)
|
||||
val fitTerms = Array(3) { "none" }
|
||||
val relativeFitError = FloatArray(3)
|
||||
val signals = samples.map { it.workingLumaMean.toDouble() }.toDoubleArray()
|
||||
for (channel in 0 until 3) {
|
||||
val variances = samples
|
||||
.map { it.normalizedYuvVariance[channel].toDouble() }
|
||||
.toDoubleArray()
|
||||
val fit = fitNonNegativeNoisePolynomial(
|
||||
signals,
|
||||
variances,
|
||||
fixedRead = fittedRead[channel].toDouble(),
|
||||
) ?: return null
|
||||
fittedShot[channel] = fit.shot.toFloat()
|
||||
fittedQuadratic[channel] = fit.quadratic.toFloat()
|
||||
fitTerms[channel] = buildList {
|
||||
if (fit.read > 0.0) add("read")
|
||||
if (fit.shot > 0.0) add("shot")
|
||||
if (fit.quadratic > 0.0) add("quadratic")
|
||||
}.joinToString("+").ifEmpty { "zero" }
|
||||
relativeFitError[channel] = samples.maxOf { sample ->
|
||||
val measured = sample.normalizedYuvVariance[channel].toDouble()
|
||||
val signal = sample.workingLumaMean.toDouble()
|
||||
val predicted = fit.read + fit.shot * signal +
|
||||
fit.quadratic * signal * signal
|
||||
(abs(predicted - measured) / measured.coerceAtLeast(1e-12)).toFloat()
|
||||
}
|
||||
}
|
||||
|
||||
val chromaEnvelopeSignals = DoubleArray(samples.size * 2) { index ->
|
||||
signals[index / 2]
|
||||
}
|
||||
val chromaRequiredSignalVariance = DoubleArray(samples.size * 2) { index ->
|
||||
val sampleIndex = index / 2
|
||||
val channel = 1 + index % 2
|
||||
(
|
||||
samples[sampleIndex].normalizedYuvVariance[channel] - fittedRead[channel]
|
||||
).toDouble().coerceAtLeast(0.0)
|
||||
}
|
||||
val sharedChromaFit = fitNonUnderestimatingSignalNoisePolynomial(
|
||||
chromaEnvelopeSignals,
|
||||
chromaRequiredSignalVariance,
|
||||
) ?: return null
|
||||
|
||||
// The fitted coefficients are in VGN's white-balanced camera-RGB/YUV signal domain.
|
||||
// MGC's full-resolution model applies x' = 2x, hence read' = 4*read and
|
||||
// shot' = 2*shot, while the dimensionless quadratic term is unchanged. Correlation is a
|
||||
// unit-mean shape input and does not rescale these independently measured coefficients.
|
||||
val normalizedRead = FloatArray(3) { channel ->
|
||||
fittedRead[channel] * 4f
|
||||
}
|
||||
val normalizedLumaShot = fittedShot[0] * 2f
|
||||
val normalizedLumaQuadratic = fittedQuadratic[0]
|
||||
val normalizedChromaShot = (sharedChromaFit.shot * 2.0).toFloat()
|
||||
val normalizedChromaQuadratic = sharedChromaFit.quadratic.toFloat()
|
||||
if (normalizedRead.any { !it.isFinite() || it < 0f } ||
|
||||
!normalizedLumaShot.isFinite() || normalizedLumaShot < 0f ||
|
||||
!normalizedLumaQuadratic.isFinite() || normalizedLumaQuadratic < 0f ||
|
||||
!normalizedChromaShot.isFinite() || normalizedChromaShot < 0f ||
|
||||
!normalizedChromaQuadratic.isFinite() || normalizedChromaQuadratic < 0f
|
||||
) {
|
||||
return null
|
||||
}
|
||||
PLog.i(
|
||||
TAG,
|
||||
"Demosaic YUV noise model complete " +
|
||||
"pipeline=${demosaicNoisePipelineLabel(metadata.cfaPattern)} " +
|
||||
"signals=${samples.map(DemosaicNoiseSample::workingLumaMean)} " +
|
||||
"variance=${samples.map { it.normalizedYuvVariance.contentToString() }} " +
|
||||
"readOnlySignal=${readSample.workingLumaMean} " +
|
||||
"readOnlyVariance=${readSample.normalizedYuvVariance.contentToString()} " +
|
||||
"fitTerms=${fitTerms.contentToString()} " +
|
||||
"fitRead=${fittedRead.contentToString()} " +
|
||||
"fitShot=${fittedShot.contentToString()} " +
|
||||
"fitQuadratic=${fittedQuadratic.contentToString()} " +
|
||||
"fitMaxRelativeError=${relativeFitError.contentToString()} " +
|
||||
"sharedChromaShot=${sharedChromaFit.shot} " +
|
||||
"sharedChromaQuadratic=${sharedChromaFit.quadratic} " +
|
||||
"scale2Read=${normalizedRead.contentToString()} " +
|
||||
"scale2LumaShot=$normalizedLumaShot " +
|
||||
"scale2LumaQuadratic=$normalizedLumaQuadratic " +
|
||||
"scale2ChromaShot=$normalizedChromaShot " +
|
||||
"scale2ChromaQuadratic=$normalizedChromaQuadratic",
|
||||
)
|
||||
return MgcFullResolutionDenoise.PreparedYuvNoiseModel(
|
||||
normalizedRead = normalizedRead,
|
||||
normalizedLumaShot = normalizedLumaShot,
|
||||
normalizedLumaQuadratic = normalizedLumaQuadratic,
|
||||
normalizedChromaShot = normalizedChromaShot,
|
||||
normalizedChromaQuadratic = normalizedChromaQuadratic,
|
||||
lumaCorrelation = referenceSample.lumaCorrelation,
|
||||
chromaCorrelation = referenceSample.chromaCorrelation,
|
||||
)
|
||||
}
|
||||
|
||||
private fun measureDemosaicNoiseSample(
|
||||
metadata: RawMetadata,
|
||||
referenceSignal: Float,
|
||||
component: DemosaicNoiseComponent,
|
||||
): DemosaicNoiseSample? {
|
||||
val inputRead = metadata.mgcDenoiseReadNoise
|
||||
val inputShot = metadata.mgcDenoiseShotNoise
|
||||
val inputCorrelation = metadata.mgcDenoiseCorrelation
|
||||
if (inputRead?.size != 3 || inputShot?.size != 3 ||
|
||||
inputCorrelation?.size != VGN_NOISE_SPECTRUM_BINS ||
|
||||
inputRead.any { !it.isFinite() || it < 0f } ||
|
||||
inputShot.any { !it.isFinite() || it < 0f } ||
|
||||
inputCorrelation.any { !it.isFinite() || it < 0f }
|
||||
) {
|
||||
return null
|
||||
}
|
||||
val calculationWb4 = demosaicCalculationWbGains(metadata)
|
||||
val calculationWb = floatArrayOf(calculationWb4[0], 1f, calculationWb4[3])
|
||||
val savedDemosaicWidth = demosaicWidth
|
||||
val savedDemosaicHeight = demosaicHeight
|
||||
val calibrationPixels = VGN_NOISE_CALIBRATION_SIZE * VGN_NOISE_CALIBRATION_SIZE
|
||||
val syntheticRaw = LargeDirectBuffer.allocate(
|
||||
calibrationPixels.toLong() * Short.SIZE_BYTES,
|
||||
"Demosaic noise propagation Bayer field",
|
||||
)?.order(ByteOrder.nativeOrder()) ?: return null
|
||||
val rgba = LargeDirectBuffer.allocate(
|
||||
calibrationPixels.toLong() * 4 * Short.SIZE_BYTES,
|
||||
"Demosaic noise propagation RGBA16F",
|
||||
)?.order(ByteOrder.nativeOrder()) ?: run {
|
||||
LargeDirectBuffer.free(syntheticRaw)
|
||||
return null
|
||||
}
|
||||
|
||||
val inputNoiseSum = DoubleArray(3)
|
||||
val inputNoiseSquareSum = DoubleArray(3)
|
||||
val inputNoiseCount = IntArray(3)
|
||||
var randomState = 0x4d595df4d0f33173L
|
||||
var spareGaussian = 0.0
|
||||
var hasSpareGaussian = false
|
||||
fun nextUniform(): Double {
|
||||
randomState = randomState xor (randomState shl 13)
|
||||
randomState = randomState xor (randomState ushr 7)
|
||||
randomState = randomState xor (randomState shl 17)
|
||||
return ((randomState ushr 11).toDouble() + 0.5) /
|
||||
(1L shl 53).toDouble()
|
||||
}
|
||||
fun nextGaussian(): Double {
|
||||
if (hasSpareGaussian) {
|
||||
hasSpareGaussian = false
|
||||
return spareGaussian
|
||||
}
|
||||
val radius = sqrt(-2.0 * ln(nextUniform().coerceAtLeast(1e-12)))
|
||||
val angle = 2.0 * PI * nextUniform()
|
||||
spareGaussian = radius * sin(angle)
|
||||
hasSpareGaussian = true
|
||||
return radius * cos(angle)
|
||||
}
|
||||
|
||||
val savedRawTextureId = rawTextureId
|
||||
var syntheticTextureId = 0
|
||||
try {
|
||||
syntheticRaw.clear()
|
||||
for (y in 0 until VGN_NOISE_CALIBRATION_SIZE) {
|
||||
for (x in 0 until VGN_NOISE_CALIBRATION_SIZE) {
|
||||
val canonical = RawCfaCorrection.channelIndexForPixel(
|
||||
metadata.cfaPattern,
|
||||
x,
|
||||
y,
|
||||
)
|
||||
val rgbChannel = when (canonical) {
|
||||
0 -> 0
|
||||
3 -> 2
|
||||
else -> 1
|
||||
}
|
||||
val gain = calculationWb[rgbChannel].coerceAtLeast(1e-6f)
|
||||
val rawSignal = referenceSignal / gain
|
||||
val variance = when (component) {
|
||||
DemosaicNoiseComponent.TOTAL ->
|
||||
inputRead[rgbChannel] + inputShot[rgbChannel] * rawSignal
|
||||
DemosaicNoiseComponent.READ_ONLY -> inputRead[rgbChannel]
|
||||
}.coerceAtLeast(0f)
|
||||
val noisy = (
|
||||
rawSignal + sqrt(variance.toDouble()) * nextGaussian()
|
||||
).coerceIn(0.0, 1.0)
|
||||
val quantized = (noisy * 65535.0).roundToInt().coerceIn(0, 65535)
|
||||
syntheticRaw.putShort(quantized.toShort())
|
||||
val workingNoise =
|
||||
(quantized.toDouble() / 65535.0 - rawSignal) * gain
|
||||
inputNoiseSum[rgbChannel] += workingNoise
|
||||
inputNoiseSquareSum[rgbChannel] += workingNoise * workingNoise
|
||||
inputNoiseCount[rgbChannel]++
|
||||
}
|
||||
}
|
||||
syntheticRaw.flip()
|
||||
|
||||
val calibrationMetadata = metadata.copy(
|
||||
width = VGN_NOISE_CALIBRATION_SIZE,
|
||||
height = VGN_NOISE_CALIBRATION_SIZE,
|
||||
// inputRead/inputShot are already Spatial's merged-output coefficients.
|
||||
// VGN's threshold resolver divides a per-frame profile by frameCount, so this
|
||||
// synthetic output frame must be declared as one frame or the model is reduced
|
||||
// by the burst count for a second time.
|
||||
frameCount = 1,
|
||||
blackLevel = FloatArray(4),
|
||||
whiteLevel = 65535f,
|
||||
lensShadingMap = null,
|
||||
lensShadingMapWidth = 0,
|
||||
lensShadingMapHeight = 0,
|
||||
lensShadingMapGrid = null,
|
||||
channelNoiseProfile = floatArrayOf(
|
||||
inputShot[0], inputRead[0],
|
||||
inputShot[1], inputRead[1],
|
||||
inputShot[2], inputRead[2],
|
||||
),
|
||||
noiseProfileLayout = RawNoiseProfileLayout.DNG_RGB,
|
||||
)
|
||||
rawTextureId = 0
|
||||
uploadRawTextureFromBuffer(
|
||||
buffer = syntheticRaw,
|
||||
width = VGN_NOISE_CALIBRATION_SIZE,
|
||||
height = VGN_NOISE_CALIBRATION_SIZE,
|
||||
rowStride = VGN_NOISE_CALIBRATION_SIZE * Short.SIZE_BYTES,
|
||||
)
|
||||
syntheticTextureId = rawTextureId
|
||||
setupFullResFramebuffer(VGN_NOISE_CALIBRATION_SIZE, VGN_NOISE_CALIBRATION_SIZE)
|
||||
when {
|
||||
RawMetadata.isQuadBayer(calibrationMetadata.cfaPattern) -> {
|
||||
check(ensureQuadBayerPrograms()) {
|
||||
"Unable to initialize Quad Bayer noise propagation programs"
|
||||
}
|
||||
runQuadBayerDemosaic(
|
||||
metadata = calibrationMetadata,
|
||||
width = VGN_NOISE_CALIBRATION_SIZE,
|
||||
height = VGN_NOISE_CALIBRATION_SIZE,
|
||||
highlightReconstructionEnabled = false,
|
||||
)
|
||||
}
|
||||
|
||||
else -> {
|
||||
check(ensureVgnPrograms()) {
|
||||
"Unable to initialize VGN noise propagation programs"
|
||||
}
|
||||
runStandardBayerVgnDemosaic(
|
||||
metadata = calibrationMetadata,
|
||||
width = VGN_NOISE_CALIBRATION_SIZE,
|
||||
height = VGN_NOISE_CALIBRATION_SIZE,
|
||||
highlightReconstructionEnabled = false,
|
||||
)
|
||||
}
|
||||
}
|
||||
GLES30.glBindBuffer(GLES30.GL_PIXEL_PACK_BUFFER, 0)
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, demosaicFramebufferId)
|
||||
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 8)
|
||||
rgba.clear()
|
||||
GLES30.glReadPixels(
|
||||
0,
|
||||
0,
|
||||
VGN_NOISE_CALIBRATION_SIZE,
|
||||
VGN_NOISE_CALIBRATION_SIZE,
|
||||
GLES30.GL_RGBA,
|
||||
GLES30.GL_HALF_FLOAT,
|
||||
rgba,
|
||||
)
|
||||
checkGlError("Demosaic noise propagation readback")
|
||||
|
||||
val analysisSamples = VGN_NOISE_ANALYSIS_SIZE * VGN_NOISE_ANALYSIS_SIZE
|
||||
val workingRgb = Array(3) { FloatArray(analysisSamples) }
|
||||
val mean = DoubleArray(3)
|
||||
var sample = 0
|
||||
for (y in 0 until VGN_NOISE_ANALYSIS_SIZE) {
|
||||
val sourceY = VGN_NOISE_ANALYSIS_ORIGIN + y
|
||||
for (x in 0 until VGN_NOISE_ANALYSIS_SIZE) {
|
||||
val sourceX = VGN_NOISE_ANALYSIS_ORIGIN + x
|
||||
val pixelOffset = (
|
||||
sourceY * VGN_NOISE_CALIBRATION_SIZE + sourceX
|
||||
) * 4 * Short.SIZE_BYTES
|
||||
for (channel in 0 until 3) {
|
||||
val value = Half.toFloat(
|
||||
rgba.getShort(pixelOffset + channel * Short.SIZE_BYTES),
|
||||
) * calculationWb[channel]
|
||||
workingRgb[channel][sample] = value
|
||||
mean[channel] += value
|
||||
}
|
||||
sample++
|
||||
}
|
||||
}
|
||||
for (channel in 0 until 3) mean[channel] /= analysisSamples.toDouble()
|
||||
val workingYuvMean = DoubleArray(3) { outputChannel ->
|
||||
var value = 0.0
|
||||
for (inputChannel in 0 until 3) {
|
||||
value += MGC_DENOISE_RGB_TO_YUV[outputChannel * 3 + inputChannel] *
|
||||
mean[inputChannel]
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
val outputVariance = DoubleArray(3)
|
||||
val yuvVariance = DoubleArray(3)
|
||||
val yuvResidual = Array(3) { FloatArray(analysisSamples) }
|
||||
for (index in 0 until analysisSamples) {
|
||||
val red = workingRgb[0][index] - mean[0].toFloat()
|
||||
val green = workingRgb[1][index] - mean[1].toFloat()
|
||||
val blue = workingRgb[2][index] - mean[2].toFloat()
|
||||
outputVariance[0] += red * red
|
||||
outputVariance[1] += green * green
|
||||
outputVariance[2] += blue * blue
|
||||
for (outputChannel in 0 until 3) {
|
||||
val offset = outputChannel * 3
|
||||
val residual =
|
||||
MGC_DENOISE_RGB_TO_YUV[offset] * red +
|
||||
MGC_DENOISE_RGB_TO_YUV[offset + 1] * green +
|
||||
MGC_DENOISE_RGB_TO_YUV[offset + 2] * blue
|
||||
yuvVariance[outputChannel] += residual * residual
|
||||
yuvResidual[outputChannel][index] = residual
|
||||
}
|
||||
}
|
||||
val rgbVarianceScale = FloatArray(3)
|
||||
for (channel in 0 until 3) {
|
||||
outputVariance[channel] /= analysisSamples.toDouble()
|
||||
val count = inputNoiseCount[channel].coerceAtLeast(1).toDouble()
|
||||
val inputMean = inputNoiseSum[channel] / count
|
||||
val inputVariance =
|
||||
inputNoiseSquareSum[channel] / count - inputMean * inputMean
|
||||
if (!inputVariance.isFinite() || inputVariance <= 0.0 ||
|
||||
!outputVariance[channel].isFinite() || outputVariance[channel] <= 0.0
|
||||
) {
|
||||
return null
|
||||
}
|
||||
rgbVarianceScale[channel] =
|
||||
(outputVariance[channel] / inputVariance).toFloat()
|
||||
}
|
||||
val normalizedYuvVariance = FloatArray(3) { channel ->
|
||||
(yuvVariance[channel] / analysisSamples.toDouble()).toFloat()
|
||||
}
|
||||
if (!workingYuvMean[0].isFinite() || workingYuvMean[0] <= 0.0 ||
|
||||
normalizedYuvVariance.any { !it.isFinite() || it <= 0f }
|
||||
) {
|
||||
return null
|
||||
}
|
||||
|
||||
val cosine = Array(VGN_NOISE_SPECTRUM_BINS) {
|
||||
FloatArray(VGN_NOISE_ANALYSIS_SIZE)
|
||||
}
|
||||
val sine = Array(VGN_NOISE_SPECTRUM_BINS) {
|
||||
FloatArray(VGN_NOISE_ANALYSIS_SIZE)
|
||||
}
|
||||
for (bin in 0 until VGN_NOISE_SPECTRUM_BINS) {
|
||||
val omega = (bin + 0.5) * 2.0 * PI / VGN_NOISE_SPECTRUM_BINS - PI
|
||||
for (position in 0 until VGN_NOISE_ANALYSIS_SIZE) {
|
||||
cosine[bin][position] = cos(omega * position).toFloat()
|
||||
sine[bin][position] = sin(omega * position).toFloat()
|
||||
}
|
||||
}
|
||||
fun propagatedCorrelation(channels: IntArray): FloatArray? {
|
||||
val demosaicPower = DoubleArray(VGN_NOISE_SPECTRUM_BINS)
|
||||
for (bin in 0 until VGN_NOISE_SPECTRUM_BINS) {
|
||||
var accumulatedPower = 0.0
|
||||
for (channel in channels) {
|
||||
val residual = yuvResidual[channel]
|
||||
for (line in 0 until VGN_NOISE_ANALYSIS_SIZE) {
|
||||
var horizontalReal = 0.0
|
||||
var horizontalImaginary = 0.0
|
||||
var verticalReal = 0.0
|
||||
var verticalImaginary = 0.0
|
||||
for (position in 0 until VGN_NOISE_ANALYSIS_SIZE) {
|
||||
val horizontal = residual[
|
||||
line * VGN_NOISE_ANALYSIS_SIZE + position
|
||||
]
|
||||
val vertical = residual[
|
||||
position * VGN_NOISE_ANALYSIS_SIZE + line
|
||||
]
|
||||
val real = cosine[bin][position]
|
||||
val imaginary = sine[bin][position]
|
||||
horizontalReal += horizontal * real
|
||||
horizontalImaginary -= horizontal * imaginary
|
||||
verticalReal += vertical * real
|
||||
verticalImaginary -= vertical * imaginary
|
||||
}
|
||||
accumulatedPower +=
|
||||
horizontalReal * horizontalReal +
|
||||
horizontalImaginary * horizontalImaginary +
|
||||
verticalReal * verticalReal +
|
||||
verticalImaginary * verticalImaginary
|
||||
}
|
||||
}
|
||||
demosaicPower[bin] = accumulatedPower /
|
||||
(2.0 * VGN_NOISE_ANALYSIS_SIZE * VGN_NOISE_ANALYSIS_SIZE)
|
||||
}
|
||||
val demosaicPowerMean = demosaicPower.average()
|
||||
if (!demosaicPowerMean.isFinite() || demosaicPowerMean <= 0.0) return null
|
||||
val composed = DoubleArray(VGN_NOISE_SPECTRUM_BINS) { index ->
|
||||
inputCorrelation[index].toDouble() *
|
||||
(demosaicPower[index] / demosaicPowerMean)
|
||||
}
|
||||
val compositionMean = composed.average()
|
||||
if (!compositionMean.isFinite() || compositionMean <= 0.0) return null
|
||||
return FloatArray(VGN_NOISE_SPECTRUM_BINS) { index ->
|
||||
(composed[index] / compositionMean).toFloat()
|
||||
}.takeIf { spectrum ->
|
||||
spectrum.all { it.isFinite() && it >= 0f }
|
||||
}
|
||||
}
|
||||
|
||||
val lumaCorrelation = propagatedCorrelation(intArrayOf(0)) ?: return null
|
||||
// The native chroma ABI uses one shared shot/quadratic curve and one spectrum.
|
||||
// Summed Cb+Cr power gives that spectrum the same variance weighting as the curve.
|
||||
val chromaCorrelation = propagatedCorrelation(intArrayOf(1, 2)) ?: return null
|
||||
val lumaCorrelationMin = lumaCorrelation.minOrNull() ?: 0f
|
||||
val lumaCorrelationMax = lumaCorrelation.maxOrNull() ?: 0f
|
||||
val chromaCorrelationMin = chromaCorrelation.minOrNull() ?: 0f
|
||||
val chromaCorrelationMax = chromaCorrelation.maxOrNull() ?: 0f
|
||||
PLog.i(
|
||||
TAG,
|
||||
"Demosaic noise propagation complete " +
|
||||
"pipeline=${demosaicNoisePipelineLabel(metadata.cfaPattern)} " +
|
||||
"component=$component " +
|
||||
"size=${VGN_NOISE_CALIBRATION_SIZE}x$VGN_NOISE_CALIBRATION_SIZE " +
|
||||
"reference=$referenceSignal " +
|
||||
"workingLumaMean=${workingYuvMean[0]} " +
|
||||
"normalizedYuvVariance=${normalizedYuvVariance.contentToString()} " +
|
||||
"measuredPointVarianceRatio=${rgbVarianceScale.contentToString()} " +
|
||||
"lumaCorrelation=$lumaCorrelationMin..$lumaCorrelationMax/" +
|
||||
"${lumaCorrelation.average()} " +
|
||||
"chromaCorrelation=$chromaCorrelationMin..$chromaCorrelationMax/" +
|
||||
chromaCorrelation.average(),
|
||||
)
|
||||
return DemosaicNoiseSample(
|
||||
referenceSignal = referenceSignal,
|
||||
workingLumaMean = workingYuvMean[0].toFloat(),
|
||||
normalizedYuvVariance = normalizedYuvVariance,
|
||||
lumaCorrelation = lumaCorrelation,
|
||||
chromaCorrelation = chromaCorrelation,
|
||||
)
|
||||
} catch (error: Exception) {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"${demosaicNoisePipelineLabel(metadata.cfaPattern)} noise propagation failed",
|
||||
error,
|
||||
)
|
||||
return null
|
||||
} finally {
|
||||
GLES30.glPixelStorei(GLES30.GL_PACK_ALIGNMENT, 1)
|
||||
if (syntheticTextureId != 0) {
|
||||
GLES30.glDeleteTextures(1, intArrayOf(syntheticTextureId), 0)
|
||||
}
|
||||
rawTextureId = savedRawTextureId
|
||||
if (savedDemosaicWidth > 0 && savedDemosaicHeight > 0) {
|
||||
setupFullResFramebuffer(savedDemosaicWidth, savedDemosaicHeight)
|
||||
}
|
||||
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
|
||||
LargeDirectBuffer.free(syntheticRaw)
|
||||
LargeDirectBuffer.free(rgba)
|
||||
}
|
||||
}
|
||||
|
||||
private fun demosaicNoisePipelineLabel(cfaPattern: Int): String =
|
||||
if (RawMetadata.isQuadBayer(cfaPattern)) "QUAD_BAYER" else "STANDARD_BAYER_VGN"
|
||||
|
||||
/**
|
||||
* Collapses each standard Bayer 2x2 cell to one camera-RGB texel for capture-side exposure
|
||||
* matching. The result stays in the same un-white-balanced, lens-shading-corrected domain as
|
||||
@@ -5986,6 +5450,9 @@ class RawDemosaicProcessor {
|
||||
highlightReconstructionEnabled: Boolean,
|
||||
globalOriginX: Int = 0,
|
||||
globalOriginY: Int = 0,
|
||||
rawInputTextureId: Int = rawTextureId,
|
||||
linearOutputTargetTextureId: Int = linearOutputTextureId,
|
||||
outputTargetTextureId: Int = demosaicTextureId,
|
||||
) {
|
||||
val hotPixelNoise = resolveChromaDenoiseNoiseModel(metadata, 1f)
|
||||
val (_, denoiseReadNoiseOffset) = resolveDenoiseProfileNoiseModel(metadata, 1f)
|
||||
@@ -5993,9 +5460,9 @@ class RawDemosaicProcessor {
|
||||
vgnDemosaicAlgorithm.execute(
|
||||
VgnDemosaicAlgorithm.Input(
|
||||
metadata = metadata,
|
||||
rawTextureId = rawTextureId,
|
||||
linearOutputTextureId = linearOutputTextureId,
|
||||
outputTextureId = demosaicTextureId,
|
||||
rawTextureId = rawInputTextureId,
|
||||
linearOutputTextureId = linearOutputTargetTextureId,
|
||||
outputTextureId = outputTargetTextureId,
|
||||
lensShadingTextureId = lensShadingTextureId,
|
||||
width = width,
|
||||
height = height,
|
||||
@@ -6035,6 +5502,8 @@ class RawDemosaicProcessor {
|
||||
highlightReconstructionEnabled: Boolean = true,
|
||||
globalOriginX: Int = 0,
|
||||
globalOriginY: Int = 0,
|
||||
rawInputTextureId: Int = rawTextureId,
|
||||
outputTargetTextureId: Int = demosaicTextureId,
|
||||
) {
|
||||
val blackLevel4 = FloatArray(4) { index ->
|
||||
metadata.blackLevel.getOrElse(index) {
|
||||
@@ -6044,8 +5513,8 @@ class RawDemosaicProcessor {
|
||||
checkNotNull(
|
||||
quadBayerDemosaicAlgorithm.execute(
|
||||
QuadBayerDemosaicAlgorithm.Input(
|
||||
rawTextureId = rawTextureId,
|
||||
outputTextureId = demosaicTextureId,
|
||||
rawTextureId = rawInputTextureId,
|
||||
outputTextureId = outputTargetTextureId,
|
||||
width = width,
|
||||
height = height,
|
||||
cfaPattern = metadata.cfaPattern,
|
||||
@@ -8790,6 +8259,7 @@ class RawDemosaicProcessor {
|
||||
chromaDenoiseAlgorithm.release()
|
||||
filmicHighlightReconstructionAlgorithm.release()
|
||||
|
||||
demosaicNoisePropagationCalibrator.release()
|
||||
vgnDemosaicAlgorithm.release()
|
||||
quadBayerDemosaicAlgorithm.release()
|
||||
profileGainTableAlgorithm.release()
|
||||
|
||||
@@ -39,12 +39,15 @@ internal data class RawRenderTile(
|
||||
* consumer. Their origins are aligned to the sensor CFA period.
|
||||
*/
|
||||
internal object RawTilePlanner {
|
||||
/** Phocus switches OutputImageThreaded above nine million effective output pixels. */
|
||||
const val THREADED_OUTPUT_THRESHOLD_PIXELS = 9_000_000L
|
||||
/** Ordinary 12 MP 4:3 captures stay on the full-frame path in either orientation. */
|
||||
const val FULL_FRAME_MAX_SHORT_EDGE_PX = 3_072
|
||||
const val FULL_FRAME_MAX_LONG_EDGE_PX = 4_096
|
||||
|
||||
fun shouldTile(outputWidth: Int, outputHeight: Int): Boolean {
|
||||
return outputWidth.toLong() * outputHeight.toLong() >
|
||||
THREADED_OUTPUT_THRESHOLD_PIXELS
|
||||
val shortEdge = minOf(outputWidth, outputHeight)
|
||||
val longEdge = maxOf(outputWidth, outputHeight)
|
||||
return shortEdge > FULL_FRAME_MAX_SHORT_EDGE_PX ||
|
||||
longEdge > FULL_FRAME_MAX_LONG_EDGE_PX
|
||||
}
|
||||
|
||||
fun plan(
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Test
|
||||
import kotlin.math.PI
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.max
|
||||
import kotlin.math.sin
|
||||
|
||||
class DemosaicNoiseSpectrumTest {
|
||||
@Test
|
||||
fun halfBinFftMatchesLegacyDirectTransform() {
|
||||
val size = DemosaicNoiseSpectrum.SIZE
|
||||
val residuals = Array(3) { channel ->
|
||||
FloatArray(size * size) { index ->
|
||||
val x = index % size
|
||||
val y = index / size
|
||||
(
|
||||
sin((x + 1) * (channel + 2) * 0.071) +
|
||||
cos((y + 3) * (channel + 1) * 0.113) +
|
||||
0.15 * sin((x + y + 5) * 0.037)
|
||||
).toFloat()
|
||||
}
|
||||
}
|
||||
val channels = intArrayOf(0, 2)
|
||||
|
||||
val expected = legacyDirectPower(residuals, channels)
|
||||
val actual = DemosaicNoiseSpectrum.halfBinDirectionalPower(residuals, channels)
|
||||
|
||||
for (bin in 0 until size) {
|
||||
val tolerance = max(1e-10, abs(expected[bin]) * 1e-9)
|
||||
assertEquals("bin=$bin", expected[bin], actual[bin], tolerance)
|
||||
}
|
||||
}
|
||||
|
||||
private fun legacyDirectPower(
|
||||
residuals: Array<FloatArray>,
|
||||
channels: IntArray,
|
||||
): DoubleArray {
|
||||
val size = DemosaicNoiseSpectrum.SIZE
|
||||
val power = DoubleArray(size)
|
||||
for (bin in 0 until size) {
|
||||
val omega = (bin + 0.5) * 2.0 * PI / size - PI
|
||||
var accumulatedPower = 0.0
|
||||
for (channel in channels) {
|
||||
val residual = residuals[channel]
|
||||
for (line in 0 until size) {
|
||||
var horizontalReal = 0.0
|
||||
var horizontalImaginary = 0.0
|
||||
var verticalReal = 0.0
|
||||
var verticalImaginary = 0.0
|
||||
for (position in 0 until size) {
|
||||
val real = cos(omega * position)
|
||||
val imaginary = sin(omega * position)
|
||||
val horizontal = residual[line * size + position]
|
||||
val vertical = residual[position * size + line]
|
||||
horizontalReal += horizontal * real
|
||||
horizontalImaginary -= horizontal * imaginary
|
||||
verticalReal += vertical * real
|
||||
verticalImaginary -= vertical * imaginary
|
||||
}
|
||||
accumulatedPower +=
|
||||
horizontalReal * horizontalReal +
|
||||
horizontalImaginary * horizontalImaginary +
|
||||
verticalReal * verticalReal +
|
||||
verticalImaginary * verticalImaginary
|
||||
}
|
||||
}
|
||||
power[bin] = accumulatedPower / (2.0 * size * size)
|
||||
}
|
||||
return power
|
||||
}
|
||||
}
|
||||
@@ -161,9 +161,14 @@ class RawTilePlannerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
fun phocusThresholdUsesEffectiveCropPixels() {
|
||||
assertTrue(!RawTilePlanner.shouldTile(3_000, 3_000))
|
||||
assertTrue(RawTilePlanner.shouldTile(3_001, 3_000))
|
||||
fun fullFrameLimitIsInclusiveAndRotationInvariant() {
|
||||
assertTrue(!RawTilePlanner.shouldTile(3_072, 4_096))
|
||||
assertTrue(!RawTilePlanner.shouldTile(4_096, 3_072))
|
||||
assertTrue(!RawTilePlanner.shouldTile(4_000, 3_000))
|
||||
assertTrue(RawTilePlanner.shouldTile(3_073, 4_096))
|
||||
assertTrue(RawTilePlanner.shouldTile(4_096, 3_073))
|
||||
assertTrue(RawTilePlanner.shouldTile(3_072, 4_097))
|
||||
assertTrue(RawTilePlanner.shouldTile(4_097, 3_072))
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -120,6 +120,13 @@ shader storage block binding gets value 12, out of range [0 - 7]
|
||||
|
||||
## SSBO 与 image format
|
||||
|
||||
### `R16UI` 采样不代表可用于 image store
|
||||
|
||||
GLES 3.1 可以通过 `usampler2D` 采样 `R16UI` texture,但核心 GLSL ES 3.10 image
|
||||
format qualifier 不包含 `r16ui`。需要 compute shader 写入并由 RAW sampler 读取时,使用
|
||||
`RGBA16UI` + `layout(rgba16ui) writeonly uimage2D`,下游继续读取 `.r`;不要声明
|
||||
`layout(r16ui)`,也不要由 texture 可分配、可采样推断它可用于 image load/store。
|
||||
|
||||
### `readonly` SSBO 元素不能直接作为用户函数实参
|
||||
|
||||
**证据**:OPPO PLW110,Mali-G720-Immortalis MC12,驱动 `v1.r44p1-01eac0.7c759d1daf93e2baa476e2d4d07e761b`。
|
||||
|
||||
Reference in new issue
Block a user