feat: YUV Sabre reconstruction and compute LK alignment

This commit is contained in:
zhoubinjia committed 2026-11-12 17:44:02 +08:00
1 parent bfffdf112c
commit 5552cb82fb
5 files changed
+942 -92

No files matched your search

@@ -83,4 +83,102 @@ internal object GlesYuvAlignmentShaders {
oAlignment = vec4(flow, initialAlignment.z, 0.0);
}
""".trimIndent()
/**
* One cooperative group solves one tile using exactly the fragment path's sample lattice.
* The filtered current pyramid produces fractional residuals, so both the residual mean
* and gradient products stay Float32. Tree reduction changes addition order, not the warp,
* sample count, residual centering or determinant regularization.
*
* The host dispatches one group per grid cell, binds a distinct immutable RGBA32F image,
* and makes image writes visible to the next sampler/framebuffer consumer before reuse.
*/
val blockLucasKanadeCompute = """
#version 310 es
precision highp float;
precision highp int;
precision highp isampler2D;
precision highp sampler2D;
layout(local_size_x = ${GlesComputeWorkGroup.LINEAR_SIZE}, local_size_y = 1, local_size_z = 1) in;
layout(rgba32f, binding = 0) writeonly uniform highp image2D uOutput;
uniform highp isampler2D uReference;
uniform highp sampler2D uCurrent;
uniform highp sampler2D uProducts0;
uniform highp sampler2D uInitialAlignment;
uniform ivec2 uImageSize;
uniform ivec2 uGridSize;
uniform int uTileStride;
uniform int uTileSize;
uniform int uNormalize;
uniform int uHasInitialAlignment;
shared vec4 sProducts[${GlesComputeWorkGroup.LINEAR_SIZE}];
shared float sResidual[${GlesComputeWorkGroup.LINEAR_SIZE}];
float referenceAt(ivec2 p) {
return float(texelFetch(uReference,
clamp(p, ivec2(0), uImageSize - 1), 0).r);
}
vec2 gradientAt(ivec2 p) {
return clamp(vec2(
referenceAt(p + ivec2(1, 0)) - referenceAt(p - ivec2(1, 0)),
referenceAt(p + ivec2(0, 1)) - referenceAt(p - ivec2(0, 1))
), vec2(-32768.0), vec2(32767.0));
}
void main() {
ivec2 tile = ivec2(gl_WorkGroupID.xy);
int lane = int(gl_LocalInvocationIndex);
vec3 initialAlignment = uHasInitialAlignment != 0
? texelFetch(uInitialAlignment, clamp(tile, ivec2(0), uGridSize - 1), 0).xyz
: vec3(0.0);
vec2 flow = initialAlignment.xy;
ivec2 origin = (tile + ivec2(1)) * uTileStride;
int sampleStep = uTileSize >= 32 ? 2 : 1;
int sampleSide = uTileSize / sampleStep;
int sampleCount = sampleSide * sampleSide;
vec2 inverseSize = 1.0 / vec2(uImageSize);
vec2 target = vec2(0.0);
vec2 gradientSum = vec2(0.0);
float residualSum = 0.0;
for (int i = lane; i < sampleCount; i += ${GlesComputeWorkGroup.LINEAR_SIZE}) {
ivec2 p = origin + ivec2(i % sampleSide, i / sampleSide) * sampleStep;
vec2 encoded = textureLod(uCurrent,
(vec2(p) + flow + 0.5) * inverseSize, 0.0).rg;
float residual = dot(encoded, vec2(16.0, 1.0)) - referenceAt(p);
vec2 gradient = gradientAt(p);
target += residual * gradient;
if (uNormalize != 0) {
residualSum += residual;
gradientSum += gradient;
}
}
// Tiles with fewer samples than lanes still initialize all shared elements.
// Every lane reaches every barrier, including the unnormalized finest level.
sProducts[lane] = vec4(target, gradientSum);
sResidual[lane] = residualSum;
memoryBarrierShared();
barrier();
for (int stride = ${GlesComputeWorkGroup.LINEAR_SIZE / 2}; stride > 0; stride >>= 1) {
if (lane < stride) {
sProducts[lane] += sProducts[lane + stride];
sResidual[lane] += sResidual[lane + stride];
}
memoryBarrierShared();
barrier();
}
if (lane == 0) {
float count = float(sampleCount);
target = sProducts[0].xy;
if (uNormalize != 0) target -= (sResidual[0] / count) * sProducts[0].zw;
vec4 products0 = texelFetch(uProducts0, tile, 0);
vec2 b = 0.5 * target / count;
float inverseDeterminant = 1.0 / (1.0 + products0.w);
vec2 delta = inverseDeterminant * vec2(
products0.z * b.y - products0.y * b.x,
products0.z * b.x - products0.x * b.y
);
flow += clamp(delta, vec2(-1.0), vec2(1.0));
imageStore(uOutput, tile, vec4(flow, initialAlignment.z, 0.0));
}
}
""".trimIndent()
}
@@ -0,0 +1,60 @@
package com.hinnka.mycamera.processor
/**
* YUV's half-resolution LK geometry. Keep the 32-pixel sparse fit where it has real image
* support, recursively round each downsampled extent, and stop before a level loses its
* gradient halo or complete tiles. No level is manufactured by clamping its grid to one.
*/
internal class GlesYuvLkPyramidPlan(width: Int, height: Int) {
data class Level(
val width: Int,
val height: Int,
val scale: Int,
val downsample: Int,
val tileSize: Int,
val gridWidth: Int,
val gridHeight: Int,
)
val levels: List<Level>
init {
require(width > 0 && height > 0)
val fineWidth = width / 2 + width % 2
val fineHeight = height / 2 + height % 2
val shortestSide = minOf(fineWidth, fineHeight)
// The first tile starts at tileSize and its central differences need one extra
// source pixel. Candidate SAD uses a two-pixel sample lattice, so the smallest
// supported tile is two pixels and needs a five-pixel guide extent.
require(shortestSide >= 5) { "YUV dimensions cannot support an LK gradient tile" }
var tileSize = 32
while (2 * tileSize + 1 > shortestSide) tileSize /= 2
val result = ArrayList<Level>()
var scale = 1
var tileLimit = 64
while (scale < 256) {
val finest = result.isEmpty()
val downsample = if (finest) 1 else if (result.size == 1) 2 else 4
val levelWidth = if (finest) fineWidth else
(result.last().width - 1 + downsample / 2) / downsample + 1
val levelHeight = if (finest) fineHeight else
(result.last().height - 1 + downsample / 2) / downsample + 1
val margin = if (finest) 1 else 3
val gridWidth = (levelWidth - margin) / tileSize - 1
val gridHeight = (levelHeight - margin) / tileSize - 1
if (gridWidth <= 0 || gridHeight <= 0) break
result += Level(
levelWidth, levelHeight, scale, downsample,
tileSize, gridWidth, gridHeight,
)
scale *= if (finest) 2 else 4
// Preserve smaller tiles chosen for small inputs instead of increasing them
// back to the ordinary eight-pixel coarse-level minimum.
tileSize = minOf(tileSize, tileLimit.coerceAtLeast(8))
tileLimit /= 4
}
check(result.isNotEmpty())
levels = result
}
}
@@ -0,0 +1,448 @@
package com.hinnka.mycamera.processor
/**
* Sabre's structure-adaptive reconstruction for ISP YUV, in the incoming Y/Cb/Cr code-value domain.
* No Bayer phase, camera white balance, RAW noise profile or square-root colour transform is used.
* Chroma samples are centred on their 2x2 luma blocks, as in the existing YUV input contract.
*/
internal object GlesYuvSabreShaders {
// Noise varies more slowly than image structure. Keep 128 robust samples per 64x64 native
// region; covariance and rejection remain dense. This avoids a sort for every 32x32 region.
const val NOISE_TILE_SIZE = 32
private const val NOISE_SIGMA_STORAGE_SCALE = 256
val prepareBlocks = """
#version 300 es
precision highp float;
precision highp int;
precision highp sampler2D;
uniform sampler2D uLuma;
uniform sampler2D uChroma;
uniform ivec2 uInputSize;
uniform ivec2 uChromaSize;
out vec4 oBlock;
void main() {
ivec2 q = ivec2(gl_FragCoord.xy);
float y = 0.0;
for (int dy = 0; dy < 2; ++dy) {
for (int dx = 0; dx < 2; ++dx) {
y += texelFetch(uLuma, min(2 * q + ivec2(dx, dy), uInputSize - 1), 0).r;
}
}
oBlock = vec4(y * 0.25, texelFetch(uChroma, min(q, uChromaSize - 1), 0).rg, 0.0);
}
""".trimIndent()
val guideAndAlignment = """
#version 300 es
precision highp float;
precision highp int;
precision highp sampler2D;
uniform sampler2D uBlocks;
uniform ivec2 uGuideSize;
layout(location = 0) out vec4 oGuide;
layout(location = 1) out highp int oGray;
layout(location = 2) out vec2 oLinearGray;
void main() {
ivec2 p = ivec2(gl_FragCoord.xy);
vec3 mean = vec3(0.0);
float centerY = texelFetch(uBlocks, p, 0).r;
float deltaSum = 0.0;
float deltaSquareSum = 0.0;
for (int y = -1; y <= 1; ++y) {
for (int x = -1; x <= 1; ++x) {
vec3 v = texelFetch(uBlocks, clamp(p + ivec2(x, y), ivec2(0), uGuideSize - 1), 0).rgb;
mean += v * (x == 0 ? 0.5 : 0.25) * (y == 0 ? 0.5 : 0.25);
float delta = v.r - centerY;
deltaSum += delta;
deltaSquareSum += delta * delta;
}
}
// Centre before accumulating moments: white P010 patches must not subtract
// nearly equal order-one squares to recover a much smaller local variance.
float variance = max(deltaSquareSum / 9.0 - (deltaSum / 9.0) * (deltaSum / 9.0), 0.0);
oGuide = vec4(mean, variance * 1024.0);
oGray = int(floor(clamp(mean.r, 0.0, 1.0) * 16383.0 + 0.5));
float coarse = floor(float(oGray) / 16.0);
oLinearGray = vec2(coarse, float(oGray) - 16.0 * coarse);
}
""".trimIndent()
/**
* Local robust high-frequency noise estimate, independently for native and guide samples.
* Each group sorts 128 stratified checkerboard samples from a 32x32 guide cell. The separable second
* difference [-.5,1,-.5] rejects affine ramps; its white-noise standard deviation is 1.5.
* After the known guide [1,2,1]/4 filter, the residual/guide sigma ratio is 1/4. These are
* effective local estimates: unknown ISP denoising correlations are not a RAW shot/read model.
* Store standard deviations multiplied by 256, not variances: even the P010 guide quantization
* floor then stays in the normal FP16 range. Consumers undo this encoding before arithmetic.
* The two output images are ceil(guideSize/NOISE_TILE_SIZE), immutable RGBA16F, write-only.
*/
val noiseEstimate = """
#version 310 es
precision highp float;
precision highp int;
precision highp sampler2D;
layout(local_size_x = ${GlesComputeWorkGroup.LINEAR_SIZE}, local_size_y = 1, local_size_z = 1) in;
layout(rgba16f, binding = 0) writeonly uniform highp image2D uNativeNoiseOutput;
layout(rgba16f, binding = 1) writeonly uniform highp image2D uGuideNoiseOutput;
uniform sampler2D uLuma;
uniform sampler2D uChroma;
uniform sampler2D uGuide;
uniform ivec2 uInputSize;
uniform ivec2 uGuideSize;
uniform float uCodeStep;
shared vec3 sNative[${GlesComputeWorkGroup.LINEAR_SIZE}];
shared vec3 sGuide[${GlesComputeWorkGroup.LINEAR_SIZE}];
void main() {
int lane = int(gl_LocalInvocationIndex);
ivec2 cell = ivec2(gl_WorkGroupID.xy);
ivec2 begin = cell * $NOISE_TILE_SIZE;
ivec2 extent = min(ivec2($NOISE_TILE_SIZE), uGuideSize - begin);
// Spread the sample lattice over the actual tail cell instead of duplicating its edge.
ivec2 lattice = ivec2(lane % 16, 2 * (lane / 16) + (lane % 2));
ivec2 q = begin + min(lattice * extent / 16, extent - 1);
// Guide residuals need its filter radius plus the residual radius. Avoid the
// artificially quieter CLAMP_TO_EDGE border whenever the input has full support.
ivec2 margin = min(ivec2(2), (uGuideSize - 1) / 2);
q = clamp(q, margin, uGuideSize - 1 - margin);
ivec2 p = clamp(2 * q + ivec2((lane / 16) % 2, lane % 2), ivec2(1), uInputSize - 2);
vec3 nativeResidual = vec3(0.0);
vec3 guideResidual = vec3(0.0);
for (int y = -1; y <= 1; ++y) {
for (int x = -1; x <= 1; ++x) {
float weight = (x == 0 ? 1.0 : -0.5) * (y == 0 ? 1.0 : -0.5);
ivec2 offset = ivec2(x, y);
nativeResidual += weight * vec3(
texelFetch(uLuma, p + offset, 0).r,
texelFetch(uChroma, q + offset, 0).rg);
guideResidual += weight * texelFetch(uGuide, q + offset, 0).rgb;
}
}
sNative[lane] = abs(nativeResidual);
sGuide[lane] = abs(guideResidual);
memoryBarrierShared();
barrier();
// Each comparator has one writer. Every lane participates in every barrier.
for (int size = 2; size <= ${GlesComputeWorkGroup.LINEAR_SIZE}; size *= 2) {
for (int stride = size / 2; stride > 0; stride /= 2) {
int partner = lane ^ stride;
if (partner > lane) {
vec3 a = sNative[lane];
vec3 b = sNative[partner];
vec3 c = sGuide[lane];
vec3 d = sGuide[partner];
bool ascending = (lane & size) == 0;
sNative[lane] = ascending ? min(a, b) : max(a, b);
sNative[partner] = ascending ? max(a, b) : min(a, b);
sGuide[lane] = ascending ? min(c, d) : max(c, d);
sGuide[partner] = ascending ? max(c, d) : min(c, d);
}
memoryBarrierShared();
barrier();
}
}
if (lane == 0) {
const float inverseGaussianMad = 1.4826022185;
vec3 nativeSigma = 0.5 * (sNative[63] + sNative[64]) * (inverseGaussianMad / 1.5);
vec3 guideSigma = 0.5 * (sGuide[63] + sGuide[64]) * (inverseGaussianMad * 4.0);
float quantizationSigma = uCodeStep * 0.2886751346;
nativeSigma = max(nativeSigma, vec3(quantizationSigma));
// 2x2 luma averaging halves sigma; the separable guide filter multiplies it by 3/8.
guideSigma = max(guideSigma, quantizationSigma * vec3(0.1875, 0.375, 0.375));
imageStore(uNativeNoiseOutput, cell, vec4(nativeSigma * float($NOISE_SIGMA_STORAGE_SCALE), 1.0));
imageStore(uGuideNoiseOutput, cell, vec4(guideSigma * float($NOISE_SIGMA_STORAGE_SCALE), 1.0));
}
}
""".trimIndent()
/** Inverse covariance is in full-resolution pixel units; alpha is extra chroma variance. */
val covariance = """
#version 300 es
precision highp float;
precision highp int;
precision highp sampler2D;
uniform sampler2D uGuide;
uniform sampler2D uNativeNoise;
uniform sampler2D uGuideNoise;
uniform ivec2 uGuideSize;
out vec4 oCovariance;
float yAt(ivec2 p) {
return texelFetch(uGuide, clamp(p, ivec2(0), uGuideSize - 1), 0).r;
}
vec3 noiseAt(sampler2D noise, vec2 p) {
return texture(noise, (p + 0.5) / (float($NOISE_TILE_SIZE) * vec2(textureSize(noise, 0)))).rgb / float($NOISE_SIGMA_STORAGE_SCALE);
}
void main() {
ivec2 p = ivec2(gl_FragCoord.xy);
vec3 tensor = vec3(0.0);
for (int y = -1; y <= 1; ++y) {
for (int x = -1; x <= 1; ++x) {
ivec2 q = p + ivec2(x, y);
// A central difference spans four full-resolution pixels.
vec2 gradient = 0.25 * vec2(yAt(q + ivec2(1, 0)) - yAt(q - ivec2(1, 0)),
yAt(q + ivec2(0, 1)) - yAt(q - ivec2(0, 1)));
tensor += vec3(gradient * gradient, gradient.x * gradient.y);
}
}
tensor /= 9.0;
vec3 nativeSigma = noiseAt(uNativeNoise, vec2(p));
float guideSigma = noiseAt(uGuideNoise, vec2(p)).r;
float noiseGradient = guideSigma * guideSigma * 0.125;
float trace = tensor.x + tensor.y;
float separation = length(vec2(tensor.x - tensor.y, 2.0 * tensor.z));
float major = 0.5 * (trace + separation);
float signal = max(major - noiseGradient, 0.0);
float confidence = signal / (signal + 4.0 * noiseGradient);
float coherence = separation / (trace + 2.0 * noiseGradient);
float directionality = clamp(coherence * confidence, 0.0, 1.0);
// atan yields the dominant gradient direction without a near-zero eigenvector divide.
float angle = separation > 0.0 ? 0.5 * atan(2.0 * tensor.z, tensor.x - tensor.y) : 0.0;
vec2 normal = vec2(cos(angle), sin(angle));
float localContrast = sqrt(max(texelFetch(uGuide, p, 0).a / 1024.0, 0.0));
float flatness = nativeSigma.r / (nativeSigma.r + localContrast);
float isotropicSigma = mix(0.55, 0.95, flatness);
float normalSigma = mix(isotropicSigma, 0.45, directionality);
float tangentSigma = mix(isotropicSigma, 1.15, directionality);
float normalPrecision = 1.0 / (normalSigma * normalSigma);
float tangentPrecision = 1.0 / (tangentSigma * tangentSigma);
float difference = normalPrecision - tangentPrecision;
vec3 inverseCovariance = vec3(
tangentPrecision + difference * normal.x * normal.x,
tangentPrecision + difference * normal.y * normal.y,
difference * normal.x * normal.y);
float chromaSigma = max(nativeSigma.g, nativeSigma.b);
float chromaFlatness = chromaSigma / (chromaSigma + localContrast);
oCovariance = vec4(inverseCovariance, mix(0.25, 1.0, chromaFlatness));
}
""".trimIndent()
val rejection = """
#version 300 es
precision highp float;
precision highp int;
precision highp sampler2D;
uniform sampler2D uReferenceGuide;
uniform sampler2D uCurrentGuide;
uniform sampler2D uReferenceNoise;
uniform sampler2D uCurrentNoise;
uniform sampler2D uAlignment;
uniform ivec2 uGuideSize;
uniform ivec2 uAlignmentGridSize;
uniform int uAlignmentTileSize;
out float oReverseWeight;
vec2 flowAt(ivec2 tile) {
return texelFetch(uAlignment, clamp(tile, ivec2(0), uAlignmentGridSize - 1), 0).xy;
}
vec3 noiseAt(sampler2D noise, vec2 p) {
return texture(noise, (p + 0.5) / (float($NOISE_TILE_SIZE) * vec2(textureSize(noise, 0)))).rgb / float($NOISE_SIGMA_STORAGE_SCALE);
}
void main() {
ivec2 p = ivec2(gl_FragCoord.xy);
ivec2 tile = clamp(p / uAlignmentTileSize, ivec2(0), uAlignmentGridSize - 1);
vec2 flow = flowAt(tile);
vec2 currentP = vec2(p) + flow;
if (any(lessThan(currentP, vec2(0.0))) || any(greaterThan(currentP, vec2(uGuideSize - 1)))) {
oReverseWeight = 1.0;
return;
}
vec2 minimumFlow = flow;
vec2 maximumFlow = flow;
for (int y = -1; y <= 1; ++y) {
for (int x = -1; x <= 1; ++x) {
vec2 other = flowAt(tile + ivec2(x, y));
minimumFlow = min(minimumFlow, other);
maximumFlow = max(maximumFlow, other);
}
}
vec4 base = texelFetch(uReferenceGuide, p, 0);
vec4 current = texture(uCurrentGuide, (currentP + 0.5) / vec2(uGuideSize));
base.a /= 1024.0;
current.a /= 1024.0;
vec3 baseSigma = noiseAt(uReferenceNoise, vec2(p));
vec3 currentSigma = noiseAt(uCurrentNoise, currentP);
vec3 noiseVariance = baseSigma * baseSigma + currentSigma * currentSigma;
vec3 difference = current.rgb - base.rgb;
vec3 signalDifference = max(difference * difference - noiseVariance, vec3(0.0));
float localVariance = 2.0 * min(base.a, current.a);
vec3 tolerance = max(noiseVariance, localVariance * vec3(1.0, 0.25, 0.25));
// This dimensionless slope is paired with Sabre's 5x5-sum dilation below.
// Unit slope rejects ordinary independent frame noise: for normalized Gaussian
// residuals its expected reverse weight is ~0.22, above dilation's 0.088 cutoff.
// The shared 0.07 slope gives ~0.023; it does not import a RAW noise model.
float distance = ${MgcSabreRejectionTuning.COLOR_DIFFERENCE_RGB} *
dot(signalDifference / tolerance, vec3(0.5, 0.25, 0.25));
// Quarter-guide-pixel flow discontinuities are half a native luma pixel.
bool motion = length(maximumFlow - minimumFlow) > 0.25;
bool textured = base.a > 25.0 * baseSigma.r * baseSigma.r;
float robustness = motion && textured ? 6.0 : 1.0;
oReverseWeight = 1.0 - exp2(-distance * robustness);
}
""".trimIndent()
val dilation = GlesMgcRawSpatialShaders.dilateRejection
private val mergeCommon = """
precision highp float;
precision highp int;
precision highp sampler2D;
uniform sampler2D uCovariance;
uniform sampler2D uAlignment;
uniform sampler2D uFrameWeight;
uniform ivec2 uInputSize;
uniform ivec2 uGuideSize;
uniform int uUseFrameWeight;
vec2 flowAt(vec2 fullPixel) {
ivec2 tile = clamp(ivec2(floor(fullPixel / 16.0)), ivec2(0), textureSize(uAlignment, 0) - 1);
return texelFetch(uAlignment, tile, 0).xy;
}
float acceptanceAt(vec2 fullPixel) {
// Dilation produces one sample per four native pixels; a partial tail clamps to its last cell.
return uUseFrameWeight != 0
? texture(uFrameWeight, (fullPixel + 0.5) / (4.0 * vec2(textureSize(uFrameWeight, 0)))).r
: 1.0;
}
bool inside(vec2 p, ivec2 size) {
return all(greaterThanEqual(p, vec2(0.0))) && all(lessThanEqual(p, vec2(size - 1)));
}
float kernelWeight(vec2 offset, vec3 precisionMatrix) {
float distance = dot(offset * offset, precisionMatrix.xy) + 2.0 * offset.x * offset.y * precisionMatrix.z;
return exp(-0.5 * distance);
}
vec4 covarianceAt(vec2 fullPixel) {
// A half-resolution guide sample is centred at fullPixel = 2*q + 0.5.
return texture(uCovariance, (fullPixel + 0.5) / (2.0 * vec2(uGuideSize)));
}
""".trimIndent()
/** RG16F output: per-frame normalized luma times acceptance, acceptance. Additive blending. */
val mergeLuma = "#version 300 es\n" + mergeCommon + "\n" + """
uniform sampler2D uCurrentY;
out vec2 oLumaAndWeight;
void main() {
vec2 p = floor(gl_FragCoord.xy);
vec2 source = p + 2.0 * flowAt(p);
if (!inside(source, uInputSize)) {
oLumaAndWeight = vec2(0.0);
return;
}
float acceptance = acceptanceAt(p);
vec3 precisionMatrix = covarianceAt(source).rgb;
ivec2 anchor = ivec2(roundEven(source));
float sum = 0.0;
float sumWeight = 0.0;
for (int y = -1; y <= 1; ++y) {
for (int x = -1; x <= 1; ++x) {
ivec2 q = anchor + ivec2(x, y);
if (any(lessThan(q, ivec2(0))) || any(greaterThanEqual(q, uInputSize))) continue;
float weight = kernelWeight(vec2(q) - source, precisionMatrix);
sum += weight * texelFetch(uCurrentY, q, 0).r;
sumWeight += weight;
}
}
oLumaAndWeight = vec2(sum / sumWeight, 1.0) * acceptance;
}
""".trimIndent()
/** RGBA16F output: normalized Cb/Cr times acceptance, unused, acceptance. */
val mergeChroma = "#version 300 es\n" + mergeCommon + "\n" + """
uniform sampler2D uCurrentCbCr;
out vec4 oChromaAndWeight;
void main() {
vec2 p = floor(gl_FragCoord.xy);
vec2 fullPixel = 2.0 * p + 0.5;
vec2 source = p + flowAt(fullPixel);
ivec2 chromaSize = (uInputSize + 1) / 2;
if (!inside(source, chromaSize)) {
oChromaAndWeight = vec4(0.0);
return;
}
float acceptance = acceptanceAt(fullPixel);
vec4 covariance = covarianceAt(2.0 * source + 0.5);
float determinant = covariance.x * covariance.y - covariance.z * covariance.z;
vec3 spatialCovariance = vec3(covariance.y, covariance.x, -covariance.z) / determinant;
spatialCovariance.xy += covariance.a;
float chromaDeterminant = spatialCovariance.x * spatialCovariance.y - spatialCovariance.z * spatialCovariance.z;
vec3 precisionMatrix = vec3(spatialCovariance.y, spatialCovariance.x, -spatialCovariance.z) / chromaDeterminant;
ivec2 anchor = ivec2(roundEven(source));
vec2 sum = vec2(0.0);
float sumWeight = 0.0;
for (int y = -1; y <= 1; ++y) {
for (int x = -1; x <= 1; ++x) {
ivec2 q = anchor + ivec2(x, y);
if (any(lessThan(q, ivec2(0))) || any(greaterThanEqual(q, chromaSize))) continue;
float weight = kernelWeight(2.0 * (vec2(q) - source), precisionMatrix);
sum += weight * texelFetch(uCurrentCbCr, q, 0).rg;
sumWeight += weight;
}
}
oChromaAndWeight = vec4(sum / sumWeight, 0.0, 1.0) * acceptance;
}
""".trimIndent()
/** Normalize each native sample before interpolating chroma; confidence is not colour alpha. */
private val normalizedSource = """
precision highp float;
precision highp int;
precision highp sampler2D;
uniform sampler2D uLumaAccumulator;
uniform sampler2D uChromaAccumulator;
uniform ivec2 uInputSize;
vec2 chromaAt(ivec2 p) {
ivec2 size = (uInputSize + 1) / 2;
vec4 value = texelFetch(uChromaAccumulator, clamp(p, ivec2(0), size - 1), 0);
// The identity reference contributes positive weight at every native pixel.
return value.rg / value.a;
}
vec3 normalizedYcc(ivec2 p) {
p = clamp(p, ivec2(0), uInputSize - 1);
vec2 luma = texelFetch(uLumaAccumulator, p, 0).rg;
vec2 chromaPosition = (vec2(p) - 0.5) * 0.5;
ivec2 anchor = ivec2(floor(chromaPosition));
vec2 fraction = fract(chromaPosition);
vec2 chroma = mix(
mix(chromaAt(anchor), chromaAt(anchor + ivec2(1, 0)), fraction.x),
mix(chromaAt(anchor + ivec2(0, 1)), chromaAt(anchor + ivec2(1, 1)), fraction.x),
fraction.y);
return vec3(luma.r / luma.g, chroma);
}
""".trimIndent()
val resolve = "#version 300 es\n" + normalizedSource + "\n" + """
out vec4 oYcc;
void main() {
oYcc = vec4(normalizedYcc(ivec2(gl_FragCoord.xy)), 1.0);
}
""".trimIndent()
/** Native-sized output avoids materializing a full RGBA16F YCC resolve surface. */
val normalizedOutput = "#version 300 es\n" + normalizedSource + "\n" + """
uniform vec3 uTransformX;
uniform vec3 uTransformY;
uniform int uIsP010;
uniform int uDirectSource;
uniform ivec2 uDirectOffset;
out vec4 oColor;
void main() {
ivec2 outputPixel = ivec2(gl_FragCoord.xy);
ivec2 sourcePixel;
if (uDirectSource != 0) {
sourcePixel = outputPixel + uDirectOffset;
} else {
vec2 source = vec2(
float(outputPixel.x) * uTransformX.x + float(outputPixel.y) * uTransformX.y + uTransformX.z,
float(outputPixel.x) * uTransformY.x + float(outputPixel.y) * uTransformY.y + uTransformY.z);
sourcePixel = ivec2(floor(source + 0.5));
}
vec3 ycc = normalizedYcc(sourcePixel);
float y = ycc.r;
float cb = ycc.g - 0.5;
float cr = ycc.b - 0.5;
vec3 rgb = uIsP010 != 0
? vec3(y + 1.4746 * cr, y - 0.16455 * cb - 0.57135 * cr, y + 1.8814 * cb)
: vec3(y + 1.402 * cr, y - 0.344136 * cb - 0.714136 * cr, y + 1.772 * cb);
oColor = vec4(clamp(rgb, 0.0, 1.0), 1.0);
}
""".trimIndent()
}
@@ -26,10 +26,9 @@ import kotlin.math.min
import kotlin.math.roundToInt
/**
* GLES YUV burst processor using Spatial's alignment, rejection and additive RBF merge graph.
* YUV planes feed Spatial's half-resolution rejection guide and Fixed14 candidate pyramid.
* LK uses a filterable current pyramid and sparse fine-level fits to limit alignment cost;
* temporal rejection and additive reconstruction retain Spatial's contracts.
* YUV burst processing with Sabre-style directional reconstruction in the ISP's YCbCr domain.
* Native luma/chroma grids retain independent weights; guides and measured noise share the
* same encoded domain. HDR retains its existing Spatial/Mertens processing path.
*/
class GlesYuvStacker(
private val width: Int,
@@ -61,6 +60,9 @@ class GlesYuvStacker(
val height: Int,
val scaleToGuidePixels: Float,
val linearTexture: Int = 0,
val tileSize: Int = 0,
val gridWidth: Int = 0,
val gridHeight: Int = 0,
)
private data class Alignment(
@@ -146,6 +148,20 @@ class GlesYuvStacker(
private var hardwareFrameCount = 0
private var planeFrameCount = 0
private var inputSamplingComplete = false
private var sabreMode = false
private val sabreAlignmentPlan by lazy { GlesYuvLkPyramidPlan(width, height) }
private var noiseEstimateProgram = 0
private var covarianceProgram = 0
private var sabreChromaMergeProgram = 0
private var sabreResolveProgram = 0
private var nativeNoiseTexture = 0
private var referenceGuideNoiseTexture = 0
private var currentGuideNoiseTexture = 0
private var covarianceTexture = 0
private var lumaAccumulatorTexture = 0
private var chromaAccumulatorTexture = 0
private val noiseWidth get() = ceilDiv(guideWidth, GlesYuvSabreShaders.NOISE_TILE_SIZE)
private val noiseHeight get() = ceilDiv(guideHeight, GlesYuvSabreShaders.NOISE_TILE_SIZE)
private var prepareBlocksProgram = 0
private var guideProgram = 0
@@ -239,8 +255,8 @@ class GlesYuvStacker(
}
private val guideWidth get() = rejectionGeometry.guideWidth
private val guideHeight get() = rejectionGeometry.guideHeight
private val mergeWeightWidth get() = rejectionGeometry.mergeWeightWidth
private val mergeWeightHeight get() = rejectionGeometry.mergeWeightHeight
private val mergeWeightWidth get() = if (sabreMode) ceilDiv(width, 4) else rejectionGeometry.mergeWeightWidth
private val mergeWeightHeight get() = if (sabreMode) ceilDiv(height, 4) else rejectionGeometry.mergeWeightHeight
private val rejectionFilterWidth get() = rejectionGeometry.filterWidth
private val rejectionFilterHeight get() = rejectionGeometry.filterHeight
private val renderOutputWidth = outputWidth
@@ -274,7 +290,8 @@ class GlesYuvStacker(
return null
}
timing.start("mode=YUV input=${width}x$height output=${gpuOutputWidth}x$gpuOutputHeight frames=${images.size} format=${formatName(inputFormat)} lanczos=$outputUpscaleEnabled alignment=rg16f-sparse2 inputPreference=hardwarebuffer fallbackUpload=ring2")
sabreMode = true
timing.start("mode=YUV-Sabre input=${width}x$height output=${gpuOutputWidth}x$gpuOutputHeight frames=${images.size} format=${formatName(inputFormat)} lanczos=$outputUpscaleEnabled alignment=compute-rg16f-sparse2 noise=local-mad domain=encoded-ycc inputPreference=hardwarebuffer fallbackUpload=ring2")
var succeeded = false
val startTime = System.currentTimeMillis()
val originalThreadPriority = GlesGpuScheduler.lowerCurrentThreadPriority(TAG)
@@ -288,7 +305,7 @@ class GlesYuvStacker(
RawStackRuntimeDebug.d(TAG) {
"GLES stack format=${formatName(inputFormat)} " +
"internal=${if (highPrecisionInput) "R16F/RG16F" else "R8/RG8"} " +
"spatialGuide=${guideWidth}x$guideHeight flowGrid=${gridWidth}x${gridHeight} " +
"sabreGuide=${guideWidth}x$guideHeight flowGrid=${gridWidth}x${gridHeight} " +
"lanczos=${outputUpscaleEnabled} outputScale=${outputScaleFactor.formatScale()}"
}
@@ -301,8 +318,9 @@ class GlesYuvStacker(
val curPyramid = timing.cpu("allocate.currentPyramid") { createPyramid(linearSampling = true) }
prepareGuideAndPyramid(refY, refCbCr, referenceGuideTexture, refPyramid, 1.0f)
val referenceAlignmentProducts = buildReferenceAlignmentProducts(refPyramid)
clearAccumulator()
accumulateFrame(refY, refCbCr, isReference = true, currentToReferenceScale = 1.0f)
prepareSabreNoiseAndCovariance(refY, refCbCr, referenceGuideTexture, referenceGuideNoiseTexture)
clearSabreAccumulators()
accumulateSabreFrame(refY, refCbCr, isReference = true)
timing.cpu("scheduler.yield") { GlesGpuScheduler.yieldToUiRenderer() }
for (index in 1 until images.size) {
@@ -311,17 +329,17 @@ class GlesYuvStacker(
PLog.w(TAG, "Failed to upload frame $index YUV planes")
return null
}
prepareSpatialTemporalFrame(
referencePyramid = refPyramid,
currentPyramid = curPyramid,
referenceAlignmentProducts = referenceAlignmentProducts,
currentToReferenceScale = 1.0f,
)
accumulateFrame(curY, curCbCr, isReference = false, currentToReferenceScale = 1.0f)
prepareGuideAndPyramid(curY, curCbCr, currentGuideTexture, curPyramid, 1.0f)
val alignment = alignPyramids(refPyramid, curPyramid, referenceAlignmentProducts)
mergeAlignmentTexture = alignment.texture
prepareSabreNoiseAndCovariance(curY, curCbCr, currentGuideTexture, currentGuideNoiseTexture)
renderSabreRejection(alignment)
accumulateSabreFrame(curY, curCbCr, isReference = false)
timing.cpu("scheduler.yield") { GlesGpuScheduler.yieldToUiRenderer() }
}
timing.frame("output")
if (outputUpscaleEnabled) resolveSabreAccumulator()
normalizeOutput()
timing.cpu("scheduler.yield") { GlesGpuScheduler.yieldToUiRenderer() }
val bitmap = readOutputBitmap() ?: return null
@@ -351,6 +369,7 @@ class GlesYuvStacker(
return null
}
sabreMode = false
timing.start("mode=HDR input=${width}x$height output=${gpuOutputWidth}x$gpuOutputHeight frames=${frames.size} format=${formatName(inputFormat)} alignment=rg16f-sparse2 inputPreference=hardwarebuffer fallbackUpload=ring2")
var succeeded = false
val originalThreadPriority = GlesGpuScheduler.lowerCurrentThreadPriority(TAG)
@@ -570,6 +589,14 @@ class GlesYuvStacker(
}
private fun initPrograms() {
globalAlignment.init()
if (sabreMode) {
val limit = IntArray(1)
GLES30.glGetIntegerv(GLES31.GL_MAX_IMAGE_UNITS, limit, 0)
check(limit[0] >= 2) { "YUV noise estimation requires two image bindings" }
GLES30.glGetIntegerv(GLES31.GL_MAX_COMPUTE_IMAGE_UNIFORMS, limit, 0)
check(limit[0] >= 2) { "YUV noise estimation requires two compute images" }
}
if (hardwareInput.isSupported()) {
try {
hardwareInputProgram = linkGraphicsProgram(
@@ -581,16 +608,15 @@ class GlesYuvStacker(
}
}
PLog.i(TAG, "YUV input preferred=${if (hardwareInputProgram != 0) "hardwarebuffer" else "planes"}")
globalAlignment.init()
prepareBlocksProgram = linkGraphicsProgram(
FULLSCREEN_VERTEX_SHADER,
GlesYuvSpatialShaders.prepareBlocks,
"yuv_spatial_prepare_blocks",
if (sabreMode) GlesYuvSabreShaders.prepareBlocks else GlesYuvSpatialShaders.prepareBlocks,
"yuv_prepare_blocks",
)
guideProgram = linkGraphicsProgram(
FULLSCREEN_VERTEX_SHADER,
GlesYuvSpatialShaders.guideAndAlignment,
"yuv_spatial_guide",
if (sabreMode) GlesYuvSabreShaders.guideAndAlignment else GlesYuvSpatialShaders.guideAndAlignment,
"yuv_guide",
)
downsampleProgram = linkGraphicsProgram(
FULLSCREEN_VERTEX_SHADER,
@@ -612,47 +638,65 @@ class GlesYuvStacker(
GlesMgcRawSpatialShaders.yuvUpsampleAlignment,
"yuv_spatial_upsample_alignment",
)
blockLucasKanadeProgram = linkGraphicsProgram(
blockLucasKanadeProgram = if (sabreMode) linkComputeProgram(
GlesYuvAlignmentShaders.blockLucasKanadeCompute, "yuv_sabre_block_lk",
) else linkGraphicsProgram(
FULLSCREEN_VERTEX_SHADER,
GlesYuvAlignmentShaders.blockLucasKanade,
"yuv_spatial_block_lk",
)
rejectionProgram = linkGraphicsProgram(
if (sabreMode) {
noiseEstimateProgram = linkComputeProgram(GlesYuvSabreShaders.noiseEstimate, "yuv_sabre_noise")
covarianceProgram = linkGraphicsProgram(FULLSCREEN_VERTEX_SHADER, GlesYuvSabreShaders.covariance, "yuv_sabre_covariance")
rejectionProgram = linkGraphicsProgram(FULLSCREEN_VERTEX_SHADER, GlesYuvSabreShaders.rejection, "yuv_sabre_rejection")
rejectionDownsampleProgram = linkGraphicsProgram(FULLSCREEN_VERTEX_SHADER, GlesMgcRawSpatialShaders.dilateRejection, "yuv_sabre_dilation")
accumulateProgram = linkGraphicsProgram(FULLSCREEN_VERTEX_SHADER, GlesYuvSabreShaders.mergeLuma, "yuv_sabre_merge_luma")
sabreChromaMergeProgram = linkGraphicsProgram(FULLSCREEN_VERTEX_SHADER, GlesYuvSabreShaders.mergeChroma, "yuv_sabre_merge_chroma")
if (outputUpscaleEnabled) {
sabreResolveProgram = linkGraphicsProgram(FULLSCREEN_VERTEX_SHADER, GlesYuvSabreShaders.resolve, "yuv_sabre_resolve")
}
} else {
rejectionProgram = linkGraphicsProgram(
FULLSCREEN_VERTEX_SHADER,
GlesYuvSpatialShaders.rejection,
"yuv_spatial_rejection",
)
rejectionDownsampleProgram = linkGraphicsProgram(
FULLSCREEN_VERTEX_SHADER,
GlesYuvSpatialShaders.rejectionDownsample,
"yuv_spatial_rejection_downsample",
)
clippedGaussianProgram = linkGraphicsProgram(
FULLSCREEN_VERTEX_SHADER,
GlesYuvSpatialShaders.clippedGaussian,
"yuv_spatial_pixel_difference_blur",
)
rejectionFilterDownsampleProgram = linkGraphicsProgram(
FULLSCREEN_VERTEX_SHADER,
GlesMgcRawSpatialShaders.rejectionFilterDownsample,
"yuv_spatial_rejection_filter_downsample",
)
rejectionFilterProgram = linkGraphicsProgram(
FULLSCREEN_VERTEX_SHADER,
GlesMgcRawSpatialShaders.rejectionFilter,
"yuv_spatial_rejection_filter",
)
rejectionPostprocessProgram = linkGraphicsProgram(
FULLSCREEN_VERTEX_SHADER,
GlesMgcRawSpatialShaders.rejectionPostprocess,
"yuv_spatial_rejection_postprocess",
)
accumulateProgram = linkGraphicsProgram(
FULLSCREEN_VERTEX_SHADER,
GlesYuvSpatialShaders.merge,
"yuv_spatial_merge",
)
}
normalizeProgram = linkGraphicsProgram(
FULLSCREEN_VERTEX_SHADER,
GlesYuvSpatialShaders.rejection,
"yuv_spatial_rejection",
if (sabreMode) GlesYuvSabreShaders.normalizedOutput else NORMALIZE_FRAGMENT_SHADER,
"normalize",
)
rejectionDownsampleProgram = linkGraphicsProgram(
FULLSCREEN_VERTEX_SHADER,
GlesYuvSpatialShaders.rejectionDownsample,
"yuv_spatial_rejection_downsample",
)
clippedGaussianProgram = linkGraphicsProgram(
FULLSCREEN_VERTEX_SHADER,
GlesYuvSpatialShaders.clippedGaussian,
"yuv_spatial_pixel_difference_blur",
)
rejectionFilterDownsampleProgram = linkGraphicsProgram(
FULLSCREEN_VERTEX_SHADER,
GlesMgcRawSpatialShaders.rejectionFilterDownsample,
"yuv_spatial_rejection_filter_downsample",
)
rejectionFilterProgram = linkGraphicsProgram(
FULLSCREEN_VERTEX_SHADER,
GlesMgcRawSpatialShaders.rejectionFilter,
"yuv_spatial_rejection_filter",
)
rejectionPostprocessProgram = linkGraphicsProgram(
FULLSCREEN_VERTEX_SHADER,
GlesMgcRawSpatialShaders.rejectionPostprocess,
"yuv_spatial_rejection_postprocess",
)
accumulateProgram = linkGraphicsProgram(
FULLSCREEN_VERTEX_SHADER,
GlesYuvSpatialShaders.merge,
"yuv_spatial_merge",
)
normalizeProgram = linkGraphicsProgram(FULLSCREEN_VERTEX_SHADER, NORMALIZE_FRAGMENT_SHADER, "normalize")
readbackResolveProgram = linkGraphicsProgram(FULLSCREEN_VERTEX_SHADER, READBACK_RESOLVE_FRAGMENT_SHADER, "readback_resolve")
if (outputUpscaleEnabled) {
lanczosOutputProgram = linkGraphicsProgram(
@@ -669,7 +713,8 @@ class GlesYuvStacker(
val maxTextureSize = IntArray(1)
GLES30.glGetIntegerv(GLES30.GL_MAX_TEXTURE_SIZE, maxTextureSize, 0)
val maxSize = maxTextureSize[0].coerceAtLeast(1)
if (gpuOutputWidth > maxSize || gpuOutputHeight > maxSize ||
if (width > maxSize || height > maxSize ||
gpuOutputWidth > maxSize || gpuOutputHeight > maxSize ||
renderOutputWidth > maxSize || renderOutputHeight > maxSize
) {
throw IllegalStateException(
@@ -741,16 +786,29 @@ class GlesYuvStacker(
GLES30.GL_NEAREST,
)
rawReverseWeightTexture = createTexture2D(guideWidth, guideHeight, GLES30.GL_R8, GLES30.GL_LINEAR)
rawPixelDifferenceTexture = createTexture2D(guideWidth, guideHeight, GLES30.GL_R8, GLES30.GL_LINEAR)
initialWeightTexture = createTexture2D(mergeWeightWidth, mergeWeightHeight, GLES30.GL_R8, GLES30.GL_LINEAR)
pixelDifferenceTexture = createTexture2D(mergeWeightWidth, mergeWeightHeight, GLES30.GL_R8, GLES30.GL_LINEAR)
pixelDifferenceHorizontalTexture = createTexture2D(mergeWeightWidth, mergeWeightHeight, GLES30.GL_R16F, GLES30.GL_LINEAR)
smoothedPixelDifferenceTexture = createTexture2D(mergeWeightWidth, mergeWeightHeight, GLES30.GL_R8, GLES30.GL_NEAREST)
downsampledLumaTexture = createTexture2D(rejectionFilterWidth, rejectionFilterHeight, GLES30.GL_R32F, GLES30.GL_NEAREST)
downsampledRejectionTexture = createTexture2D(rejectionFilterWidth, rejectionFilterHeight, GLES30.GL_R32F, GLES30.GL_NEAREST)
filteredRejectionTexture = createTexture2D(rejectionFilterWidth, rejectionFilterHeight, GLES30.GL_R8, GLES30.GL_LINEAR)
if (sabreMode) {
nativeNoiseTexture = createTexture2D(noiseWidth, noiseHeight, GLES30.GL_RGBA16F, GLES30.GL_LINEAR)
referenceGuideNoiseTexture = createTexture2D(noiseWidth, noiseHeight, GLES30.GL_RGBA16F, GLES30.GL_LINEAR)
currentGuideNoiseTexture = createTexture2D(noiseWidth, noiseHeight, GLES30.GL_RGBA16F, GLES30.GL_LINEAR)
covarianceTexture = createTexture2D(guideWidth, guideHeight, GLES30.GL_RGBA16F, GLES30.GL_LINEAR)
lumaAccumulatorTexture = createTexture2D(width, height, GLES30.GL_RG16F, GLES30.GL_NEAREST)
chromaAccumulatorTexture = createTexture2D(chromaWidth, chromaHeight, GLES30.GL_RGBA16F, GLES30.GL_NEAREST)
} else {
rawPixelDifferenceTexture = createTexture2D(guideWidth, guideHeight, GLES30.GL_R8, GLES30.GL_LINEAR)
initialWeightTexture = createTexture2D(mergeWeightWidth, mergeWeightHeight, GLES30.GL_R8, GLES30.GL_LINEAR)
pixelDifferenceTexture = createTexture2D(mergeWeightWidth, mergeWeightHeight, GLES30.GL_R8, GLES30.GL_LINEAR)
pixelDifferenceHorizontalTexture = createTexture2D(mergeWeightWidth, mergeWeightHeight, GLES30.GL_R16F, GLES30.GL_LINEAR)
smoothedPixelDifferenceTexture = createTexture2D(mergeWeightWidth, mergeWeightHeight, GLES30.GL_R8, GLES30.GL_NEAREST)
downsampledLumaTexture = createTexture2D(rejectionFilterWidth, rejectionFilterHeight, GLES30.GL_R32F, GLES30.GL_NEAREST)
downsampledRejectionTexture = createTexture2D(rejectionFilterWidth, rejectionFilterHeight, GLES30.GL_R32F, GLES30.GL_NEAREST)
filteredRejectionTexture = createTexture2D(rejectionFilterWidth, rejectionFilterHeight, GLES30.GL_R8, GLES30.GL_LINEAR)
}
frameWeightTexture = createTexture2D(mergeWeightWidth, mergeWeightHeight, GLES30.GL_R8, GLES30.GL_LINEAR)
accumulatorTexture = createTexture2D(width, height, GLES30.GL_RGBA16F, GLES30.GL_NEAREST)
// Native output resolves directly from independent accumulators. Lanczos reuses a
// normalized surface so each of its 36 taps needs one fetch, not five plane fetches.
if (!sabreMode || outputUpscaleEnabled) {
accumulatorTexture = createTexture2D(width, height, GLES30.GL_RGBA16F, GLES30.GL_NEAREST)
}
currentAccumulatorTexture = accumulatorTexture
outputTexture = createTexture2D(gpuOutputWidth, gpuOutputHeight, GLES30.GL_RGBA8, GLES30.GL_NEAREST)
if (cpuRotateReadback) {
@@ -769,6 +827,14 @@ class GlesYuvStacker(
}
private fun createPyramid(linearSampling: Boolean = false): List<TextureLevel> {
if (sabreMode) return sabreAlignmentPlan.levels.map { level ->
TextureLevel(
createTexture2D(level.width, level.height, GLES30.GL_R16I, GLES30.GL_NEAREST),
level.width, level.height, level.scale.toFloat(),
if (linearSampling) createTexture2D(level.width, level.height, GLES30.GL_RG16F, GLES30.GL_LINEAR) else 0,
level.tileSize, level.gridWidth, level.gridHeight,
)
}
val levels = ArrayList<TextureLevel>(ALIGN_PYRAMID_DOWNSAMPLE_STEPS.size + 1)
var levelWidth = guideWidth
var levelHeight = guideHeight
@@ -1346,7 +1412,7 @@ class GlesYuvStacker(
levels: List<TextureLevel>,
currentToReferenceScale: Float,
) {
bindFramebufferOutput(blockTexture, "prepareSpatialBlocks")
bindFramebufferOutput(blockTexture, "prepareYuvBlocks")
GLES30.glViewport(0, 0, guideWidth, guideHeight)
GLES30.glUseProgram(prepareBlocksProgram)
bindTexture(prepareBlocksProgram, "uLuma", 0, yTexture)
@@ -1355,7 +1421,7 @@ class GlesYuvStacker(
GLES30.glUniform2i(uniform(prepareBlocksProgram, "uChromaSize"), chromaWidth, chromaHeight)
GLES30.glUniform1i(uniform(prepareBlocksProgram, "uIsP010"), if (highPrecisionInput) 1 else 0)
GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3)
finishFramebufferPass("prepareSpatialBlocks")
finishFramebufferPass("prepareYuvBlocks")
val first = levels.first()
val guideOutputs = if (first.linearTexture != 0) {
@@ -1363,7 +1429,7 @@ class GlesYuvStacker(
} else {
intArrayOf(guideTexture, first.texture)
}
bindFramebufferOutputs(guideOutputs, "prepareSpatialGuideAndAlignment")
bindFramebufferOutputs(guideOutputs, "prepareYuvGuideAndAlignment")
GLES30.glViewport(0, 0, guideWidth, guideHeight)
GLES30.glUseProgram(guideProgram)
bindTexture(guideProgram, "uBlocks", 0, blockTexture)
@@ -1379,12 +1445,12 @@ class GlesYuvStacker(
currentToReferenceScale * GUIDE_CLIPPING_POINT,
)
GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3)
finishFramebufferPass("prepareSpatialGuideAndAlignment")
finishFramebufferPass("prepareYuvGuideAndAlignment")
for (index in 1 until levels.size) {
val input = levels[index - 1]
val output = levels[index]
val step = ALIGN_PYRAMID_DOWNSAMPLE_STEPS[index - 1]
val step = if (sabreMode) sabreAlignmentPlan.levels[index].downsample else ALIGN_PYRAMID_DOWNSAMPLE_STEPS[index - 1]
val program = if (step == 4) downsample4Program else downsampleProgram
val pyramidOutputs = if (output.linearTexture != 0) {
intArrayOf(output.texture, output.linearTexture)
@@ -1443,7 +1509,10 @@ class GlesYuvStacker(
private fun finishFramebufferPass(label: String) {
try {
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
GLES31.glMemoryBarrier(GLES31.GL_FRAMEBUFFER_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT)
GLES31.glMemoryBarrier(
GLES31.GL_FRAMEBUFFER_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT or
if (sabreMode) GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT else 0,
)
checkGlError(label)
} finally {
timing.endPass(label)
@@ -1459,6 +1528,110 @@ class GlesYuvStacker(
currentAccumulatorTexture = accumulatorTexture
}
/** Noise is measured in the same encoded YCbCr domain as guide differences and kernels. */
private fun prepareSabreNoiseAndCovariance(y: Int, cbcr: Int, guide: Int, guideNoise: Int) {
timing.compute("sabre.noise") {
check(noiseWidth in 1..65535 && noiseHeight in 1..65535)
GLES30.glUseProgram(noiseEstimateProgram)
bindTexture(noiseEstimateProgram, "uLuma", 0, y)
bindTexture(noiseEstimateProgram, "uChroma", 1, cbcr)
bindTexture(noiseEstimateProgram, "uGuide", 2, guide)
GLES30.glUniform2i(uniform(noiseEstimateProgram, "uInputSize"), width, height)
GLES30.glUniform2i(uniform(noiseEstimateProgram, "uGuideSize"), guideWidth, guideHeight)
GLES30.glUniform1f(uniform(noiseEstimateProgram, "uCodeStep"), if (highPrecisionInput) 64f / 65535f else 1f / 255f)
GLES31.glBindImageTexture(0, nativeNoiseTexture, 0, false, 0, GLES31.GL_WRITE_ONLY, GLES30.GL_RGBA16F)
GLES31.glBindImageTexture(1, guideNoise, 0, false, 0, GLES31.GL_WRITE_ONLY, GLES30.GL_RGBA16F)
GLES31.glDispatchCompute(noiseWidth, noiseHeight, 1)
finishComputeImages("sabre.noise", 2, GLES30.GL_RGBA16F)
}
bindFramebufferOutput(covarianceTexture, "sabre.covariance")
GLES30.glViewport(0, 0, guideWidth, guideHeight)
GLES30.glUseProgram(covarianceProgram)
bindTexture(covarianceProgram, "uGuide", 0, guide)
bindTexture(covarianceProgram, "uNativeNoise", 1, nativeNoiseTexture)
bindTexture(covarianceProgram, "uGuideNoise", 2, guideNoise)
GLES30.glUniform2i(uniform(covarianceProgram, "uGuideSize"), guideWidth, guideHeight)
GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3)
finishFramebufferPass("sabre.covariance")
}
private fun clearSabreAccumulators() {
for ((texture, size) in listOf(
lumaAccumulatorTexture to (width to height),
chromaAccumulatorTexture to (chromaWidth to chromaHeight),
)) {
bindFramebufferOutput(texture, "sabre.clear")
GLES30.glViewport(0, 0, size.first, size.second)
GLES30.glClearColor(0f, 0f, 0f, 0f)
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
finishFramebufferPass("sabre.clear")
}
}
private fun renderSabreRejection(alignment: Alignment) {
check(alignment.gridMin == 0 && alignment.scaleToGuidePixels == 1f)
bindFramebufferOutput(rawReverseWeightTexture, "sabre.rejection")
GLES30.glViewport(0, 0, guideWidth, guideHeight)
GLES30.glUseProgram(rejectionProgram)
bindTexture(rejectionProgram, "uReferenceGuide", 0, referenceGuideTexture)
bindTexture(rejectionProgram, "uCurrentGuide", 1, currentGuideTexture)
bindTexture(rejectionProgram, "uReferenceNoise", 2, referenceGuideNoiseTexture)
bindTexture(rejectionProgram, "uCurrentNoise", 3, currentGuideNoiseTexture)
bindTexture(rejectionProgram, "uAlignment", 4, alignment.texture)
GLES30.glUniform2i(uniform(rejectionProgram, "uGuideSize"), guideWidth, guideHeight)
GLES30.glUniform2i(uniform(rejectionProgram, "uAlignmentGridSize"), alignment.gridWidth, alignment.gridHeight)
GLES30.glUniform1i(uniform(rejectionProgram, "uAlignmentTileSize"), alignment.tileStride)
GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3)
finishFramebufferPass("sabre.rejection")
bindFramebufferOutput(frameWeightTexture, "sabre.dilation")
GLES30.glViewport(0, 0, mergeWeightWidth, mergeWeightHeight)
GLES30.glUseProgram(rejectionDownsampleProgram)
bindTexture(rejectionDownsampleProgram, "uRejection", 0, rawReverseWeightTexture)
GLES30.glUniform2i(uniform(rejectionDownsampleProgram, "uInputSize"), guideWidth, guideHeight)
GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3)
finishFramebufferPass("sabre.dilation")
}
private fun accumulateSabreFrame(y: Int, cbcr: Int, isReference: Boolean) {
for (chroma in listOf(false, true)) {
val program = if (chroma) sabreChromaMergeProgram else accumulateProgram
val label = if (chroma) "sabre.merge.chroma" else "sabre.merge.luma"
bindFramebufferOutput(if (chroma) chromaAccumulatorTexture else lumaAccumulatorTexture, label)
GLES30.glViewport(0, 0, if (chroma) chromaWidth else width, if (chroma) chromaHeight else height)
GLES30.glUseProgram(program)
bindTexture(program, "uCurrentY", 0, y)
bindTexture(program, "uCurrentCbCr", 1, cbcr)
bindTexture(program, "uCovariance", 2, covarianceTexture)
bindTexture(program, "uAlignment", 3, if (isReference) zeroFlowTexture else mergeAlignmentTexture)
bindTexture(program, "uFrameWeight", 4, if (isReference) identityWeightTexture else frameWeightTexture)
GLES30.glUniform2i(uniform(program, "uInputSize"), width, height)
GLES30.glUniform2i(uniform(program, "uGuideSize"), guideWidth, guideHeight)
GLES30.glUniform1i(uniform(program, "uUseFrameWeight"), if (isReference) 0 else 1)
GLES30.glEnable(GLES30.GL_BLEND)
try {
GLES30.glBlendEquation(GLES30.GL_FUNC_ADD)
GLES30.glBlendFunc(GLES30.GL_ONE, GLES30.GL_ONE)
GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3)
} finally {
GLES30.glDisable(GLES30.GL_BLEND)
}
finishFramebufferPass(label)
}
}
private fun resolveSabreAccumulator() {
bindFramebufferOutput(accumulatorTexture, "sabre.resolve")
GLES30.glViewport(0, 0, width, height)
GLES30.glUseProgram(sabreResolveProgram)
bindTexture(sabreResolveProgram, "uLumaAccumulator", 0, lumaAccumulatorTexture)
bindTexture(sabreResolveProgram, "uChromaAccumulator", 1, chromaAccumulatorTexture)
GLES30.glUniform2i(uniform(sabreResolveProgram, "uInputSize"), width, height)
GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3)
finishFramebufferPass("sabre.resolve")
currentAccumulatorTexture = accumulatorTexture
}
private fun prepareSpatialTemporalFrame(
referencePyramid: List<TextureLevel>,
currentPyramid: List<TextureLevel>,
@@ -1478,9 +1651,9 @@ class GlesYuvStacker(
private fun buildReferenceAlignmentProducts(
reference: List<TextureLevel>,
): List<ReferenceAlignmentProducts> {
check(reference.size == ALIGN_LEVEL_TILE_STRIDES.size)
check(reference.size == if (sabreMode) sabreAlignmentPlan.levels.size else ALIGN_LEVEL_TILE_STRIDES.size)
return reference.mapIndexed { levelIndex, level ->
val tileSize = ALIGN_LEVEL_TILE_STRIDES[levelIndex]
val tileSize = if (sabreMode) level.tileSize else ALIGN_LEVEL_TILE_STRIDES[levelIndex]
val productGridWidth = alignmentGridWidth(level, tileSize)
val productGridHeight = alignmentGridHeight(level, tileSize)
val products0 = createTexture2D(
@@ -1527,22 +1700,25 @@ class GlesYuvStacker(
current: List<TextureLevel>,
referenceProducts: List<ReferenceAlignmentProducts>,
): Alignment {
check(reference.size == current.size && reference.size == ALIGN_LEVEL_TILE_STRIDES.size)
check(reference.size == current.size)
check(referenceProducts.size == reference.size)
val coarseIndex = reference.lastIndex
var alignment = renderLucasKanadeLevel(
reference = reference[coarseIndex],
current = current[coarseIndex],
initial = null,
tileStride = ALIGN_LEVEL_TILE_STRIDES[coarseIndex],
tileSize = ALIGN_LEVEL_TILE_STRIDES[coarseIndex],
iterations = ALIGN_LK_ITERATIONS_COARSER,
normalize = true,
tileStride = if (sabreMode) reference[coarseIndex].tileSize else ALIGN_LEVEL_TILE_STRIDES[coarseIndex],
tileSize = if (sabreMode) reference[coarseIndex].tileSize else ALIGN_LEVEL_TILE_STRIDES[coarseIndex],
iterations = if (coarseIndex == 0) ALIGN_LK_ITERATIONS_FINEST else ALIGN_LK_ITERATIONS_COARSER,
normalize = coarseIndex != 0,
referenceProducts = referenceProducts[coarseIndex],
)
for (levelIndex in coarseIndex - 1 downTo 0) {
val level = reference[levelIndex]
val tileSize = ALIGN_LEVEL_TILE_STRIDES[levelIndex]
val tileSize = if (sabreMode) level.tileSize else ALIGN_LEVEL_TILE_STRIDES[levelIndex]
val globalCandidate = if (sabreMode) timing.compute("alignment.globalHistogram") {
globalAlignment.estimate(alignment.texture, alignment.gridWidth, alignment.gridHeight)
} else 0
alignment = renderUpsampledAlignment(
reference = level,
current = current[levelIndex],
@@ -1552,6 +1728,7 @@ class GlesYuvStacker(
targetGridMin = ALIGN_LK_GRID_MIN,
targetTileStride = tileSize,
targetTileSize = tileSize,
globalCandidate = globalCandidate,
)
alignment = renderLucasKanadeLevel(
reference = level,
@@ -1568,7 +1745,7 @@ class GlesYuvStacker(
referenceProducts = referenceProducts[levelIndex],
)
}
val globalCandidate = timing.gpu("alignment.globalHistogram") {
val globalCandidate = if (sabreMode) 0 else timing.compute("alignment.globalHistogram") {
globalAlignment.estimate(alignment.texture, alignment.gridWidth, alignment.gridHeight)
}
alignment = renderUpsampledAlignment(
@@ -1583,9 +1760,10 @@ class GlesYuvStacker(
globalCandidate = globalCandidate,
)
RawStackRuntimeDebug.d(TAG) {
"YUV Spatial alignment guide=${guideWidth}x$guideHeight " +
"YUV ${if (sabreMode) "Sabre" else "Spatial"} alignment guide=${guideWidth}x$guideHeight " +
"flowGrid=${alignment.gridWidth}x${alignment.gridHeight} " +
"global=gpu-histogram"
"global=${if (sabreMode) "pyramid-transitions" else "final-grid"} " +
"solver=${if (sabreMode) "compute" else "fragment"} levels=${reference.size}"
}
return alignment
}
@@ -1612,8 +1790,11 @@ class GlesYuvStacker(
var input = initial
repeat(iterations) { iteration ->
val output = alignmentScratchTarget(levelGridWidth, levelGridHeight, input?.texture ?: 0)
bindFramebufferOutput(output, "alignment.lk.scale=${reference.scaleToGuidePixels}.iteration=$iteration")
GLES30.glViewport(0, 0, levelGridWidth, levelGridHeight)
val label = "alignment.lk.scale=${reference.scaleToGuidePixels}.iteration=$iteration"
if (!sabreMode) {
bindFramebufferOutput(output, label)
GLES30.glViewport(0, 0, levelGridWidth, levelGridHeight)
}
GLES30.glUseProgram(blockLucasKanadeProgram)
bindTexture(blockLucasKanadeProgram, "uReference", 0, reference.texture)
check(current.linearTexture != 0) { "YUV LK requires a filterable current pyramid" }
@@ -1651,8 +1832,17 @@ class GlesYuvStacker(
uniform(blockLucasKanadeProgram, "uHasInitialAlignment"),
if (input != null) 1 else 0,
)
GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3)
finishFramebufferPass("alignment.lk.scale=${reference.scaleToGuidePixels}.iteration=$iteration")
if (sabreMode) {
timing.compute(label) {
check(levelGridWidth in 1..65535 && levelGridHeight in 1..65535)
GLES31.glBindImageTexture(0, output, 0, false, 0, GLES31.GL_WRITE_ONLY, GLES30.GL_RGBA32F)
GLES31.glDispatchCompute(levelGridWidth, levelGridHeight, 1)
finishComputeImages(label, 1, GLES30.GL_RGBA32F)
}
} else {
GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3)
finishFramebufferPass(label)
}
input = Alignment(
texture = output,
gridWidth = levelGridWidth,
@@ -2037,7 +2227,12 @@ class GlesYuvStacker(
bindFramebufferOutput(targetTexture, label)
GLES30.glViewport(0, 0, gpuOutputWidth, gpuOutputHeight)
GLES30.glUseProgram(program)
bindTexture(program, "uAccumulator", 0, accumulatorTexture)
if (sabreMode && !outputUpscaleEnabled) {
bindTexture(program, "uLumaAccumulator", 0, lumaAccumulatorTexture)
bindTexture(program, "uChromaAccumulator", 1, chromaAccumulatorTexture)
} else {
bindTexture(program, "uAccumulator", 0, accumulatorTexture)
}
GLES31.glUniform2i(GLES31.glGetUniformLocation(program, "uInputSize"), width, height)
val transform = if (outputUpscaleEnabled) computeOutputResampleTransform() else computeRenderTransform()
GLES31.glUniform3f(
@@ -2562,6 +2757,39 @@ class GlesYuvStacker(
}
}
private fun linkComputeProgram(source: String, name: String): Int {
GlesComputeWorkGroup.requireBaselineCompatible(source, name)
val shader = compileShader(GLES31.GL_COMPUTE_SHADER, source, name)
var program = 0
var retained = false
try {
program = GLES30.glCreateProgram()
GLES30.glAttachShader(program, shader)
GLES30.glLinkProgram(program)
val linked = IntArray(1)
GLES30.glGetProgramiv(program, GLES30.GL_LINK_STATUS, linked, 0)
check(linked[0] != 0) { "Program $name linking failed: ${GLES30.glGetProgramInfoLog(program)}" }
programs += program
retained = true
return program
} finally {
GLES30.glDeleteShader(shader)
if (!retained && program != 0) GLES30.glDeleteProgram(program)
}
}
private fun finishComputeImages(label: String, count: Int, format: Int) {
// Scratch targets alternate between image writes, sampler reads and framebuffer writes.
GLES31.glMemoryBarrier(
GLES31.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT or GLES31.GL_TEXTURE_FETCH_BARRIER_BIT or
GLES31.GL_FRAMEBUFFER_BARRIER_BIT,
)
repeat(count) { unit ->
GLES31.glBindImageTexture(unit, 0, 0, false, 0, GLES31.GL_WRITE_ONLY, format)
}
checkGlError(label)
}
private fun compileShader(type: Int, source: String, name: String): Int {
val shader = GLES30.glCreateShader(type)
GLES30.glShaderSource(shader, source)
@@ -2747,13 +2975,13 @@ class GlesYuvStacker(
}
private fun alignmentGridWidth(level: TextureLevel, tileStride: Int): Int =
alignmentGridExtent(
if (sabreMode) level.gridWidth else alignmentGridExtent(
ceilDiv(guideWidth, level.scaleToGuidePixels.toInt()),
tileStride,
)
private fun alignmentGridHeight(level: TextureLevel, tileStride: Int): Int =
alignmentGridExtent(
if (sabreMode) level.gridHeight else alignmentGridExtent(
ceilDiv(guideHeight, level.scaleToGuidePixels.toInt()),
tileStride,
)
@@ -33,6 +33,7 @@ internal class GlesYuvTiming {
private var counterOverflow = false
private var disjoint = false
private var aborted = false
private var computePasses = 0
fun start(description: String) {
if (!enabled) return
@@ -110,6 +111,19 @@ internal class GlesYuvTiming {
}
}
/** Elapsed queries can report zero for compute on Adreno. Never label that as GPU time. */
fun <T> compute(stage: String, block: () -> T): T {
if (!enabled) return block()
computePasses++
val sample = Sample(stage, frame, System.nanoTime(), "compute-pass")
try {
return block()
} finally {
sample.cpuNs = System.nanoTime() - sample.startNs
samples += sample
}
}
/** Called immediately before glReadPixels, never at individual render-pass boundaries. */
fun awaitReadback(checkGlError: (String) -> Unit) {
if (!enabled) return
@@ -191,17 +205,19 @@ internal class GlesYuvTiming {
"wallMs=${ms(System.nanoTime() - startNs)} " +
"gpuMs=${if (validGpu) ms(gpuSamples.sumOf { it.gpuNs ?: 0L }) else "NA"} " +
"gpuStatus=$gpuStatus passes=${gpuSamples.size} " +
"gpuCoverage=${if (computePasses > 0) "graphics-only" else "timed-passes"} computePasses=$computePasses " +
"cpuScopes=inclusive cpuGpu=overlap queueTail=remaining-at-readback",
)
for ((label, frameSamples) in samples.groupBy { it.frame }) {
val passes = frameSamples.filter { it.kind == "gpu-pass" }
val compute = frameSamples.filter { it.kind == "compute-pass" }
val first = frameSamples.minOf { it.startNs }
val last = frameSamples.maxOf { it.startNs + it.cpuNs }
PLog.i(
TAG,
"capture=$capture frame=$label submitStartMs=${ms(first - startNs)} " +
"submitEndMs=${ms(last - startNs)} " +
"cpuSubmitMs=${ms(passes.sumOf { it.cpuNs })} " +
"cpuSubmitMs=${ms(passes.sumOf { it.cpuNs } + compute.sumOf { it.cpuNs })} " +
"gpuMs=${if (validGpu) ms(passes.sumOf { it.gpuNs ?: 0L }) else "NA"}",
)
}