feat: raw pipeline optimize

(cherry picked from commit c504c2b6b9)
This commit is contained in:
zhoubinjia authored and Hinnka committed 2026-08-01 13:13:02 +08:00
1 parent 18e0ba8328
commit b6fb42e3e5
5 files changed
+382 -38

No files matched your search

@@ -237,7 +237,11 @@ class RawDemosaicProcessor {
// It is also above the native level-35 gate, so the complete IIR2 pass 1/2/3 chain runs.
private const val VGN_COLOR_NOISE_LEVEL = 50
private const val VGN_ADVANCED_COLOR_NOISE_ENABLED = true
private const val RAW_TILE_CORE_EDGE_PX = 2048
private const val RAW_TILE_CORE_EDGE_PX = 4096
// Shader prewarming only needs representative resource dimensions. Keep it independent
// from the production tile core so increasing render throughput does not reserve a
// full-size capture working set while the camera is opening.
private const val RAW_PREWARM_CORE_EDGE_PX = 2048
// Phocus GetStripMargin(50) returns 60 pixels for gradient/color-noise interpolation.
// The remaining 52 pixels cover chroma denoise, NLM, shadows/highlights and sharpening.
private const val RAW_TILE_SUPPORT_PX = 112
@@ -400,10 +404,12 @@ class RawDemosaicProcessor {
cameraWhite = floatArrayOf(1f, 1f, 1f),
frameCount = frameCount.coerceAtLeast(1),
)
val textures = IntArray(1)
val textures = IntArray(2)
GLES30.glGenTextures(textures.size, textures, 0)
val previousRawTextureId = rawTextureId
return try {
val linearRawTexture = textures[0]
val meteringRawTexture = textures[1]
createCaptureWarmupTexture(
textureId = linearRawTexture,
internalFormat = GLES30.GL_RGBA16UI,
@@ -413,6 +419,26 @@ class RawDemosaicProcessor {
height = programSize.height,
pixels = null,
)
createCaptureWarmupTexture(
textureId = meteringRawTexture,
internalFormat = GLES30.GL_R16UI,
format = GLES30.GL_RED_INTEGER,
type = GLES30.GL_UNSIGNED_SHORT,
width = programSize.width,
height = programSize.height,
pixels = null,
)
rawTextureId = meteringRawTexture
setupFullResFramebuffer(
(programSize.width + 1) / 2,
(programSize.height + 1) / 2,
)
runHalfResolutionMeteringDemosaic(
metadata = metadata,
width = programSize.width,
height = programSize.height,
)
rawTextureId = previousRawTextureId
// High-resolution capture uses the same bounded tile capacity as rendering. Prewarm
// must not allocate whole-frame intermediates merely to compile a small viewport.
setupFullResFramebuffer(resourceSize.width, resourceSize.height)
@@ -510,6 +536,7 @@ class RawDemosaicProcessor {
)
exposureReady && profileReady
} finally {
rawTextureId = previousRawTextureId
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0)
GLES30.glDeleteTextures(textures.size, textures, 0)
}
@@ -842,6 +869,7 @@ class RawDemosaicProcessor {
private var pgtmGoogleGainCurvesProgram = 0
private val pgtmPhotonPrograms =
IntArray(DngPhotonLocalToneMapGpuShaders.Pass.entries.size)
private var meteringHalfResolutionProgram = 0
private var linearRcdProgram = 0
private var warpRectilinearProgram = 0
private var linearRawRgbProgram = 0
@@ -1907,6 +1935,14 @@ class RawDemosaicProcessor {
RawTilePlanner.shouldTile(outputSourceBounds.width(), outputSourceBounds.height()) ||
RawTilePlanner.shouldTile(actualWidth, actualHeight)
val hasActiveWarp = applicableDngWarpRectilinear?.isNotEmpty() == true
val captureProfilePreparationRequested =
exposurePreviewRequest != null || captureProfileToneMapMode != null
val useHalfResolutionMeteringDemosaic =
exposurePreviewRequest != null &&
actualSamplesPerPixel == 1 &&
actualMetadata.frameCount == 1 &&
actualMetadata.cfaPattern in RawMetadata.CFA_RGGB..RawMetadata.CFA_BGGR &&
!hasActiveWarp
val tileBlockingReason = when {
!highResolutionOutput -> null
actualSamplesPerPixel !in setOf(1, 3, 4) ->
@@ -1915,7 +1951,7 @@ class RawDemosaicProcessor {
hasActiveWarp -> "DNG WarpRectilinear requires a displacement-aware source region"
colorEngine == RawRenderingEngine.DarktableFilmic ->
"Darktable Filmic wavelet reconstruction requires scale-by-scale tiling"
exposurePreviewRequest != null || captureProfileToneMapMode != null ->
captureProfilePreparationRequested ->
"capture metering/profile preparation"
else -> null
}
@@ -1973,7 +2009,15 @@ class RawDemosaicProcessor {
return@withContext null
}
if (rawRenderTiles.isEmpty()) {
setupFullResFramebuffer(actualWidth, actualHeight)
when {
useHalfResolutionMeteringDemosaic -> setupFullResFramebuffer(
(actualWidth + 1) / 2,
(actualHeight + 1) / 2,
)
!captureProfilePreparationRequested || exposurePreviewRequest != null ->
setupFullResFramebuffer(actualWidth, actualHeight)
}
}
if (borrowedGpuSource != null) {
if (rawTextureId != 0 && rawTextureId != borrowedGpuSource.textureId) {
@@ -2273,7 +2317,18 @@ class RawDemosaicProcessor {
// 4. Full-frame demosaic is only valid for the legacy path. High-resolution
// rendering performs the same work from renderRawTiles() after all shared
// profile/exposure state has been resolved.
if (actualSamplesPerPixel in 3..4) {
if (useHalfResolutionMeteringDemosaic) {
runHalfResolutionMeteringDemosaic(
metadata = actualMetadata,
width = actualWidth,
height = actualHeight,
)
} else if (captureProfilePreparationRequested && exposurePreviewRequest == null) {
PLog.d(
TAG,
"RAW capture profile preparation skipped demosaic: exposure matching disabled",
)
} else if (actualSamplesPerPixel in 3..4) {
renderLinearRawRgbToTexture(
sourceTextureId = rawTextureId,
sourceSamplesPerPixel = actualSamplesPerPixel,
@@ -2317,7 +2372,12 @@ class RawDemosaicProcessor {
)
}
}
applicableDngWarpRectilinear?.let { warps ->
applicableDngWarpRectilinear
?.takeUnless {
useHalfResolutionMeteringDemosaic ||
(captureProfilePreparationRequested && exposurePreviewRequest == null)
}
?.let { warps ->
var appliedWarpCount = 0
for (offset in warps.indices step 8) {
val parameters = warps.copyOfRange(offset, offset + 8)
@@ -2348,7 +2408,7 @@ class RawDemosaicProcessor {
}
}
if (exposurePreviewRequest != null || captureProfileToneMapMode != null) {
if (captureProfilePreparationRequested) {
val solvedExposureEv = exposurePreviewRequest?.let { request ->
renderExposurePreviewRequest(
request = request,
@@ -4763,6 +4823,7 @@ class RawDemosaicProcessor {
initShaderProgram()
if (sharpenProgram == 0 || passthroughProgram == 0 ||
chromaDenoiseGuideProgram == 0 || chromaDenoiseProgram == 0 ||
meteringHalfResolutionProgram == 0 ||
linearRcdProgram == 0 || linearRawRgbProgram == 0 ||
linearRawRgbExpandProgram == 0
) {
@@ -4771,6 +4832,7 @@ class RawDemosaicProcessor {
"sharpen=$sharpenProgram pass=$passthroughProgram " +
"chromaGuide=$chromaDenoiseGuideProgram " +
"chromaDenoise=$chromaDenoiseProgram " +
"meteringHalf=$meteringHalfResolutionProgram " +
"linearRcd=$linearRcdProgram linearRawRgb=$linearRawRgbProgram " +
"linearRawRgbExpand=$linearRawRgbExpandProgram"
)
@@ -4914,6 +4976,7 @@ class RawDemosaicProcessor {
PLog.d(
TAG,
"Shader programs created: passthrough=$passthroughProgram " +
"meteringHalf=$meteringHalfResolutionProgram " +
"pgtmStats=$pgtmCellStatsProgram googlePgtmCurves=$pgtmGoogleGainCurvesProgram " +
"photonPgtm=localLaplacianBgu"
)
@@ -5273,6 +5336,10 @@ class RawDemosaicProcessor {
"DNG_PHOTON_PGTM_${pass.name}",
)
}
meteringHalfResolutionProgram = compileComputeProgram(
RawMeteringDemosaicShaders.HALF_RESOLUTION,
"RAW_METERING_HALF_RESOLUTION",
)
val fShaderLinearRcd = compileShader(
GLES30.GL_FRAGMENT_SHADER,
FRAGMENT_SHADER_LINEAR_RCD,
@@ -7752,6 +7819,108 @@ class RawDemosaicProcessor {
}
}
/**
* 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
* the full VGN output, so the existing DCP/default-curve preview path remains authoritative.
*/
private fun runHalfResolutionMeteringDemosaic(
metadata: RawMetadata,
width: Int,
height: Int,
) {
require(meteringHalfResolutionProgram != 0) {
"RAW metering half-resolution program is unavailable"
}
require(metadata.cfaPattern in RawMetadata.CFA_RGGB..RawMetadata.CFA_BGGR) {
"Half-resolution metering requires a standard 2x2 Bayer CFA"
}
val outputWidth = (width + 1) / 2
val outputHeight = (height + 1) / 2
check(demosaicWidth == outputWidth && demosaicHeight == outputHeight) {
"RAW metering target mismatch: ${demosaicWidth}x$demosaicHeight, " +
"expected=${outputWidth}x$outputHeight"
}
val startNs = System.nanoTime()
val blackLevel4 = FloatArray(4) { index ->
metadata.blackLevel.getOrElse(index) {
metadata.blackLevel.firstOrNull() ?: 0f
}.coerceAtLeast(0f)
}
GLES31.glUseProgram(meteringHalfResolutionProgram)
GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + RCD_RAW_TEXTURE_UNIT)
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, rawTextureId)
GLES31.glUniform1i(
GLES31.glGetUniformLocation(meteringHalfResolutionProgram, "uRawTexture"),
RCD_RAW_TEXTURE_UNIT,
)
bindLensShadingForProgram(meteringHalfResolutionProgram, metadata)
GLES31.glUniform2i(
GLES31.glGetUniformLocation(meteringHalfResolutionProgram, "uImageSize"),
width,
height,
)
GLES31.glUniform2i(
GLES31.glGetUniformLocation(meteringHalfResolutionProgram, "uOutputSize"),
outputWidth,
outputHeight,
)
GLES31.glUniform1i(
GLES31.glGetUniformLocation(meteringHalfResolutionProgram, "uCfaPattern"),
metadata.cfaPattern,
)
GLES31.glUniform4fv(
GLES31.glGetUniformLocation(meteringHalfResolutionProgram, "uBlackLevel"),
1,
blackLevel4,
0,
)
GLES31.glUniform1f(
GLES31.glGetUniformLocation(meteringHalfResolutionProgram, "uWhiteLevel"),
metadata.whiteLevel,
)
GLES31.glBindImageTexture(
0,
demosaicTextureId,
0,
false,
0,
GLES31.GL_WRITE_ONLY,
GLES30.GL_RGBA16F,
)
GLES31.glDispatchCompute(
GlesComputeWorkGroup.imageGroupCount(outputWidth),
GlesComputeWorkGroup.imageGroupCount(outputHeight),
1,
)
GLES31.glMemoryBarrier(
GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or
GLES31.GL_TEXTURE_FETCH_BARRIER_BIT,
)
checkGlError("RAW metering half-resolution demosaic")
GlesGpuScheduler.waitForGpuCheckpoint(TAG, "RAW metering half-resolution demosaic")
GLES31.glBindImageTexture(
0,
0,
0,
false,
0,
GLES31.GL_READ_ONLY,
GLES30.GL_RGBA16F,
)
GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + RCD_LENS_SHADING_TEXTURE_UNIT)
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0)
GLES31.glActiveTexture(GLES31.GL_TEXTURE0 + RCD_RAW_TEXTURE_UNIT)
GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0)
PLog.d(
TAG,
"RAW metering half-resolution demosaic complete: " +
"source=${width}x$height output=${outputWidth}x$outputHeight " +
"cfa=${metadata.cfaPattern} tookMs=" +
"${(System.nanoTime() - startNs) / 1_000_000}",
)
}
private fun runStandardBayerRcdDemosaic(
metadata: RawMetadata,
width: Int,
@@ -11418,7 +11587,7 @@ class RawDemosaicProcessor {
sourceHeight = sourceHeight,
outputSourceBounds = RawTileRect(0, 0, sourceWidth, sourceHeight),
rotation = 0,
coreEdgePx = RAW_TILE_CORE_EDGE_PX,
coreEdgePx = RAW_PREWARM_CORE_EDGE_PX,
supportPx = RAW_TILE_SUPPORT_PX,
cfaPeriod = 2,
).first().sourceWorking
@@ -11975,6 +12144,10 @@ class RawDemosaicProcessor {
if (quadRefineProgram != 0) GLES31.glDeleteProgram(quadRefineProgram)
if (quadWriteOutputProgram != 0) GLES31.glDeleteProgram(quadWriteOutputProgram)
if (pgtmCellStatsProgram != 0) GLES31.glDeleteProgram(pgtmCellStatsProgram)
if (meteringHalfResolutionProgram != 0) {
GLES31.glDeleteProgram(meteringHalfResolutionProgram)
meteringHalfResolutionProgram = 0
}
if (pgtmGoogleGainCurvesProgram != 0) {
GLES31.glDeleteProgram(pgtmGoogleGainCurvesProgram)
}
@@ -0,0 +1,127 @@
package com.hinnka.mycamera.raw
/**
* Capture-metering RAW preparation.
*
* Each output texel collapses one standard 2x2 Bayer cell into un-white-balanced camera RGB.
* Spatial interpolation is deliberately omitted: exposure matching consumes a 256-pixel preview,
* while preserving the RAW black-level and lens-shading domains is materially more important than
* reconstructing full-resolution edges.
*/
internal object RawMeteringDemosaicShaders {
val HALF_RESOLUTION = """
#version 310 es
layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in;
precision highp float;
precision highp int;
precision highp usampler2D;
precision highp image2D;
uniform highp usampler2D uRawTexture;
uniform sampler2D uLensShadingMap;
uniform ivec2 uImageSize;
uniform ivec2 uOutputSize;
uniform int uCfaPattern;
uniform vec4 uBlackLevel;
uniform float uWhiteLevel;
uniform int uLensShadingEnabled;
uniform int uLensShadingUsesDngGrid;
uniform vec2 uLensShadingMapSize;
uniform vec4 uLensShadingGrid;
uniform vec2 uLensShadingBoundsOrigin;
uniform vec2 uLensShadingBoundsSize;
layout(rgba16f, binding = 0) writeonly uniform image2D uOutput;
int channelAt(int pattern, ivec2 coord) {
int index = (coord.x & 1) + ((coord.y & 1) << 1);
if (pattern == 1) {
if (index == 0) return 1;
if (index == 1) return 0;
if (index == 2) return 3;
return 2;
}
if (pattern == 2) {
if (index == 0) return 2;
if (index == 1) return 3;
if (index == 2) return 0;
return 1;
}
if (pattern == 3) {
if (index == 0) return 3;
if (index == 1) return 2;
if (index == 2) return 1;
return 0;
}
return index;
}
int lensShadingChannelAt(int channel, ivec2 coord) {
if (uLensShadingUsesDngGrid != 0 || channel == 0 || channel == 3) {
return channel;
}
return (coord.y & 1) == 0 ? 1 : 2;
}
float lensShadingGainAt(int channel, ivec2 coord) {
if (uLensShadingEnabled == 0) return 1.0;
vec2 normalized = (vec2(coord) + vec2(0.5)) / vec2(uImageSize);
vec2 uv = normalized;
if (uLensShadingUsesDngGrid != 0) {
vec2 boundsSize = max(uLensShadingBoundsSize, vec2(1.0));
normalized =
(vec2(coord) + vec2(0.5) - uLensShadingBoundsOrigin) / boundsSize;
vec2 mapIndex = (normalized - uLensShadingGrid.xy) /
max(uLensShadingGrid.zw, vec2(1e-8));
uv = (mapIndex + vec2(0.5)) / max(uLensShadingMapSize, vec2(1.0));
}
vec4 gains = texture(uLensShadingMap, uv);
return max(gains[lensShadingChannelAt(channel, coord)], 0.0);
}
float normalizedRawAt(ivec2 coord, int channel) {
float raw = float(texelFetch(uRawTexture, coord, 0).r);
float black = uBlackLevel[clamp(channel, 0, 3)];
float sensorRange = max(uWhiteLevel - black, 1.0);
return clamp((raw - black) / sensorRange, 0.0, 1.0) *
lensShadingGainAt(channel, coord);
}
void main() {
ivec2 outputCoord = ivec2(gl_GlobalInvocationID.xy);
if (any(greaterThanEqual(outputCoord, uOutputSize))) return;
ivec2 base = outputCoord * 2;
vec3 sums = vec3(0.0);
vec3 counts = vec3(0.0);
for (int dy = 0; dy < 2; ++dy) {
for (int dx = 0; dx < 2; ++dx) {
ivec2 coord = min(base + ivec2(dx, dy), uImageSize - ivec2(1));
int channel = channelAt(uCfaPattern, coord);
float value = normalizedRawAt(coord, channel);
if (channel == 0) {
sums.r += value;
counts.r += 1.0;
} else if (channel == 3) {
sums.b += value;
counts.b += 1.0;
} else {
sums.g += value;
counts.g += 1.0;
}
}
}
float fallback = (sums.r + sums.g + sums.b) /
max(counts.r + counts.g + counts.b, 1.0);
vec3 cameraRgb = vec3(
counts.r > 0.0 ? sums.r / counts.r : fallback,
counts.g > 0.0 ? sums.g / counts.g : fallback,
counts.b > 0.0 ? sums.b / counts.b : fallback
);
imageStore(uOutput, outputCoord, vec4(max(cameraRgb, vec3(0.0)), 1.0));
}
""".trimIndent()
}
@@ -76,22 +76,8 @@ internal object RawTilePlanner {
} else {
outputSourceBounds.height
}
// A cropped core can start at any sensor phase. Reserving phase - 1 additional pixels
// keeps both sides at or above the requested support after the working origin is aligned.
val workWidth = stableWorkingLength(
sourceSize = sourceWidth,
requestedLength = coreEdge + support * 2 + phase - 1,
phase = phase,
)
val workHeight = stableWorkingLength(
sourceSize = sourceHeight,
requestedLength = coreEdge + support * 2 + phase - 1,
phase = phase,
)
val result = ArrayList<RawRenderTile>()
val cores = ArrayList<Pair<RawTileRect, RawTileRect>>()
var outputTop = 0
var index = 0
while (outputTop < outputHeight) {
val outputBottom = minOf(outputHeight, outputTop + coreEdge)
var outputLeft = 0
@@ -103,25 +89,46 @@ internal object RawTilePlanner {
sourceBounds = outputSourceBounds,
rotation = rotation,
)
result += RawRenderTile(
index = index++,
outputCore = outputCore,
sourceCore = sourceCore,
sourceWorking = fixedWorkingRect(
core = sourceCore,
sourceWidth = sourceWidth,
sourceHeight = sourceHeight,
workWidth = workWidth,
workHeight = workHeight,
support = support,
phase = phase,
),
)
cores += outputCore to sourceCore
outputLeft = outputRight
}
outputTop = outputBottom
}
return result
// A crop or an edge tile may be much smaller than the configured maximum core. Size the
// reusable working texture from the largest core that is actually present; otherwise a
// one-tile crop below coreEdge needlessly expands back to almost the full sensor.
val largestSourceCoreWidth = cores.maxOf { it.second.width }
val largestSourceCoreHeight = cores.maxOf { it.second.height }
// A cropped core can start at any sensor phase. Reserving phase - 1 additional pixels
// keeps both sides at or above the requested support after the working origin is aligned.
val workWidth = stableWorkingLength(
sourceSize = sourceWidth,
requestedLength = largestSourceCoreWidth + support * 2 + phase - 1,
phase = phase,
)
val workHeight = stableWorkingLength(
sourceSize = sourceHeight,
requestedLength = largestSourceCoreHeight + support * 2 + phase - 1,
phase = phase,
)
return cores.mapIndexed { index, (outputCore, sourceCore) ->
RawRenderTile(
index = index,
outputCore = outputCore,
sourceCore = sourceCore,
sourceWorking = fixedWorkingRect(
core = sourceCore,
sourceWidth = sourceWidth,
sourceHeight = sourceHeight,
workWidth = workWidth,
workHeight = workHeight,
support = support,
phase = phase,
),
)
}
}
private fun outputToSource(
@@ -0,0 +1,19 @@
package com.hinnka.mycamera.raw
import com.hinnka.mycamera.processor.GlesComputeWorkGroup
import org.junit.Assert.assertEquals
import org.junit.Test
class RawMeteringDemosaicShadersTest {
@Test
fun halfResolutionShaderFitsGles31Baseline() {
assertEquals(
GlesComputeWorkGroup.Size(8, 8, 1),
GlesComputeWorkGroup.declaredSize(RawMeteringDemosaicShaders.HALF_RESOLUTION),
)
GlesComputeWorkGroup.requireBaselineCompatible(
RawMeteringDemosaicShaders.HALF_RESOLUTION,
"RAW_METERING_HALF_RESOLUTION",
)
}
}
@@ -118,4 +118,22 @@ class RawTilePlannerTest {
assertTrue(!RawTilePlanner.shouldTile(3_000, 3_000))
assertTrue(RawTilePlanner.shouldTile(3_001, 3_000))
}
@Test
fun fourKCoreKeepsSingleCroppedTileBoundedToItsActualSourceCore() {
val tiles = RawTilePlanner.plan(
sourceWidth = 4_080,
sourceHeight = 3_064,
outputSourceBounds = RawTileRect(675, 507, 3_404, 2_556),
rotation = 90,
coreEdgePx = 4_096,
supportPx = 112,
cfaPeriod = 2,
)
assertEquals(1, tiles.size)
assertEquals(RawTileRect(0, 0, 2_049, 2_729), tiles.single().outputCore)
assertEquals(2_954, tiles.single().sourceWorking.width)
assertEquals(2_274, tiles.single().sourceWorking.height)
}
}