feat: Lucas-Kanade precision fixes and Sabre alignment offsets

This commit is contained in:
zhoubinjia committed 2026-09-23 13:49:48 +08:00
1 parent 2557a1d6e5
commit 70728d1168
8 files changed
+553 -374

No files matched your search

@@ -690,9 +690,9 @@ internal object GlesMgcRawSpatialShaders {
""".trimIndent() """.trimIndent()
/** /**
* Read4xDownSample and the input preparation for * SabreProcessor's FilterRejectionMap uses S16/U8 BoxDownsample before the Halide
* Downsample4xAndFilterRejectionMap from the embedded rejection.cl. V25 calls it after * bilateral filter. Both sums round once to integers, including repeated edge samples
* DilateMask/Downsample2x, so it reads RAW/4 base luma and acceptance and produces RAW/16. * in a partial 4x4 block. The OpenCL path's fractional averages are a different contract.
*/ */
val rejectionFilterDownsample = """ val rejectionFilterDownsample = """
#version 300 es #version 300 es
@@ -706,63 +706,25 @@ internal object GlesMgcRawSpatialShaders {
layout(location = 0) out float oLuma; layout(location = 0) out float oLuma;
layout(location = 1) out float oRejection; layout(location = 1) out float oRejection;
float lumaLinearAt(vec2 coordinate) {
vec2 shifted = coordinate - vec2(0.5);
ivec2 p0 = ivec2(floor(shifted));
vec2 fraction = fract(shifted);
ivec2 maximum = uInputSize - ivec2(1);
float v00 = float(texelFetch(
uBaseLuma, clamp(p0, ivec2(0), maximum), 0
).r);
float v10 = float(texelFetch(
uBaseLuma, clamp(p0 + ivec2(1, 0), ivec2(0), maximum), 0
).r);
float v01 = float(texelFetch(
uBaseLuma, clamp(p0 + ivec2(0, 1), ivec2(0), maximum), 0
).r);
float v11 = float(texelFetch(
uBaseLuma, clamp(p0 + ivec2(1), ivec2(0), maximum), 0
).r);
return mix(
mix(v00, v10, fraction.x),
mix(v01, v11, fraction.x),
fraction.y
);
}
float rejectionLinearAt(vec2 coordinate) {
return texture(
uRejection,
coordinate / vec2(uInputSize)
).r;
}
void main() { void main() {
vec2 center = 4.0 * floor(gl_FragCoord.xy) + vec2(2.0); ivec2 origin = ivec2(gl_FragCoord.xy) * 4;
center = clamp( int luma = 0;
center, int rejection = 0;
vec2(2.0), for (int y = 0; y < 4; ++y) {
vec2(uInputSize) - vec2(2.0) for (int x = 0; x < 4; ++x) {
); ivec2 p = min(origin + ivec2(x, y), uInputSize - ivec2(1));
float luma = 0.0; luma += texelFetch(uBaseLuma, p, 0).r;
float rejection = 0.0; rejection += int(floor(texelFetch(uRejection, p, 0).r * 255.0 + 0.5));
for (int y = -1; y <= 1; y += 2) {
for (int x = -1; x <= 1; x += 2) {
vec2 coordinate = center + vec2(x, y);
luma += lumaLinearAt(coordinate);
rejection += rejectionLinearAt(coordinate);
} }
} }
// The source reads CL_SNORM_INT16 and multiplies by 32767 / 16383. oLuma = float((luma + 8) >> 4) / 16383.0;
oLuma = 0.25 * luma / 16383.0; oRejection = float((rejection + 8) >> 4) / 255.0;
oRejection = 0.25 * rejection;
} }
""".trimIndent() """.trimIndent()
/** /**
* Downsample4xAndFilterRejectionMap from the embedded rejection.cl. The input textures contain * RejectionMapFilterHalide (38B13E0). Compare quantized weights directly, without
* the exact Read4xDownSample results, so the 7x7 loop is algebraically identical to the fused * OpenCL's one-code tolerance, and retain the native round-to-even U8 output.
* OpenCL kernel while avoiding repeated 4x4 source reads.
*/ */
val rejectionFilter = """ val rejectionFilter = """
#version 300 es #version 300 es
@@ -818,8 +780,7 @@ internal object GlesMgcRawSpatialShaders {
ivec2 q = p + ivec2(dx, dy); ivec2 q = p + ivec2(dx, dy);
float deltaLuma = valueAt(uLuma, q); float deltaLuma = valueAt(uLuma, q);
float deltaRejection = valueAt(uRejection, q); float deltaRejection = valueAt(uRejection, q);
float sigma = centerRejection < float sigma = centerRejection < deltaRejection
deltaRejection - 1.0 / 255.0
? uColorSigma ? uColorSigma
: uColorSigma * ( : uColorSigma * (
uClipRejection != 0 ? uColorSigmaBoost : 1.0 uClipRejection != 0 ? uColorSigmaBoost : 1.0
@@ -836,15 +797,18 @@ internal object GlesMgcRawSpatialShaders {
weightSum += weight; weightSum += weight;
} }
} }
oFilteredRejection = weightSum > 0.0 float filtered = weightSum > 0.0
? weightedRejection / weightSum ? weightedRejection / weightSum
: centerRejection; : centerRejection;
oFilteredRejection = roundEven(clamp(filtered, 0.0, 1.0) * 255.0) / 255.0;
} }
""".trimIndent() """.trimIndent()
/** /**
* Upsample4xAndPostProcess from the embedded rejection.cl. A separate output texture avoids * FilterRejectionMap's LinearKernel resample and strong postprocess. V25's U8
* undefined framebuffer feedback while preserving the source equation. * linear AOT (5C1208C) uses fixed 4x coordinates and two integer interpolation
* stages, vertical first. Normalized texture sampling stretches ceil-sized grids
* and loses the intermediate U8 rounding.
*/ */
val rejectionPostprocess = """ val rejectionPostprocess = """
#version 300 es #version 300 es
@@ -858,26 +822,48 @@ internal object GlesMgcRawSpatialShaders {
uniform float uPixelDifferenceThreshold; uniform float uPixelDifferenceThreshold;
uniform float uClippedThreshold; uniform float uClippedThreshold;
out float oRejection; out float oRejection;
int filteredAt(ivec2 p) {
p = clamp(p, ivec2(0), textureSize(uFilteredWeight, 0) - ivec2(1));
return int(floor(texelFetch(uFilteredWeight, p, 0).r * 255.0 + 0.5));
}
int lerpU8(int a, int b, int fraction) {
int sum = a * (255 - fraction) + b * fraction;
// NEON urshr #8 followed by raddhn: rounded division by 255.
return (sum + ((sum + 128) >> 8) + 128) >> 8;
}
int upsampledAt(ivec2 p) {
vec2 coordinate = (vec2(p) + vec2(0.5)) * 0.25 - vec2(0.5);
ivec2 source = ivec2(floor(coordinate));
ivec2 fraction = ivec2(fract(coordinate) * 256.0);
int left = lerpU8(
filteredAt(source), filteredAt(source + ivec2(0, 1)), fraction.y
);
int right = lerpU8(
filteredAt(source + ivec2(1, 0)), filteredAt(source + ivec2(1)), fraction.y
);
return lerpU8(left, right, fraction.x);
}
void main() { void main() {
ivec2 p = ivec2(gl_FragCoord.xy); ivec2 p = ivec2(gl_FragCoord.xy);
float original = texelFetch(uOriginalWeight, p, 0).r; int original = int(floor(texelFetch(uOriginalWeight, p, 0).r * 255.0 + 0.5));
float pixelDifference = texelFetch(uPixelDifference, p, 0).r; int pixelDifference = int(floor(texelFetch(uPixelDifference, p, 0).r * 255.0 + 0.5));
vec2 uv = (vec2(p) + vec2(0.5)) / vec2(uSize); int pixelThreshold = int(floor(uPixelDifferenceThreshold * 255.0 + 0.5));
float filtered = texture(uFilteredWeight, uv).r; int clippedThreshold = int(floor(uClippedThreshold * 255.0 + 0.5));
float postprocessed = filtered; int filtered = upsampledAt(p);
int postprocessed = filtered;
if (filtered > original) { if (filtered > original) {
float weight = pixelDifference < uPixelDifferenceThreshold float weight = pixelDifference <= pixelThreshold
? 0.0 ? 0.0
: pixelDifference; : float(pixelDifference) / 255.0;
postprocessed = postprocessed = int(float(original) + weight * float(filtered - original));
original + weight * (filtered - original);
} }
if (uClippedThreshold > 0.0 && if (clippedThreshold > 0 &&
original <= uClippedThreshold && original <= clippedThreshold &&
pixelDifference <= uPixelDifferenceThreshold) { pixelDifference <= pixelThreshold) {
postprocessed = original; postprocessed = original;
} }
oRejection = postprocessed; oRejection = float(postprocessed) / 255.0;
} }
""".trimIndent() """.trimIndent()
@@ -2116,9 +2102,10 @@ internal object GlesMgcRawSpatialShaders {
""".trimIndent() """.trimIndent()
/** /**
* GrayPyramidDownsample4xHalide (0x3bcef58). Unlike two separately quantized * GrayPyramidDownsampleS16_4xHalide (worker 0x3c1c740, called by 0x38cd9b8).
* 2x passes, the original evaluates the complete separable seven-tap triangle * Two 2x triangle stages each round to S16. Collapsing their seven-tap kernel
* and converts to S16 only once. * into one floating-point sum loses the intermediate rounding. Evaluate the
* intermediate halo from the clamped source, just as the original worker does.
*/ */
val grayDownsample4 = buildGrayDownsample4(linearOutput = false) val grayDownsample4 = buildGrayDownsample4(linearOutput = false)
val yuvGrayDownsample4 = buildGrayDownsample4(linearOutput = true) val yuvGrayDownsample4 = buildGrayDownsample4(linearOutput = true)
@@ -2133,35 +2120,43 @@ internal object GlesMgcRawSpatialShaders {
uniform ivec2 uInputSize; uniform ivec2 uInputSize;
layout(location = 0) out highp int oGray; layout(location = 0) out highp int oGray;
${if (linearOutput) "layout(location = 1) out highp vec2 oLinearGray;" else ""} ${if (linearOutput) "layout(location = 1) out highp vec2 oLinearGray;" else ""}
float valueAt(ivec2 p) { int valueAt(ivec2 p) {
return float(texelFetch( return texelFetch(
uInput, uInput,
clamp(p, ivec2(0), uInputSize - ivec2(1)), clamp(p, ivec2(0), uInputSize - ivec2(1)),
0 0
).r); ).r;
} }
float triangleWeight(int offset) { int firstStageAt(ivec2 p) {
return float(4 - abs(offset)) * (1.0 / 16.0); int sum = 0;
for (int y = -1; y <= 1; ++y) {
for (int x = -1; x <= 1; ++x) {
sum += valueAt(p + ivec2(x, y)) *
(2 - abs(x)) * (2 - abs(y));
}
}
return (sum + 8) >> 4;
} }
void main() { void main() {
ivec2 p = ivec2(gl_FragCoord.xy) * 4; ivec2 p = ivec2(gl_FragCoord.xy) * 4;
float value = 0.0; int sum = 0;
for (int y = -3; y <= 3; ++y) { for (int y = -1; y <= 1; ++y) {
float wy = triangleWeight(y); for (int x = -1; x <= 1; ++x) {
for (int x = -3; x <= 3; ++x) { sum += firstStageAt(p + 2 * ivec2(x, y)) *
value += valueAt(p + ivec2(x, y)) * (2 - abs(x)) * (2 - abs(y));
triangleWeight(x) * wy;
} }
} }
oGray = int(clamp(floor(value + 0.5), -32768.0, 32767.0)); oGray = (sum + 8) >> 4;
${if (linearOutput) "float coarseGray = floor(float(oGray) / 16.0); oLinearGray = vec2(coarseGray, float(oGray) - coarseGray * 16.0);" else ""} ${if (linearOutput) "float coarseGray = floor(float(oGray) / 16.0); oLinearGray = vec2(coarseGray, float(oGray) - coarseGray * 16.0);" else ""}
} }
""".trimIndent() """.trimIndent()
/** /**
* GradientAndGradientProductsHalide (0x3bf25c0; worker 0x3be9a1c). The generated kernel * GradientAndGradientProductsHalide (0x3bf25c0; worker 0x3be9a1c). The generated kernel
* stores central differences as saturated S16 and five per-tile Float32 products in this * stores central differences as saturated S16. Cache the Hessian as xx, yy, xy, det(H).
* order: xx, yy, xy, base*x and base*y. * LK accumulates the image residual directly, so reference intensity products are not
* needed. Materializing det(H) before adding its +1 regularizer also prevents GLES
* reassociation from losing that unit beside the much larger xx*yy product.
*/ */
val alignmentGradientProducts = buildAlignmentGradientProducts(sparseFineLevels = false) val alignmentGradientProducts = buildAlignmentGradientProducts(sparseFineLevels = false)
val yuvAlignmentGradientProducts = buildAlignmentGradientProducts(sparseFineLevels = true) val yuvAlignmentGradientProducts = buildAlignmentGradientProducts(sparseFineLevels = true)
@@ -2176,9 +2171,7 @@ internal object GlesMgcRawSpatialShaders {
uniform ivec2 uImageSize; uniform ivec2 uImageSize;
uniform int uTileStride; uniform int uTileStride;
uniform int uTileSize; uniform int uTileSize;
uniform int uNormalize;
layout(location = 0) out vec4 oProducts0; layout(location = 0) out vec4 oProducts0;
layout(location = 1) out float oProducts1;
float valueAt(ivec2 p) { float valueAt(ivec2 p) {
return float(texelFetch( return float(texelFetch(
@@ -2204,45 +2197,45 @@ internal object GlesMgcRawSpatialShaders {
ivec2 origin = (tile + ivec2(1)) * uTileStride; ivec2 origin = (tile + ivec2(1)) * uTileStride;
int sampleStep = ${if (sparseFineLevels) "uTileSize >= 32 ? 2 : 1" else "1"}; int sampleStep = ${if (sparseFineLevels) "uTileSize >= 32 ? 2 : 1" else "1"};
float count = float((uTileSize / sampleStep) * (uTileSize / sampleStep)); float count = float((uTileSize / sampleStep) * (uTileSize / sampleStep));
float meanBase = 0.0;
if (uNormalize != 0) {
for (int y = 0; y < 64; y += sampleStep) {
if (y >= uTileSize) break;
for (int x = 0; x < 64; x += sampleStep) {
if (x >= uTileSize) break;
meanBase += valueAt(origin + ivec2(x, y));
}
}
meanBase /= count;
}
float xx = 0.0; float xx = 0.0;
float yy = 0.0; float yy = 0.0;
float xy = 0.0; float xy = 0.0;
float baseX = 0.0;
float baseY = 0.0;
for (int y = 0; y < 64; y += sampleStep) { for (int y = 0; y < 64; y += sampleStep) {
if (y >= uTileSize) break; if (y >= uTileSize) break;
for (int x = 0; x < 64; x += sampleStep) { for (int x = 0; x < 64; x += sampleStep) {
if (x >= uTileSize) break; if (x >= uTileSize) break;
ivec2 p = origin + ivec2(x, y); ivec2 p = origin + ivec2(x, y);
vec2 gradient = gradientAt(p); vec2 gradient = gradientAt(p);
float base = valueAt(p) - meanBase;
xx += gradient.x * gradient.x; xx += gradient.x * gradient.x;
yy += gradient.y * gradient.y; yy += gradient.y * gradient.y;
xy += gradient.x * gradient.y; xy += gradient.x * gradient.y;
baseX += base * gradient.x;
baseY += base * gradient.y;
} }
} }
float inverseCount = 1.0 / count; float inverseCount = 1.0 / count;
oProducts0 = vec4( vec3 hessian = vec3(
0.25 * xx * inverseCount, 0.25 * xx * inverseCount,
0.25 * yy * inverseCount, 0.25 * yy * inverseCount,
0.25 * xy * inverseCount, 0.25 * xy * inverseCount
0.5 * baseX * inverseCount
); );
oProducts1 = 0.5 * baseY * inverseCount; // A Gram determinant is non-negative. Form it from orthogonal residual energy
// instead of subtracting nearly equal xx*yy and xy*xy on one-dimensional edges.
// With a = max(xx, yy), c = xy: det(H) = a * mean((gMinor-c/a*gMajor)^2)/4.
bool xMajor = hessian.x >= hessian.y;
float major = xMajor ? hessian.x : hessian.y;
float slope = major > 0.0 ? hessian.z / major : 0.0;
float orthogonalEnergy = 0.0;
for (int y = 0; y < 64; y += sampleStep) {
if (y >= uTileSize) break;
for (int x = 0; x < 64; x += sampleStep) {
if (x >= uTileSize) break;
vec2 gradient = gradientAt(origin + ivec2(x, y));
float residual = xMajor
? gradient.y - slope * gradient.x
: gradient.x - slope * gradient.y;
orthogonalEnergy += residual * residual;
}
}
oProducts0 = vec4(hessian, major * (0.25 * orthogonalEnergy * inverseCount));
} }
""".trimIndent() """.trimIndent()
@@ -2255,7 +2248,8 @@ internal object GlesMgcRawSpatialShaders {
*/ */
val upsampleAlignment = buildUpsampleAlignment(globalCandidateTexture = false) val upsampleAlignment = buildUpsampleAlignment(globalCandidateTexture = false)
val upsampleAlignmentWithGpuCandidate = buildUpsampleAlignment(globalCandidateTexture = true) val rawUpsampleAlignment = buildUpsampleAlignment(globalCandidateTexture = true)
val yuvUpsampleAlignment = buildUpsampleAlignment(globalCandidateTexture = true, sampleStep = 2) val yuvUpsampleAlignment = buildUpsampleAlignment(globalCandidateTexture = true, sampleStep = 2)
private fun buildUpsampleAlignment(globalCandidateTexture: Boolean, sampleStep: Int = 1) = """ private fun buildUpsampleAlignment(globalCandidateTexture: Boolean, sampleStep: Int = 1) = """
@@ -2274,6 +2268,7 @@ internal object GlesMgcRawSpatialShaders {
uniform int uInitialTileStride; uniform int uInitialTileStride;
uniform int uTargetTileStride; uniform int uTargetTileStride;
uniform int uTargetTileSize; uniform int uTargetTileSize;
uniform ivec2 uTargetImageOffset;
uniform float uInitialScale; uniform float uInitialScale;
uniform int uHasGlobalCandidate; uniform int uHasGlobalCandidate;
${if (globalCandidateTexture) "uniform highp sampler2D uGlobalCandidateTexture;" else "uniform vec2 uGlobalCandidate;"} ${if (globalCandidateTexture) "uniform highp sampler2D uGlobalCandidateTexture;" else "uniform vec2 uGlobalCandidate;"}
@@ -2346,38 +2341,41 @@ internal object GlesMgcRawSpatialShaders {
nextX = boundedInitialTile(nextX); nextX = boundedInitialTile(nextX);
nextY = boundedInitialTile(nextY); nextY = boundedInitialTile(nextY);
ivec2 origin = targetLogicalTile * uTargetTileStride; // Original AlignAlt shifts both image buffer minima by +offset. The
// corresponding physical image window therefore moves by -offset.
ivec2 origin = targetLogicalTile * uTargetTileStride - uTargetImageOffset;
vec2 bestFlow = candidateFlow(nearest); vec2 bestFlow = candidateFlow(nearest);
vec2 nearestFlow = bestFlow; vec2 nearestFlow = bestFlow;
float bestCost = candidateCost(origin, bestFlow); float bestCost = candidateCost(origin, bestFlow);
float nearestCost = bestCost; float nearestCost = bestCost;
float candidateIndex = 0.0; float candidateIndex = 0.0;
// The generated worker's candidate order is nearest, next Y, next X. // The generated worker's candidate order is nearest, next X, next Y.
// Strict less-than comparison makes this ordering observable on equal costs. // Strict less-than comparison makes this ordering observable on equal costs.
// SAD depends only on the rounded displacement. Reuse its cost, but keep the // SAD depends only on the rounded displacement. Reuse its cost, but keep the
// original fractional flow and candidate order even when displacements coincide. // original fractional flow and candidate order even when displacements coincide.
vec2 flowY = candidateFlow(nextY);
float costY = all(equal(roundEven(flowY), roundEven(nearestFlow))) ? nearestCost :
candidateCost(origin, flowY);
if (costY < bestCost) {
bestFlow = flowY;
bestCost = costY;
candidateIndex = 1.0;
}
vec2 flowX = candidateFlow(nextX); vec2 flowX = candidateFlow(nextX);
float costX = all(equal(roundEven(flowX), roundEven(nearestFlow))) ? nearestCost : float costX = all(equal(roundEven(flowX), roundEven(nearestFlow))) ? nearestCost :
all(equal(roundEven(flowX), roundEven(flowY))) ? costY :
candidateCost(origin, flowX); candidateCost(origin, flowX);
if (costX < bestCost) { if (costX < bestCost) {
bestFlow = flowX; bestFlow = flowX;
bestCost = costX; bestCost = costX;
candidateIndex = 1.0;
}
vec2 flowY = candidateFlow(nextY);
float costY = all(equal(roundEven(flowY), roundEven(nearestFlow))) ? nearestCost :
all(equal(roundEven(flowY), roundEven(flowX))) ? costX :
candidateCost(origin, flowY);
if (costY < bestCost) {
bestFlow = flowY;
bestCost = costY;
candidateIndex = 2.0; candidateIndex = 2.0;
} }
// AlignPyramid::AlignAlt's final merge-grid pass supplies the robust global // AlignAlt's ordinary pyramid transitions use threshold=1 and include the
// translation as the fourth candidate. Pyramid-level transitions leave it absent. // whole-grid histogram candidate. The final merge-grid call at 0x38D29BC
// passes threshold=-1 and uses only the three neighboring candidates.
if (uHasGlobalCandidate != 0) { if (uHasGlobalCandidate != 0) {
vec2 globalFlow = ${if (globalCandidateTexture) "texelFetch(uGlobalCandidateTexture, ivec2(0), 0).xy" else "uGlobalCandidate"} * uInitialScale; vec2 globalFlow = ${if (globalCandidateTexture) "texelFetch(uGlobalCandidateTexture, ivec2(0), 0).xy" else "uGlobalCandidate"} * uInitialScale;
float globalCost = all(equal(roundEven(globalFlow), roundEven(nearestFlow))) ? nearestCost : float globalCost = all(equal(roundEven(globalFlow), roundEven(nearestFlow))) ? nearestCost :
@@ -2409,7 +2407,6 @@ internal object GlesMgcRawSpatialShaders {
uniform highp isampler2D uReference; uniform highp isampler2D uReference;
uniform highp isampler2D uCurrent; uniform highp isampler2D uCurrent;
uniform sampler2D uProducts0; uniform sampler2D uProducts0;
uniform sampler2D uProducts1;
uniform sampler2D uInitialAlignment; uniform sampler2D uInitialAlignment;
uniform ivec2 uImageSize; uniform ivec2 uImageSize;
uniform ivec2 uGridSize; uniform ivec2 uGridSize;
@@ -2490,18 +2487,18 @@ internal object GlesMgcRawSpatialShaders {
vec2 flow = initialAlignment.xy; vec2 flow = initialAlignment.xy;
ivec2 origin = (tile + ivec2(1)) * uTileStride; ivec2 origin = (tile + ivec2(1)) * uTileStride;
float count = float(uTileSize * uTileSize); float count = float(uTileSize * uTileSize);
float meanCurrent = 0.0; float meanResidual = 0.0;
if (uNormalize != 0) { if (uNormalize != 0) {
for (int y = 0; y < 64; ++y) { for (int y = 0; y < 64; ++y) {
if (y >= uTileSize) break; if (y >= uTileSize) break;
for (int x = 0; x < 64; ++x) { for (int x = 0; x < 64; ++x) {
if (x >= uTileSize) break; if (x >= uTileSize) break;
meanCurrent += warpedCurrentAt( meanResidual += warpedCurrentAt(
vec2(origin + ivec2(x, y)) + flow vec2(origin + ivec2(x, y)) + flow
); ) - referenceAt(origin + ivec2(x, y));
} }
} }
meanCurrent /= count; meanResidual /= count;
} }
float targetX = 0.0; float targetX = 0.0;
@@ -2511,21 +2508,21 @@ internal object GlesMgcRawSpatialShaders {
for (int x = 0; x < 64; ++x) { for (int x = 0; x < 64; ++x) {
if (x >= uTileSize) break; if (x >= uTileSize) break;
ivec2 p = origin + ivec2(x, y); ivec2 p = origin + ivec2(x, y);
float current = warpedCurrentAt(vec2(p) + flow) - meanCurrent; // Subtract before reduction. Separately accumulating current*gradient
// and reference*gradient loses small residuals to Float32 cancellation.
float residual = warpedCurrentAt(vec2(p) + flow) -
referenceAt(p) - meanResidual;
vec2 gradient = gradientAt(p); vec2 gradient = gradientAt(p);
targetX += current * gradient.x; targetX += residual * gradient.x;
targetY += current * gradient.y; targetY += residual * gradient.y;
} }
} }
vec4 products0 = texelFetch(uProducts0, tile, 0); vec4 products0 = texelFetch(uProducts0, tile, 0);
float products1 = texelFetch(uProducts1, tile, 0).r; float bx = 0.5 * targetX / count;
float bx = 0.5 * targetX / count - products0.w; float by = 0.5 * targetY / count;
float by = 0.5 * targetY / count - products1; // det(H) crossed a Float32 texture boundary in the reference pass. Keep +1
float inverseDeterminant = 1.0 / ( // here: evaluating 1 + xx*yy - xy*xy can turn a rank-one tile into 1/0.
1.0 + float inverseDeterminant = 1.0 / (1.0 + products0.w);
products0.x * products0.y -
products0.z * products0.z
);
vec2 delta = inverseDeterminant * vec2( vec2 delta = inverseDeterminant * vec2(
products0.z * by - products0.y * bx, products0.z * by - products0.y * bx,
products0.z * bx - products0.x * by products0.z * bx - products0.x * by
@@ -2677,9 +2674,9 @@ internal object GlesMgcRawSpatialShaders {
/** /**
* ConvertAlignmentHalide (0x362479c) evaluates the 3x3 flow range on the alignment grid. * ConvertAlignmentHalide (0x362479c) evaluates the 3x3 flow range on the alignment grid.
* Expand that tile-owned range and normalized displacement together onto RAW/2 for our * Sabre retains that sparse grid (tile size 1 here); Spatial expands each tile-owned
* dense consumers. Clamp the center tile before its neighborhood so the grid's halo uses * value onto RAW/2. Clamp the center tile before its neighborhood so the grid's halo
* the same complete converted value as nearest sampling of the original sparse texture. * uses the same complete converted value as nearest sampling of the sparse texture.
*/ */
val convertAlignment = """ val convertAlignment = """
#version 300 es #version 300 es
@@ -2768,7 +2765,7 @@ internal object GlesMgcRawSpatialShaders {
""".trimIndent() """.trimIndent()
/** /**
* UnblockerRaw10Halide (0x35dd50c), operating on unpacked native RAW values. * V25 UnblockerRaw16Halide (0x36380AC), operating on unpacked native RAW values.
* *
* The original receives fullres_tile_size=8, scale=1 and offset=0.45. Each output cell * The original receives fullres_tile_size=8, scale=1 and offset=0.45. Each output cell
* therefore covers an 8x8 Bayer-quad / 16x16 full-resolution region. The 128/9 variance * therefore covers an 8x8 Bayer-quad / 16x16 full-resolution region. The 128/9 variance
@@ -2794,69 +2791,87 @@ internal object GlesMgcRawSpatialShaders {
uniform float uOutputOffset; uniform float uOutputOffset;
out float oUnblocker; out float oUnblocker;
vec2 greensAt(ivec2 q) { uvec2 greensAt(ivec2 q) {
ivec2 p = clamp(q * 2, ivec2(0), uRawSize - ivec2(2)); // Raw16 Unblocker mirrors Bayer quads, repeating the boundary quad.
float p00 = float(texelFetch(uRaw, p, 0).r); ivec2 period = (uRawSize / 2) * 2;
float p10 = float(texelFetch(uRaw, p + ivec2(1, 0), 0).r); q = (q % period + period) % period;
float p01 = float(texelFetch(uRaw, p + ivec2(0, 1), 0).r); ivec2 p = min(q, period - ivec2(1) - q) * 2;
float p11 = float(texelFetch(uRaw, p + ivec2(1), 0).r); uint p00 = texelFetch(uRaw, p, 0).r;
vec4 v; uint p10 = texelFetch(uRaw, p + ivec2(1, 0), 0).r;
if (uCfaPattern == 0) v = vec4(p00, p10, p01, p11); uint p01 = texelFetch(uRaw, p + ivec2(0, 1), 0).r;
else if (uCfaPattern == 1) v = vec4(p10, p00, p11, p01); uint p11 = texelFetch(uRaw, p + ivec2(1), 0).r;
else if (uCfaPattern == 2) v = vec4(p01, p11, p00, p10); uvec4 v;
else v = vec4(p11, p01, p10, p00); if (uCfaPattern == 0) v = uvec4(p00, p10, p01, p11);
else if (uCfaPattern == 1) v = uvec4(p10, p00, p11, p01);
else if (uCfaPattern == 2) v = uvec4(p01, p11, p00, p10);
else v = uvec4(p11, p01, p10, p00);
return v.yz; return v.yz;
} }
float averageGreen(ivec2 q) { uint averageGreen(ivec2 q) {
q = clamp(q, ivec2(0), (uRawSize / 2) - ivec2(1)); uvec2 g = greensAt(q);
vec2 g = greensAt(q); return (g.x + g.y + 1u) >> 1u;
return 0.5 * (g.x + g.y);
} }
float blurredGreen(ivec2 q) { uint verticalGreen(ivec2 q) {
float value = 0.0; uint outer = (averageGreen(q - ivec2(0, 1)) +
for (int y = -1; y <= 1; ++y) { averageGreen(q + ivec2(0, 1))) >> 1u;
float wy = y == 0 ? 0.5 : 0.25; return (outer + averageGreen(q) + 1u) >> 1u;
for (int x = -1; x <= 1; ++x) { }
float wx = x == 0 ? 0.5 : 0.25; uint blurredGreen(ivec2 q) {
value += averageGreen(q + ivec2(x, y)) * wx * wy; uint outer = (verticalGreen(q - ivec2(1, 0)) +
} verticalGreen(q + ivec2(1, 0)) + 1u) >> 1u;
} return (outer + verticalGreen(q)) >> 1u;
return value; }
// Low/high limbs preserve the original integer moments for RAW16 as well
// as RAW10. A float sum loses low bits before the variance subtraction.
uvec2 addWide(uvec2 a, uvec2 b) {
uint low = a.x + b.x;
return uvec2(low, a.y + b.y + (low < a.x ? 1u : 0u));
}
float roundedVariance(uint sum, uvec2 squareSum, uint countShift) {
uvec2 numerator = uvec2(
squareSum.x << countShift,
(squareSum.y << countShift) | (squareSum.x >> (32u - countShift))
);
// sum <= 128 * 65535, so the doubled 16-bit cross product fits U32.
// Keep this in ES 3.00 without extended-integer built-ins.
uint lo16 = sum & 65535u;
uint hi16 = sum >> 16u;
uint cross = 2u * lo16 * hi16;
uvec2 squared = addWide(uvec2(lo16 * lo16, hi16 * hi16),
uvec2(cross << 16u, cross >> 16u));
numerator = uvec2(
numerator.x - squared.x,
numerator.y - squared.y - (numerator.x < squared.x ? 1u : 0u)
);
uint divisorShift = countShift * 2u;
numerator = addWide(numerator, uvec2(1u << (divisorShift - 1u), 0u));
return float((numerator.x >> divisorShift) |
(numerator.y << (32u - divisorShift)));
} }
void main() { void main() {
// The original AOT evaluates one extra cell on every side before its // The original AOT evaluates one extra cell on every side before its
// UnblockerBlur pass. uTileOffset is (-1, -1) for that padded domain. // UnblockerBlur pass. uTileOffset is (-1, -1) for that padded domain.
ivec2 tile = ivec2(gl_FragCoord.xy) + uTileOffset; ivec2 tile = ivec2(gl_FragCoord.xy) + uTileOffset;
ivec2 origin = tile * 8; ivec2 origin = tile * 8;
float preSum = 0.0; uint preSum = 0u;
float preSquareSum = 0.0; uvec2 preSquareSum = uvec2(0u);
float postSum = 0.0; uint postSum = 0u;
float postSquareSum = 0.0; uvec2 postSquareSum = uvec2(0u);
for (int y = 0; y < 8; ++y) { for (int y = 0; y < 8; ++y) {
for (int x = 0; x < 8; ++x) { for (int x = 0; x < 8; ++x) {
ivec2 q = origin + ivec2(x, y); ivec2 q = origin + ivec2(x, y);
vec2 g = greensAt(clamp( uvec2 g = greensAt(q);
q, ivec2(0), (uRawSize / 2) - ivec2(1) uint b = blurredGreen(q);
));
float b = blurredGreen(q);
preSum += g.x + g.y; preSum += g.x + g.y;
preSquareSum += dot(g, g); preSquareSum = addWide(preSquareSum, uvec2(g.x * g.x, 0u));
preSquareSum = addWide(preSquareSum, uvec2(g.y * g.y, 0u));
postSum += b; postSum += b;
postSquareSum += b * b; postSquareSum = addWide(postSquareSum, uvec2(b * b, 0u));
} }
} }
float preCount = 128.0; float preMean = float((preSum + 64u) >> 7u);
float postCount = 64.0; float preVariance = roundedVariance(preSum, preSquareSum, 7u);
float preMean = preSum / preCount; float postVariance = roundedVariance(postSum, postSquareSum, 6u);
float postMean = postSum / postCount;
float preVariance = max(
preSquareSum / preCount - preMean * preMean,
0.0
);
float postVariance = max(
postSquareSum / postCount - postMean * postMean,
0.0
);
float signal = max(preMean - uBlackLevelGreen, 0.0); float signal = max(preMean - uBlackLevelGreen, 0.0);
float predictedNoise = float predictedNoise =
(uNoiseQuadratic * signal + uNoiseScale) * signal + (uNoiseQuadratic * signal + uNoiseScale) * signal +
@@ -2869,9 +2884,9 @@ internal object GlesMgcRawSpatialShaders {
float ratio = denominator > 0.0 float ratio = denominator > 0.0
? correctedVariance / denominator ? correctedVariance / denominator
: 0.0; : 0.0;
float mapped = uOutputScale * ( float mapped = denominator > 0.0
sqrt(max(ratio, 0.0)) - uOutputOffset ? uOutputScale * (sqrt(max(ratio, 0.0)) - uOutputOffset)
); : (correctedVariance > 0.0 ? uOutputScale : 0.0);
// The AOT converts with fcvtzs before storing U8. Quantize explicitly so the // The AOT converts with fcvtzs before storing U8. Quantize explicitly so the
// normalized GL_R8 conversion cannot round a boundary upward. // normalized GL_R8 conversion cannot round a boundary upward.
oUnblocker = floor(clamp(mapped, 0.0, 1.0) * 255.0) / 255.0; oUnblocker = floor(clamp(mapped, 0.0, 1.0) * 255.0) / 255.0;
@@ -79,6 +79,9 @@ internal class GlesMgcRawSpatialStacker(
val width: Int, val width: Int,
val height: Int, val height: Int,
val scaleToBayerQuads: Float, val scaleToBayerQuads: Float,
val tileSize: Int,
val gridWidth: Int,
val gridHeight: Int,
) )
private data class Alignment( private data class Alignment(
@@ -88,6 +91,8 @@ internal class GlesMgcRawSpatialStacker(
val tileStride: Int, val tileStride: Int,
val scaleToBayerQuads: Float, val scaleToBayerQuads: Float,
val gridMin: Int, val gridMin: Int,
val offsetX: Int = 0,
val offsetY: Int = 0,
) )
private data class GlobalAlignmentCandidate( private data class GlobalAlignmentCandidate(
@@ -136,9 +141,7 @@ internal class GlesMgcRawSpatialStacker(
val gridHeight: Int, val gridHeight: Int,
val tileStride: Int, val tileStride: Int,
val tileSize: Int, val tileSize: Int,
val normalize: Boolean,
val products0: Int, val products0: Int,
val products1: Int,
) )
private data class PreparedTemporalFrame( private data class PreparedTemporalFrame(
@@ -472,7 +475,6 @@ internal class GlesMgcRawSpatialStacker(
private val uniformLocations = HashMap<Int, HashMap<String, Int>>() private val uniformLocations = HashMap<Int, HashMap<String, Int>>()
private val textureSpecs = HashMap<Int, TextureSpec>() private val textureSpecs = HashMap<Int, TextureSpec>()
private val noiseLutCache = HashMap<List<Int>, CachedNoiseLut>() private val noiseLutCache = HashMap<List<Int>, CachedNoiseLut>()
private var globalAlignment: GlesSpatialGlobalAlignment? = null
private val validatedRenderTargetSpecs = HashSet<List<TextureSpec>>() private val validatedRenderTargetSpecs = HashSet<List<TextureSpec>>()
private val temporalScratchTextures = SequentialScratchTextures() private val temporalScratchTextures = SequentialScratchTextures()
private var activeSequentialScratchTextures: SequentialScratchTextures? = null private var activeSequentialScratchTextures: SequentialScratchTextures? = null
@@ -488,6 +490,8 @@ internal class GlesMgcRawSpatialStacker(
private var alignProgram = 0 private var alignProgram = 0
private var alignmentGradientProductsProgram = 0 private var alignmentGradientProductsProgram = 0
private var upsampleAlignmentProgram = 0 private var upsampleAlignmentProgram = 0
private var medianAlignmentProgram = 0
private var globalAlignment: GlesSpatialGlobalAlignment? = null
private var blockLucasKanadeProgram = 0 private var blockLucasKanadeProgram = 0
private var convertAlignmentProgram = 0 private var convertAlignmentProgram = 0
private var strengthAlignmentProgram = 0 private var strengthAlignmentProgram = 0
@@ -541,11 +545,19 @@ internal class GlesMgcRawSpatialStacker(
size = PIXEL_DIFFERENCE_KERNEL_SIZE, size = PIXEL_DIFFERENCE_KERNEL_SIZE,
sigma = PIXEL_DIFFERENCE_SMOOTH_SIGMA, sigma = PIXEL_DIFFERENCE_SMOOTH_SIGMA,
) )
private val alignmentPlan = MgcRawLkPyramidPlan(
width, height,
if (processorPipeline == MgcRawProcessorPipeline.SPATIAL) {
SPATIAL_ALIGN_MAX_TILE_SIZE
} else {
SABRE_ALIGN_MAX_TILE_SIZE
},
)
private val conservativeRgbFlowBounds = MgcSpatialRgbFlowBounds( private val conservativeRgbFlowBounds = MgcSpatialRgbFlowBounds(
-MAX_ALIGNMENT_DISPLACEMENT_BAYER_QUADS, -alignmentPlan.maximumDisplacement,
-MAX_ALIGNMENT_DISPLACEMENT_BAYER_QUADS, -alignmentPlan.maximumDisplacement,
MAX_ALIGNMENT_DISPLACEMENT_BAYER_QUADS, alignmentPlan.maximumDisplacement,
MAX_ALIGNMENT_DISPLACEMENT_BAYER_QUADS, alignmentPlan.maximumDisplacement,
) )
fun processFrames(frames: List<RawStackFrame>): RawStackResult? { fun processFrames(frames: List<RawStackFrame>): RawStackResult? {
@@ -1785,8 +1797,7 @@ internal class GlesMgcRawSpatialStacker(
frames = rgbMergeFrames, frames = rgbMergeFrames,
images = images, images = images,
outputExposureScale = outputExposure.normalizationScale, outputExposureScale = outputExposure.normalizationScale,
mergeSharpness = RGB_AOT_MERGE_SHARPNESS_SCALE * mergeSharpness = finishRawSharpenAttenuationScale,
finishRawSharpenAttenuationScale,
capture = aotCapture, capture = aotCapture,
preparedAlignment = preparedStrengthAtlases.first, preparedAlignment = preparedStrengthAtlases.first,
preparedRejection = preparedStrengthAtlases.second, preparedRejection = preparedStrengthAtlases.second,
@@ -2301,6 +2312,8 @@ internal class GlesMgcRawSpatialStacker(
referenceGrayPyramid, referenceGrayPyramid,
currentGrayPyramid, currentGrayPyramid,
referenceAlignmentProducts, referenceAlignmentProducts,
frameIndex = index,
finalTileSupport = MgcSabreAlignmentOffset.tileSupport(kernelTuning.referenceSnr),
) )
val flow = createConvertedAlignment(alignment) val flow = createConvertedAlignment(alignment)
val unblockerWidth = ceilDiv(width, UNBLOCKER_FULLRES_TILE_SIZE * 2) val unblockerWidth = ceilDiv(width, UNBLOCKER_FULLRES_TILE_SIZE * 2)
@@ -3092,10 +3105,7 @@ internal class GlesMgcRawSpatialStacker(
GlesMgcRawSpatialShaders.alignmentGradientProducts, GlesMgcRawSpatialShaders.alignmentGradientProducts,
"mgc_sabre_alignment_gradient_products", "mgc_sabre_alignment_gradient_products",
) )
upsampleAlignmentProgram = linkProgram( upsampleAlignmentProgram = initMergeUpsampleAlignment()
GlesMgcRawSpatialShaders.upsampleAlignment,
"mgc_sabre_upsample_alignment",
)
blockLucasKanadeProgram = linkProgram( blockLucasKanadeProgram = linkProgram(
GlesMgcRawSpatialShaders.blockLucasKanade, GlesMgcRawSpatialShaders.blockLucasKanade,
"mgc_sabre_block_lucas_kanade", "mgc_sabre_block_lucas_kanade",
@@ -3155,13 +3165,18 @@ internal class GlesMgcRawSpatialStacker(
).also { it.initPrograms() } ).also { it.initPrograms() }
} }
private fun initSpatialUpsampleAlignment(): Int { private fun initMergeUpsampleAlignment(): Int {
if (processorPipeline == MgcRawProcessorPipeline.SPATIAL) {
medianAlignmentProgram = linkProgram(
GlesMgcRawSpatialShaders.medianAlignment, "mgc_median_alignment",
)
}
if (supportsComputePrograms) { if (supportsComputePrograms) {
val reduction = GlesSpatialGlobalAlignment(cpuCompatibleMean = true) val reduction = GlesSpatialGlobalAlignment(cpuCompatibleMean = true)
try { try {
reduction.init() reduction.init()
val program = linkProgram( val program = linkProgram(
GlesMgcRawSpatialShaders.upsampleAlignmentWithGpuCandidate, GlesMgcRawSpatialShaders.rawUpsampleAlignment,
"mgc_upsample_alignment_gpu_candidate", "mgc_upsample_alignment_gpu_candidate",
) )
globalAlignment = reduction globalAlignment = reduction
@@ -3200,7 +3215,7 @@ internal class GlesMgcRawSpatialStacker(
GlesMgcRawSpatialShaders.alignmentGradientProducts, GlesMgcRawSpatialShaders.alignmentGradientProducts,
"mgc_alignment_gradient_products", "mgc_alignment_gradient_products",
) )
upsampleAlignmentProgram = initSpatialUpsampleAlignment() upsampleAlignmentProgram = initMergeUpsampleAlignment()
blockLucasKanadeProgram = linkProgram( blockLucasKanadeProgram = linkProgram(
GlesMgcRawSpatialShaders.blockLucasKanade, GlesMgcRawSpatialShaders.blockLucasKanade,
"mgc_block_lucas_kanade", "mgc_block_lucas_kanade",
@@ -3738,18 +3753,20 @@ internal class GlesMgcRawSpatialStacker(
width = finestWidth, width = finestWidth,
height = finestHeight, height = finestHeight,
scaleToBayerQuads = 1f, scaleToBayerQuads = 1f,
tileSize = alignmentPlan.levels.first().tileSize,
gridWidth = alignmentPlan.levels.first().gridWidth,
gridHeight = alignmentPlan.levels.first().gridHeight,
) )
var levelWidth = finestWidth var levelWidth = finestWidth
var levelHeight = finestHeight var levelHeight = finestHeight
var scaleToBayerQuads = 1 for (level in alignmentPlan.levels.drop(1)) {
for (step in ALIGN_PYRAMID_DOWNSAMPLE_STEPS) { val step = level.downsample
check(step == 2 || step == 4) check(step == 2 || step == 4)
scaleToBayerQuads *= step
// Every downsampled level carries the positive-side support sample used by // Every downsampled level carries the positive-side support sample used by
// Halide's clamped interpolation. The finest level itself has no extra sample. // Halide's clamped interpolation. The finest level itself has no extra sample.
val nextWidth = ceilDiv(finestWidth, scaleToBayerQuads) + 1 val nextWidth = level.width
val nextHeight = ceilDiv(finestHeight, scaleToBayerQuads) + 1 val nextHeight = level.height
val nextTexture = createTexture( val nextTexture = createTexture(
nextWidth, nextWidth,
nextHeight, nextHeight,
@@ -3767,7 +3784,10 @@ internal class GlesMgcRawSpatialStacker(
texture = nextTexture, texture = nextTexture,
width = nextWidth, width = nextWidth,
height = nextHeight, height = nextHeight,
scaleToBayerQuads = scaleToBayerQuads.toFloat(), scaleToBayerQuads = level.scale.toFloat(),
tileSize = level.tileSize,
gridWidth = level.gridWidth,
gridHeight = level.gridHeight,
) )
} }
return levels return levels
@@ -3775,8 +3795,18 @@ internal class GlesMgcRawSpatialStacker(
/** Returns the logical RAW/4 base-luma input required by FilterRejectionMap. */ /** Returns the logical RAW/4 base-luma input required by FilterRejectionMap. */
private fun buildRejectionBaseLuma(referenceGrayPyramid: List<TextureLevel>): Int { private fun buildRejectionBaseLuma(referenceGrayPyramid: List<TextureLevel>): Int {
check(referenceGrayPyramid.size > 1) { if (referenceGrayPyramid.size == 1) {
"FilterRejectionMap requires the RAW/4 reference-luma pyramid level" // PrepareBase may stop before RAW/4 has a valid LK tile. Rejection still needs
// that luma image; its existence must not depend on the alignment tile count.
val fine = referenceGrayPyramid.first()
val lumaWidth = fine.width / 2 + 1
val lumaHeight = fine.height / 2 + 1
val luma = createTexture(lumaWidth, lumaHeight, GLES30.GL_R16I, GLES30.GL_NEAREST)
GLES30.glUseProgram(downsampleProgram)
bindTexture(downsampleProgram, "uInput", 0, fine.texture)
uniform2i(downsampleProgram, "uInputSize", fine.width, fine.height)
draw(downsampleProgram, lumaWidth, lumaHeight, intArrayOf(luma))
return luma
} }
val raw4 = referenceGrayPyramid[1] val raw4 = referenceGrayPyramid[1]
check(raw4.width >= mergeWeightWidth && raw4.height >= mergeWeightHeight) { check(raw4.width >= mergeWeightWidth && raw4.height >= mergeWeightHeight) {
@@ -3792,16 +3822,17 @@ internal class GlesMgcRawSpatialStacker(
* *
* Gradient products depend on neither the current frame nor its initial flow. Keeping these * Gradient products depend on neither the current frame nor its initial flow. Keeping these
* small textures alive across temporal frames removes four serial tile reductions per frame * small textures alive across temporal frames removes four serial tile reductions per frame
* without changing LK iterations, accumulation order, or output precision. * without changing LK iterations. The alpha channel materializes det(H) before LK adds
* its regularizer; LK accumulates current-minus-reference residuals instead of subtracting
* two large intensity-product sums.
*/ */
private fun buildReferenceAlignmentProducts( private fun buildReferenceAlignmentProducts(
reference: List<TextureLevel>, reference: List<TextureLevel>,
): List<ReferenceAlignmentProducts> { ): List<ReferenceAlignmentProducts> {
check(reference.size == ALIGN_LEVEL_TILE_STRIDES.size) check(reference.size == alignmentPlan.levels.size)
val startNs = System.nanoTime() val startNs = System.nanoTime()
return reference.mapIndexed { levelIndex, level -> return reference.map { level ->
val tileSize = ALIGN_LEVEL_TILE_STRIDES[levelIndex] val tileSize = level.tileSize
val normalize = levelIndex != 0
val gridWidth = alignmentGridWidth(level, tileSize) val gridWidth = alignmentGridWidth(level, tileSize)
val gridHeight = alignmentGridHeight(level, tileSize) val gridHeight = alignmentGridHeight(level, tileSize)
val products0 = createTexture( val products0 = createTexture(
@@ -3810,12 +3841,6 @@ internal class GlesMgcRawSpatialStacker(
GLES30.GL_RGBA32F, GLES30.GL_RGBA32F,
GLES30.GL_NEAREST, GLES30.GL_NEAREST,
) )
val products1 = createTexture(
gridWidth,
gridHeight,
GLES30.GL_R32F,
GLES30.GL_NEAREST,
)
GLES30.glUseProgram(alignmentGradientProductsProgram) GLES30.glUseProgram(alignmentGradientProductsProgram)
bindTexture( bindTexture(
alignmentGradientProductsProgram, alignmentGradientProductsProgram,
@@ -3831,16 +3856,11 @@ internal class GlesMgcRawSpatialStacker(
) )
uniform1i(alignmentGradientProductsProgram, "uTileStride", tileSize) uniform1i(alignmentGradientProductsProgram, "uTileStride", tileSize)
uniform1i(alignmentGradientProductsProgram, "uTileSize", tileSize) uniform1i(alignmentGradientProductsProgram, "uTileSize", tileSize)
uniform1i(
alignmentGradientProductsProgram,
"uNormalize",
if (normalize) 1 else 0,
)
draw( draw(
alignmentGradientProductsProgram, alignmentGradientProductsProgram,
gridWidth, gridWidth,
gridHeight, gridHeight,
intArrayOf(products0, products1), intArrayOf(products0),
) )
ReferenceAlignmentProducts( ReferenceAlignmentProducts(
referenceTexture = level.texture, referenceTexture = level.texture,
@@ -3848,9 +3868,7 @@ internal class GlesMgcRawSpatialStacker(
gridHeight = gridHeight, gridHeight = gridHeight,
tileStride = tileSize, tileStride = tileSize,
tileSize = tileSize, tileSize = tileSize,
normalize = normalize,
products0 = products0, products0 = products0,
products1 = products1,
) )
}.also { products -> }.also { products ->
PLog.i( PLog.i(
@@ -3863,36 +3881,22 @@ internal class GlesMgcRawSpatialStacker(
} }
/** /**
* BuildAlignPyramidForBurst (0x3883e98), using the options captured at runtime from this * Execute the LK plan with two finest and three coarser iterations. Spatial's configured
* MGC build: * maximum tile also determines AlignAlt's final candidate-window origin, as in 38CA05C.
* * Spatial's default 16-quad configuration uses a 16-quad final window with no inset.
* [target=256, minTile=8, maxTile=64, finestTile=-1, * The merge grid remains stride 8 regardless of the LK support. Sabre's existing LK-only
* finestLkIterations=2, coarserLkIterations=3] * configuration is separate from its SNR-selected final support; this is not a claim of
* normalizeFinest=false, normalizeCoarser=true, useL1Search=false * parity with the original classic Sabre L1 search path.
*
* Runtime Halide entry tracing gives the complete execution geometry for 4080x3064:
*
* 65x49 / tile 8 / grid 6x4 / normalize
* 256x193 / tile 16 / grid 14x10 / normalize
* 1021x767 / tile 32 / grid 30x22 / normalize
* 2040x1532 / tile 32 / grid 62x46 / no normalization
*
* The first three levels use three LK iterations; the finest uses two. The standalone
* AlignL1 search is absent, but UpsampleAlignment still selects among three neighboring
* coarse-flow candidates using target-level L1 residuals before every finer LK level.
* AlignPyramid::AlignAlt then performs one final UpsampleAlignment pass from the 32-quad
* finest LK grid to Spatial MergeBayerRaw16's full 8-quad grid. The final pass evaluates
* 16x16 target blocks and selects a whole neighboring LK candidate by L1 residual; it is
* not a bilinear resample. That final output is the alignment object consumed by merge and
* separately converted into MGC's sparse normalized-flow grid for rejection.
*/ */
private fun alignPyramids( private fun alignPyramids(
reference: List<TextureLevel>, reference: List<TextureLevel>,
current: List<TextureLevel>, current: List<TextureLevel>,
referenceProducts: List<ReferenceAlignmentProducts>, referenceProducts: List<ReferenceAlignmentProducts>,
frameIndex: Int = 0,
finalTileSupport: Int = alignmentPlan.maximumTileSize,
): Alignment { ): Alignment {
check(reference.size == current.size) check(reference.size == current.size)
check(reference.size == ALIGN_LEVEL_TILE_STRIDES.size) check(reference.size == alignmentPlan.levels.size)
check(referenceProducts.size == reference.size) check(referenceProducts.size == reference.size)
// Scoped to this solve: the frame arena may recycle these names on the next frame. // Scoped to this solve: the frame arena may recycle these names on the next frame.
val scratch = AlignmentScratch { w, h -> val scratch = AlignmentScratch { w, h ->
@@ -3904,10 +3908,10 @@ internal class GlesMgcRawSpatialStacker(
reference = coarse, reference = coarse,
current = current[coarseIndex], current = current[coarseIndex],
initial = null, initial = null,
tileStride = ALIGN_LEVEL_TILE_STRIDES[coarseIndex], tileStride = coarse.tileSize,
tileSize = ALIGN_LEVEL_TILE_STRIDES[coarseIndex], tileSize = coarse.tileSize,
iterations = ALIGN_LK_ITERATIONS_COARSER, iterations = if (coarseIndex == 0) ALIGN_LK_ITERATIONS_FINEST else ALIGN_LK_ITERATIONS_COARSER,
normalize = true, normalize = coarseIndex != 0,
referenceProducts = referenceProducts[coarseIndex], referenceProducts = referenceProducts[coarseIndex],
scratch = scratch, scratch = scratch,
) )
@@ -3915,14 +3919,15 @@ internal class GlesMgcRawSpatialStacker(
val schedule = ArrayList<String>().apply { val schedule = ArrayList<String>().apply {
add( add(
"${coarse.width}x${coarse.height}:" + "${coarse.width}x${coarse.height}:" +
"${ALIGN_LEVEL_TILE_STRIDES[coarseIndex]}px," + "${coarse.tileSize}px," +
"LK${ALIGN_LK_ITERATIONS_COARSER},normalize=true" "LK${if (coarseIndex == 0) ALIGN_LK_ITERATIONS_FINEST else ALIGN_LK_ITERATIONS_COARSER}," +
"normalize=${coarseIndex != 0}"
) )
} }
for (levelIndex in coarseIndex - 1 downTo 0) { for (levelIndex in coarseIndex - 1 downTo 0) {
val level = reference[levelIndex] val level = reference[levelIndex]
val coarser = reference[levelIndex + 1] val coarser = reference[levelIndex + 1]
val tileSize = ALIGN_LEVEL_TILE_STRIDES[levelIndex] val tileSize = level.tileSize
val scale = val scale =
coarser.scaleToBayerQuads / level.scaleToBayerQuads coarser.scaleToBayerQuads / level.scaleToBayerQuads
val finest = levelIndex == 0 val finest = levelIndex == 0
@@ -3932,6 +3937,12 @@ internal class GlesMgcRawSpatialStacker(
ALIGN_LK_ITERATIONS_COARSER ALIGN_LK_ITERATIONS_COARSER
} }
val normalize = !finest val normalize = !finest
// V25 estimates this candidate from the complete preceding flow grid,
// before each ordinary pyramid transition (38D389C / 38D3B04).
val gpuCandidate = globalAlignment?.estimate(
alignment.texture, alignment.gridWidth, alignment.gridHeight,
) ?: 0
val globalCandidate = if (gpuCandidate == 0) estimateGlobalAlignmentCandidate(alignment) else null
val upsampled = renderUpsampledAlignment( val upsampled = renderUpsampledAlignment(
reference = level, reference = level,
current = current[levelIndex], current = current[levelIndex],
@@ -3942,6 +3953,8 @@ internal class GlesMgcRawSpatialStacker(
targetTileStride = tileSize, targetTileStride = tileSize,
targetTileSize = tileSize, targetTileSize = tileSize,
scratch = scratch, scratch = scratch,
globalCandidate = globalCandidate,
gpuGlobalCandidate = gpuCandidate,
) )
alignment = renderLucasKanadeLevel( alignment = renderLucasKanadeLevel(
reference = level, reference = level,
@@ -3957,13 +3970,20 @@ internal class GlesMgcRawSpatialStacker(
schedule += schedule +=
"${level.width}x${level.height}:${tileSize}px," + "${level.width}x${level.height}:${tileSize}px," +
"LK$iterations,normalize=$normalize," + "LK$iterations,normalize=$normalize," +
"levelScale=$scale" "levelScale=$scale,global=histogram"
} }
val finalUpsampleMode = if (processorPipeline == MgcRawProcessorPipeline.SPATIAL) { // MGC's caller selects the non-overlapping 8-quad layout for every merge enum
val gpuCandidate = globalAlignment?.estimate( // from Sabre through Spatial RGB (0x344BF84 / 0x5B94448). The finest LK grid
alignment.texture, alignment.gridWidth, alignment.gridHeight, // is only an intermediate result; feeding it directly to Sabre leaves 64-RAW-pixel
) ?: 0 // blocks and skips the final local/global candidate selection.
val globalCandidate = if (gpuCandidate == 0) estimateGlobalAlignmentCandidate(alignment) else null val finalUpsampleMode = run {
val candidateSupport = minOf(MERGE_BAYER_RAW_TILE_SIZE, finalTileSupport)
val windowInset = (finalTileSupport - candidateSupport) / 2
val offset = if (processorPipeline == MgcRawProcessorPipeline.SABRE) {
MgcSabreAlignmentOffset.forFrame(frameIndex, MERGE_BAYER_RAW_TILE_SIZE / 2)
} else {
MgcSabreAlignmentOffset.ZERO
}
alignment = renderUpsampledAlignment( alignment = renderUpsampledAlignment(
reference = reference.first(), reference = reference.first(),
current = current.first(), current = current.first(),
@@ -3972,15 +3992,37 @@ internal class GlesMgcRawSpatialStacker(
targetGridHeight = bayerAlignmentHeight, targetGridHeight = bayerAlignmentHeight,
targetGridMin = MERGE_ALIGNMENT_GRID_MIN, targetGridMin = MERGE_ALIGNMENT_GRID_MIN,
targetTileStride = MERGE_BAYER_RAW_TILE_SIZE / 2, targetTileStride = MERGE_BAYER_RAW_TILE_SIZE / 2,
targetTileSize = MERGE_BAYER_RAW_TILE_SIZE, targetTileSize = candidateSupport,
globalCandidate = globalCandidate, targetOffsetX = offset.x,
gpuGlobalCandidateTexture = gpuCandidate, targetOffsetY = offset.y,
targetWindowInset = windowInset,
scratch = scratch, scratch = scratch,
) )
if (processorPipeline == MgcRawProcessorPipeline.SPATIAL) {
// SpatialMergeProcessor::Run writes median_filter_alignment=true
// (35F1204); AlignAlt applies MedianFilter3x3Halide twice after the
// final upsample (38D2A58). Rejection and merge must share that result.
repeat(2) {
val output = scratch.target(
alignment.gridWidth, alignment.gridHeight, alignment.texture,
)
GLES30.glUseProgram(medianAlignmentProgram)
bindTexture(medianAlignmentProgram, "uAlignment", 0, alignment.texture)
uniform2i(
medianAlignmentProgram, "uGridSize",
alignment.gridWidth, alignment.gridHeight,
)
draw(
medianAlignmentProgram, alignment.gridWidth, alignment.gridHeight,
intArrayOf(output),
)
alignment = alignment.copy(texture = output)
}
}
schedule += schedule +=
"${reference.first().width}x${reference.first().height}:" + "${reference.first().width}x${reference.first().height}:" +
"${MERGE_BAYER_RAW_TILE_SIZE / 2}px," + "${MERGE_BAYER_RAW_TILE_SIZE / 2}px," +
"UpsampleL1(tile=${MERGE_BAYER_RAW_TILE_SIZE})" "UpsampleL1(tile=$candidateSupport,inset=$windowInset)"
check( check(
alignment.gridWidth == bayerAlignmentWidth && alignment.gridWidth == bayerAlignmentWidth &&
alignment.gridHeight == bayerAlignmentHeight && alignment.gridHeight == bayerAlignmentHeight &&
@@ -3988,16 +4030,9 @@ internal class GlesMgcRawSpatialStacker(
alignment.scaleToBayerQuads == 1f && alignment.scaleToBayerQuads == 1f &&
alignment.gridMin == MERGE_ALIGNMENT_GRID_MIN alignment.gridMin == MERGE_ALIGNMENT_GRID_MIN
) { ) {
"Spatial AlignAlt final output does not match MergeBayerRaw16's alignment grid" "MGC AlignAlt final output does not match the 8-quad merge alignment grid"
} }
if (globalCandidate == null) { "merge-grid/offset(${offset.x},${offset.y})"
"merge-grid/global-gpu"
} else {
"merge-grid/global-${if (globalCandidate.usedHistogramPeak) "mode" else "mean"}" +
"(${globalCandidate.x},${globalCandidate.y},n=${globalCandidate.peakSupport})"
}
} else {
"level-transitions-only"
} }
PLog.i( PLog.i(
TAG, TAG,
@@ -4008,8 +4043,9 @@ internal class GlesMgcRawSpatialStacker(
"flowScale=${alignment.scaleToBayerQuads} useL1=false " + "flowScale=${alignment.scaleToBayerQuads} useL1=false " +
"gradientProducts=cached " + "gradientProducts=cached " +
"upsampleL1=$finalUpsampleMode/3-candidate " + "upsampleL1=$finalUpsampleMode/3-candidate " +
"median=false " + "medianPasses=${if (processorPipeline == MgcRawProcessorPipeline.SPATIAL) 2 else 0} " +
"runtimeOptions=256/8/64/-1/2/3/0/1/0 " + "runtimeOptions=256/8/${alignmentPlan.maximumTileSize}/-1/2/3/0/1/0 " +
"finalSupport=$finalTileSupport " +
"schedule=${schedule.joinToString(" -> ")}", "schedule=${schedule.joinToString(" -> ")}",
) )
return alignment return alignment
@@ -4019,10 +4055,9 @@ internal class GlesMgcRawSpatialStacker(
* UpsampleAlignmentI16Halide selects a whole coarse-flow candidate rather than blending * UpsampleAlignmentI16Halide selects a whole coarse-flow candidate rather than blending
* neighboring motion vectors. This preserves discontinuities at moving-object boundaries. * neighboring motion vectors. This preserves discontinuities at moving-object boundaries.
* *
* The original runtime uses three candidates at pyramid transitions. Before the final * Ordinary pyramid transitions include the global histogram candidate with cost
* merge-grid expansion it derives one global motion candidate from the finest LK field and * multiplier 1. The final call at 0x38D29F4 passes threshold=-1 and reads only the
* invokes the four-candidate worker. The global candidate is important when all three local * three local candidates.
* neighbors belong to the same erroneous motion island.
*/ */
private fun renderUpsampledAlignment( private fun renderUpsampledAlignment(
reference: TextureLevel, reference: TextureLevel,
@@ -4034,8 +4069,11 @@ internal class GlesMgcRawSpatialStacker(
targetTileStride: Int, targetTileStride: Int,
targetTileSize: Int, targetTileSize: Int,
scratch: AlignmentScratch, scratch: AlignmentScratch,
targetOffsetX: Int = 0,
targetOffsetY: Int = 0,
targetWindowInset: Int = 0,
globalCandidate: GlobalAlignmentCandidate? = null, globalCandidate: GlobalAlignmentCandidate? = null,
gpuGlobalCandidateTexture: Int = 0, gpuGlobalCandidate: Int = 0,
): Alignment { ): Alignment {
require(reference.width == current.width && reference.height == current.height) require(reference.width == current.width && reference.height == current.height)
require(targetGridWidth > 0 && targetGridHeight > 0) require(targetGridWidth > 0 && targetGridHeight > 0)
@@ -4065,23 +4103,22 @@ internal class GlesMgcRawSpatialStacker(
uniform1i(upsampleAlignmentProgram, "uInitialTileStride", initial.tileStride) uniform1i(upsampleAlignmentProgram, "uInitialTileStride", initial.tileStride)
uniform1i(upsampleAlignmentProgram, "uTargetTileStride", targetTileStride) uniform1i(upsampleAlignmentProgram, "uTargetTileStride", targetTileStride)
uniform1i(upsampleAlignmentProgram, "uTargetTileSize", targetTileSize) uniform1i(upsampleAlignmentProgram, "uTargetTileSize", targetTileSize)
uniform2i(
upsampleAlignmentProgram, "uTargetImageOffset",
targetOffsetX - targetWindowInset, targetOffsetY - targetWindowInset,
)
uniform1f(upsampleAlignmentProgram, "uInitialScale", initialScale) uniform1f(upsampleAlignmentProgram, "uInitialScale", initialScale)
uniform1i( uniform1i(
upsampleAlignmentProgram, upsampleAlignmentProgram, "uHasGlobalCandidate",
"uHasGlobalCandidate", if (globalCandidate != null || gpuGlobalCandidate != 0) 1 else 0,
if (globalCandidate != null || gpuGlobalCandidateTexture != 0) 1 else 0,
) )
if (globalAlignment != null) { if (globalAlignment != null) {
// Bind a valid float sampler even at transitions where the global branch is off.
bindTexture( bindTexture(
upsampleAlignmentProgram, "uGlobalCandidateTexture", 3, upsampleAlignmentProgram, "uGlobalCandidateTexture", 3,
gpuGlobalCandidateTexture.takeIf { it != 0 } ?: initial.texture, if (gpuGlobalCandidate != 0) gpuGlobalCandidate else initial.texture,
) )
} else { } else {
uniform2f( uniform2f(upsampleAlignmentProgram, "uGlobalCandidate", globalCandidate?.x ?: 0f, globalCandidate?.y ?: 0f)
upsampleAlignmentProgram, "uGlobalCandidate",
globalCandidate?.x ?: 0f, globalCandidate?.y ?: 0f,
)
} }
draw( draw(
upsampleAlignmentProgram, upsampleAlignmentProgram,
@@ -4097,11 +4134,13 @@ internal class GlesMgcRawSpatialStacker(
tileStride = targetTileStride, tileStride = targetTileStride,
scaleToBayerQuads = reference.scaleToBayerQuads, scaleToBayerQuads = reference.scaleToBayerQuads,
gridMin = targetGridMin, gridMin = targetGridMin,
offsetX = targetOffsetX,
offsetY = targetOffsetY,
) )
} }
/** /**
* EstimateGlobalAlignment from MGC V25's final AlignPyramid::AlignAlt pass. * EstimateGlobalAlignment from MGC V25's intermediate AlignPyramid::AlignAlt transitions.
* *
* Flow components are rounded with C llroundf semantics and accumulated into a 129x129 * Flow components are rounded with C llroundf semantics and accumulated into a 129x129
* histogram over [-64, 64]. A peak supported by at least ten tiles is used directly; * histogram over [-64, 64]. A peak supported by at least ten tiles is used directly;
@@ -4227,8 +4266,7 @@ internal class GlesMgcRawSpatialStacker(
referenceProducts.gridWidth == gridWidth && referenceProducts.gridWidth == gridWidth &&
referenceProducts.gridHeight == gridHeight && referenceProducts.gridHeight == gridHeight &&
referenceProducts.tileStride == tileStride && referenceProducts.tileStride == tileStride &&
referenceProducts.tileSize == tileSize && referenceProducts.tileSize == tileSize
referenceProducts.normalize == normalize
) { ) {
"Cached LK reference products do not match the requested pyramid level" "Cached LK reference products do not match the requested pyramid level"
} }
@@ -4236,6 +4274,8 @@ internal class GlesMgcRawSpatialStacker(
var input = initial var input = initial
repeat(iterations) { repeat(iterations) {
val output = scratch.target(gridWidth, gridHeight, input?.texture ?: 0) val output = scratch.target(gridWidth, gridHeight, input?.texture ?: 0)
// Texture allocation changes the active unit's binding; finish it before binding inputs.
val inputTexture = input?.texture ?: createZeroFlowTexture()
GLES30.glUseProgram(blockLucasKanadeProgram) GLES30.glUseProgram(blockLucasKanadeProgram)
bindTexture(blockLucasKanadeProgram, "uReference", 0, reference.texture) bindTexture(blockLucasKanadeProgram, "uReference", 0, reference.texture)
bindTexture(blockLucasKanadeProgram, "uCurrent", 1, current.texture) bindTexture(blockLucasKanadeProgram, "uCurrent", 1, current.texture)
@@ -4245,17 +4285,10 @@ internal class GlesMgcRawSpatialStacker(
2, 2,
referenceProducts.products0, referenceProducts.products0,
) )
bindTexture(
blockLucasKanadeProgram,
"uProducts1",
3,
referenceProducts.products1,
)
val inputTexture = input?.texture ?: createZeroFlowTexture()
bindTexture( bindTexture(
blockLucasKanadeProgram, blockLucasKanadeProgram,
"uInitialAlignment", "uInitialAlignment",
4, 3,
inputTexture, inputTexture,
) )
uniform2i( uniform2i(
@@ -4356,6 +4389,24 @@ internal class GlesMgcRawSpatialStacker(
require(alignment.gridWidth > 0 && alignment.gridHeight > 0) { require(alignment.gridWidth > 0 && alignment.gridHeight > 0) {
"ConvertAlignment requires a non-empty alignment grid" "ConvertAlignment requires a non-empty alignment grid"
} }
if (processorPipeline == MgcRawProcessorPipeline.SABRE) {
// Preserve the original sparse texture and its per-frame transform. Expanding
// it first to RAW/2 quantizes shifted tile boundaries to two RAW pixels.
require(alignment.gridMin == 0 && alignment.scaleToBayerQuads == 1f)
val output = createTexture(
alignment.gridWidth, alignment.gridHeight, GLES30.GL_RGBA16F, GLES30.GL_NEAREST,
)
renderConvertedAlignment(
alignment, output, 1, alignment.gridWidth, alignment.gridHeight,
)
return ConvertedAlignment(
texture = output,
scaleX = (width / 2).toFloat() / (alignment.gridWidth * alignment.tileStride),
scaleY = (height / 2).toFloat() / (alignment.gridHeight * alignment.tileStride),
offsetX = 2f * alignment.offsetX / width,
offsetY = 2f * alignment.offsetY / height,
)
}
val strideInBayerQuads = val strideInBayerQuads =
alignment.tileStride.toFloat() * alignment.scaleToBayerQuads alignment.tileStride.toFloat() * alignment.scaleToBayerQuads
require(strideInBayerQuads.isFinite() && strideInBayerQuads > 0f) { require(strideInBayerQuads.isFinite() && strideInBayerQuads > 0f) {
@@ -4395,6 +4446,8 @@ internal class GlesMgcRawSpatialStacker(
alignment: Alignment, alignment: Alignment,
output: Int, output: Int,
alignmentTileSize: Int, alignmentTileSize: Int,
outputWidth: Int = rejectionWidth,
outputHeight: Int = rejectionHeight,
) { ) {
GLES30.glUseProgram(convertAlignmentProgram) GLES30.glUseProgram(convertAlignmentProgram)
bindTexture(convertAlignmentProgram, "uAlignment", 0, alignment.texture) bindTexture(convertAlignmentProgram, "uAlignment", 0, alignment.texture)
@@ -4419,8 +4472,8 @@ internal class GlesMgcRawSpatialStacker(
) )
draw( draw(
convertAlignmentProgram, convertAlignmentProgram,
rejectionWidth, outputWidth,
rejectionHeight, outputHeight,
intArrayOf(output), intArrayOf(output),
) )
} }
@@ -9386,6 +9439,18 @@ internal class GlesMgcRawSpatialStacker(
private fun ensureGles3() { private fun ensureGles3() {
DngCaptureDiagnostics.recordCurrentGl() DngCaptureDiagnostics.recordCurrentGl()
DngCaptureDiagnostics.put("merge.floatSamplerPrecision", "highp") DngCaptureDiagnostics.put("merge.floatSamplerPrecision", "highp")
DngCaptureDiagnostics.put("merge.alignmentSolver", "residual-gram-determinant")
DngCaptureDiagnostics.put("merge.rejectionFilterContract", "v25-halide-box4-u8-linear4")
DngCaptureDiagnostics.put("merge.unblockerContract", "v25-raw16-integer-moments-mirror")
DngCaptureDiagnostics.put("merge.alignmentContract", "v25-lk-plan-rounded4-global-final-support")
DngCaptureDiagnostics.put("merge.alignmentMaxTile", alignmentPlan.maximumTileSize)
DngCaptureDiagnostics.put(
"merge.alignmentMedianPasses",
if (processorPipeline == MgcRawProcessorPipeline.SPATIAL) 2 else 0,
)
if (processorPipeline == MgcRawProcessorPipeline.SABRE) {
DngCaptureDiagnostics.put("merge.sabreFlowLayout", "sparse-8quad-per-frame-offset")
}
val version = GLES30.glGetString(GLES30.GL_VERSION).orEmpty() val version = GLES30.glGetString(GLES30.GL_VERSION).orEmpty()
check(version.contains("OpenGL ES 3.")) { check(version.contains("OpenGL ES 3.")) {
"MGC Spatial merge requires GLES3, got: $version" "MGC Spatial merge requires GLES3, got: $version"
@@ -9480,9 +9545,9 @@ internal class GlesMgcRawSpatialStacker(
private fun release() { private fun release() {
if (eglDisplay != EGL14.EGL_NO_DISPLAY) { if (eglDisplay != EGL14.EGL_NO_DISPLAY) {
noiseLutCache.clear()
globalAlignment?.release() globalAlignment?.release()
globalAlignment = null globalAlignment = null
noiseLutCache.clear()
rgbChromaPostprocessor?.release() rgbChromaPostprocessor?.release()
rgbChromaPostprocessor = null rgbChromaPostprocessor = null
if (programs.isNotEmpty()) { if (programs.isNotEmpty()) {
@@ -9544,26 +9609,21 @@ internal class GlesMgcRawSpatialStacker(
private fun ceilDiv(value: Int, divisor: Int): Int = private fun ceilDiv(value: Int, divisor: Int): Int =
ceil(value.toDouble() / divisor.toDouble()).toInt().coerceAtLeast(1) ceil(value.toDouble() / divisor.toDouble()).toInt().coerceAtLeast(1)
private fun alignmentGridExtent(
nominalLevelExtent: Int,
tileStride: Int,
): Int = max(1, ceilDiv(nominalLevelExtent, tileStride) - 2)
private fun alignmentGridWidth( private fun alignmentGridWidth(
level: TextureLevel, level: TextureLevel,
tileStride: Int, tileStride: Int,
): Int = alignmentGridExtent( ): Int {
ceilDiv(ceilDiv(width, 2), level.scaleToBayerQuads.toInt()), check(tileStride == level.tileSize)
tileStride, return level.gridWidth
) }
private fun alignmentGridHeight( private fun alignmentGridHeight(
level: TextureLevel, level: TextureLevel,
tileStride: Int, tileStride: Int,
): Int = alignmentGridExtent( ): Int {
ceilDiv(ceilDiv(height, 2), level.scaleToBayerQuads.toInt()), check(tileStride == level.tileSize)
tileStride, return level.gridHeight
) }
private fun rgbBandHeightCandidates(): IntArray = intArrayOf( private fun rgbBandHeightCandidates(): IntArray = intArrayOf(
outputHeight, outputHeight,
@@ -9617,7 +9677,6 @@ internal class GlesMgcRawSpatialStacker(
const val EGL_OPENGL_ES3_BIT_KHR = 0x00000040 const val EGL_OPENGL_ES3_BIT_KHR = 0x00000040
const val RAW_BYTES_PER_PIXEL = 2 const val RAW_BYTES_PER_PIXEL = 2
const val RGB_AOT_TILE_SIZE = 16 const val RGB_AOT_TILE_SIZE = 16
const val RGB_AOT_MERGE_SHARPNESS_SCALE = 0.8f
const val RGB_RAW_WINDOW_SLOTS = 2 const val RGB_RAW_WINDOW_SLOTS = 2
const val RGB_MAX_IN_FLIGHT_PASSES = 2 const val RGB_MAX_IN_FLIGHT_PASSES = 2
const val RGB_DIAGNOSTIC_PBO_SLOTS = 2 const val RGB_DIAGNOSTIC_PBO_SLOTS = 2
@@ -9628,14 +9687,16 @@ internal class GlesMgcRawSpatialStacker(
const val RGB_CHROMA_GUIDE_RAW_RADIUS = 2 const val RGB_CHROMA_GUIDE_RAW_RADIUS = 2
const val ALIGN_TARGET_FINEST_DIMENSION = 256 const val ALIGN_TARGET_FINEST_DIMENSION = 256
const val ALIGN_MIN_TILE_SIZE = 8 const val ALIGN_MIN_TILE_SIZE = 8
const val ALIGN_MAX_TILE_SIZE = 64 // Preferred Spatial options (38B0E48 / default tuning 528DA38) use 16 quads.
// SabreProcessor also selects these options when its merge engine is Spatial RGB.
// Same-input replay against a successful MGC 9.7.047 Spatial RGB RAW confirms
// this configuration; 32 changes the finest grids and final candidate origin.
const val SPATIAL_ALIGN_MAX_TILE_SIZE = 16
// Classic Sabre has a separate SNR-selected LK/L1 schedule. Keep its existing
// LK support independent until that full schedule has numerical parity.
const val SABRE_ALIGN_MAX_TILE_SIZE = 32
const val ALIGN_LK_ITERATIONS_FINEST = 2 const val ALIGN_LK_ITERATIONS_FINEST = 2
const val ALIGN_LK_ITERATIONS_COARSER = 3 const val ALIGN_LK_ITERATIONS_COARSER = 3
// Every LK iteration clamps its update to one pixel in that pyramid level. Mapped back
// to Bayer quads, the 32x/8x/2x/1x schedule is bounded by
// 3*32 + 3*8 + 3*2 + 2*1 = 128. Using the analytical bound keeps RGB tile planning on
// the GPU command stream instead of synchronously reading every alignment texture.
const val MAX_ALIGNMENT_DISPLACEMENT_BAYER_QUADS = 128f
const val ALIGN_LK_GRID_MIN = 1 const val ALIGN_LK_GRID_MIN = 1
const val MERGE_ALIGNMENT_GRID_MIN = 0 const val MERGE_ALIGNMENT_GRID_MIN = 0
const val GLOBAL_ALIGNMENT_RADIUS = 64 const val GLOBAL_ALIGNMENT_RADIUS = 64
@@ -9648,9 +9709,6 @@ internal class GlesMgcRawSpatialStacker(
// merge tile on its own flow instead of switching interpolation on and off as // merge tile on its own flow instead of switching interpolation on and off as
// neighboring motion crosses a tolerance boundary. // neighboring motion crosses a tolerance boundary.
const val SPATIAL_INTERPOLATION_FLOW_TOLERANCE = -1f const val SPATIAL_INTERPOLATION_FLOW_TOLERANCE = -1f
val ALIGN_PYRAMID_DOWNSAMPLE_STEPS = intArrayOf(2, 4, 4)
// Indexed from the finest one-sample-per-Bayer-quad level to the coarsest.
val ALIGN_LEVEL_TILE_STRIDES = intArrayOf(32, 32, 16, 8)
// Captured at UnblockerRaw10Halide entry on the original MGC full-resolution path. // Captured at UnblockerRaw10Halide entry on the original MGC full-resolution path.
const val UNBLOCKER_FULLRES_TILE_SIZE = 8 const val UNBLOCKER_FULLRES_TILE_SIZE = 8
const val UNBLOCKER_OUTPUT_SCALE = 1f const val UNBLOCKER_OUTPUT_SCALE = 1f
@@ -18,7 +18,6 @@ internal object GlesYuvAlignmentShaders {
uniform highp isampler2D uReference; uniform highp isampler2D uReference;
uniform highp sampler2D uCurrent; uniform highp sampler2D uCurrent;
uniform highp sampler2D uProducts0; uniform highp sampler2D uProducts0;
uniform highp sampler2D uProducts1;
uniform highp sampler2D uInitialAlignment; uniform highp sampler2D uInitialAlignment;
uniform ivec2 uImageSize; uniform ivec2 uImageSize;
uniform ivec2 uGridSize; uniform ivec2 uGridSize;
@@ -50,7 +49,7 @@ internal object GlesYuvAlignmentShaders {
vec2 inverseSize = 1.0 / vec2(uImageSize); vec2 inverseSize = 1.0 / vec2(uImageSize);
vec2 target = vec2(0.0); vec2 target = vec2(0.0);
vec2 gradientSum = vec2(0.0); vec2 gradientSum = vec2(0.0);
float currentSum = 0.0; float residualSum = 0.0;
for (int y = 0; y < 64; y += sampleStep) { for (int y = 0; y < 64; y += sampleStep) {
if (y >= uTileSize) break; if (y >= uTileSize) break;
for (int x = 0; x < 64; x += sampleStep) { for (int x = 0; x < 64; x += sampleStep) {
@@ -61,22 +60,21 @@ internal object GlesYuvAlignmentShaders {
vec2 encoded = textureLod(uCurrent, vec2 encoded = textureLod(uCurrent,
(vec2(p) + flow + 0.5) * inverseSize, 0.0).rg; (vec2(p) + flow + 0.5) * inverseSize, 0.0).rg;
float current = dot(encoded, vec2(16.0, 1.0)); float current = dot(encoded, vec2(16.0, 1.0));
float residual = current - referenceAt(p);
vec2 gradient = gradientAt(p); vec2 gradient = gradientAt(p);
target += current * gradient; target += residual * gradient;
if (uNormalize != 0) { if (uNormalize != 0) {
currentSum += current; residualSum += residual;
gradientSum += gradient; gradientSum += gradient;
} }
} }
} }
// sum((current - mean) * gradient), with no second image traversal. // Center the residual itself, avoiding subtraction of large intensity products.
if (uNormalize != 0) target -= (currentSum / count) * gradientSum; if (uNormalize != 0) target -= (residualSum / count) * gradientSum;
vec4 products0 = texelFetch(uProducts0, tile, 0); vec4 products0 = texelFetch(uProducts0, tile, 0);
float products1 = texelFetch(uProducts1, tile, 0).r; vec2 b = 0.5 * target / count;
vec2 b = 0.5 * target / count - vec2(products0.w, products1); // The shared reference pass materializes det(H) in alpha before adding +1.
float inverseDeterminant = 1.0 / ( float inverseDeterminant = 1.0 / (1.0 + products0.w);
1.0 + products0.x * products0.y - products0.z * products0.z
);
vec2 delta = inverseDeterminant * vec2( vec2 delta = inverseDeterminant * vec2(
products0.z * b.y - products0.y * b.x, products0.z * b.y - products0.y * b.x,
products0.z * b.x - products0.x * b.y products0.z * b.x - products0.x * b.y
@@ -78,9 +78,7 @@ class GlesYuvStacker(
val gridHeight: Int, val gridHeight: Int,
val tileStride: Int, val tileStride: Int,
val tileSize: Int, val tileSize: Int,
val normalize: Boolean,
val products0: Int, val products0: Int,
val products1: Int,
) )
private interface MertensFramebufferSource { private interface MertensFramebufferSource {
@@ -1483,7 +1481,6 @@ class GlesYuvStacker(
check(reference.size == ALIGN_LEVEL_TILE_STRIDES.size) check(reference.size == ALIGN_LEVEL_TILE_STRIDES.size)
return reference.mapIndexed { levelIndex, level -> return reference.mapIndexed { levelIndex, level ->
val tileSize = ALIGN_LEVEL_TILE_STRIDES[levelIndex] val tileSize = ALIGN_LEVEL_TILE_STRIDES[levelIndex]
val normalize = levelIndex != 0
val productGridWidth = alignmentGridWidth(level, tileSize) val productGridWidth = alignmentGridWidth(level, tileSize)
val productGridHeight = alignmentGridHeight(level, tileSize) val productGridHeight = alignmentGridHeight(level, tileSize)
val products0 = createTexture2D( val products0 = createTexture2D(
@@ -1492,14 +1489,8 @@ class GlesYuvStacker(
GLES30.GL_RGBA32F, GLES30.GL_RGBA32F,
GLES30.GL_NEAREST, GLES30.GL_NEAREST,
) )
val products1 = createTexture2D(
productGridWidth,
productGridHeight,
GLES30.GL_R32F,
GLES30.GL_NEAREST,
)
bindFramebufferOutputs( bindFramebufferOutputs(
intArrayOf(products0, products1), intArrayOf(products0),
"buildReferenceAlignmentProducts level $levelIndex", "buildReferenceAlignmentProducts level $levelIndex",
) )
GLES30.glViewport(0, 0, productGridWidth, productGridHeight) GLES30.glViewport(0, 0, productGridWidth, productGridHeight)
@@ -1518,10 +1509,6 @@ class GlesYuvStacker(
uniform(alignmentGradientProductsProgram, "uTileSize"), uniform(alignmentGradientProductsProgram, "uTileSize"),
tileSize, tileSize,
) )
GLES30.glUniform1i(
uniform(alignmentGradientProductsProgram, "uNormalize"),
if (normalize) 1 else 0,
)
GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3) GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3)
finishFramebufferPass("buildReferenceAlignmentProducts level $levelIndex") finishFramebufferPass("buildReferenceAlignmentProducts level $levelIndex")
ReferenceAlignmentProducts( ReferenceAlignmentProducts(
@@ -1530,9 +1517,7 @@ class GlesYuvStacker(
gridHeight = productGridHeight, gridHeight = productGridHeight,
tileStride = tileSize, tileStride = tileSize,
tileSize = tileSize, tileSize = tileSize,
normalize = normalize,
products0 = products0, products0 = products0,
products1 = products1,
) )
} }
} }
@@ -1622,8 +1607,7 @@ class GlesYuvStacker(
referenceProducts.gridWidth == levelGridWidth && referenceProducts.gridWidth == levelGridWidth &&
referenceProducts.gridHeight == levelGridHeight && referenceProducts.gridHeight == levelGridHeight &&
referenceProducts.tileStride == tileStride && referenceProducts.tileStride == tileStride &&
referenceProducts.tileSize == tileSize && referenceProducts.tileSize == tileSize
referenceProducts.normalize == normalize
) )
var input = initial var input = initial
repeat(iterations) { iteration -> repeat(iterations) { iteration ->
@@ -1635,11 +1619,10 @@ class GlesYuvStacker(
check(current.linearTexture != 0) { "YUV LK requires a filterable current pyramid" } check(current.linearTexture != 0) { "YUV LK requires a filterable current pyramid" }
bindTexture(blockLucasKanadeProgram, "uCurrent", 1, current.linearTexture) bindTexture(blockLucasKanadeProgram, "uCurrent", 1, current.linearTexture)
bindTexture(blockLucasKanadeProgram, "uProducts0", 2, referenceProducts.products0) bindTexture(blockLucasKanadeProgram, "uProducts0", 2, referenceProducts.products0)
bindTexture(blockLucasKanadeProgram, "uProducts1", 3, referenceProducts.products1)
bindTexture( bindTexture(
blockLucasKanadeProgram, blockLucasKanadeProgram,
"uInitialAlignment", "uInitialAlignment",
4, 3,
input?.texture ?: zeroFlowTexture, input?.texture ?: zeroFlowTexture,
) )
GLES30.glUniform2i( GLES30.glUniform2i(
@@ -1731,6 +1714,7 @@ class GlesYuvStacker(
uniform(upsampleAlignmentProgram, "uTargetTileSize"), uniform(upsampleAlignmentProgram, "uTargetTileSize"),
targetTileSize, targetTileSize,
) )
GLES30.glUniform2i(uniform(upsampleAlignmentProgram, "uTargetImageOffset"), 0, 0)
GLES30.glUniform1f( GLES30.glUniform1f(
uniform(upsampleAlignmentProgram, "uInitialScale"), uniform(upsampleAlignmentProgram, "uInitialScale"),
initialScale, initialScale,
@@ -0,0 +1,64 @@
package com.hinnka.mycamera.processor
/** Geometry of V25's LK-only BuildAlignPyramid / PrepareBase path. */
internal class MgcRawLkPyramidPlan(
rawWidth: Int,
rawHeight: Int,
val maximumTileSize: 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(rawWidth > 0 && rawHeight > 0)
require(maximumTileSize == 16 || maximumTileSize == 32 || maximumTileSize == 64)
val fineWidth = (rawWidth + 1) / 2
val fineHeight = (rawHeight + 1) / 2
val result = ArrayList<Level>()
var scale = 1
var tileLimit = 64
var tileSize = maximumTileSize
while (scale < 256) {
val finest = result.isEmpty()
val downsample = if (finest) 1 else if (result.size == 1) 2 else 4
// PrepareBase (38CC150) divides each inclusive maximum coordinate with
// llround, then adds one. Rounding the original dimensions by total scale
// does not preserve this recurrence, notably for odd extents and deep levels.
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
// The gradient sampler needs one source pixel at the finest level and three
// at coarser levels. The extra positive-side gray sample is not another tile.
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
tileSize = minOf(tileSize, tileLimit).coerceAtLeast(8)
tileLimit /= 4
}
require(result.isNotEmpty()) { "RAW dimensions cannot support the requested LK tile" }
levels = result
}
/** Every LK iteration changes the flow by at most one pixel of its gray level. */
val maximumDisplacement: Float
get() = levels.mapIndexed { index, level ->
level.scale * if (index == 0) 2 else 3
}.sum().toFloat()
}
@@ -0,0 +1,43 @@
package com.hinnka.mycamera.processor
import kotlin.math.abs
import kotlin.math.floor
import kotlin.math.sign
/** SabreProcessor's per-frame alignment-grid offsets (V25 0x38C9310 / 0x38CAEBC). */
internal data class MgcSabreAlignmentOffset(val x: Int, val y: Int) {
companion object {
val ZERO = MgcSabreAlignmentOffset(0, 0)
private val xSequence = floatArrayOf(
-0.45f, -0.05f, 0.35f, -0.15f, 0.25f,
-0.25f, 0.15f, -0.35f, 0.05f, 0.45f,
)
private val ySequence = floatArrayOf(
-0.4811529517f, -0.00901698973f, 0.4631189704f, 0.372949034f, -0.1549150348f,
-0.2450849712f, 0.227050975f, 0.1368810385f, -0.3909830153f, 0.08115295321f,
)
/** Base-frame SNR table constructed at 0x38C8290 and evaluated at 0x38C8DAC. */
fun tileSupport(baseFrameSnr: Float): Int {
require(baseFrameSnr.isFinite())
return when {
baseFrameSnr < 0.5f -> 32
baseFrameSnr < 2.7f -> 64
else -> 16
}
}
fun forFrame(frameIndex: Int, tileStride: Int): MgcSabreAlignmentOffset {
require(frameIndex >= 0 && tileStride > 0)
if (frameIndex == 0) return ZERO
val index = (frameIndex - 1) % xSequence.size
// Original FRINTA: nearest integer with halfway cases away from zero.
fun scaled(value: Float): Int {
val product = value * tileStride
return (sign(product) * floor(abs(product) + 0.5f)).toInt()
}
return MgcSabreAlignmentOffset(scaled(xSequence[index]), scaled(ySequence[index]))
}
}
}
+17 -1
View File
@@ -33,10 +33,26 @@
PMA110 / Adreno 840 / GLES 3.2 V@0842.44 上,直方图的整数统计与 CPU 一致,但 PMA110 / Adreno 840 / GLES 3.2 V@0842.44 上,直方图的整数统计与 CPU 一致,但
`float(sum) / float(count)` 在部分输入上与 JVM Float 相差 1 ULP,并可传到候选位移。 `float(sum) / float(count)` 在部分输入上与 JVM Float 相差 1 ULP,并可传到候选位移。
这是浮点除法精度差异,不能仅凭 `highp` 声明认定迁移无损。 这是浮点除法精度差异,不能仅凭 `highp` 声明认定迁移无损。
RAW Spatial 的 `GlesSpatialGlobalAlignment(cpuCompatibleMean = true)` 在无十票峰值时, `GlesSpatialGlobalAlignment(cpuCompatibleMean = true)` 的兼容模式在无十票峰值时,
以整数长除法生成 Float 有效位并执行 ties-to-even 舍入;此分支的票数与整数和都可被 以整数长除法生成 Float 有效位并执行 ties-to-even 舍入;此分支的票数与整数和都可被
Float 精确表示。实机验证需同时比较均值纹理和最终候选输出,不能只比较直方图票数。 Float 精确表示。实机验证需同时比较均值纹理和最终候选输出,不能只比较直方图票数。
### LK 正则项与浮点表达式重排
本地 ANGLE Metal 上,LK 的 `1 + xx*yy - xy*xy` 在 `xx=yy=xy=4096` 时丢失
`+1`,使完全相同的两张斜坡图产生 `(-1,-1)` 更新。仅改成
`1 + (xx*yy - xy*xy)` 仍不能在该后端保住求值顺序;同一括号写法在 ANGLE
SwiftShader 上则能保住。这是跨编译后端的浮点求值约束,尚未以此探针验证 PMA110,
不能记为该设备独有的驱动缺陷。原 MGC ARM64 也存在先加 1 后减乘积的数值退化。
- `highp` 不等于禁止重排;括号也不能替代 [`precise` 的求值约束](https://registry.khronos.org/OpenGL/extensions/EXT/EXT_gpu_shader5.txt)。
`precise` 不能直接用于通用 GLSL ES 3.00;不要为此无条件提高整条管线的版本要求。
- 参考帧 pass 将非负 Gram 行列式存入 `RGBA32F.a`,LK 在读取后才加 `1.0`。
这道纹理读写边界防止编译器把正则项重新合并到大乘积中,不增加 pass 或 CPU 回读。
- 验证必须贯穿实际参考乘积 producer、纹理分配/写入、LK sampler 和 flow 回读;只验证
手工填入的 Hessian 或 shader 编译不能证明整个计算链成立。覆盖平坦图、单方向梯度、
已知平移与不同 tile 大小,并以独立高精度计算检查非零位移响应。
### 能力快照 ### 能力快照
EGL context `makeCurrent` 后、编译任何 shader 前记录: EGL context `makeCurrent` 后、编译任何 shader 前记录:
+2 -1
View File
@@ -42,7 +42,8 @@ def read_makernote(path: Path) -> dict:
raise ValueError("Invalid ExifIFD pointer") raise ValueError("Invalid ExifIFD pointer")
exif = struct.unpack(byte_order + "I", pointer)[0] exif = struct.unpack(byte_order + "I", pointer)[0]
kind, count, pointer = find_tag(exif, 0x927C) kind, count, pointer = find_tag(exif, 0x927C)
if kind != 7 or not 1 <= count <= 16 * 1024 * 1024: # Bounded local merge replay captures can include up to 32 frames of RAW/texture ROIs.
if kind != 7 or not 1 <= count <= 32 * 1024 * 1024:
raise ValueError("Invalid or oversized MakerNote") raise ValueError("Invalid or oversized MakerNote")
payload = pointer[:count] if count <= 4 else read( payload = pointer[:count] if count <= 4 else read(
struct.unpack(byte_order + "I", pointer)[0], count struct.unpack(byte_order + "I", pointer)[0], count