feat: revert to ml ae
This commit is contained in:
1 parent
58460bb26e
commit
8556733d8e
17 files changed
+633
-3016
No files matched your search
Binary file not shown.
@@ -172,12 +172,9 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeGenerateGains
|
||||
jfloatArray guide_slopes_array, jfloatArray acr_curve_array,
|
||||
jfloat diagnostic_start, jfloat diagnostic_end,
|
||||
jfloat diagnostic_feather, jint diagnostic_mode,
|
||||
jfloat portrait_relighting_gain,
|
||||
jfloatArray portrait_relighting_weights_array,
|
||||
jfloatArray output_gains_array) {
|
||||
if (coefficients_array == nullptr || guide_shifts_array == nullptr ||
|
||||
guide_slopes_array == nullptr || acr_curve_array == nullptr ||
|
||||
portrait_relighting_weights_array == nullptr ||
|
||||
output_gains_array == nullptr || source_grid_width <= 0 ||
|
||||
source_grid_height <= 0 || source_grid_depth <= 0 ||
|
||||
coefficient_count != 2 || output_grid_width <= 0 ||
|
||||
@@ -191,8 +188,6 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeGenerateGains
|
||||
render_max_gain_blend_threshold < 0.0f ||
|
||||
!std::isfinite(min_table_gain) || min_table_gain <= 0.0f ||
|
||||
!std::isfinite(max_table_gain) || max_table_gain < min_table_gain ||
|
||||
!std::isfinite(portrait_relighting_gain) ||
|
||||
portrait_relighting_gain <= 0.0f ||
|
||||
diagnostic_mode < -1 || diagnostic_mode > 1) {
|
||||
LogError("Rejected invalid HDRNet PGTM parameters");
|
||||
return JNI_FALSE;
|
||||
@@ -212,7 +207,6 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeGenerateGains
|
||||
env->GetArrayLength(coefficients_array) != coefficient_values ||
|
||||
env->GetArrayLength(guide_slopes_array) != guide_count ||
|
||||
acr_curve_count < 2 ||
|
||||
env->GetArrayLength(portrait_relighting_weights_array) != cell_count ||
|
||||
env->GetArrayLength(output_gains_array) != output_values) {
|
||||
LogError("Rejected mismatched HDRNet PGTM array geometry");
|
||||
return JNI_FALSE;
|
||||
@@ -231,12 +225,9 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeGenerateGains
|
||||
ScopedFloatArray guide_shifts(env, guide_shifts_array);
|
||||
ScopedFloatArray guide_slopes(env, guide_slopes_array);
|
||||
ScopedFloatArray acr_curve(env, acr_curve_array);
|
||||
ScopedFloatArray portrait_relighting_weights(
|
||||
env, portrait_relighting_weights_array);
|
||||
ScopedFloatArray output_gains(env, output_gains_array);
|
||||
if (coefficients.data() == nullptr || guide_shifts.data() == nullptr ||
|
||||
guide_slopes.data() == nullptr || acr_curve.data() == nullptr ||
|
||||
portrait_relighting_weights.data() == nullptr ||
|
||||
output_gains.data() == nullptr) {
|
||||
LogError("Unable to acquire HDRNet PGTM arrays");
|
||||
return JNI_FALSE;
|
||||
@@ -244,22 +235,12 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeGenerateGains
|
||||
if (!IsFiniteArray(coefficients.data(), static_cast<int>(coefficient_values)) ||
|
||||
!IsFiniteArray(guide_shifts.data(), guide_count) ||
|
||||
!IsFiniteArray(guide_slopes.data(), guide_count) ||
|
||||
!IsFiniteArray(portrait_relighting_weights.data(),
|
||||
static_cast<int>(cell_count)) ||
|
||||
!IsValidAcrCurve(acr_curve.data(), acr_curve_count)) {
|
||||
LogError("Rejected non-finite HDRNet PGTM input");
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
try {
|
||||
for (int64_t cell = 0; cell < cell_count; ++cell) {
|
||||
const float weight =
|
||||
portrait_relighting_weights.data()[static_cast<size_t>(cell)];
|
||||
if (weight < 0.0f || weight > 1.0f) {
|
||||
LogError("Rejected out-of-range portrait relighting weight");
|
||||
return JNI_FALSE;
|
||||
}
|
||||
}
|
||||
std::vector<AxisSample> x_samples(static_cast<size_t>(output_grid_width));
|
||||
std::vector<AxisSample> y_samples(static_cast<size_t>(output_grid_height));
|
||||
std::vector<AxisSample> range_samples(static_cast<size_t>(point_count));
|
||||
@@ -297,10 +278,6 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeGenerateGains
|
||||
for (int cell = 0; cell < cell_count; ++cell) {
|
||||
const int x = cell % output_grid_width;
|
||||
const int y = cell / output_grid_width;
|
||||
const float portrait_relighting_weight =
|
||||
portrait_relighting_weights.data()[static_cast<size_t>(cell)];
|
||||
const float portrait_relighting_quotient = std::pow(
|
||||
portrait_relighting_gain, portrait_relighting_weight);
|
||||
float* const gain_curve =
|
||||
output_gains.data() + static_cast<size_t>(cell) * point_count;
|
||||
for (int point = 0; point < point_count; ++point) {
|
||||
@@ -337,12 +314,8 @@ Java_com_hinnka_mycamera_raw_DngHdrNetProfileGainTableNative_nativeGenerateGains
|
||||
const float render_gain = std::clamp(
|
||||
predicted_luma / (short_intensity + kHdrNetGainEpsilon),
|
||||
render_min_gain, render_max_gain_for_luma);
|
||||
// MGC keeps portrait_tet_gain out of long TET when downstream relighting is expected.
|
||||
// Apply that quotient locally in HDRNet's target domain. The soft mask exponent makes
|
||||
// the blend linear in log exposure and leaves the long/short HDR ratio untouched.
|
||||
const float target_luma = std::clamp(
|
||||
short_intensity * render_gain * portrait_relighting_quotient,
|
||||
0.0f, 1.0f);
|
||||
short_intensity * render_gain, 0.0f, 1.0f);
|
||||
const float pre_curve_target = InputForAcrOutput(
|
||||
target_luma, acr_curve.data(), acr_curve_count);
|
||||
// The N axis is final-short intensity = stored source * baselineGain * sourceToShortGain.
|
||||
|
||||
@@ -64,7 +64,6 @@ import com.hinnka.mycamera.raw.RawSharpeningDefaults
|
||||
import com.hinnka.mycamera.raw.RawAdaptiveExposureMode
|
||||
import com.hinnka.mycamera.raw.RawCaptureProfileCoordinator
|
||||
import com.hinnka.mycamera.raw.RawPhotonHdrRatioMetadata
|
||||
import com.hinnka.mycamera.raw.RawPhotonPortraitRelightingMetadata
|
||||
import com.hinnka.mycamera.raw.SpectralFilmTuning
|
||||
import com.hinnka.mycamera.raw.RawToneMappingParameters
|
||||
import com.hinnka.mycamera.raw.RawWhiteLevelCorrection
|
||||
@@ -2400,14 +2399,10 @@ object GalleryManager {
|
||||
) ?: return@withContext
|
||||
preparedDemosaicSourceToRelease = preparedProfile.gpuDemosaicedRawSource
|
||||
updatedMetadata = updatedMetadata.copy(
|
||||
customProperties = RawPhotonPortraitRelightingMetadata.write(
|
||||
properties = RawPhotonHdrRatioMetadata.write(
|
||||
updatedMetadata.customProperties,
|
||||
preparedProfile.hdrRatio,
|
||||
preparedProfile.finalShortGain,
|
||||
),
|
||||
gain = preparedProfile.portraitRelightingGain,
|
||||
mask = preparedProfile.portraitRelightingMask,
|
||||
customProperties = RawPhotonHdrRatioMetadata.write(
|
||||
updatedMetadata.customProperties,
|
||||
preparedProfile.hdrRatio,
|
||||
preparedProfile.finalShortGain,
|
||||
),
|
||||
)
|
||||
|
||||
@@ -3707,14 +3702,10 @@ object GalleryManager {
|
||||
return@withContext
|
||||
}
|
||||
updatedMetadata = updatedMetadata.copy(
|
||||
customProperties = RawPhotonPortraitRelightingMetadata.write(
|
||||
properties = RawPhotonHdrRatioMetadata.write(
|
||||
updatedMetadata.customProperties,
|
||||
dngProfilePreparation.hdrRatio,
|
||||
dngProfilePreparation.finalShortGain,
|
||||
),
|
||||
gain = dngProfilePreparation.portraitRelightingGain,
|
||||
mask = dngProfilePreparation.portraitRelightingMask,
|
||||
customProperties = RawPhotonHdrRatioMetadata.write(
|
||||
updatedMetadata.customProperties,
|
||||
dngProfilePreparation.hdrRatio,
|
||||
dngProfilePreparation.finalShortGain,
|
||||
),
|
||||
)
|
||||
val profileElapsedMs = System.currentTimeMillis() - profileStartMs
|
||||
@@ -5693,9 +5684,6 @@ object GalleryManager {
|
||||
val rawNoiseReduction = resolveNoiseReduction(rawMetadata, 0f)
|
||||
val rawChromaNoiseReduction = rawMetadata.chromaNoiseReduction
|
||||
?: ChromaDenoiseDefaults.RAW_CAPTURE_DEFAULT_STRENGTH
|
||||
val persistedPortraitRelighting = RawPhotonPortraitRelightingMetadata.read(
|
||||
rawMetadata.customProperties,
|
||||
)
|
||||
val processedBitmap = RawDemosaicProcessor.getInstance().process(
|
||||
context,
|
||||
dngFile.absolutePath, metadata?.ratio, metadata?.cropRegion, 0,
|
||||
@@ -5735,8 +5723,6 @@ object GalleryManager {
|
||||
photonSourceToShortGain = RawPhotonHdrRatioMetadata.readFinalShortGain(
|
||||
rawMetadata.customProperties,
|
||||
),
|
||||
photonPortraitRelightingGain = persistedPortraitRelighting?.gain,
|
||||
photonPortraitRelightingMask = persistedPortraitRelighting?.mask,
|
||||
rawCfaCorrectionMode = updatedMetadata?.rawCfaCorrectionMode,
|
||||
rawBlackBorderCrop = rawMetadata.rawBlackBorderCrop,
|
||||
spectralFilmStock = updatedMetadata?.spectralFilmStock,
|
||||
|
||||
@@ -316,9 +316,6 @@ internal class GlesMgcRawBaseFrameSelector(
|
||||
"baseRgb=${result.stats.baseFrameMetering?.let {
|
||||
"${com.hinnka.mycamera.raw.RawSceneExposureMath.INPUT_WIDTH}x" +
|
||||
com.hinnka.mycamera.raw.RawSceneExposureMath.INPUT_HEIGHT
|
||||
} ?: "unavailable"} " +
|
||||
"classicAe=${result.stats.baseFrameMetering?.classicAe?.let {
|
||||
"${it.width}x${it.height}"
|
||||
} ?: "unavailable"} uploadMs=$uploadMs submitMs=${result.submitMs} " +
|
||||
"gpuWaitMs=${result.gpuWaitMs} mapMs=${result.mapMs} totalMs=$totalMs " +
|
||||
"budgetMs=$FAST_MOMENTS_BUDGET_MS",
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
package com.hinnka.mycamera.processor
|
||||
|
||||
import android.graphics.Rect
|
||||
import android.opengl.GLES30
|
||||
import android.opengl.GLES31
|
||||
import com.hinnka.mycamera.raw.RawClassicAeSplitAlgorithm
|
||||
import com.hinnka.mycamera.raw.RawSceneClassicAeMeteringFrame
|
||||
import com.hinnka.mycamera.raw.RawSceneExposureMath
|
||||
import com.hinnka.mycamera.raw.RawSceneFastMomentsMeteringFrame
|
||||
import com.hinnka.mycamera.raw.RawSceneAERawStats
|
||||
@@ -21,9 +18,9 @@ internal data class GlesRawAEStatsResult(
|
||||
/**
|
||||
* Builds all selected-base AE statistics on the active GLES context.
|
||||
*
|
||||
* Exactly one compute pass reads the RAW texture. It emits a 16x16 block surface containing both
|
||||
* Fast Moments maxima and camera-RGB means. The 64x64 metering and 40-wide Classic-AE passes read
|
||||
* only that compact surface; no full-resolution intermediate or second RAW traversal exists.
|
||||
* One compute pass emits the mode-2 16x16 RAW maxima. A second pass directly area-reduces complete
|
||||
* Bayer periods into the 64x64 ML metering surface, matching MGC's ResampleBayerToRgb geometry.
|
||||
* Neither path constructs a full-resolution demosaiced intermediate.
|
||||
*/
|
||||
internal class GlesRawAEStats(
|
||||
private val width: Int,
|
||||
@@ -33,11 +30,6 @@ internal class GlesRawAEStats(
|
||||
private val whiteLevel: Int,
|
||||
private val maxShaderStorageBlockBytes: Long,
|
||||
) {
|
||||
private data class FastReadback(
|
||||
val channelMax: FloatArray,
|
||||
val clippedCfaSamples: Long,
|
||||
)
|
||||
|
||||
private val blackLevel = FloatArray(4) { channel ->
|
||||
blackLevel.getOrElse(channel) { 0f }
|
||||
}
|
||||
@@ -50,7 +42,6 @@ internal class GlesRawAEStats(
|
||||
require(width > 0 && height > 0 && cfaPattern in 0..3 && whiteLevel > 0)
|
||||
require(blackLevel.all(Float::isFinite))
|
||||
val buildStartNs = System.nanoTime()
|
||||
val sourceBounds = Rect(0, 0, width, height)
|
||||
val downsample = RawSceneExposureMath.FAST_MOMENTS_RAW_STATS_DOWNSAMPLE
|
||||
check(downsample > 0 && downsample % 2 == 0) {
|
||||
"Fast Moments downsample must preserve complete Bayer periods: $downsample"
|
||||
@@ -82,24 +73,6 @@ internal class GlesRawAEStats(
|
||||
} else {
|
||||
0
|
||||
}
|
||||
val classicOutputSize = if (canBuildMetering) {
|
||||
RawClassicAeSplitAlgorithm.outputSize(sourceBounds, cfaPattern)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val classicPixelCount = classicOutputSize?.let {
|
||||
Math.multiplyExact(it.width, it.height)
|
||||
} ?: 0
|
||||
val classicBuffer = if (classicPixelCount > 0) {
|
||||
createBuffer(
|
||||
checkedBufferBytes(classicPixelCount, CLASSIC_CELL_BYTES, "Classic split"),
|
||||
GLES30.GL_STREAM_READ,
|
||||
"Classic split",
|
||||
)
|
||||
} else {
|
||||
0
|
||||
}
|
||||
|
||||
return try {
|
||||
val fastProgram = linkComputeProgram(
|
||||
GlesRawAEStatsShaders.FAST_MOMENTS,
|
||||
@@ -113,15 +86,6 @@ internal class GlesRawAEStats(
|
||||
} else {
|
||||
0
|
||||
}
|
||||
val classicSplitProgram = if (classicOutputSize != null) {
|
||||
linkComputeProgram(
|
||||
GlesRawAEStatsShaders.CLASSIC_SPLIT,
|
||||
"Classic AE selected-base split",
|
||||
)
|
||||
} else {
|
||||
0
|
||||
}
|
||||
|
||||
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, rawTexture)
|
||||
GLES31.glUseProgram(fastProgram)
|
||||
@@ -146,16 +110,21 @@ internal class GlesRawAEStats(
|
||||
|
||||
if (baseMeteringProgram != 0) {
|
||||
GLES31.glUseProgram(baseMeteringProgram)
|
||||
GLES31.glUniform1i(uniformLocation(baseMeteringProgram, "uRaw"), 0)
|
||||
GLES31.glUniform2i(
|
||||
uniformLocation(baseMeteringProgram, "uInputSize"),
|
||||
statsWidth,
|
||||
statsHeight,
|
||||
uniformLocation(baseMeteringProgram, "uSourceSize"),
|
||||
width,
|
||||
height,
|
||||
)
|
||||
GLES31.glUniform2i(
|
||||
uniformLocation(baseMeteringProgram, "uOutputSize"),
|
||||
RawSceneExposureMath.INPUT_WIDTH,
|
||||
RawSceneExposureMath.INPUT_HEIGHT,
|
||||
)
|
||||
GLES31.glUniform1i(
|
||||
uniformLocation(baseMeteringProgram, "uCfaPattern"),
|
||||
cfaPattern,
|
||||
)
|
||||
GLES31.glUniform4fv(
|
||||
uniformLocation(baseMeteringProgram, "uBlackLevel"),
|
||||
1,
|
||||
@@ -166,8 +135,7 @@ internal class GlesRawAEStats(
|
||||
uniformLocation(baseMeteringProgram, "uWhiteLevel"),
|
||||
whiteLevel.toFloat(),
|
||||
)
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, fastBuffer)
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, meteringBuffer)
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, meteringBuffer)
|
||||
GLES31.glDispatchCompute(
|
||||
GlesComputeWorkGroup.imageGroupCount(RawSceneExposureMath.INPUT_WIDTH),
|
||||
GlesComputeWorkGroup.imageGroupCount(RawSceneExposureMath.INPUT_HEIGHT),
|
||||
@@ -175,37 +143,6 @@ internal class GlesRawAEStats(
|
||||
)
|
||||
}
|
||||
|
||||
if (classicSplitProgram != 0 && classicOutputSize != null) {
|
||||
GLES31.glUseProgram(classicSplitProgram)
|
||||
GLES31.glUniform2i(
|
||||
uniformLocation(classicSplitProgram, "uInputSize"),
|
||||
statsWidth,
|
||||
statsHeight,
|
||||
)
|
||||
GLES31.glUniform2i(
|
||||
uniformLocation(classicSplitProgram, "uOutputSize"),
|
||||
classicOutputSize.width,
|
||||
classicOutputSize.height,
|
||||
)
|
||||
GLES31.glUniform4fv(
|
||||
uniformLocation(classicSplitProgram, "uBlackLevel"),
|
||||
1,
|
||||
blackLevel,
|
||||
0,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
uniformLocation(classicSplitProgram, "uWhiteLevel"),
|
||||
whiteLevel.toFloat(),
|
||||
)
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 0, fastBuffer)
|
||||
GLES31.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, classicBuffer)
|
||||
GLES31.glDispatchCompute(
|
||||
GlesComputeWorkGroup.imageGroupCount(classicOutputSize.width),
|
||||
GlesComputeWorkGroup.imageGroupCount(classicOutputSize.height),
|
||||
1,
|
||||
)
|
||||
}
|
||||
|
||||
GLES31.glMemoryBarrier(
|
||||
GLES31.GL_SHADER_STORAGE_BARRIER_BIT or
|
||||
GLES31.GL_BUFFER_UPDATE_BARRIER_BIT,
|
||||
@@ -236,40 +173,19 @@ internal class GlesRawAEStats(
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val classicAe = if (classicBuffer != 0 && classicOutputSize != null) {
|
||||
mapBuffer(
|
||||
classicBuffer,
|
||||
classicPixelCount * CLASSIC_CELL_BYTES,
|
||||
"Classic split",
|
||||
) { mapped ->
|
||||
readClassicAeMeteringFrame(
|
||||
mapped = mapped,
|
||||
width = classicOutputSize.width,
|
||||
height = classicOutputSize.height,
|
||||
clippedCfaSamples = fastReadback.clippedCfaSamples,
|
||||
cfaSampleCount = RawClassicAeSplitAlgorithm.cfaSampleCount(
|
||||
sourceBounds,
|
||||
cfaPattern,
|
||||
),
|
||||
)
|
||||
}
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val mapMs = elapsedMs(mapStartNs)
|
||||
val stats = RawSceneAERawStats(
|
||||
width = statsWidth,
|
||||
height = statsHeight,
|
||||
sourceWidth = width,
|
||||
sourceHeight = height,
|
||||
channelMax = fastReadback.channelMax,
|
||||
channelMax = fastReadback,
|
||||
sensorNormalized = true,
|
||||
sourceBounds = floatArrayOf(0f, 0f, 1f, 1f),
|
||||
sourceRotationDegrees = 0,
|
||||
baseFrameMetering = baseSensorRgb?.let { sensorRgb ->
|
||||
RawSceneFastMomentsMeteringFrame(
|
||||
sensorRgb = sensorRgb,
|
||||
classicAe = classicAe,
|
||||
)
|
||||
},
|
||||
)
|
||||
@@ -296,9 +212,8 @@ internal class GlesRawAEStats(
|
||||
}
|
||||
}
|
||||
|
||||
private fun readFastStats(mapped: ByteBuffer, pixelCount: Int): FastReadback {
|
||||
private fun readFastStats(mapped: ByteBuffer, pixelCount: Int): FloatArray {
|
||||
val channelMax = FloatArray(pixelCount * 4)
|
||||
var clippedCfaSamples = 0L
|
||||
for (pixel in 0 until pixelCount) {
|
||||
val inputOffset = pixel * STATS_CELL_BYTES
|
||||
val outputOffset = pixel * 4
|
||||
@@ -307,11 +222,9 @@ internal class GlesRawAEStats(
|
||||
inputOffset + channel * Float.SIZE_BYTES,
|
||||
)
|
||||
}
|
||||
clippedCfaSamples += mapped.getFloat(inputOffset + 7 * Float.SIZE_BYTES)
|
||||
.toLong()
|
||||
}
|
||||
check(channelMax.all { it.isFinite() && it >= 0f })
|
||||
return FastReadback(channelMax, clippedCfaSamples)
|
||||
return channelMax
|
||||
}
|
||||
|
||||
private fun readBaseFrameSensorRgb(mapped: ByteBuffer, pixelCount: Int): FloatArray =
|
||||
@@ -328,50 +241,6 @@ internal class GlesRawAEStats(
|
||||
check(output.all { it.isFinite() && it >= 0f })
|
||||
}
|
||||
|
||||
private fun readClassicAeMeteringFrame(
|
||||
mapped: ByteBuffer,
|
||||
width: Int,
|
||||
height: Int,
|
||||
clippedCfaSamples: Long,
|
||||
cfaSampleCount: Int,
|
||||
): RawSceneClassicAeMeteringFrame {
|
||||
val pixelCount = Math.multiplyExact(width, height)
|
||||
val brightRgb = FloatArray(pixelCount * 3)
|
||||
val darkRgb = FloatArray(pixelCount * 3)
|
||||
val brightMask = ByteArray(pixelCount)
|
||||
for (pixel in 0 until pixelCount) {
|
||||
val inputOffset = pixel * CLASSIC_CELL_BYTES
|
||||
val outputOffset = pixel * 3
|
||||
for (channel in 0..2) {
|
||||
brightRgb[outputOffset + channel] = mapped.getFloat(
|
||||
inputOffset + channel * Float.SIZE_BYTES,
|
||||
)
|
||||
darkRgb[outputOffset + channel] = mapped.getFloat(
|
||||
inputOffset + VEC4_BYTES + channel * Float.SIZE_BYTES,
|
||||
)
|
||||
}
|
||||
val maskCode = mapped.getFloat(inputOffset + 3 * Float.SIZE_BYTES)
|
||||
.toInt()
|
||||
.coerceIn(0, 255)
|
||||
brightMask[pixel] = maskCode.toByte()
|
||||
}
|
||||
check(brightRgb.all(Float::isFinite) && darkRgb.all(Float::isFinite))
|
||||
return RawSceneClassicAeMeteringFrame(
|
||||
width = width,
|
||||
height = height,
|
||||
brightRgb = brightRgb,
|
||||
darkRgb = darkRgb,
|
||||
brightMask = brightMask,
|
||||
clippedFraction = if (cfaSampleCount > 0) {
|
||||
(clippedCfaSamples.toDouble() / cfaSampleCount.toDouble())
|
||||
.coerceIn(0.0, 1.0)
|
||||
.toFloat()
|
||||
} else {
|
||||
0f
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
private inline fun <T> mapBuffer(
|
||||
buffer: Int,
|
||||
byteCount: Int,
|
||||
@@ -471,6 +340,5 @@ internal class GlesRawAEStats(
|
||||
private companion object {
|
||||
const val VEC4_BYTES = 4 * Float.SIZE_BYTES
|
||||
const val STATS_CELL_BYTES = 2 * VEC4_BYTES
|
||||
const val CLASSIC_CELL_BYTES = 2 * VEC4_BYTES
|
||||
}
|
||||
}
|
||||
@@ -101,39 +101,80 @@ internal object GlesRawAEStatsShaders {
|
||||
#version 310 es
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
precision highp usampler2D;
|
||||
|
||||
layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in;
|
||||
uniform ivec2 uInputSize;
|
||||
uniform highp usampler2D uRaw;
|
||||
uniform ivec2 uSourceSize;
|
||||
uniform ivec2 uOutputSize;
|
||||
uniform int uCfaPattern;
|
||||
uniform vec4 uBlackLevel;
|
||||
uniform float uWhiteLevel;
|
||||
struct StatsCell {
|
||||
vec4 maxima;
|
||||
vec4 cameraRgb;
|
||||
};
|
||||
layout(std430, binding = 0) readonly buffer InputCells {
|
||||
StatsCell cells[];
|
||||
} inputCells;
|
||||
layout(std430, binding = 1) writeonly buffer OutputValues {
|
||||
layout(std430, binding = 0) writeonly buffer OutputValues {
|
||||
vec4 values[];
|
||||
} outputValues;
|
||||
|
||||
int canonicalChannel(ivec2 position) {
|
||||
int phase = ((position.y & 1) << 1) | (position.x & 1);
|
||||
int pattern = uCfaPattern & 3;
|
||||
if (pattern == 0) return phase;
|
||||
if (pattern == 1) {
|
||||
const int channels[4] = int[4](1, 0, 3, 2);
|
||||
return channels[phase];
|
||||
}
|
||||
if (pattern == 2) {
|
||||
const int channels[4] = int[4](2, 3, 0, 1);
|
||||
return channels[phase];
|
||||
}
|
||||
const int channels[4] = int[4](3, 2, 1, 0);
|
||||
return channels[phase];
|
||||
}
|
||||
|
||||
float rawCode(uint code) {
|
||||
return float(code >> 8) * 256.0 + float(code & 255u);
|
||||
}
|
||||
|
||||
void main() {
|
||||
ivec2 outputCoord = ivec2(gl_GlobalInvocationID.xy);
|
||||
if (any(greaterThanEqual(outputCoord, uOutputSize))) return;
|
||||
ivec2 start = outputCoord * uInputSize / uOutputSize;
|
||||
ivec2 end = (outputCoord + 1) * uInputSize / uOutputSize;
|
||||
end = min(max(end, start + 1), uInputSize);
|
||||
vec3 sum = vec3(0.0);
|
||||
int count = 0;
|
||||
for (int y = start.y; y < end.y; ++y) {
|
||||
for (int x = start.x; x < end.x; ++x) {
|
||||
StatsCell localCell = inputCells.cells[y * uInputSize.x + x];
|
||||
sum += localCell.cameraRgb.rgb;
|
||||
count += 1;
|
||||
|
||||
// MGC partitions source rows directly by output row. Its wide-row kernel then assigns
|
||||
// each consecutive group of four RAW samples to floor(outputWidth * x / sourceWidth).
|
||||
// Reconstruct the corresponding gather interval here; do not impose 2x2-CFA-period
|
||||
// boundaries, because the original keeps independent sample counts for every channel.
|
||||
int startY = outputCoord.y * uSourceSize.y / uOutputSize.y;
|
||||
int endY = (outputCoord.y + 1) * uSourceSize.y / uOutputSize.y;
|
||||
bool usesWideRowKernel = uSourceSize.x >= 12 * uOutputSize.x;
|
||||
int horizontalDenominator = usesWideRowKernel
|
||||
? uOutputSize.x * 4
|
||||
: uOutputSize.x;
|
||||
int horizontalGroupSize = usesWideRowKernel ? 4 : 1;
|
||||
int startX = horizontalGroupSize * (
|
||||
(outputCoord.x * uSourceSize.x + horizontalDenominator - 1) /
|
||||
horizontalDenominator
|
||||
);
|
||||
int endX = min(
|
||||
horizontalGroupSize * (
|
||||
((outputCoord.x + 1) * uSourceSize.x + horizontalDenominator - 1) /
|
||||
horizontalDenominator
|
||||
),
|
||||
uSourceSize.x
|
||||
);
|
||||
vec4 sums = vec4(0.0);
|
||||
ivec4 counts = ivec4(0);
|
||||
for (int sourceY = startY; sourceY < endY; ++sourceY) {
|
||||
for (int sourceX = startX; sourceX < endX; ++sourceX) {
|
||||
ivec2 position = ivec2(sourceX, sourceY);
|
||||
int channel = canonicalChannel(position);
|
||||
sums[channel] += rawCode(texelFetch(uRaw, position, 0).r);
|
||||
counts[channel] += 1;
|
||||
}
|
||||
}
|
||||
vec3 mean = sum / float(max(count, 1));
|
||||
vec3 mean = vec3(
|
||||
sums.r / float(max(counts.r, 1)),
|
||||
(sums.g + sums.b) / float(max(counts.g + counts.b, 1)),
|
||||
sums.a / float(max(counts.a, 1))
|
||||
);
|
||||
vec3 black = vec3(
|
||||
uBlackLevel.r,
|
||||
0.5 * (uBlackLevel.g + uBlackLevel.b),
|
||||
@@ -149,93 +190,4 @@ internal object GlesRawAEStatsShaders {
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
val CLASSIC_SPLIT = """
|
||||
#version 310 es
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
|
||||
layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in;
|
||||
uniform ivec2 uInputSize;
|
||||
uniform ivec2 uOutputSize;
|
||||
uniform vec4 uBlackLevel;
|
||||
uniform float uWhiteLevel;
|
||||
struct StatsCell {
|
||||
vec4 maxima;
|
||||
vec4 cameraRgb;
|
||||
};
|
||||
layout(std430, binding = 0) readonly buffer InputCells {
|
||||
StatsCell cells[];
|
||||
} inputCells;
|
||||
struct SplitCell {
|
||||
vec4 bright;
|
||||
vec4 dark;
|
||||
};
|
||||
layout(std430, binding = 1) writeonly buffer OutputCells {
|
||||
SplitCell cells[];
|
||||
} outputCells;
|
||||
|
||||
void main() {
|
||||
ivec2 outputCoord = ivec2(gl_GlobalInvocationID.xy);
|
||||
if (any(greaterThanEqual(outputCoord, uOutputSize))) return;
|
||||
ivec2 start = outputCoord * uInputSize / uOutputSize;
|
||||
ivec2 end = (outputCoord + 1) * uInputSize / uOutputSize;
|
||||
end = min(max(end, start + 1), uInputSize);
|
||||
vec3 mean = vec3(0.0);
|
||||
int sampleCount = 0;
|
||||
for (int y = start.y; y < end.y; ++y) {
|
||||
for (int x = start.x; x < end.x; ++x) {
|
||||
StatsCell localCell = inputCells.cells[y * uInputSize.x + x];
|
||||
mean += localCell.cameraRgb.rgb;
|
||||
sampleCount += 1;
|
||||
}
|
||||
}
|
||||
mean /= float(max(sampleCount, 1));
|
||||
float meanSum = mean.r + mean.g + mean.b;
|
||||
vec3 brightSum = vec3(0.0);
|
||||
vec3 darkSum = vec3(0.0);
|
||||
int brightCount = 0;
|
||||
for (int y = start.y; y < end.y; ++y) {
|
||||
for (int x = start.x; x < end.x; ++x) {
|
||||
StatsCell localCell = inputCells.cells[y * uInputSize.x + x];
|
||||
vec3 sampleRgb = localCell.cameraRgb.rgb;
|
||||
if (sampleRgb.r + sampleRgb.g + sampleRgb.b > meanSum) {
|
||||
brightSum += sampleRgb;
|
||||
brightCount += 1;
|
||||
} else {
|
||||
darkSum += sampleRgb;
|
||||
}
|
||||
}
|
||||
}
|
||||
int darkCount = sampleCount - brightCount;
|
||||
vec3 bright = brightSum / float(max(brightCount, 1));
|
||||
vec3 dark = darkSum / float(max(darkCount, 1));
|
||||
vec3 black = vec3(
|
||||
uBlackLevel.r,
|
||||
0.5 * (uBlackLevel.g + uBlackLevel.b),
|
||||
uBlackLevel.a
|
||||
);
|
||||
for (int channel = 0; channel < 3; ++channel) {
|
||||
if (bright[channel] > black[channel] ||
|
||||
dark[channel] > 2.0 * black[channel]) {
|
||||
bright[channel] = max(bright[channel] - black[channel], 0.0);
|
||||
dark[channel] = max(dark[channel] - black[channel], 0.0);
|
||||
} else {
|
||||
float merged = max(
|
||||
0.5 * (bright[channel] + dark[channel]) - black[channel],
|
||||
0.0
|
||||
);
|
||||
bright[channel] = merged;
|
||||
dark[channel] = merged;
|
||||
}
|
||||
}
|
||||
float sensorRange = max(
|
||||
uWhiteLevel - max(black.r, max(black.g, black.b)),
|
||||
1.0
|
||||
);
|
||||
float maskCode = float(255 * brightCount / max(sampleCount, 1));
|
||||
int outputIndex = outputCoord.y * uOutputSize.x + outputCoord.x;
|
||||
outputCells.cells[outputIndex].bright = vec4(bright / sensorRange, maskCode);
|
||||
outputCells.cells[outputIndex].dark = vec4(dark / sensorRange, 0.0);
|
||||
}
|
||||
""".trimIndent()
|
||||
}
|
||||
@@ -17,8 +17,6 @@ internal object DngHdrNetProfileGainTableNative {
|
||||
renderMaxGainBlendThreshold: Float,
|
||||
minTableGain: Float,
|
||||
maxTableGain: Float,
|
||||
portraitRelightingGain: Float,
|
||||
portraitRelightingWeights: FloatArray,
|
||||
): FloatArray? {
|
||||
val outputCount = plan.cellCount.toLong() * plan.pointCount
|
||||
if (outputCount !in 1..Int.MAX_VALUE.toLong()) return null
|
||||
@@ -47,8 +45,6 @@ internal object DngHdrNetProfileGainTableNative {
|
||||
diagnosticEnd = diagnosticBand?.end ?: 1f,
|
||||
diagnosticFeather = diagnosticBand?.feather ?: 0f,
|
||||
diagnosticMode = diagnosticBand?.mode?.ordinal ?: -1,
|
||||
portraitRelightingGain = portraitRelightingGain,
|
||||
portraitRelightingWeights = portraitRelightingWeights,
|
||||
outputGains = output,
|
||||
)
|
||||
return output.takeIf { completed }
|
||||
@@ -77,8 +73,6 @@ internal object DngHdrNetProfileGainTableNative {
|
||||
diagnosticEnd: Float,
|
||||
diagnosticFeather: Float,
|
||||
diagnosticMode: Int,
|
||||
portraitRelightingGain: Float,
|
||||
portraitRelightingWeights: FloatArray,
|
||||
outputGains: FloatArray,
|
||||
): Boolean
|
||||
}
|
||||
@@ -945,20 +945,14 @@ internal object DngPhotonProfileGainTableInputShader {
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
precision highp sampler2D;
|
||||
precision highp sampler3D;
|
||||
|
||||
uniform sampler2D uLinearRgbTexture;
|
||||
uniform sampler3D uHueSatMap;
|
||||
uniform ivec2 uImageSize;
|
||||
uniform ivec4 uStatsBounds;
|
||||
uniform mat3 uColorCorrectionMatrix;
|
||||
uniform float uBaselineGain;
|
||||
uniform float uSourceToShortGain;
|
||||
uniform float uHdrRatio;
|
||||
uniform int uHueSatEnabled;
|
||||
uniform ivec3 uHueSatDivisions;
|
||||
uniform int uHueSatEncoding;
|
||||
uniform int uHueSatSupportOverrange;
|
||||
uniform int uWarpCount;
|
||||
|
||||
layout(std430, binding = 0) writeonly buffer HdrNetInputBuffer {
|
||||
@@ -968,8 +962,6 @@ internal object DngPhotonProfileGainTableInputShader {
|
||||
float warpParameters[];
|
||||
};
|
||||
|
||||
${DcpHueSatMapGl.SHADER_FUNCTIONS}
|
||||
|
||||
vec2 warpDestinationToSource(vec2 destinationPixel) {
|
||||
vec2 sourcePixel = destinationPixel;
|
||||
// DNG rendering applies opcodes in file order. Sampling the original linear texture
|
||||
@@ -1038,56 +1030,53 @@ internal object DngPhotonProfileGainTableInputShader {
|
||||
sourceStart = clamp(sourceStart, ivec2(0), uImageSize - ivec2(1));
|
||||
sourceEnd = clamp(sourceEnd, sourceStart + ivec2(1), uImageSize);
|
||||
|
||||
vec3 cameraRgbSum = vec3(0.0);
|
||||
vec3 profileRgbSum = vec3(0.0);
|
||||
int sampleCount = 0;
|
||||
for (int y = sourceStart.y; y < sourceEnd.y; ++y) {
|
||||
for (int x = sourceStart.x; x < sourceEnd.x; ++x) {
|
||||
ivec2 sourceCoordinate = ivec2(round(
|
||||
warpDestinationToSource(vec2(x, y))
|
||||
));
|
||||
cameraRgbSum += max(
|
||||
texelFetch(uLinearRgbTexture, sourceCoordinate, 0).rgb,
|
||||
vec3(0.0)
|
||||
);
|
||||
vec3 storedCameraRgb = texelFetch(
|
||||
uLinearRgbTexture,
|
||||
sourceCoordinate,
|
||||
0
|
||||
).rgb;
|
||||
// The demosaic texture is un-white-balanced camera RGB. The render-stage
|
||||
// camera-to-working matrix includes the selected camera white, matching
|
||||
// MGC's uCcm contract without applying WB a second time.
|
||||
vec3 cameraRgb = storedCameraRgb * uBaselineGain * uSourceToShortGain;
|
||||
// MGC clamps only positive overrange before box downsampling. Negative
|
||||
// samples remain in the average and are clamped by the final box pass.
|
||||
vec3 profileRgb = min(uColorCorrectionMatrix * cameraRgb, vec3(1.0));
|
||||
profileRgbSum += profileRgb;
|
||||
++sampleCount;
|
||||
}
|
||||
}
|
||||
// Restore the multi-frame source from its shorter-exposure normalization before
|
||||
// moving it into final-short space. This BaselineExposure is source-domain metadata,
|
||||
// not the additional appearance exposure used by Pixel's DNG pipeline.
|
||||
vec3 storedCameraRgb = cameraRgbSum / float(max(sampleCount, 1));
|
||||
vec3 cameraRgb = storedCameraRgb * uBaselineGain * uSourceToShortGain;
|
||||
vec3 profileRgb = clamp(
|
||||
uColorCorrectionMatrix * cameraRgb,
|
||||
vec3(0.0),
|
||||
// MGC deliberately preserves negative black-referenced samples through the box
|
||||
// downsample and into HDRNet. Only positive overrange is clipped. Clearing the
|
||||
// negative tail here changes the first convolution's dark-region response and can
|
||||
// drive the recovered affine grid to its 0.03 minimum-gain floor.
|
||||
vec3 modelRgb = min(
|
||||
profileRgbSum / float(max(sampleCount, 1)),
|
||||
vec3(1.0)
|
||||
);
|
||||
if (uHueSatEnabled != 0) {
|
||||
profileRgb = clamp(
|
||||
dngApplyHueSatMap(
|
||||
profileRgb,
|
||||
uHueSatMap,
|
||||
uHueSatDivisions,
|
||||
uHueSatEncoding,
|
||||
uHueSatSupportOverrange != 0
|
||||
),
|
||||
vec3(0.0),
|
||||
vec3(1.0)
|
||||
);
|
||||
}
|
||||
|
||||
// This TFLite is the 1x2 normal HDRNet model recovered from MGC's TensorFlow
|
||||
// graph. Its original fused first-convolution shader constructs channel four from
|
||||
// Rec.601 luma and the HDR ratio, clamped to the training maximum of 12.
|
||||
const vec3 HDRNET_LUMA_WEIGHTS = vec3(
|
||||
0.298828125,
|
||||
0.5869140625,
|
||||
0.1142578125
|
||||
);
|
||||
float shortLuma = max(dot(profileRgb, HDRNET_LUMA_WEIGHTS), 0.0);
|
||||
float longLuma = min(dot(modelRgb, HDRNET_LUMA_WEIGHTS) * uHdrRatio, 12.0);
|
||||
|
||||
int outputIndex =
|
||||
(outputPosition.y * OUTPUT_SIZE.x + outputPosition.x) * 4;
|
||||
hdrNetInput[outputIndex] = profileRgb.r;
|
||||
hdrNetInput[outputIndex + 1] = profileRgb.g;
|
||||
hdrNetInput[outputIndex + 2] = profileRgb.b;
|
||||
hdrNetInput[outputIndex + 3] = min(shortLuma * uHdrRatio, 12.0);
|
||||
hdrNetInput[outputIndex] = modelRgb.r;
|
||||
hdrNetInput[outputIndex + 1] = modelRgb.g;
|
||||
hdrNetInput[outputIndex + 2] = modelRgb.b;
|
||||
hdrNetInput[outputIndex + 3] = longLuma;
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
@@ -1398,8 +1387,6 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
val rendererBaselineExposureEv: Float,
|
||||
val hdrRatio: Float,
|
||||
val sourceToShortGain: Float,
|
||||
val portraitRelightingGain: Float,
|
||||
val portraitRelightingMask: FloatArray?,
|
||||
val colorCorrectionMatrix: FloatArray,
|
||||
val hueSatMap: DcpHueSatMap?,
|
||||
val hueSatMapSupportsOverrange: Boolean,
|
||||
@@ -1576,33 +1563,6 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
LINEAR_RGB_TEXTURE_UNIT,
|
||||
)
|
||||
|
||||
val activeHueSatMap = input.hueSatMap?.takeIf { it.isValid }
|
||||
GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + HUE_SAT_TEXTURE_UNIT)
|
||||
val hueSatTextureId = activeHueSatMap?.let(input.ensureHueSatTexture)
|
||||
?: input.ensureDummyHueSatTexture()
|
||||
GLES31.glBindTexture(GLES30.GL_TEXTURE_3D, hueSatTextureId)
|
||||
GLES31.glUniform1i(
|
||||
GLES31.glGetUniformLocation(hdrNetInputProgram, "uHueSatMap"),
|
||||
HUE_SAT_TEXTURE_UNIT,
|
||||
)
|
||||
GLES31.glUniform1i(
|
||||
GLES31.glGetUniformLocation(hdrNetInputProgram, "uHueSatEnabled"),
|
||||
if (activeHueSatMap != null) 1 else 0,
|
||||
)
|
||||
GLES31.glUniform3i(
|
||||
GLES31.glGetUniformLocation(hdrNetInputProgram, "uHueSatDivisions"),
|
||||
activeHueSatMap?.hueDivisions ?: 1,
|
||||
activeHueSatMap?.satDivisions ?: 1,
|
||||
activeHueSatMap?.valueDivisions ?: 1,
|
||||
)
|
||||
GLES31.glUniform1i(
|
||||
GLES31.glGetUniformLocation(hdrNetInputProgram, "uHueSatEncoding"),
|
||||
activeHueSatMap?.encoding ?: DcpHueSatMap.ENCODING_LINEAR,
|
||||
)
|
||||
GLES31.glUniform1i(
|
||||
GLES31.glGetUniformLocation(hdrNetInputProgram, "uHueSatSupportOverrange"),
|
||||
if (input.hueSatMapSupportsOverrange) 1 else 0,
|
||||
)
|
||||
GLES31.glUniform2i(
|
||||
GLES31.glGetUniformLocation(hdrNetInputProgram, "uImageSize"),
|
||||
linearRgbTextureWidth,
|
||||
@@ -1672,7 +1632,6 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
input = input,
|
||||
plan = plan,
|
||||
colorCorrectionMatrix = safeColorCorrectionMatrix,
|
||||
hueSatEnabled = activeHueSatMap != null,
|
||||
values = inputFloats,
|
||||
)
|
||||
val modelInput = ByteBuffer.allocateDirect(inputFloats.size * Float.SIZE_BYTES)
|
||||
@@ -1690,13 +1649,13 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
DngPhotonProfileGainTableGenerator.HDRNET_OUTPUT_FLOAT_COUNT,
|
||||
)
|
||||
modelOutput.asFloatBuffer().get(coefficients)
|
||||
logHdrNetOutputContract(coefficients, plan.hdrRatio)
|
||||
val pgtmStartNs = System.nanoTime()
|
||||
val map = DngPhotonProfileGainTableGenerator.mapFromHdrNetCoefficients(
|
||||
plan = plan,
|
||||
coefficients = coefficients,
|
||||
portraitRelightingGain = input.portraitRelightingGain,
|
||||
portraitRelightingMask = input.portraitRelightingMask,
|
||||
) ?: return null
|
||||
// logHdrNetGainTableContract(map)
|
||||
val pgtmReadyNs = System.nanoTime()
|
||||
val textureId = uploadProfileGainTableTexture(map) ?: return null
|
||||
try {
|
||||
@@ -1723,12 +1682,11 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
"mapInputEffectiveScale=${plan.rendererMapInputEffectiveScale} " +
|
||||
"mapInputInvariantError=" +
|
||||
"${plan.rendererMapInputEffectiveScale - plan.hdrNetInputScale} " +
|
||||
"portraitRelightingApplied=" +
|
||||
"${input.portraitRelightingMask != null && input.portraitRelightingGain != 1f} " +
|
||||
"portraitRelightingGain=${input.portraitRelightingGain} " +
|
||||
"portraitRelightingMaskRms=" +
|
||||
"${RawSceneExposureMath.faceMaskRms(input.portraitRelightingMask)} " +
|
||||
"portraitRelightingDomain=POST_HDRNET_TARGET_PRE_ACR3_PRE_PGTM " +
|
||||
"modelInputChannels=R_G_B_LONG_LUMA " +
|
||||
"modelInputFinalClamp=UPPER_ONE_ONLY_NEGATIVE_PRESERVED " +
|
||||
"modelInputHueSat=false " +
|
||||
"modelInputAux=MIN_REC601_LUMA_X_HDR_RATIO_12 " +
|
||||
"hdrRatioDomain=MODEL_AUX_AND_POST_INFERENCE_COEFFICIENT_UNROLL " +
|
||||
"baselineAppliedToHdrNetInput=true " +
|
||||
"baselineRole=MULTIFRAME_SOURCE_NORMALIZATION_RESTORE " +
|
||||
"mapInputDomain=FINAL_SHORT_RIMM_PXL_INTENSITY_AFTER_SOURCE_RESTORE " +
|
||||
@@ -3254,7 +3212,6 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
input: Input,
|
||||
plan: HdrNetProfileGainTablePlan,
|
||||
colorCorrectionMatrix: FloatArray,
|
||||
hueSatEnabled: Boolean,
|
||||
values: FloatArray,
|
||||
) {
|
||||
val whiteBalance = input.metadata.whiteBalanceGains
|
||||
@@ -3295,7 +3252,10 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
"HDRNet input contract: wb=${whiteBalance.contentToString()} " +
|
||||
"cameraNeutral=${cameraNeutral.contentToString()} " +
|
||||
"mappedNeutral=${mappedNeutral.contentToString()} " +
|
||||
"matrix=${colorCorrectionMatrix.take(9)} hueSat=$hueSatEnabled " +
|
||||
"matrix=${colorCorrectionMatrix.take(9)} " +
|
||||
"whiteBalanceDomain=BAKED_IN_COLOR_CORRECTION_MATRIX " +
|
||||
"modelInputChannels=R_G_B_LONG_LUMA " +
|
||||
"modelInputFinalClamp=UPPER_ONE_ONLY_NEGATIVE_PRESERVED hueSat=false " +
|
||||
"sourceBaselineGain=${plan.sourceBaselineGain} " +
|
||||
"rendererBaselineGain=${plan.rendererBaselineGain} " +
|
||||
"sourceToShort=${plan.sourceToShortGain} " +
|
||||
@@ -3304,6 +3264,8 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
"mapInputEffectiveScale=${plan.rendererMapInputEffectiveScale} " +
|
||||
"mapInputInvariantError=" +
|
||||
"${plan.rendererMapInputEffectiveScale - plan.hdrNetInputScale} " +
|
||||
"modelInputAux=MIN_REC601_LUMA_X_HDR_RATIO_12 " +
|
||||
"hdrRatioDomain=MODEL_AUX_AND_POST_INFERENCE_COEFFICIENT_UNROLL " +
|
||||
"channelMin=${minimums.contentToString()} " +
|
||||
"channelMean=${means.contentToString()} " +
|
||||
"channelMax=${maximums.contentToString()} " +
|
||||
@@ -3311,6 +3273,92 @@ internal class DngPhotonProfileGainTableAlgorithm {
|
||||
)
|
||||
}
|
||||
|
||||
private fun logHdrNetOutputContract(coefficients: FloatArray, hdrRatio: Float) {
|
||||
if (coefficients.size % DngPhotonProfileGainTableGenerator.HDRNET_COEFFICIENT_COUNT != 0) {
|
||||
return
|
||||
}
|
||||
val minimums = floatArrayOf(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY)
|
||||
val maximums = floatArrayOf(Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY)
|
||||
val sums = DoubleArray(2)
|
||||
var pairCount = 0
|
||||
for (offset in coefficients.indices step 2) {
|
||||
for (component in 0..1) {
|
||||
val value = coefficients[offset + component]
|
||||
minimums[component] = minOf(minimums[component], value)
|
||||
maximums[component] = maxOf(maximums[component], value)
|
||||
sums[component] += value.toDouble()
|
||||
}
|
||||
++pairCount
|
||||
}
|
||||
val means = FloatArray(2) { component ->
|
||||
(sums[component] / pairCount.coerceAtLeast(1)).toFloat()
|
||||
}
|
||||
val affineScaleMinimum = minimums[0] * (hdrRatio - 1f) + 1f
|
||||
val affineScaleMean = means[0] * (hdrRatio - 1f) + 1f
|
||||
val affineScaleMaximum = maximums[0] * (hdrRatio - 1f) + 1f
|
||||
PLog.d(
|
||||
TAG,
|
||||
"HDRNet model output contract: layout=Y_X_Z_ONE_SCALE_RESIDUAL_BIAS " +
|
||||
"coefficientMin=${minimums.contentToString()} " +
|
||||
"coefficientMean=${means.contentToString()} " +
|
||||
"coefficientMax=${maximums.contentToString()} " +
|
||||
"affineScaleAfterRatio=[$affineScaleMinimum,$affineScaleMean,$affineScaleMaximum] " +
|
||||
"hdrRatio=$hdrRatio",
|
||||
)
|
||||
}
|
||||
|
||||
private fun logHdrNetGainTableContract(map: DngProfileGainTableMap) {
|
||||
val pointCount = map.mapPointsN
|
||||
if (pointCount <= 0 || map.gains.isEmpty()) return
|
||||
val requestedPoints = intArrayOf(0, 1, 4, 16, 64, 128, pointCount - 1)
|
||||
val points = requestedPoints.distinct().filter { it in 0 until pointCount }
|
||||
val pointMin = FloatArray(points.size) { Float.POSITIVE_INFINITY }
|
||||
val pointMax = FloatArray(points.size) { Float.NEGATIVE_INFINITY }
|
||||
val pointSum = DoubleArray(points.size)
|
||||
var gainMin = Float.POSITIVE_INFINITY
|
||||
var gainMax = Float.NEGATIVE_INFINITY
|
||||
var gainSum = 0.0
|
||||
var finiteCount = 0
|
||||
var nonFiniteCount = 0
|
||||
var renderFloorCount = 0
|
||||
var belowPointOneCount = 0
|
||||
map.gains.forEachIndexed { index, gain ->
|
||||
if (!gain.isFinite()) {
|
||||
nonFiniteCount++
|
||||
return@forEachIndexed
|
||||
}
|
||||
gainMin = min(gainMin, gain)
|
||||
gainMax = max(gainMax, gain)
|
||||
gainSum += gain
|
||||
finiteCount++
|
||||
if (gain <= 0.031f) renderFloorCount++
|
||||
if (gain <= 0.1f) belowPointOneCount++
|
||||
val point = index % pointCount
|
||||
val selected = points.indexOf(point)
|
||||
if (selected >= 0) {
|
||||
pointMin[selected] = min(pointMin[selected], gain)
|
||||
pointMax[selected] = max(pointMax[selected], gain)
|
||||
pointSum[selected] += gain
|
||||
}
|
||||
}
|
||||
val cellCount = map.gains.size / pointCount
|
||||
val pointSummary = points.indices.joinToString(prefix = "[", postfix = "]") { index ->
|
||||
val mean = if (cellCount > 0) pointSum[index] / cellCount else Double.NaN
|
||||
"${points[index]}:${pointMin[index]}/$mean/${pointMax[index]}"
|
||||
}
|
||||
PLog.i(
|
||||
TAG,
|
||||
"HDRNet PGTM gain contract: gainMin=$gainMin " +
|
||||
"gainMean=${if (finiteCount > 0) gainSum / finiteCount else Double.NaN} " +
|
||||
"gainMax=$gainMax finiteCount=$finiteCount nonFiniteCount=$nonFiniteCount " +
|
||||
"atOrBelowRenderFloorFraction=" +
|
||||
"${renderFloorCount.toDouble() / map.gains.size.coerceAtLeast(1)} " +
|
||||
"atOrBelowPointOneFraction=" +
|
||||
"${belowPointOneCount.toDouble() / map.gains.size.coerceAtLeast(1)} " +
|
||||
"pointGainMinMeanMax=$pointSummary",
|
||||
)
|
||||
}
|
||||
|
||||
private companion object {
|
||||
const val TAG = "PhotonPGTM"
|
||||
const val HDRNET_MODEL_ASSET = "mgc_hdrnet/hdrnet_coefficients.tflite"
|
||||
|
||||
@@ -74,21 +74,13 @@ internal object DngPhotonProfileGainTableGenerator {
|
||||
0.051524382f,
|
||||
)
|
||||
|
||||
/** Luma definition used by MGC's HDRNet input preparation and bilateral-grid guide. */
|
||||
internal val HDRNET_LUMA_WEIGHTS = floatArrayOf(
|
||||
0.298828125f,
|
||||
0.5869140625f,
|
||||
0.1142578125f,
|
||||
0f,
|
||||
0f,
|
||||
)
|
||||
|
||||
/**
|
||||
* Normalized ProfileGainTableMap intensity direction written by Pixel's MGC pipeline.
|
||||
*
|
||||
* This is deliberately distinct from [HDRNET_LUMA_WEIGHTS]. HDRNet keeps its learned luma
|
||||
* definition for its guide and fourth input channel, while the DNG table N axis combines
|
||||
* half of standard RGB luma with one eighth of min-RGB and three eighths of max-RGB.
|
||||
* This is deliberately distinct from the HDRNet tensor, whose channels are Y, U, V, 1.
|
||||
* The DNG table N axis combines half of standard RGB luma with one eighth of min-RGB and
|
||||
* three eighths of max-RGB. Pixel DNGs scale all five values together for final-short space;
|
||||
* [hdrNetPlan] performs the same scale after accounting for renderer BaselineExposure.
|
||||
*/
|
||||
internal val PXL_PROFILE_GAIN_TABLE_INPUT_WEIGHTS = floatArrayOf(
|
||||
0.1495f,
|
||||
@@ -191,8 +183,6 @@ internal object DngPhotonProfileGainTableGenerator {
|
||||
fun mapFromHdrNetCoefficients(
|
||||
plan: HdrNetProfileGainTablePlan,
|
||||
coefficients: FloatArray,
|
||||
portraitRelightingGain: Float = 1f,
|
||||
portraitRelightingMask: FloatArray? = null,
|
||||
): DngProfileGainTableMap? {
|
||||
if (coefficients.size != HDRNET_OUTPUT_FLOAT_COUNT) {
|
||||
PLog.e(
|
||||
@@ -201,22 +191,6 @@ internal object DngPhotonProfileGainTableGenerator {
|
||||
)
|
||||
return null
|
||||
}
|
||||
if (!portraitRelightingGain.isFinite() || portraitRelightingGain <= 0f) {
|
||||
PLog.e(TAG, "Rejected invalid portrait relighting gain=$portraitRelightingGain")
|
||||
return null
|
||||
}
|
||||
val portraitRelightingWeights = buildPortraitRelightingWeights(
|
||||
plan = plan,
|
||||
mask = portraitRelightingMask,
|
||||
) ?: if (portraitRelightingMask == null) {
|
||||
FloatArray(plan.cellCount)
|
||||
} else {
|
||||
PLog.e(
|
||||
TAG,
|
||||
"Rejected invalid portrait relighting mask size=${portraitRelightingMask.size}",
|
||||
)
|
||||
return null
|
||||
}
|
||||
val gains = DngHdrNetProfileGainTableNative.generateGains(
|
||||
plan = plan,
|
||||
coefficients = coefficients,
|
||||
@@ -228,8 +202,6 @@ internal object DngPhotonProfileGainTableGenerator {
|
||||
renderMaxGainBlendThreshold = HDRNET_RENDER_MAX_GAIN_BLEND_THRESHOLD,
|
||||
minTableGain = MIN_TABLE_GAIN,
|
||||
maxTableGain = MAX_TABLE_GAIN,
|
||||
portraitRelightingGain = portraitRelightingGain,
|
||||
portraitRelightingWeights = portraitRelightingWeights,
|
||||
) ?: run {
|
||||
PLog.e(TAG, "Native HDRNet ProfileGainTableMap generation failed")
|
||||
return null
|
||||
@@ -250,63 +222,6 @@ internal object DngPhotonProfileGainTableGenerator {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Resamples the unrotated sensor-space 64 x 64 face mask at the PGTM cell centers.
|
||||
*
|
||||
* Native PGTM generation interprets each value as an exponent for the portrait exposure
|
||||
* quotient. That is, the local quotient is `portraitGain ^ mask`, which blends exposure in
|
||||
* the same logarithmic domain as MGC's portrait-TET migration rather than linearly mixing
|
||||
* gain values. The actual quotient is applied to HDRNet's target luma before ACR3 inversion.
|
||||
*/
|
||||
private fun buildPortraitRelightingWeights(
|
||||
plan: HdrNetProfileGainTablePlan,
|
||||
mask: FloatArray?,
|
||||
): FloatArray? {
|
||||
if (mask == null) return FloatArray(plan.cellCount)
|
||||
val maskWidth = RawSceneExposureMath.INPUT_WIDTH
|
||||
val maskHeight = RawSceneExposureMath.INPUT_HEIGHT
|
||||
if (mask.size != maskWidth * maskHeight ||
|
||||
mask.any { !it.isFinite() || it !in 0f..1f }
|
||||
) {
|
||||
return null
|
||||
}
|
||||
return FloatArray(plan.cellCount) { cell ->
|
||||
val x = cell % plan.grid.mapPointsH
|
||||
val y = cell / plan.grid.mapPointsH
|
||||
bilinearMaskSample(
|
||||
mask = mask,
|
||||
width = maskWidth,
|
||||
height = maskHeight,
|
||||
normalizedX = plan.grid.mapOriginH + x * plan.grid.mapSpacingH,
|
||||
normalizedY = plan.grid.mapOriginV + y * plan.grid.mapSpacingV,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun bilinearMaskSample(
|
||||
mask: FloatArray,
|
||||
width: Int,
|
||||
height: Int,
|
||||
normalizedX: Double,
|
||||
normalizedY: Double,
|
||||
): Float {
|
||||
val sampleX = (normalizedX.coerceIn(0.0, 1.0) * width - 0.5)
|
||||
.coerceIn(0.0, width - 1.0)
|
||||
val sampleY = (normalizedY.coerceIn(0.0, 1.0) * height - 0.5)
|
||||
.coerceIn(0.0, height - 1.0)
|
||||
val x0 = sampleX.toInt().coerceIn(0, width - 1)
|
||||
val y0 = sampleY.toInt().coerceIn(0, height - 1)
|
||||
val x1 = (x0 + 1).coerceAtMost(width - 1)
|
||||
val y1 = (y0 + 1).coerceAtMost(height - 1)
|
||||
val xAmount = (sampleX - x0).toFloat()
|
||||
val yAmount = (sampleY - y0).toFloat()
|
||||
val top = mask[y0 * width + x0] * (1f - xAmount) +
|
||||
mask[y0 * width + x1] * xAmount
|
||||
val bottom = mask[y1 * width + x0] * (1f - xAmount) +
|
||||
mask[y1 * width + x1] * xAmount
|
||||
return (top * (1f - yAmount) + bottom * yAmount).coerceIn(0f, 1f)
|
||||
}
|
||||
|
||||
/** Exact MGC HDRNet guide: sum(slopes * relu(luma - shifts)), then clamp for slicing. */
|
||||
internal fun hdrNetGuide(luma: Float): Float {
|
||||
var guide = 0f
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -150,6 +150,13 @@ internal class RawAEStatsAlgorithm {
|
||||
uniform float uWhiteLevel;
|
||||
layout(rgba16f, binding = 0) writeonly uniform image2D uOutput;
|
||||
|
||||
// Preserve MGC CountClippedPixels' exact integer predicate across the RGBA16F
|
||||
// readback boundary. Values in the upper half-ULP below 1.0 otherwise round to
|
||||
// 1.0 and turn merely near-white RAW samples into clipped samples. 0.99951171875
|
||||
// is the largest binary16 value below one, so the two states remain distinct after
|
||||
// imageStore: raw < white -> at most 0x3bff, raw >= white -> exactly 0x3c00.
|
||||
const float FP16_MAX_BELOW_ONE = 0.99951171875;
|
||||
|
||||
int channelAt(int pattern, ivec2 coord) {
|
||||
int basePattern = pattern >= 8 ? pattern - 8 :
|
||||
(pattern >= 4 ? pattern - 4 : pattern);
|
||||
@@ -183,8 +190,12 @@ internal class RawAEStatsAlgorithm {
|
||||
int channel = channelAt(uCfaPattern, coord);
|
||||
float raw = float(texelFetch(uRawTexture, coord, 0).r);
|
||||
float black = uBlackLevel[channel];
|
||||
float sensor = max(raw - black, 0.0) /
|
||||
max(uWhiteLevel - black, 1.0);
|
||||
bool rawClipped = raw >= uWhiteLevel;
|
||||
float sensor = rawClipped ? 1.0 : min(
|
||||
max(raw - black, 0.0) /
|
||||
max(uWhiteLevel - black, 1.0),
|
||||
FP16_MAX_BELOW_ONE
|
||||
);
|
||||
maxima[channel] = max(maxima[channel], sensor);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,476 +0,0 @@
|
||||
package com.hinnka.mycamera.raw
|
||||
|
||||
import android.graphics.Rect
|
||||
import android.opengl.GLES30
|
||||
import android.opengl.GLES31
|
||||
import com.hinnka.mycamera.processor.GlesComputeWorkGroup
|
||||
|
||||
/** GPU transcription of MGC's non-QCOM RawToLoResRgb Classic-AE split. */
|
||||
internal class RawClassicAeSplitAlgorithm {
|
||||
data class Size(val width: Int, val height: Int)
|
||||
|
||||
data class Input(
|
||||
val rawTextureId: Int,
|
||||
val outputTextureId: Int,
|
||||
val imageWidth: Int,
|
||||
val imageHeight: Int,
|
||||
val sourceBounds: Rect,
|
||||
val cfaPattern: Int,
|
||||
val blackLevel: FloatArray,
|
||||
val whiteLevel: Float,
|
||||
val component: Int,
|
||||
)
|
||||
|
||||
private var rawToLoResProgram = 0
|
||||
private var splitProgram = 0
|
||||
|
||||
fun initialize(): Boolean {
|
||||
if (rawToLoResProgram == 0) {
|
||||
rawToLoResProgram = RawGlesProgram.compileCompute(
|
||||
RAW_TO_LO_RES_SHADER,
|
||||
"RAW_CLASSIC_AE_RAW_TO_LO_RES",
|
||||
)
|
||||
}
|
||||
if (splitProgram == 0) {
|
||||
splitProgram = RawGlesProgram.compileCompute(
|
||||
SPLIT_SHADER,
|
||||
"RAW_CLASSIC_AE_SPLIT",
|
||||
)
|
||||
}
|
||||
return rawToLoResProgram != 0 && splitProgram != 0
|
||||
}
|
||||
|
||||
fun execute(input: Input): Boolean {
|
||||
if (!initialize()) return false
|
||||
val outputSize = outputSize(input.sourceBounds, input.cfaPattern) ?: return false
|
||||
val loResSize = loResSize(input.sourceBounds, input.cfaPattern) ?: return false
|
||||
require(input.rawTextureId != 0 && input.outputTextureId != 0)
|
||||
require(input.imageWidth > 0 && input.imageHeight > 0)
|
||||
require(input.component in 0..1)
|
||||
require(input.blackLevel.size >= 4)
|
||||
require(
|
||||
input.sourceBounds.left >= 0 && input.sourceBounds.top >= 0 &&
|
||||
input.sourceBounds.right <= input.imageWidth &&
|
||||
input.sourceBounds.bottom <= input.imageHeight &&
|
||||
!input.sourceBounds.isEmpty,
|
||||
)
|
||||
require(
|
||||
input.whiteLevel.isFinite() && input.whiteLevel > 0f &&
|
||||
input.blackLevel.take(4).all {
|
||||
it.isFinite() && it >= 0f && input.whiteLevel > it
|
||||
},
|
||||
)
|
||||
val loResTexture = IntArray(1)
|
||||
try {
|
||||
GLES30.glGenTextures(1, loResTexture, 0)
|
||||
if (loResTexture[0] == 0) return false
|
||||
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, loResTexture[0])
|
||||
GLES30.glTexStorage2D(
|
||||
GLES30.GL_TEXTURE_2D,
|
||||
1,
|
||||
GLES30.GL_RGBA16F,
|
||||
loResSize.width,
|
||||
loResSize.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,
|
||||
)
|
||||
|
||||
// V25 first box-resamples the CFA into one <=180-edge camera-RGB image.
|
||||
GLES31.glUseProgram(rawToLoResProgram)
|
||||
GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + RAW_TEXTURE_UNIT)
|
||||
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, input.rawTextureId)
|
||||
GLES31.glUniform1i(
|
||||
GLES31.glGetUniformLocation(rawToLoResProgram, "uRawTexture"),
|
||||
RAW_TEXTURE_UNIT,
|
||||
)
|
||||
GLES31.glUniform2i(
|
||||
GLES31.glGetUniformLocation(rawToLoResProgram, "uImageSize"),
|
||||
input.imageWidth,
|
||||
input.imageHeight,
|
||||
)
|
||||
GLES31.glUniform2i(
|
||||
GLES31.glGetUniformLocation(rawToLoResProgram, "uOutputSize"),
|
||||
loResSize.width,
|
||||
loResSize.height,
|
||||
)
|
||||
GLES31.glUniform4i(
|
||||
GLES31.glGetUniformLocation(rawToLoResProgram, "uSourceBounds"),
|
||||
input.sourceBounds.left,
|
||||
input.sourceBounds.top,
|
||||
input.sourceBounds.right,
|
||||
input.sourceBounds.bottom,
|
||||
)
|
||||
GLES31.glUniform1i(
|
||||
GLES31.glGetUniformLocation(rawToLoResProgram, "uCfaPattern"),
|
||||
input.cfaPattern,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(rawToLoResProgram, "uWhiteLevel"),
|
||||
input.whiteLevel,
|
||||
)
|
||||
GLES31.glBindImageTexture(
|
||||
0,
|
||||
loResTexture[0],
|
||||
0,
|
||||
false,
|
||||
0,
|
||||
GLES31.GL_WRITE_ONLY,
|
||||
GLES30.GL_RGBA16F,
|
||||
)
|
||||
GLES31.glDispatchCompute(
|
||||
GlesComputeWorkGroup.imageGroupCount(loResSize.width),
|
||||
GlesComputeWorkGroup.imageGroupCount(loResSize.height),
|
||||
1,
|
||||
)
|
||||
GLES31.glMemoryBarrier(
|
||||
GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or
|
||||
GLES31.GL_TEXTURE_FETCH_BARRIER_BIT,
|
||||
)
|
||||
RawGlesProgram.logErrors("RAW Classic AE RawToLoResRgb")
|
||||
|
||||
// CreateForClassicAe then splits that RGB image into a fixed 40-pixel-wide surface.
|
||||
GLES31.glUseProgram(splitProgram)
|
||||
GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + LO_RES_TEXTURE_UNIT)
|
||||
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, loResTexture[0])
|
||||
GLES31.glUniform1i(
|
||||
GLES31.glGetUniformLocation(splitProgram, "uLoResTexture"),
|
||||
LO_RES_TEXTURE_UNIT,
|
||||
)
|
||||
GLES31.glUniform2i(
|
||||
GLES31.glGetUniformLocation(splitProgram, "uInputSize"),
|
||||
loResSize.width,
|
||||
loResSize.height,
|
||||
)
|
||||
GLES31.glUniform2i(
|
||||
GLES31.glGetUniformLocation(splitProgram, "uOutputSize"),
|
||||
outputSize.width,
|
||||
outputSize.height,
|
||||
)
|
||||
GLES31.glUniform4fv(
|
||||
GLES31.glGetUniformLocation(splitProgram, "uBlackLevel"),
|
||||
1,
|
||||
input.blackLevel,
|
||||
0,
|
||||
)
|
||||
GLES31.glUniform1f(
|
||||
GLES31.glGetUniformLocation(splitProgram, "uWhiteLevel"),
|
||||
input.whiteLevel,
|
||||
)
|
||||
GLES31.glUniform1i(
|
||||
GLES31.glGetUniformLocation(splitProgram, "uComponent"),
|
||||
input.component,
|
||||
)
|
||||
GLES31.glBindImageTexture(
|
||||
0,
|
||||
input.outputTextureId,
|
||||
0,
|
||||
false,
|
||||
0,
|
||||
GLES31.GL_WRITE_ONLY,
|
||||
GLES30.GL_RGBA16F,
|
||||
)
|
||||
GLES31.glDispatchCompute(
|
||||
GlesComputeWorkGroup.imageGroupCount(outputSize.width),
|
||||
GlesComputeWorkGroup.imageGroupCount(outputSize.height),
|
||||
1,
|
||||
)
|
||||
GLES31.glMemoryBarrier(
|
||||
GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or
|
||||
GLES31.GL_FRAMEBUFFER_BARRIER_BIT,
|
||||
)
|
||||
RawGlesProgram.logErrors("RAW Classic AE split component ${input.component}")
|
||||
return true
|
||||
} finally {
|
||||
GLES31.glBindImageTexture(
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
false,
|
||||
0,
|
||||
GLES31.GL_READ_ONLY,
|
||||
GLES30.GL_RGBA16F,
|
||||
)
|
||||
GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + LO_RES_TEXTURE_UNIT)
|
||||
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0)
|
||||
GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + RAW_TEXTURE_UNIT)
|
||||
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0)
|
||||
if (loResTexture[0] != 0) {
|
||||
GLES30.glDeleteTextures(1, loResTexture, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun release() {
|
||||
if (rawToLoResProgram != 0) {
|
||||
GLES31.glDeleteProgram(rawToLoResProgram)
|
||||
rawToLoResProgram = 0
|
||||
}
|
||||
if (splitProgram != 0) {
|
||||
GLES31.glDeleteProgram(splitProgram)
|
||||
splitProgram = 0
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val LO_RES_MAX_EDGE = 180
|
||||
private const val CLASSIC_AE_WIDTH = 40
|
||||
private const val RAW_TEXTURE_UNIT = 0
|
||||
private const val LO_RES_TEXTURE_UNIT = 1
|
||||
|
||||
fun outputSize(sourceBounds: Rect, cfaPattern: Int): Size? {
|
||||
if (sourceBounds.isEmpty || cfaPattern !in 0..11) return null
|
||||
val width = sourceBounds.width()
|
||||
val height = sourceBounds.height()
|
||||
if (width <= 0 || height <= 0) return null
|
||||
return Size(
|
||||
width = CLASSIC_AE_WIDTH,
|
||||
height = maxOf(
|
||||
1,
|
||||
kotlin.math.floor(
|
||||
height.toDouble() / width.toDouble() * CLASSIC_AE_WIDTH + 0.5,
|
||||
).toInt(),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
internal fun loResSize(sourceBounds: Rect, cfaPattern: Int): Size? {
|
||||
if (sourceBounds.isEmpty || cfaPattern !in 0..11) return null
|
||||
val colorBlockSize = when (cfaPattern) {
|
||||
in 0..3 -> 1
|
||||
in 4..7 -> 2
|
||||
else -> 4
|
||||
}
|
||||
val cfaPeriod = colorBlockSize * 2
|
||||
val sampleWidth = sourceBounds.width() / cfaPeriod
|
||||
val sampleHeight = sourceBounds.height() / cfaPeriod
|
||||
if (sampleWidth <= 0 || sampleHeight <= 0) return null
|
||||
val directThreshold = if (colorBlockSize == 1) 539 else 899
|
||||
if (maxOf(sourceBounds.width(), sourceBounds.height()) <= directThreshold) {
|
||||
return Size(sampleWidth, sampleHeight)
|
||||
}
|
||||
return if (sampleWidth >= sampleHeight) {
|
||||
Size(
|
||||
LO_RES_MAX_EDGE,
|
||||
maxOf(1, LO_RES_MAX_EDGE * sampleHeight / sampleWidth),
|
||||
)
|
||||
} else {
|
||||
Size(
|
||||
maxOf(1, LO_RES_MAX_EDGE * sampleWidth / sampleHeight),
|
||||
LO_RES_MAX_EDGE,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun cfaSampleCount(sourceBounds: Rect, cfaPattern: Int): Int {
|
||||
val colorBlockSize = when (cfaPattern) {
|
||||
in 0..3 -> 1
|
||||
in 4..7 -> 2
|
||||
in 8..11 -> 4
|
||||
else -> return 0
|
||||
}
|
||||
val cfaPeriod = colorBlockSize * 2
|
||||
return (sourceBounds.width() / cfaPeriod) * (sourceBounds.height() / cfaPeriod)
|
||||
}
|
||||
|
||||
private val RAW_TO_LO_RES_SHADER = """
|
||||
#version 310 es
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
precision highp usampler2D;
|
||||
precision highp image2D;
|
||||
|
||||
layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in;
|
||||
uniform highp usampler2D uRawTexture;
|
||||
uniform ivec2 uImageSize;
|
||||
uniform ivec2 uOutputSize;
|
||||
uniform ivec4 uSourceBounds;
|
||||
uniform int uCfaPattern;
|
||||
uniform float uWhiteLevel;
|
||||
layout(rgba16f, binding = 0) writeonly uniform image2D uOutput;
|
||||
|
||||
int colorBlockSize() {
|
||||
return uCfaPattern >= 8 ? 4 : (uCfaPattern >= 4 ? 2 : 1);
|
||||
}
|
||||
|
||||
int channelAt(ivec2 coord) {
|
||||
int pattern = uCfaPattern & 3;
|
||||
int blockSize = colorBlockSize();
|
||||
int blockColumn = ((coord.x - uSourceBounds.x) / blockSize) & 1;
|
||||
int blockRow = ((coord.y - uSourceBounds.y) / blockSize) & 1;
|
||||
if (pattern == 0) {
|
||||
if (blockRow == 0) return blockColumn == 0 ? 0 : 1;
|
||||
return blockColumn == 0 ? 2 : 3;
|
||||
} else if (pattern == 1) {
|
||||
if (blockRow == 0) return blockColumn == 0 ? 1 : 0;
|
||||
return blockColumn == 0 ? 3 : 2;
|
||||
} else if (pattern == 2) {
|
||||
if (blockRow == 0) return blockColumn == 0 ? 2 : 3;
|
||||
return blockColumn == 0 ? 0 : 1;
|
||||
}
|
||||
if (blockRow == 0) return blockColumn == 0 ? 3 : 2;
|
||||
return blockColumn == 0 ? 1 : 0;
|
||||
}
|
||||
|
||||
float rawAt(ivec2 coord) {
|
||||
uint code = texelFetch(uRawTexture, coord, 0).r;
|
||||
// Avoid driver paths that lower uint16 -> float directly to FP16.
|
||||
return float(code >> 8) * 256.0 + float(code & 255u);
|
||||
}
|
||||
|
||||
vec4 cfaSample(ivec2 sampleCoord) {
|
||||
int blockSize = colorBlockSize();
|
||||
int period = blockSize * 2;
|
||||
ivec2 origin = uSourceBounds.xy + sampleCoord * period;
|
||||
vec4 sums = vec4(0.0);
|
||||
ivec4 counts = ivec4(0);
|
||||
bool clipped = false;
|
||||
for (int y = 0; y < 8; ++y) {
|
||||
if (y >= period) break;
|
||||
for (int x = 0; x < 8; ++x) {
|
||||
if (x >= period) break;
|
||||
ivec2 coord = origin + ivec2(x, y);
|
||||
if (any(greaterThanEqual(coord, uSourceBounds.zw)) ||
|
||||
any(greaterThanEqual(coord, uImageSize))) continue;
|
||||
int channel = channelAt(coord);
|
||||
float raw = rawAt(coord);
|
||||
sums[channel] += raw;
|
||||
counts[channel] += 1;
|
||||
clipped = clipped || raw >= uWhiteLevel;
|
||||
}
|
||||
}
|
||||
float red = sums.r / float(max(counts.r, 1));
|
||||
float green = (sums.g + sums.b) / float(max(counts.g + counts.b, 1));
|
||||
float blue = sums.a / float(max(counts.a, 1));
|
||||
return vec4(red, green, blue, clipped ? 1.0 : 0.0);
|
||||
}
|
||||
|
||||
void main() {
|
||||
ivec2 outputCoord = ivec2(gl_GlobalInvocationID.xy);
|
||||
if (any(greaterThanEqual(outputCoord, uOutputSize))) return;
|
||||
int period = colorBlockSize() * 2;
|
||||
ivec2 sampleSize = (uSourceBounds.zw - uSourceBounds.xy) / period;
|
||||
ivec2 start = outputCoord * sampleSize / uOutputSize;
|
||||
ivec2 end = (outputCoord + 1) * sampleSize / uOutputSize;
|
||||
end = min(max(end, start + 1), sampleSize);
|
||||
|
||||
vec4 accumulated = vec4(0.0);
|
||||
int sampleCount = 0;
|
||||
for (int y = start.y; y < end.y; ++y) {
|
||||
for (int x = start.x; x < end.x; ++x) {
|
||||
accumulated += cfaSample(ivec2(x, y));
|
||||
sampleCount += 1;
|
||||
}
|
||||
}
|
||||
vec3 mean = accumulated.rgb / float(max(sampleCount, 1));
|
||||
imageStore(uOutput, outputCoord, vec4(mean / uWhiteLevel, accumulated.a));
|
||||
}
|
||||
""".trimIndent()
|
||||
|
||||
private val SPLIT_SHADER = """
|
||||
#version 310 es
|
||||
precision highp float;
|
||||
precision highp int;
|
||||
precision highp sampler2D;
|
||||
precision highp image2D;
|
||||
|
||||
layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in;
|
||||
uniform highp sampler2D uLoResTexture;
|
||||
uniform ivec2 uInputSize;
|
||||
uniform ivec2 uOutputSize;
|
||||
uniform vec4 uBlackLevel;
|
||||
uniform float uWhiteLevel;
|
||||
uniform int uComponent;
|
||||
layout(rgba16f, binding = 0) writeonly uniform image2D uOutput;
|
||||
|
||||
void main() {
|
||||
ivec2 outputCoord = ivec2(gl_GlobalInvocationID.xy);
|
||||
if (any(greaterThanEqual(outputCoord, uOutputSize))) return;
|
||||
ivec2 start = outputCoord * uInputSize / uOutputSize;
|
||||
ivec2 end = (outputCoord + 1) * uInputSize / uOutputSize;
|
||||
end = min(max(end, start + 1), uInputSize);
|
||||
|
||||
vec3 mean = vec3(0.0);
|
||||
int sampleCount = 0;
|
||||
for (int y = start.y; y < end.y; ++y) {
|
||||
for (int x = start.x; x < end.x; ++x) {
|
||||
mean += texelFetch(uLoResTexture, ivec2(x, y), 0).rgb;
|
||||
sampleCount += 1;
|
||||
}
|
||||
}
|
||||
mean /= float(max(sampleCount, 1));
|
||||
float meanSum = mean.r + mean.g + mean.b;
|
||||
vec3 brightSum = vec3(0.0);
|
||||
vec3 darkSum = vec3(0.0);
|
||||
int brightCount = 0;
|
||||
float clippedCount = 0.0;
|
||||
for (int y = start.y; y < end.y; ++y) {
|
||||
for (int x = start.x; x < end.x; ++x) {
|
||||
vec4 loResSample = texelFetch(uLoResTexture, ivec2(x, y), 0);
|
||||
vec3 sampleRgb = loResSample.rgb;
|
||||
clippedCount += loResSample.a;
|
||||
if (sampleRgb.r + sampleRgb.g + sampleRgb.b > meanSum) {
|
||||
brightSum += sampleRgb;
|
||||
brightCount += 1;
|
||||
} else {
|
||||
darkSum += sampleRgb;
|
||||
}
|
||||
}
|
||||
}
|
||||
int darkCount = sampleCount - brightCount;
|
||||
vec3 bright = brightSum / float(max(brightCount, 1));
|
||||
vec3 dark = darkSum / float(max(darkCount, 1));
|
||||
vec3 black = vec3(
|
||||
uBlackLevel.r / uWhiteLevel,
|
||||
0.5 * (uBlackLevel.g + uBlackLevel.b) / uWhiteLevel,
|
||||
uBlackLevel.a / uWhiteLevel
|
||||
);
|
||||
for (int channel = 0; channel < 3; ++channel) {
|
||||
if (bright[channel] > black[channel] ||
|
||||
dark[channel] > 2.0 * black[channel]) {
|
||||
bright[channel] = max(bright[channel] - black[channel], 0.0);
|
||||
dark[channel] = max(dark[channel] - black[channel], 0.0);
|
||||
} else {
|
||||
float merged = max(
|
||||
0.5 * (bright[channel] + dark[channel]) - black[channel],
|
||||
0.0
|
||||
);
|
||||
bright[channel] = merged;
|
||||
dark[channel] = merged;
|
||||
}
|
||||
}
|
||||
float sensorRange = max(
|
||||
1.0 - max(black.r, max(black.g, black.b)),
|
||||
1.0 / uWhiteLevel
|
||||
);
|
||||
int maskCode = 255 * brightCount / max(sampleCount, 1);
|
||||
vec3 outputRgb = (uComponent == 0 ? bright : dark) / sensorRange;
|
||||
imageStore(
|
||||
uOutput,
|
||||
outputCoord,
|
||||
vec4(
|
||||
outputRgb,
|
||||
uComponent == 0 ? float(maskCode) / 255.0 : clippedCount
|
||||
)
|
||||
);
|
||||
}
|
||||
""".trimIndent()
|
||||
}
|
||||
}
|
||||
@@ -1507,7 +1507,6 @@ class RawDemosaicProcessor {
|
||||
private val hdrReferencePass = RawHdrReferencePass(engineTonePass)
|
||||
private val meteringDemosaicAlgorithm = RawMeteringDemosaicAlgorithm()
|
||||
private val fastMomentsStatsAlgorithm = RawAEStatsAlgorithm()
|
||||
private val classicAeSplitAlgorithm = RawClassicAeSplitAlgorithm()
|
||||
private val quadBayerDemosaicAlgorithm = QuadBayerDemosaicAlgorithm()
|
||||
private val vgnDemosaicAlgorithm = VgnDemosaicAlgorithm()
|
||||
private val demosaicNoisePropagationCalibrator = DemosaicNoisePropagationCalibrator(
|
||||
@@ -1831,8 +1830,6 @@ class RawDemosaicProcessor {
|
||||
forceRegeneratePhotonPgtm: Boolean = false,
|
||||
photonHdrRatio: Float? = null,
|
||||
photonSourceToShortGain: Float? = null,
|
||||
photonPortraitRelightingGain: Float? = null,
|
||||
photonPortraitRelightingMask: FloatArray? = null,
|
||||
rawCfaCorrectionMode: String? = null,
|
||||
rawBlackBorderCrop: RawBlackBorderCrop = RawBlackBorderCrop(),
|
||||
onMetadata: ((RawMetadata) -> Unit)? = null
|
||||
@@ -1880,8 +1877,6 @@ class RawDemosaicProcessor {
|
||||
forceRegeneratePhotonPgtm = forceRegeneratePhotonPgtm,
|
||||
photonHdrRatio = photonHdrRatio,
|
||||
photonSourceToShortGain = photonSourceToShortGain,
|
||||
photonPortraitRelightingGain = photonPortraitRelightingGain,
|
||||
photonPortraitRelightingMask = photonPortraitRelightingMask,
|
||||
rawCfaCorrectionMode = rawCfaCorrectionMode,
|
||||
rawBlackBorderCrop = rawBlackBorderCrop,
|
||||
dngFile = dngFile,
|
||||
@@ -2333,8 +2328,6 @@ class RawDemosaicProcessor {
|
||||
forceRegeneratePhotonPgtm: Boolean = false,
|
||||
photonHdrRatio: Float? = null,
|
||||
photonSourceToShortGain: Float? = null,
|
||||
photonPortraitRelightingGain: Float? = null,
|
||||
photonPortraitRelightingMask: FloatArray? = null,
|
||||
rawCfaCorrectionMode: String? = null,
|
||||
rawBlackBorderCrop: RawBlackBorderCrop = RawBlackBorderCrop(),
|
||||
dngFile: File? = null,
|
||||
@@ -3160,12 +3153,6 @@ class RawDemosaicProcessor {
|
||||
?.takeIf { it.isFinite() && it >= 1f }
|
||||
val captureSourceToShortGain = solvedSceneExposure?.finalShortGain
|
||||
?.takeIf { it.isFinite() && it > 0f }
|
||||
val capturePortraitRelightingGain =
|
||||
solvedSceneExposure?.portraitRelightingGain
|
||||
?.takeIf { it.isFinite() && it > 0f }
|
||||
?: 1f
|
||||
val capturePortraitRelightingMask =
|
||||
solvedSceneExposure?.portraitRelightingMask
|
||||
val captureProfileGainTableMap = if (
|
||||
capturePhotonPgtmRequested && captureHdrRatio != null &&
|
||||
captureSourceToShortGain != null
|
||||
@@ -3192,8 +3179,6 @@ class RawDemosaicProcessor {
|
||||
// independent BaselineExposureOffset rendering adjustment.
|
||||
hdrRatio = captureHdrRatio,
|
||||
sourceToShortGain = captureSourceToShortGain,
|
||||
portraitRelightingGain = capturePortraitRelightingGain,
|
||||
portraitRelightingMask = capturePortraitRelightingMask,
|
||||
colorCorrectionMatrix = linearColorCorrectionMatrix,
|
||||
hueSatMap = activeDcpRenderPlan?.hueSatMap,
|
||||
hueSatMapSupportsOverrange = hueSatMapSupportsOverrange,
|
||||
@@ -3232,8 +3217,6 @@ class RawDemosaicProcessor {
|
||||
exposureOffsetEv = solvedExposureEv,
|
||||
hdrRatio = captureHdrRatio,
|
||||
finalShortGain = captureSourceToShortGain,
|
||||
portraitRelightingGain = capturePortraitRelightingGain,
|
||||
portraitRelightingMask = capturePortraitRelightingMask?.copyOf(),
|
||||
rawSceneExposureSummaryText = solvedSceneExposure?.summaryText,
|
||||
profileGainTableMap = captureProfileGainTableMap,
|
||||
gpuDemosaicedRawSource = reusableDemosaicSource,
|
||||
@@ -3299,15 +3282,6 @@ class RawDemosaicProcessor {
|
||||
"PERSISTED_CAPTURE_AE_FALLBACK"
|
||||
else -> "LEGACY_METADATA_FALLBACK"
|
||||
}
|
||||
val regenerationPortraitRelightingGain = photonPortraitRelightingGain
|
||||
?.takeIf { it.isFinite() && it > 0f }
|
||||
?: 1f
|
||||
val regenerationPortraitRelightingMask = photonPortraitRelightingMask
|
||||
?.takeIf { mask ->
|
||||
mask.size == RawSceneExposureMath.INPUT_WIDTH *
|
||||
RawSceneExposureMath.INPUT_HEIGHT &&
|
||||
mask.all { it.isFinite() && it in 0f..1f }
|
||||
}
|
||||
PLog.i(
|
||||
TAG,
|
||||
"HDRNet PGTM regeneration ratio=$regenerationHdrRatio " +
|
||||
@@ -3320,11 +3294,6 @@ class RawDemosaicProcessor {
|
||||
"finalShortTetMs=${estimatedExposure?.finalShortTetMs} " +
|
||||
"finalLongTetMs=${estimatedExposure?.finalLongTetMs} " +
|
||||
"finalShortGain=${estimatedExposure?.finalShortGain} " +
|
||||
"portraitRelightingRestored=" +
|
||||
"${regenerationPortraitRelightingMask != null} " +
|
||||
"portraitRelightingGain=$regenerationPortraitRelightingGain " +
|
||||
"portraitRelightingMaskRms=" +
|
||||
"${RawSceneExposureMath.faceMaskRms(regenerationPortraitRelightingMask)} " +
|
||||
"safeUnderexposure=${estimatedExposure?.safeUnderexposure} " +
|
||||
"fractionPixelsClippedAtFinalShortTet=" +
|
||||
"${estimatedExposure?.fractionPixelsClippedAtFinalShortTet}",
|
||||
@@ -3355,8 +3324,6 @@ class RawDemosaicProcessor {
|
||||
dcpBaselineExposureOffsetOrZero(activeDcpRenderPlan),
|
||||
hdrRatio = regenerationHdrRatio,
|
||||
sourceToShortGain = regenerationSourceToShortGain,
|
||||
portraitRelightingGain = regenerationPortraitRelightingGain,
|
||||
portraitRelightingMask = regenerationPortraitRelightingMask,
|
||||
colorCorrectionMatrix = linearColorCorrectionMatrix,
|
||||
hueSatMap = activeDcpRenderPlan?.hueSatMap,
|
||||
hueSatMapSupportsOverrange = hueSatMapSupportsOverrange,
|
||||
@@ -4450,8 +4417,6 @@ class RawDemosaicProcessor {
|
||||
rendererBaselineExposureEv: Float,
|
||||
hdrRatio: Float,
|
||||
sourceToShortGain: Float,
|
||||
portraitRelightingGain: Float = 1f,
|
||||
portraitRelightingMask: FloatArray? = null,
|
||||
colorCorrectionMatrix: FloatArray,
|
||||
hueSatMap: DcpHueSatMap?,
|
||||
hueSatMapSupportsOverrange: Boolean,
|
||||
@@ -4493,8 +4458,6 @@ class RawDemosaicProcessor {
|
||||
rendererBaselineExposureEv = rendererBaselineExposureEv,
|
||||
hdrRatio = hdrRatio,
|
||||
sourceToShortGain = sourceToShortGain,
|
||||
portraitRelightingGain = portraitRelightingGain,
|
||||
portraitRelightingMask = portraitRelightingMask,
|
||||
colorCorrectionMatrix = colorCorrectionMatrix,
|
||||
hueSatMap = hueSatMap,
|
||||
hueSatMapSupportsOverrange = hueSatMapSupportsOverrange,
|
||||
@@ -7880,86 +7843,6 @@ class RawDemosaicProcessor {
|
||||
profileGainTableTextureSource = null
|
||||
}
|
||||
|
||||
private fun renderRawClassicAeSplit(
|
||||
metadata: RawMetadata,
|
||||
rawTextureId: Int,
|
||||
sourceBounds: Rect,
|
||||
stackCompletionTimeline: GpuStackCompletionTimeline?,
|
||||
): RawSceneClassicAeMeteringFrame? {
|
||||
val size = RawClassicAeSplitAlgorithm.outputSize(
|
||||
sourceBounds = sourceBounds,
|
||||
cfaPattern = metadata.cfaPattern,
|
||||
) ?: return null
|
||||
setupLinearExposurePreviewFramebuffer(size.width, size.height)
|
||||
fun renderComponent(component: Int): FloatArray? {
|
||||
if (!classicAeSplitAlgorithm.execute(
|
||||
RawClassicAeSplitAlgorithm.Input(
|
||||
rawTextureId = rawTextureId,
|
||||
outputTextureId = linearExposurePreviewTextureId,
|
||||
imageWidth = metadata.width,
|
||||
imageHeight = metadata.height,
|
||||
sourceBounds = sourceBounds,
|
||||
cfaPattern = metadata.cfaPattern,
|
||||
blackLevel = FloatArray(4) { channel ->
|
||||
metadata.blackLevel.getOrElse(channel) {
|
||||
metadata.blackLevel.firstOrNull() ?: 0f
|
||||
}
|
||||
},
|
||||
whiteLevel = metadata.whiteLevel,
|
||||
component = component,
|
||||
),
|
||||
)
|
||||
) {
|
||||
return null
|
||||
}
|
||||
return readSceneExposureChannels(
|
||||
width = size.width,
|
||||
height = size.height,
|
||||
stackCompletionTimeline = if (component == 0) stackCompletionTimeline else null,
|
||||
label = "RAW Classic AE split component $component",
|
||||
channelCount = 4,
|
||||
)
|
||||
}
|
||||
val brightReadback = renderComponent(0) ?: return null
|
||||
val darkReadback = renderComponent(1) ?: return null
|
||||
val pixelCount = size.width * size.height
|
||||
val brightRgb = FloatArray(pixelCount * 3)
|
||||
val darkRgb = FloatArray(pixelCount * 3)
|
||||
val brightMask = ByteArray(pixelCount)
|
||||
var clippedSampleCount = 0f
|
||||
for (pixel in 0 until pixelCount) {
|
||||
val readOffset = pixel * 4
|
||||
val rgbOffset = pixel * 3
|
||||
for (channel in 0..2) {
|
||||
brightRgb[rgbOffset + channel] = brightReadback[readOffset + channel]
|
||||
darkRgb[rgbOffset + channel] = darkReadback[readOffset + channel]
|
||||
}
|
||||
brightMask[pixel] = (
|
||||
brightReadback[readOffset + 3].coerceIn(0f, 1f) * 255f + 0.5f
|
||||
).toInt().coerceIn(0, 255).toByte()
|
||||
clippedSampleCount += darkReadback[readOffset + 3].coerceAtLeast(0f)
|
||||
}
|
||||
if (brightRgb.any { !it.isFinite() || it < 0f } ||
|
||||
darkRgb.any { !it.isFinite() || it < 0f }
|
||||
) {
|
||||
return null
|
||||
}
|
||||
return RawSceneClassicAeMeteringFrame(
|
||||
width = size.width,
|
||||
height = size.height,
|
||||
brightRgb = brightRgb,
|
||||
darkRgb = darkRgb,
|
||||
brightMask = brightMask,
|
||||
clippedFraction = (
|
||||
clippedSampleCount /
|
||||
RawClassicAeSplitAlgorithm.cfaSampleCount(
|
||||
sourceBounds = sourceBounds,
|
||||
cfaPattern = metadata.cfaPattern,
|
||||
).takeIf { it > 0 }?.toFloat().let { it ?: return null }
|
||||
).coerceIn(0f, 1f),
|
||||
)
|
||||
}
|
||||
|
||||
private fun renderSceneExposureRequest(
|
||||
request: RawSceneExposureRequest,
|
||||
metadata: RawMetadata,
|
||||
@@ -8120,57 +8003,6 @@ class RawDemosaicProcessor {
|
||||
lensShadingStats = lensShadingStats,
|
||||
) ?: return null
|
||||
val meteringCompletedNs = System.nanoTime()
|
||||
val legacyMeteringRgb = RawSceneExposureMath.prepareMgcLegacyMeteringRgb(
|
||||
cameraRgb = cameraRgb,
|
||||
width = width,
|
||||
height = height,
|
||||
metadata = meteringMetadata,
|
||||
lensShadingStats = lensShadingStats,
|
||||
) ?: return null
|
||||
val legacyMeteringCompletedNs = System.nanoTime()
|
||||
val rawClassicSplit = baseFrameMetering?.classicAe ?: if (
|
||||
rawSamplesPerPixel == 1 && rawTextureIdForStats != 0
|
||||
) {
|
||||
renderRawClassicAeSplit(
|
||||
metadata = metadata,
|
||||
rawTextureId = rawTextureIdForStats,
|
||||
sourceBounds = rawAeBounds,
|
||||
stackCompletionTimeline = stackCompletionTimeline,
|
||||
)
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val classicAeInput: RawSceneClassicAeMeteringFrame
|
||||
val classicAeSource: String
|
||||
if (rawClassicSplit != null) {
|
||||
classicAeInput = RawSceneExposureMath.prepareMgcClassicAeMeteringFrame(
|
||||
split = rawClassicSplit,
|
||||
metadata = meteringMetadata,
|
||||
sourceBounds = if (baseFrameMetering != null) {
|
||||
normalizedBounds
|
||||
} else {
|
||||
normalizedRawAeBounds
|
||||
},
|
||||
lensShadingStats = lensShadingStats,
|
||||
) ?: return null
|
||||
classicAeSource = if (baseFrameMetering?.classicAe != null) {
|
||||
"BASE_RAW_CLASSIC_SPLIT"
|
||||
} else {
|
||||
"DNG_RAW_CLASSIC_SPLIT"
|
||||
}
|
||||
} else {
|
||||
// LinearRaw/RGB sources have no CFA grid. MGC's RGB entry point is the defined
|
||||
// non-QCOM fallback: component 0 contains RGB, component 1 is zero, mask is 255.
|
||||
classicAeInput = RawSceneClassicAeMeteringFrame(
|
||||
width = width,
|
||||
height = height,
|
||||
brightRgb = legacyMeteringRgb,
|
||||
darkRgb = FloatArray(legacyMeteringRgb.size),
|
||||
brightMask = ByteArray(width * height) { 0xFF.toByte() },
|
||||
)
|
||||
classicAeSource = "LINEAR_RGB_CLASSIC_ENTRY"
|
||||
}
|
||||
val classicCompletedNs = System.nanoTime()
|
||||
val meteringRgbMean = FloatArray(3)
|
||||
val meteringRgbMax = FloatArray(3)
|
||||
for (pixel in 0 until width * height) {
|
||||
@@ -8195,16 +8027,18 @@ class RawDemosaicProcessor {
|
||||
"RAW_SCENE_EXPOSURE stage=INPUT_PREP_TIMING " +
|
||||
"setupMs=${elapsedMs(inputPreparationStartedNs, meteringStartedNs)} " +
|
||||
"fastMeteringMs=${elapsedMs(meteringStartedNs, meteringCompletedNs)} " +
|
||||
"legacyMeteringMs=" +
|
||||
"${elapsedMs(meteringCompletedNs, legacyMeteringCompletedNs)} " +
|
||||
"classicMs=${elapsedMs(legacyMeteringCompletedNs, classicCompletedNs)} " +
|
||||
"diagnosticsMs=${elapsedMs(classicCompletedNs, diagnosticsCompletedNs)} " +
|
||||
"diagnosticsMs=${elapsedMs(meteringCompletedNs, diagnosticsCompletedNs)} " +
|
||||
"totalMs=${elapsedMs(inputPreparationStartedNs, diagnosticsCompletedNs)}",
|
||||
)
|
||||
PLog.i(
|
||||
TAG,
|
||||
"RAW_SCENE_EXPOSURE stage=INPUT_COLOR_CONTRACT " +
|
||||
"RAW_SCENE_EXPOSURE stage=INPUT_COLOR_CONTRACT " +
|
||||
"meteringSource=$meteringInputSource " +
|
||||
"meteringGeometry=${if (baseFrameMetering != null) {
|
||||
"MGC_RAW_ROWS_X1_OR_X4_GROUPS_DIRECT_64X64"
|
||||
} else {
|
||||
"RENDERED_CAMERA_RGB_AREA_64X64_FALLBACK"
|
||||
}} " +
|
||||
"sourceBaselineRestored=$restoreFallbackBaselineExposure " +
|
||||
"sourceBaselineGain=$sourceBaselineGain " +
|
||||
"lscSource=${when {
|
||||
@@ -8218,10 +8052,7 @@ class RawDemosaicProcessor {
|
||||
"rggbGains=${gains.contentToString()} " +
|
||||
"rgbGains=${rgbGains.contentToString()} " +
|
||||
"rgb2rgb=${meteringRgbTransform.contentToString()} " +
|
||||
"classicAeSource=$classicAeSource " +
|
||||
"classicAeSize=${classicAeInput.width}x${classicAeInput.height} " +
|
||||
"rawAeBounds=$rawAeBounds " +
|
||||
"classicAeClippedFraction=${classicAeInput.clippedFraction} " +
|
||||
"meteringRgbMean=${meteringRgbMean.contentToString()} " +
|
||||
"meteringRgbMax=${meteringRgbMax.contentToString()}",
|
||||
)
|
||||
@@ -8355,11 +8186,6 @@ class RawDemosaicProcessor {
|
||||
height = height,
|
||||
rgb = meteringRgb,
|
||||
fastMomentsStats = fastMomentsStats,
|
||||
legacyAeInput = RawSceneLegacyAeInput(
|
||||
splitHdrImage = classicAeInput,
|
||||
rgbGains = rgbGains,
|
||||
rgbTransform = meteringRgbTransform,
|
||||
),
|
||||
),
|
||||
)
|
||||
} catch (error: Throwable) {
|
||||
@@ -8832,7 +8658,6 @@ class RawDemosaicProcessor {
|
||||
profileGainTableAlgorithm.release()
|
||||
meteringDemosaicAlgorithm.release()
|
||||
fastMomentsStatsAlgorithm.release()
|
||||
classicAeSplitAlgorithm.release()
|
||||
linearRcdPass.release()
|
||||
photonDehazePipeline.release()
|
||||
warpRectilinearPass.release()
|
||||
|
||||
@@ -4,8 +4,6 @@ import android.graphics.Rect
|
||||
import android.hardware.camera2.CameraCharacteristics
|
||||
import com.hinnka.mycamera.processor.GpuLinearRgbSource
|
||||
import java.nio.ByteBuffer
|
||||
import java.util.Base64
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/** Camera metadata needed to construct MGC's ordinary (range type 0) AE shot range. */
|
||||
data class RawSceneExposureDeviceLimits(
|
||||
@@ -115,10 +113,6 @@ data class RawDngCaptureProfileResult(
|
||||
val hdrRatio: Float?,
|
||||
/** Capture-time source/final-short TET quotient consumed by HDRNet input normalization. */
|
||||
val finalShortGain: Float?,
|
||||
/** MGC portrait/long TET quotient consumed by post-HDRNet local relighting. */
|
||||
val portraitRelightingGain: Float = 1f,
|
||||
/** Unrotated sensor-space 64 x 64 soft face mask used by local relighting. */
|
||||
val portraitRelightingMask: FloatArray? = null,
|
||||
/** Capture-time MGC AE inputs and results serialized as photon:SummaryText in the DNG XMP. */
|
||||
val rawSceneExposureSummaryText: String? = null,
|
||||
val profileGainTableMap: DngProfileGainTableMap?,
|
||||
@@ -140,8 +134,6 @@ data class RawDngProfilePreparation(
|
||||
val baselineExposureEv: Float,
|
||||
val hdrRatio: Float?,
|
||||
val finalShortGain: Float?,
|
||||
val portraitRelightingGain: Float = 1f,
|
||||
val portraitRelightingMask: FloatArray? = null,
|
||||
val rawSceneExposureSummaryText: String? = null,
|
||||
val profileGainTableMap: DngProfileGainTableMap?,
|
||||
val gpuDemosaicedRawSource: GpuDemosaicedRawSource? = null,
|
||||
@@ -192,56 +184,6 @@ internal object RawPhotonHdrRatioMetadata {
|
||||
}
|
||||
}
|
||||
|
||||
internal data class RawPhotonPortraitRelighting(
|
||||
val gain: Float,
|
||||
val mask: FloatArray,
|
||||
)
|
||||
|
||||
/** Capture-time portrait quotient and mask required to reproduce PGTM during gallery refresh. */
|
||||
internal object RawPhotonPortraitRelightingMetadata {
|
||||
private const val GAIN_PROPERTY = "photonPortraitRelightingGain"
|
||||
private const val MASK_PROPERTY = "photonPortraitRelightingMask64U8"
|
||||
private const val MASK_WIDTH = RawSceneExposureMath.INPUT_WIDTH
|
||||
private const val MASK_HEIGHT = RawSceneExposureMath.INPUT_HEIGHT
|
||||
private const val MASK_SIZE = MASK_WIDTH * MASK_HEIGHT
|
||||
|
||||
fun read(properties: Map<String, String>): RawPhotonPortraitRelighting? {
|
||||
val gain = properties[GAIN_PROPERTY]
|
||||
?.toFloatOrNull()
|
||||
?.takeIf { it.isFinite() && it > 0f }
|
||||
?: return null
|
||||
val encodedMask = properties[MASK_PROPERTY] ?: return null
|
||||
val bytes = try {
|
||||
Base64.getDecoder().decode(encodedMask)
|
||||
} catch (_: IllegalArgumentException) {
|
||||
return null
|
||||
}
|
||||
if (bytes.size != MASK_SIZE) return null
|
||||
val mask = FloatArray(MASK_SIZE) { index ->
|
||||
(bytes[index].toInt() and 0xFF) / 255f
|
||||
}
|
||||
return RawPhotonPortraitRelighting(gain = gain, mask = mask)
|
||||
}
|
||||
|
||||
fun write(
|
||||
properties: Map<String, String>,
|
||||
gain: Float,
|
||||
mask: FloatArray?,
|
||||
): Map<String, String> {
|
||||
if (!gain.isFinite() || gain <= 0f || mask == null || mask.size != MASK_SIZE ||
|
||||
mask.any { !it.isFinite() || it !in 0f..1f }
|
||||
) {
|
||||
return properties - GAIN_PROPERTY - MASK_PROPERTY
|
||||
}
|
||||
val bytes = ByteArray(MASK_SIZE) { index ->
|
||||
(mask[index] * 255f).roundToInt().coerceIn(0, 255).toByte()
|
||||
}
|
||||
return properties + mapOf(
|
||||
GAIN_PROPERTY to gain.toString(),
|
||||
MASK_PROPERTY to Base64.getEncoder().withoutPadding().encodeToString(bytes),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Capture-request AE compensation persisted independently from presentation ExposureBias. */
|
||||
internal object RawCaptureExposureCompensationMetadata {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -40,8 +40,6 @@ internal object RawSceneExposureMatcher {
|
||||
finalShortTetMs = estimate.finalShortTetMs,
|
||||
finalLongTetMs = estimate.finalLongTetMs,
|
||||
finalShortGain = estimate.finalShortGain,
|
||||
portraitRelightingGain = estimate.portraitRelightingGain,
|
||||
portraitRelightingMask = faceMeteringMask?.copyOf(),
|
||||
safeUnderexposure = estimate.safeUnderexposure,
|
||||
fractionPixelsClippedAtFinalShortTet =
|
||||
estimate.fractionPixelsClippedAtFinalShortTet,
|
||||
@@ -61,8 +59,6 @@ internal data class RawSceneExposureResult(
|
||||
val finalShortTetMs: Float,
|
||||
val finalLongTetMs: Float,
|
||||
val finalShortGain: Float,
|
||||
val portraitRelightingGain: Float = 1f,
|
||||
val portraitRelightingMask: FloatArray? = null,
|
||||
val safeUnderexposure: Float,
|
||||
val fractionPixelsClippedAtFinalShortTet: Float,
|
||||
val summaryText: String? = null,
|
||||
@@ -72,13 +68,6 @@ internal data class RawSceneExposureResult(
|
||||
require(finalShortTetMs.isFinite() && finalShortTetMs > 0f)
|
||||
require(finalLongTetMs.isFinite() && finalLongTetMs >= finalShortTetMs)
|
||||
require(finalShortGain.isFinite() && finalShortGain > 0f)
|
||||
require(portraitRelightingGain.isFinite() && portraitRelightingGain > 0f)
|
||||
require(
|
||||
portraitRelightingMask == null ||
|
||||
(portraitRelightingMask.size ==
|
||||
RawSceneExposureMath.INPUT_WIDTH * RawSceneExposureMath.INPUT_HEIGHT &&
|
||||
portraitRelightingMask.all { it.isFinite() && it in 0f..1f }),
|
||||
)
|
||||
require(safeUnderexposure.isFinite() && safeUnderexposure >= 1f)
|
||||
require(
|
||||
fractionPixelsClippedAtFinalShortTet.isFinite() &&
|
||||
|
||||
@@ -830,8 +830,6 @@ object RawProcessor {
|
||||
baselineExposureEv = finalBaselineExposureEv,
|
||||
hdrRatio = captureProfile?.hdrRatio,
|
||||
finalShortGain = captureProfile?.finalShortGain,
|
||||
portraitRelightingGain = captureProfile?.portraitRelightingGain ?: 1f,
|
||||
portraitRelightingMask = captureProfile?.portraitRelightingMask?.copyOf(),
|
||||
rawSceneExposureSummaryText = captureProfile?.rawSceneExposureSummaryText,
|
||||
profileGainTableMap = preparedProfileGainTableMap,
|
||||
gpuDemosaicedRawSource = captureProfile?.gpuDemosaicedRawSource,
|
||||
|
||||
Reference in new issue
Block a user