From 70728d1168dcbe014691cc17f868c59656f67c8c Mon Sep 17 00:00:00 2001 From: zhoubinjia Date: Tue, 22 Sep 2026 19:24:10 +0800 Subject: [PATCH] feat: Lucas-Kanade precision fixes and Sabre alignment offsets --- .../processor/GlesMgcRawSpatialShaders.kt | 407 +++++++++--------- .../processor/GlesMgcRawSpatialStacker.kt | 348 ++++++++------- .../processor/GlesYuvAlignmentShaders.kt | 20 +- .../mycamera/processor/GlesYuvStacker.kt | 24 +- .../mycamera/processor/MgcRawLkPyramidPlan.kt | 64 +++ .../processor/MgcSabreAlignmentOffset.kt | 43 ++ docs/gles-driver-compatibility.md | 18 +- scripts/extract_photon_makernote.py | 3 +- 8 files changed, 553 insertions(+), 374 deletions(-) create mode 100644 app/src/main/java/com/hinnka/mycamera/processor/MgcRawLkPyramidPlan.kt create mode 100644 app/src/main/java/com/hinnka/mycamera/processor/MgcSabreAlignmentOffset.kt diff --git a/app/src/main/java/com/hinnka/mycamera/processor/GlesMgcRawSpatialShaders.kt b/app/src/main/java/com/hinnka/mycamera/processor/GlesMgcRawSpatialShaders.kt index ce0c7822..f2d8108b 100644 --- a/app/src/main/java/com/hinnka/mycamera/processor/GlesMgcRawSpatialShaders.kt +++ b/app/src/main/java/com/hinnka/mycamera/processor/GlesMgcRawSpatialShaders.kt @@ -690,9 +690,9 @@ internal object GlesMgcRawSpatialShaders { """.trimIndent() /** - * Read4xDownSample and the input preparation for - * Downsample4xAndFilterRejectionMap from the embedded rejection.cl. V25 calls it after - * DilateMask/Downsample2x, so it reads RAW/4 base luma and acceptance and produces RAW/16. + * SabreProcessor's FilterRejectionMap uses S16/U8 BoxDownsample before the Halide + * bilateral filter. Both sums round once to integers, including repeated edge samples + * in a partial 4x4 block. The OpenCL path's fractional averages are a different contract. */ val rejectionFilterDownsample = """ #version 300 es @@ -706,63 +706,25 @@ internal object GlesMgcRawSpatialShaders { layout(location = 0) out float oLuma; 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() { - vec2 center = 4.0 * floor(gl_FragCoord.xy) + vec2(2.0); - center = clamp( - center, - vec2(2.0), - vec2(uInputSize) - vec2(2.0) - ); - float luma = 0.0; - float rejection = 0.0; - 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); + ivec2 origin = ivec2(gl_FragCoord.xy) * 4; + int luma = 0; + int rejection = 0; + for (int y = 0; y < 4; ++y) { + for (int x = 0; x < 4; ++x) { + ivec2 p = min(origin + ivec2(x, y), uInputSize - ivec2(1)); + luma += texelFetch(uBaseLuma, p, 0).r; + rejection += int(floor(texelFetch(uRejection, p, 0).r * 255.0 + 0.5)); } } - // The source reads CL_SNORM_INT16 and multiplies by 32767 / 16383. - oLuma = 0.25 * luma / 16383.0; - oRejection = 0.25 * rejection; + oLuma = float((luma + 8) >> 4) / 16383.0; + oRejection = float((rejection + 8) >> 4) / 255.0; } """.trimIndent() /** - * Downsample4xAndFilterRejectionMap from the embedded rejection.cl. The input textures contain - * the exact Read4xDownSample results, so the 7x7 loop is algebraically identical to the fused - * OpenCL kernel while avoiding repeated 4x4 source reads. + * RejectionMapFilterHalide (38B13E0). Compare quantized weights directly, without + * OpenCL's one-code tolerance, and retain the native round-to-even U8 output. */ val rejectionFilter = """ #version 300 es @@ -818,8 +780,7 @@ internal object GlesMgcRawSpatialShaders { ivec2 q = p + ivec2(dx, dy); float deltaLuma = valueAt(uLuma, q); float deltaRejection = valueAt(uRejection, q); - float sigma = centerRejection < - deltaRejection - 1.0 / 255.0 + float sigma = centerRejection < deltaRejection ? uColorSigma : uColorSigma * ( uClipRejection != 0 ? uColorSigmaBoost : 1.0 @@ -836,15 +797,18 @@ internal object GlesMgcRawSpatialShaders { weightSum += weight; } } - oFilteredRejection = weightSum > 0.0 + float filtered = weightSum > 0.0 ? weightedRejection / weightSum : centerRejection; + oFilteredRejection = roundEven(clamp(filtered, 0.0, 1.0) * 255.0) / 255.0; } """.trimIndent() /** - * Upsample4xAndPostProcess from the embedded rejection.cl. A separate output texture avoids - * undefined framebuffer feedback while preserving the source equation. + * FilterRejectionMap's LinearKernel resample and strong postprocess. V25's U8 + * 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 = """ #version 300 es @@ -858,26 +822,48 @@ internal object GlesMgcRawSpatialShaders { uniform float uPixelDifferenceThreshold; uniform float uClippedThreshold; 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() { ivec2 p = ivec2(gl_FragCoord.xy); - float original = texelFetch(uOriginalWeight, p, 0).r; - float pixelDifference = texelFetch(uPixelDifference, p, 0).r; - vec2 uv = (vec2(p) + vec2(0.5)) / vec2(uSize); - float filtered = texture(uFilteredWeight, uv).r; - float postprocessed = filtered; + int original = int(floor(texelFetch(uOriginalWeight, p, 0).r * 255.0 + 0.5)); + int pixelDifference = int(floor(texelFetch(uPixelDifference, p, 0).r * 255.0 + 0.5)); + int pixelThreshold = int(floor(uPixelDifferenceThreshold * 255.0 + 0.5)); + int clippedThreshold = int(floor(uClippedThreshold * 255.0 + 0.5)); + int filtered = upsampledAt(p); + int postprocessed = filtered; if (filtered > original) { - float weight = pixelDifference < uPixelDifferenceThreshold + float weight = pixelDifference <= pixelThreshold ? 0.0 - : pixelDifference; - postprocessed = - original + weight * (filtered - original); + : float(pixelDifference) / 255.0; + postprocessed = int(float(original) + weight * float(filtered - original)); } - if (uClippedThreshold > 0.0 && - original <= uClippedThreshold && - pixelDifference <= uPixelDifferenceThreshold) { + if (clippedThreshold > 0 && + original <= clippedThreshold && + pixelDifference <= pixelThreshold) { postprocessed = original; } - oRejection = postprocessed; + oRejection = float(postprocessed) / 255.0; } """.trimIndent() @@ -2116,9 +2102,10 @@ internal object GlesMgcRawSpatialShaders { """.trimIndent() /** - * GrayPyramidDownsample4xHalide (0x3bcef58). Unlike two separately quantized - * 2x passes, the original evaluates the complete separable seven-tap triangle - * and converts to S16 only once. + * GrayPyramidDownsampleS16_4xHalide (worker 0x3c1c740, called by 0x38cd9b8). + * Two 2x triangle stages each round to S16. Collapsing their seven-tap kernel + * 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 yuvGrayDownsample4 = buildGrayDownsample4(linearOutput = true) @@ -2133,35 +2120,43 @@ internal object GlesMgcRawSpatialShaders { uniform ivec2 uInputSize; layout(location = 0) out highp int oGray; ${if (linearOutput) "layout(location = 1) out highp vec2 oLinearGray;" else ""} - float valueAt(ivec2 p) { - return float(texelFetch( + int valueAt(ivec2 p) { + return texelFetch( uInput, clamp(p, ivec2(0), uInputSize - ivec2(1)), 0 - ).r); + ).r; } - float triangleWeight(int offset) { - return float(4 - abs(offset)) * (1.0 / 16.0); + int firstStageAt(ivec2 p) { + 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() { ivec2 p = ivec2(gl_FragCoord.xy) * 4; - float value = 0.0; - for (int y = -3; y <= 3; ++y) { - float wy = triangleWeight(y); - for (int x = -3; x <= 3; ++x) { - value += valueAt(p + ivec2(x, y)) * - triangleWeight(x) * wy; + int sum = 0; + for (int y = -1; y <= 1; ++y) { + for (int x = -1; x <= 1; ++x) { + sum += firstStageAt(p + 2 * ivec2(x, y)) * + (2 - abs(x)) * (2 - abs(y)); } } - 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 ""} } """.trimIndent() /** * GradientAndGradientProductsHalide (0x3bf25c0; worker 0x3be9a1c). The generated kernel - * stores central differences as saturated S16 and five per-tile Float32 products in this - * order: xx, yy, xy, base*x and base*y. + * stores central differences as saturated S16. Cache the Hessian as xx, yy, xy, det(H). + * 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 yuvAlignmentGradientProducts = buildAlignmentGradientProducts(sparseFineLevels = true) @@ -2176,9 +2171,7 @@ internal object GlesMgcRawSpatialShaders { uniform ivec2 uImageSize; uniform int uTileStride; uniform int uTileSize; - uniform int uNormalize; layout(location = 0) out vec4 oProducts0; - layout(location = 1) out float oProducts1; float valueAt(ivec2 p) { return float(texelFetch( @@ -2204,45 +2197,45 @@ internal object GlesMgcRawSpatialShaders { ivec2 origin = (tile + ivec2(1)) * uTileStride; int sampleStep = ${if (sparseFineLevels) "uTileSize >= 32 ? 2 : 1" else "1"}; 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 yy = 0.0; float xy = 0.0; - float baseX = 0.0; - float baseY = 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; ivec2 p = origin + ivec2(x, y); vec2 gradient = gradientAt(p); - float base = valueAt(p) - meanBase; xx += gradient.x * gradient.x; yy += gradient.y * gradient.y; xy += gradient.x * gradient.y; - baseX += base * gradient.x; - baseY += base * gradient.y; } } float inverseCount = 1.0 / count; - oProducts0 = vec4( + vec3 hessian = vec3( 0.25 * xx * inverseCount, 0.25 * yy * inverseCount, - 0.25 * xy * inverseCount, - 0.5 * baseX * inverseCount + 0.25 * xy * 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() @@ -2255,7 +2248,8 @@ internal object GlesMgcRawSpatialShaders { */ val upsampleAlignment = buildUpsampleAlignment(globalCandidateTexture = false) - val upsampleAlignmentWithGpuCandidate = buildUpsampleAlignment(globalCandidateTexture = true) + val rawUpsampleAlignment = buildUpsampleAlignment(globalCandidateTexture = true) + val yuvUpsampleAlignment = buildUpsampleAlignment(globalCandidateTexture = true, sampleStep = 2) private fun buildUpsampleAlignment(globalCandidateTexture: Boolean, sampleStep: Int = 1) = """ @@ -2274,6 +2268,7 @@ internal object GlesMgcRawSpatialShaders { uniform int uInitialTileStride; uniform int uTargetTileStride; uniform int uTargetTileSize; + uniform ivec2 uTargetImageOffset; uniform float uInitialScale; uniform int uHasGlobalCandidate; ${if (globalCandidateTexture) "uniform highp sampler2D uGlobalCandidateTexture;" else "uniform vec2 uGlobalCandidate;"} @@ -2346,38 +2341,41 @@ internal object GlesMgcRawSpatialShaders { nextX = boundedInitialTile(nextX); 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 nearestFlow = bestFlow; float bestCost = candidateCost(origin, bestFlow); float nearestCost = bestCost; 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. // SAD depends only on the rounded displacement. Reuse its cost, but keep the // 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); float costX = all(equal(roundEven(flowX), roundEven(nearestFlow))) ? nearestCost : - all(equal(roundEven(flowX), roundEven(flowY))) ? costY : candidateCost(origin, flowX); if (costX < bestCost) { bestFlow = flowX; 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; } - // AlignPyramid::AlignAlt's final merge-grid pass supplies the robust global - // translation as the fourth candidate. Pyramid-level transitions leave it absent. + // AlignAlt's ordinary pyramid transitions use threshold=1 and include the + // whole-grid histogram candidate. The final merge-grid call at 0x38D29BC + // passes threshold=-1 and uses only the three neighboring candidates. if (uHasGlobalCandidate != 0) { vec2 globalFlow = ${if (globalCandidateTexture) "texelFetch(uGlobalCandidateTexture, ivec2(0), 0).xy" else "uGlobalCandidate"} * uInitialScale; float globalCost = all(equal(roundEven(globalFlow), roundEven(nearestFlow))) ? nearestCost : @@ -2409,7 +2407,6 @@ internal object GlesMgcRawSpatialShaders { uniform highp isampler2D uReference; uniform highp isampler2D uCurrent; uniform sampler2D uProducts0; - uniform sampler2D uProducts1; uniform sampler2D uInitialAlignment; uniform ivec2 uImageSize; uniform ivec2 uGridSize; @@ -2490,18 +2487,18 @@ internal object GlesMgcRawSpatialShaders { vec2 flow = initialAlignment.xy; ivec2 origin = (tile + ivec2(1)) * uTileStride; float count = float(uTileSize * uTileSize); - float meanCurrent = 0.0; + float meanResidual = 0.0; if (uNormalize != 0) { for (int y = 0; y < 64; ++y) { if (y >= uTileSize) break; for (int x = 0; x < 64; ++x) { if (x >= uTileSize) break; - meanCurrent += warpedCurrentAt( + meanResidual += warpedCurrentAt( vec2(origin + ivec2(x, y)) + flow - ); + ) - referenceAt(origin + ivec2(x, y)); } } - meanCurrent /= count; + meanResidual /= count; } float targetX = 0.0; @@ -2511,21 +2508,21 @@ internal object GlesMgcRawSpatialShaders { for (int x = 0; x < 64; ++x) { if (x >= uTileSize) break; 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); - targetX += current * gradient.x; - targetY += current * gradient.y; + targetX += residual * gradient.x; + targetY += residual * gradient.y; } } vec4 products0 = texelFetch(uProducts0, tile, 0); - float products1 = texelFetch(uProducts1, tile, 0).r; - float bx = 0.5 * targetX / count - products0.w; - float by = 0.5 * targetY / count - products1; - float inverseDeterminant = 1.0 / ( - 1.0 + - products0.x * products0.y - - products0.z * products0.z - ); + float bx = 0.5 * targetX / count; + float by = 0.5 * targetY / count; + // det(H) crossed a Float32 texture boundary in the reference pass. Keep +1 + // here: evaluating 1 + xx*yy - xy*xy can turn a rank-one tile into 1/0. + float inverseDeterminant = 1.0 / (1.0 + products0.w); vec2 delta = inverseDeterminant * vec2( products0.z * by - products0.y * bx, products0.z * bx - products0.x * by @@ -2677,9 +2674,9 @@ internal object GlesMgcRawSpatialShaders { /** * 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 - * dense consumers. Clamp the center tile before its neighborhood so the grid's halo uses - * the same complete converted value as nearest sampling of the original sparse texture. + * Sabre retains that sparse grid (tile size 1 here); Spatial expands each tile-owned + * value onto RAW/2. Clamp the center tile before its neighborhood so the grid's halo + * uses the same complete converted value as nearest sampling of the sparse texture. */ val convertAlignment = """ #version 300 es @@ -2768,7 +2765,7 @@ internal object GlesMgcRawSpatialShaders { """.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 * therefore covers an 8x8 Bayer-quad / 16x16 full-resolution region. The 128/9 variance @@ -2794,69 +2791,87 @@ internal object GlesMgcRawSpatialShaders { uniform float uOutputOffset; out float oUnblocker; - vec2 greensAt(ivec2 q) { - ivec2 p = clamp(q * 2, ivec2(0), uRawSize - ivec2(2)); - float p00 = float(texelFetch(uRaw, p, 0).r); - float p10 = float(texelFetch(uRaw, p + ivec2(1, 0), 0).r); - float p01 = float(texelFetch(uRaw, p + ivec2(0, 1), 0).r); - float p11 = float(texelFetch(uRaw, p + ivec2(1), 0).r); - vec4 v; - if (uCfaPattern == 0) v = vec4(p00, p10, p01, p11); - else if (uCfaPattern == 1) v = vec4(p10, p00, p11, p01); - else if (uCfaPattern == 2) v = vec4(p01, p11, p00, p10); - else v = vec4(p11, p01, p10, p00); + uvec2 greensAt(ivec2 q) { + // Raw16 Unblocker mirrors Bayer quads, repeating the boundary quad. + ivec2 period = (uRawSize / 2) * 2; + q = (q % period + period) % period; + ivec2 p = min(q, period - ivec2(1) - q) * 2; + uint p00 = texelFetch(uRaw, p, 0).r; + uint p10 = texelFetch(uRaw, p + ivec2(1, 0), 0).r; + uint p01 = texelFetch(uRaw, p + ivec2(0, 1), 0).r; + uint p11 = texelFetch(uRaw, p + ivec2(1), 0).r; + uvec4 v; + 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; } - float averageGreen(ivec2 q) { - q = clamp(q, ivec2(0), (uRawSize / 2) - ivec2(1)); - vec2 g = greensAt(q); - return 0.5 * (g.x + g.y); + uint averageGreen(ivec2 q) { + uvec2 g = greensAt(q); + return (g.x + g.y + 1u) >> 1u; } - float blurredGreen(ivec2 q) { - float value = 0.0; - for (int y = -1; y <= 1; ++y) { - float wy = y == 0 ? 0.5 : 0.25; - for (int x = -1; x <= 1; ++x) { - float wx = x == 0 ? 0.5 : 0.25; - value += averageGreen(q + ivec2(x, y)) * wx * wy; - } - } - return value; + uint verticalGreen(ivec2 q) { + uint outer = (averageGreen(q - ivec2(0, 1)) + + averageGreen(q + ivec2(0, 1))) >> 1u; + return (outer + averageGreen(q) + 1u) >> 1u; + } + uint blurredGreen(ivec2 q) { + uint outer = (verticalGreen(q - ivec2(1, 0)) + + verticalGreen(q + ivec2(1, 0)) + 1u) >> 1u; + return (outer + verticalGreen(q)) >> 1u; + } + // 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() { // The original AOT evaluates one extra cell on every side before its // UnblockerBlur pass. uTileOffset is (-1, -1) for that padded domain. ivec2 tile = ivec2(gl_FragCoord.xy) + uTileOffset; ivec2 origin = tile * 8; - float preSum = 0.0; - float preSquareSum = 0.0; - float postSum = 0.0; - float postSquareSum = 0.0; + uint preSum = 0u; + uvec2 preSquareSum = uvec2(0u); + uint postSum = 0u; + uvec2 postSquareSum = uvec2(0u); for (int y = 0; y < 8; ++y) { for (int x = 0; x < 8; ++x) { ivec2 q = origin + ivec2(x, y); - vec2 g = greensAt(clamp( - q, ivec2(0), (uRawSize / 2) - ivec2(1) - )); - float b = blurredGreen(q); + uvec2 g = greensAt(q); + uint b = blurredGreen(q); 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; - postSquareSum += b * b; + postSquareSum = addWide(postSquareSum, uvec2(b * b, 0u)); } } - float preCount = 128.0; - float postCount = 64.0; - float preMean = preSum / preCount; - float postMean = postSum / postCount; - float preVariance = max( - preSquareSum / preCount - preMean * preMean, - 0.0 - ); - float postVariance = max( - postSquareSum / postCount - postMean * postMean, - 0.0 - ); + float preMean = float((preSum + 64u) >> 7u); + float preVariance = roundedVariance(preSum, preSquareSum, 7u); + float postVariance = roundedVariance(postSum, postSquareSum, 6u); float signal = max(preMean - uBlackLevelGreen, 0.0); float predictedNoise = (uNoiseQuadratic * signal + uNoiseScale) * signal + @@ -2869,9 +2884,9 @@ internal object GlesMgcRawSpatialShaders { float ratio = denominator > 0.0 ? correctedVariance / denominator : 0.0; - float mapped = uOutputScale * ( - sqrt(max(ratio, 0.0)) - uOutputOffset - ); + float mapped = denominator > 0.0 + ? 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 // normalized GL_R8 conversion cannot round a boundary upward. oUnblocker = floor(clamp(mapped, 0.0, 1.0) * 255.0) / 255.0; diff --git a/app/src/main/java/com/hinnka/mycamera/processor/GlesMgcRawSpatialStacker.kt b/app/src/main/java/com/hinnka/mycamera/processor/GlesMgcRawSpatialStacker.kt index e1a181ab..4ba1e1cf 100644 --- a/app/src/main/java/com/hinnka/mycamera/processor/GlesMgcRawSpatialStacker.kt +++ b/app/src/main/java/com/hinnka/mycamera/processor/GlesMgcRawSpatialStacker.kt @@ -79,6 +79,9 @@ internal class GlesMgcRawSpatialStacker( val width: Int, val height: Int, val scaleToBayerQuads: Float, + val tileSize: Int, + val gridWidth: Int, + val gridHeight: Int, ) private data class Alignment( @@ -88,6 +91,8 @@ internal class GlesMgcRawSpatialStacker( val tileStride: Int, val scaleToBayerQuads: Float, val gridMin: Int, + val offsetX: Int = 0, + val offsetY: Int = 0, ) private data class GlobalAlignmentCandidate( @@ -136,9 +141,7 @@ internal class GlesMgcRawSpatialStacker( val gridHeight: Int, val tileStride: Int, val tileSize: Int, - val normalize: Boolean, val products0: Int, - val products1: Int, ) private data class PreparedTemporalFrame( @@ -472,7 +475,6 @@ internal class GlesMgcRawSpatialStacker( private val uniformLocations = HashMap>() private val textureSpecs = HashMap() private val noiseLutCache = HashMap, CachedNoiseLut>() - private var globalAlignment: GlesSpatialGlobalAlignment? = null private val validatedRenderTargetSpecs = HashSet>() private val temporalScratchTextures = SequentialScratchTextures() private var activeSequentialScratchTextures: SequentialScratchTextures? = null @@ -488,6 +490,8 @@ internal class GlesMgcRawSpatialStacker( private var alignProgram = 0 private var alignmentGradientProductsProgram = 0 private var upsampleAlignmentProgram = 0 + private var medianAlignmentProgram = 0 + private var globalAlignment: GlesSpatialGlobalAlignment? = null private var blockLucasKanadeProgram = 0 private var convertAlignmentProgram = 0 private var strengthAlignmentProgram = 0 @@ -541,11 +545,19 @@ internal class GlesMgcRawSpatialStacker( size = PIXEL_DIFFERENCE_KERNEL_SIZE, 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( - -MAX_ALIGNMENT_DISPLACEMENT_BAYER_QUADS, - -MAX_ALIGNMENT_DISPLACEMENT_BAYER_QUADS, - MAX_ALIGNMENT_DISPLACEMENT_BAYER_QUADS, - MAX_ALIGNMENT_DISPLACEMENT_BAYER_QUADS, + -alignmentPlan.maximumDisplacement, + -alignmentPlan.maximumDisplacement, + alignmentPlan.maximumDisplacement, + alignmentPlan.maximumDisplacement, ) fun processFrames(frames: List): RawStackResult? { @@ -1785,8 +1797,7 @@ internal class GlesMgcRawSpatialStacker( frames = rgbMergeFrames, images = images, outputExposureScale = outputExposure.normalizationScale, - mergeSharpness = RGB_AOT_MERGE_SHARPNESS_SCALE * - finishRawSharpenAttenuationScale, + mergeSharpness = finishRawSharpenAttenuationScale, capture = aotCapture, preparedAlignment = preparedStrengthAtlases.first, preparedRejection = preparedStrengthAtlases.second, @@ -2301,6 +2312,8 @@ internal class GlesMgcRawSpatialStacker( referenceGrayPyramid, currentGrayPyramid, referenceAlignmentProducts, + frameIndex = index, + finalTileSupport = MgcSabreAlignmentOffset.tileSupport(kernelTuning.referenceSnr), ) val flow = createConvertedAlignment(alignment) val unblockerWidth = ceilDiv(width, UNBLOCKER_FULLRES_TILE_SIZE * 2) @@ -3092,10 +3105,7 @@ internal class GlesMgcRawSpatialStacker( GlesMgcRawSpatialShaders.alignmentGradientProducts, "mgc_sabre_alignment_gradient_products", ) - upsampleAlignmentProgram = linkProgram( - GlesMgcRawSpatialShaders.upsampleAlignment, - "mgc_sabre_upsample_alignment", - ) + upsampleAlignmentProgram = initMergeUpsampleAlignment() blockLucasKanadeProgram = linkProgram( GlesMgcRawSpatialShaders.blockLucasKanade, "mgc_sabre_block_lucas_kanade", @@ -3155,13 +3165,18 @@ internal class GlesMgcRawSpatialStacker( ).also { it.initPrograms() } } - private fun initSpatialUpsampleAlignment(): Int { + private fun initMergeUpsampleAlignment(): Int { + if (processorPipeline == MgcRawProcessorPipeline.SPATIAL) { + medianAlignmentProgram = linkProgram( + GlesMgcRawSpatialShaders.medianAlignment, "mgc_median_alignment", + ) + } if (supportsComputePrograms) { val reduction = GlesSpatialGlobalAlignment(cpuCompatibleMean = true) try { reduction.init() val program = linkProgram( - GlesMgcRawSpatialShaders.upsampleAlignmentWithGpuCandidate, + GlesMgcRawSpatialShaders.rawUpsampleAlignment, "mgc_upsample_alignment_gpu_candidate", ) globalAlignment = reduction @@ -3200,7 +3215,7 @@ internal class GlesMgcRawSpatialStacker( GlesMgcRawSpatialShaders.alignmentGradientProducts, "mgc_alignment_gradient_products", ) - upsampleAlignmentProgram = initSpatialUpsampleAlignment() + upsampleAlignmentProgram = initMergeUpsampleAlignment() blockLucasKanadeProgram = linkProgram( GlesMgcRawSpatialShaders.blockLucasKanade, "mgc_block_lucas_kanade", @@ -3738,18 +3753,20 @@ internal class GlesMgcRawSpatialStacker( width = finestWidth, height = finestHeight, scaleToBayerQuads = 1f, + tileSize = alignmentPlan.levels.first().tileSize, + gridWidth = alignmentPlan.levels.first().gridWidth, + gridHeight = alignmentPlan.levels.first().gridHeight, ) var levelWidth = finestWidth var levelHeight = finestHeight - var scaleToBayerQuads = 1 - for (step in ALIGN_PYRAMID_DOWNSAMPLE_STEPS) { + for (level in alignmentPlan.levels.drop(1)) { + val step = level.downsample check(step == 2 || step == 4) - scaleToBayerQuads *= step // Every downsampled level carries the positive-side support sample used by // Halide's clamped interpolation. The finest level itself has no extra sample. - val nextWidth = ceilDiv(finestWidth, scaleToBayerQuads) + 1 - val nextHeight = ceilDiv(finestHeight, scaleToBayerQuads) + 1 + val nextWidth = level.width + val nextHeight = level.height val nextTexture = createTexture( nextWidth, nextHeight, @@ -3767,7 +3784,10 @@ internal class GlesMgcRawSpatialStacker( texture = nextTexture, width = nextWidth, height = nextHeight, - scaleToBayerQuads = scaleToBayerQuads.toFloat(), + scaleToBayerQuads = level.scale.toFloat(), + tileSize = level.tileSize, + gridWidth = level.gridWidth, + gridHeight = level.gridHeight, ) } return levels @@ -3775,8 +3795,18 @@ internal class GlesMgcRawSpatialStacker( /** Returns the logical RAW/4 base-luma input required by FilterRejectionMap. */ private fun buildRejectionBaseLuma(referenceGrayPyramid: List): Int { - check(referenceGrayPyramid.size > 1) { - "FilterRejectionMap requires the RAW/4 reference-luma pyramid level" + if (referenceGrayPyramid.size == 1) { + // 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] 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 * 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( reference: List, ): List { - check(reference.size == ALIGN_LEVEL_TILE_STRIDES.size) + check(reference.size == alignmentPlan.levels.size) val startNs = System.nanoTime() - return reference.mapIndexed { levelIndex, level -> - val tileSize = ALIGN_LEVEL_TILE_STRIDES[levelIndex] - val normalize = levelIndex != 0 + return reference.map { level -> + val tileSize = level.tileSize val gridWidth = alignmentGridWidth(level, tileSize) val gridHeight = alignmentGridHeight(level, tileSize) val products0 = createTexture( @@ -3810,12 +3841,6 @@ internal class GlesMgcRawSpatialStacker( GLES30.GL_RGBA32F, GLES30.GL_NEAREST, ) - val products1 = createTexture( - gridWidth, - gridHeight, - GLES30.GL_R32F, - GLES30.GL_NEAREST, - ) GLES30.glUseProgram(alignmentGradientProductsProgram) bindTexture( alignmentGradientProductsProgram, @@ -3831,16 +3856,11 @@ internal class GlesMgcRawSpatialStacker( ) uniform1i(alignmentGradientProductsProgram, "uTileStride", tileSize) uniform1i(alignmentGradientProductsProgram, "uTileSize", tileSize) - uniform1i( - alignmentGradientProductsProgram, - "uNormalize", - if (normalize) 1 else 0, - ) draw( alignmentGradientProductsProgram, gridWidth, gridHeight, - intArrayOf(products0, products1), + intArrayOf(products0), ) ReferenceAlignmentProducts( referenceTexture = level.texture, @@ -3848,9 +3868,7 @@ internal class GlesMgcRawSpatialStacker( gridHeight = gridHeight, tileStride = tileSize, tileSize = tileSize, - normalize = normalize, products0 = products0, - products1 = products1, ) }.also { products -> PLog.i( @@ -3863,36 +3881,22 @@ internal class GlesMgcRawSpatialStacker( } /** - * BuildAlignPyramidForBurst (0x3883e98), using the options captured at runtime from this - * MGC build: - * - * [target=256, minTile=8, maxTile=64, finestTile=-1, - * finestLkIterations=2, coarserLkIterations=3] - * normalizeFinest=false, normalizeCoarser=true, useL1Search=false - * - * 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. + * Execute the LK plan with two finest and three coarser iterations. Spatial's configured + * 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. + * The merge grid remains stride 8 regardless of the LK support. Sabre's existing LK-only + * configuration is separate from its SNR-selected final support; this is not a claim of + * parity with the original classic Sabre L1 search path. */ private fun alignPyramids( reference: List, current: List, referenceProducts: List, + frameIndex: Int = 0, + finalTileSupport: Int = alignmentPlan.maximumTileSize, ): Alignment { check(reference.size == current.size) - check(reference.size == ALIGN_LEVEL_TILE_STRIDES.size) + check(reference.size == alignmentPlan.levels.size) check(referenceProducts.size == reference.size) // Scoped to this solve: the frame arena may recycle these names on the next frame. val scratch = AlignmentScratch { w, h -> @@ -3904,10 +3908,10 @@ internal class GlesMgcRawSpatialStacker( reference = coarse, 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 = coarse.tileSize, + tileSize = coarse.tileSize, + iterations = if (coarseIndex == 0) ALIGN_LK_ITERATIONS_FINEST else ALIGN_LK_ITERATIONS_COARSER, + normalize = coarseIndex != 0, referenceProducts = referenceProducts[coarseIndex], scratch = scratch, ) @@ -3915,14 +3919,15 @@ internal class GlesMgcRawSpatialStacker( val schedule = ArrayList().apply { add( "${coarse.width}x${coarse.height}:" + - "${ALIGN_LEVEL_TILE_STRIDES[coarseIndex]}px," + - "LK${ALIGN_LK_ITERATIONS_COARSER},normalize=true" + "${coarse.tileSize}px," + + "LK${if (coarseIndex == 0) ALIGN_LK_ITERATIONS_FINEST else ALIGN_LK_ITERATIONS_COARSER}," + + "normalize=${coarseIndex != 0}" ) } for (levelIndex in coarseIndex - 1 downTo 0) { val level = reference[levelIndex] val coarser = reference[levelIndex + 1] - val tileSize = ALIGN_LEVEL_TILE_STRIDES[levelIndex] + val tileSize = level.tileSize val scale = coarser.scaleToBayerQuads / level.scaleToBayerQuads val finest = levelIndex == 0 @@ -3932,6 +3937,12 @@ internal class GlesMgcRawSpatialStacker( ALIGN_LK_ITERATIONS_COARSER } 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( reference = level, current = current[levelIndex], @@ -3942,6 +3953,8 @@ internal class GlesMgcRawSpatialStacker( targetTileStride = tileSize, targetTileSize = tileSize, scratch = scratch, + globalCandidate = globalCandidate, + gpuGlobalCandidate = gpuCandidate, ) alignment = renderLucasKanadeLevel( reference = level, @@ -3957,13 +3970,20 @@ internal class GlesMgcRawSpatialStacker( schedule += "${level.width}x${level.height}:${tileSize}px," + "LK$iterations,normalize=$normalize," + - "levelScale=$scale" + "levelScale=$scale,global=histogram" } - val finalUpsampleMode = if (processorPipeline == MgcRawProcessorPipeline.SPATIAL) { - val gpuCandidate = globalAlignment?.estimate( - alignment.texture, alignment.gridWidth, alignment.gridHeight, - ) ?: 0 - val globalCandidate = if (gpuCandidate == 0) estimateGlobalAlignmentCandidate(alignment) else null + // MGC's caller selects the non-overlapping 8-quad layout for every merge enum + // from Sabre through Spatial RGB (0x344BF84 / 0x5B94448). The finest LK grid + // is only an intermediate result; feeding it directly to Sabre leaves 64-RAW-pixel + // blocks and skips the final local/global candidate selection. + 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( reference = reference.first(), current = current.first(), @@ -3972,15 +3992,37 @@ internal class GlesMgcRawSpatialStacker( targetGridHeight = bayerAlignmentHeight, targetGridMin = MERGE_ALIGNMENT_GRID_MIN, targetTileStride = MERGE_BAYER_RAW_TILE_SIZE / 2, - targetTileSize = MERGE_BAYER_RAW_TILE_SIZE, - globalCandidate = globalCandidate, - gpuGlobalCandidateTexture = gpuCandidate, + targetTileSize = candidateSupport, + targetOffsetX = offset.x, + targetOffsetY = offset.y, + targetWindowInset = windowInset, 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 += "${reference.first().width}x${reference.first().height}:" + "${MERGE_BAYER_RAW_TILE_SIZE / 2}px," + - "UpsampleL1(tile=${MERGE_BAYER_RAW_TILE_SIZE})" + "UpsampleL1(tile=$candidateSupport,inset=$windowInset)" check( alignment.gridWidth == bayerAlignmentWidth && alignment.gridHeight == bayerAlignmentHeight && @@ -3988,16 +4030,9 @@ internal class GlesMgcRawSpatialStacker( alignment.scaleToBayerQuads == 1f && 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/global-gpu" - } else { - "merge-grid/global-${if (globalCandidate.usedHistogramPeak) "mode" else "mean"}" + - "(${globalCandidate.x},${globalCandidate.y},n=${globalCandidate.peakSupport})" - } - } else { - "level-transitions-only" + "merge-grid/offset(${offset.x},${offset.y})" } PLog.i( TAG, @@ -4008,8 +4043,9 @@ internal class GlesMgcRawSpatialStacker( "flowScale=${alignment.scaleToBayerQuads} useL1=false " + "gradientProducts=cached " + "upsampleL1=$finalUpsampleMode/3-candidate " + - "median=false " + - "runtimeOptions=256/8/64/-1/2/3/0/1/0 " + + "medianPasses=${if (processorPipeline == MgcRawProcessorPipeline.SPATIAL) 2 else 0} " + + "runtimeOptions=256/8/${alignmentPlan.maximumTileSize}/-1/2/3/0/1/0 " + + "finalSupport=$finalTileSupport " + "schedule=${schedule.joinToString(" -> ")}", ) return alignment @@ -4019,10 +4055,9 @@ internal class GlesMgcRawSpatialStacker( * UpsampleAlignmentI16Halide selects a whole coarse-flow candidate rather than blending * neighboring motion vectors. This preserves discontinuities at moving-object boundaries. * - * The original runtime uses three candidates at pyramid transitions. Before the final - * merge-grid expansion it derives one global motion candidate from the finest LK field and - * invokes the four-candidate worker. The global candidate is important when all three local - * neighbors belong to the same erroneous motion island. + * Ordinary pyramid transitions include the global histogram candidate with cost + * multiplier 1. The final call at 0x38D29F4 passes threshold=-1 and reads only the + * three local candidates. */ private fun renderUpsampledAlignment( reference: TextureLevel, @@ -4034,8 +4069,11 @@ internal class GlesMgcRawSpatialStacker( targetTileStride: Int, targetTileSize: Int, scratch: AlignmentScratch, + targetOffsetX: Int = 0, + targetOffsetY: Int = 0, + targetWindowInset: Int = 0, globalCandidate: GlobalAlignmentCandidate? = null, - gpuGlobalCandidateTexture: Int = 0, + gpuGlobalCandidate: Int = 0, ): Alignment { require(reference.width == current.width && reference.height == current.height) require(targetGridWidth > 0 && targetGridHeight > 0) @@ -4065,23 +4103,22 @@ internal class GlesMgcRawSpatialStacker( uniform1i(upsampleAlignmentProgram, "uInitialTileStride", initial.tileStride) uniform1i(upsampleAlignmentProgram, "uTargetTileStride", targetTileStride) uniform1i(upsampleAlignmentProgram, "uTargetTileSize", targetTileSize) + uniform2i( + upsampleAlignmentProgram, "uTargetImageOffset", + targetOffsetX - targetWindowInset, targetOffsetY - targetWindowInset, + ) uniform1f(upsampleAlignmentProgram, "uInitialScale", initialScale) uniform1i( - upsampleAlignmentProgram, - "uHasGlobalCandidate", - if (globalCandidate != null || gpuGlobalCandidateTexture != 0) 1 else 0, + upsampleAlignmentProgram, "uHasGlobalCandidate", + if (globalCandidate != null || gpuGlobalCandidate != 0) 1 else 0, ) if (globalAlignment != null) { - // Bind a valid float sampler even at transitions where the global branch is off. bindTexture( upsampleAlignmentProgram, "uGlobalCandidateTexture", 3, - gpuGlobalCandidateTexture.takeIf { it != 0 } ?: initial.texture, + if (gpuGlobalCandidate != 0) gpuGlobalCandidate else initial.texture, ) } else { - uniform2f( - upsampleAlignmentProgram, "uGlobalCandidate", - globalCandidate?.x ?: 0f, globalCandidate?.y ?: 0f, - ) + uniform2f(upsampleAlignmentProgram, "uGlobalCandidate", globalCandidate?.x ?: 0f, globalCandidate?.y ?: 0f) } draw( upsampleAlignmentProgram, @@ -4097,11 +4134,13 @@ internal class GlesMgcRawSpatialStacker( tileStride = targetTileStride, scaleToBayerQuads = reference.scaleToBayerQuads, 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 * 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.gridHeight == gridHeight && referenceProducts.tileStride == tileStride && - referenceProducts.tileSize == tileSize && - referenceProducts.normalize == normalize + referenceProducts.tileSize == tileSize ) { "Cached LK reference products do not match the requested pyramid level" } @@ -4236,6 +4274,8 @@ internal class GlesMgcRawSpatialStacker( var input = initial repeat(iterations) { 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) bindTexture(blockLucasKanadeProgram, "uReference", 0, reference.texture) bindTexture(blockLucasKanadeProgram, "uCurrent", 1, current.texture) @@ -4245,17 +4285,10 @@ internal class GlesMgcRawSpatialStacker( 2, referenceProducts.products0, ) - bindTexture( - blockLucasKanadeProgram, - "uProducts1", - 3, - referenceProducts.products1, - ) - val inputTexture = input?.texture ?: createZeroFlowTexture() bindTexture( blockLucasKanadeProgram, "uInitialAlignment", - 4, + 3, inputTexture, ) uniform2i( @@ -4356,6 +4389,24 @@ internal class GlesMgcRawSpatialStacker( require(alignment.gridWidth > 0 && alignment.gridHeight > 0) { "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 = alignment.tileStride.toFloat() * alignment.scaleToBayerQuads require(strideInBayerQuads.isFinite() && strideInBayerQuads > 0f) { @@ -4395,6 +4446,8 @@ internal class GlesMgcRawSpatialStacker( alignment: Alignment, output: Int, alignmentTileSize: Int, + outputWidth: Int = rejectionWidth, + outputHeight: Int = rejectionHeight, ) { GLES30.glUseProgram(convertAlignmentProgram) bindTexture(convertAlignmentProgram, "uAlignment", 0, alignment.texture) @@ -4419,8 +4472,8 @@ internal class GlesMgcRawSpatialStacker( ) draw( convertAlignmentProgram, - rejectionWidth, - rejectionHeight, + outputWidth, + outputHeight, intArrayOf(output), ) } @@ -9386,6 +9439,18 @@ internal class GlesMgcRawSpatialStacker( private fun ensureGles3() { DngCaptureDiagnostics.recordCurrentGl() 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() check(version.contains("OpenGL ES 3.")) { "MGC Spatial merge requires GLES3, got: $version" @@ -9480,9 +9545,9 @@ internal class GlesMgcRawSpatialStacker( private fun release() { if (eglDisplay != EGL14.EGL_NO_DISPLAY) { + noiseLutCache.clear() globalAlignment?.release() globalAlignment = null - noiseLutCache.clear() rgbChromaPostprocessor?.release() rgbChromaPostprocessor = null if (programs.isNotEmpty()) { @@ -9544,26 +9609,21 @@ internal class GlesMgcRawSpatialStacker( private fun ceilDiv(value: Int, divisor: Int): Int = 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( level: TextureLevel, tileStride: Int, - ): Int = alignmentGridExtent( - ceilDiv(ceilDiv(width, 2), level.scaleToBayerQuads.toInt()), - tileStride, - ) + ): Int { + check(tileStride == level.tileSize) + return level.gridWidth + } private fun alignmentGridHeight( level: TextureLevel, tileStride: Int, - ): Int = alignmentGridExtent( - ceilDiv(ceilDiv(height, 2), level.scaleToBayerQuads.toInt()), - tileStride, - ) + ): Int { + check(tileStride == level.tileSize) + return level.gridHeight + } private fun rgbBandHeightCandidates(): IntArray = intArrayOf( outputHeight, @@ -9617,7 +9677,6 @@ internal class GlesMgcRawSpatialStacker( const val EGL_OPENGL_ES3_BIT_KHR = 0x00000040 const val RAW_BYTES_PER_PIXEL = 2 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_MAX_IN_FLIGHT_PASSES = 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 ALIGN_TARGET_FINEST_DIMENSION = 256 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_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 MERGE_ALIGNMENT_GRID_MIN = 0 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 // neighboring motion crosses a tolerance boundary. 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. const val UNBLOCKER_FULLRES_TILE_SIZE = 8 const val UNBLOCKER_OUTPUT_SCALE = 1f diff --git a/app/src/main/java/com/hinnka/mycamera/processor/GlesYuvAlignmentShaders.kt b/app/src/main/java/com/hinnka/mycamera/processor/GlesYuvAlignmentShaders.kt index ec086933..17d1e38b 100644 --- a/app/src/main/java/com/hinnka/mycamera/processor/GlesYuvAlignmentShaders.kt +++ b/app/src/main/java/com/hinnka/mycamera/processor/GlesYuvAlignmentShaders.kt @@ -18,7 +18,6 @@ internal object GlesYuvAlignmentShaders { uniform highp isampler2D uReference; uniform highp sampler2D uCurrent; uniform highp sampler2D uProducts0; - uniform highp sampler2D uProducts1; uniform highp sampler2D uInitialAlignment; uniform ivec2 uImageSize; uniform ivec2 uGridSize; @@ -50,7 +49,7 @@ internal object GlesYuvAlignmentShaders { vec2 inverseSize = 1.0 / vec2(uImageSize); vec2 target = vec2(0.0); vec2 gradientSum = vec2(0.0); - float currentSum = 0.0; + float residualSum = 0.0; for (int y = 0; y < 64; y += sampleStep) { if (y >= uTileSize) break; for (int x = 0; x < 64; x += sampleStep) { @@ -61,22 +60,21 @@ internal object GlesYuvAlignmentShaders { vec2 encoded = textureLod(uCurrent, (vec2(p) + flow + 0.5) * inverseSize, 0.0).rg; float current = dot(encoded, vec2(16.0, 1.0)); + float residual = current - referenceAt(p); vec2 gradient = gradientAt(p); - target += current * gradient; + target += residual * gradient; if (uNormalize != 0) { - currentSum += current; + residualSum += residual; gradientSum += gradient; } } } - // sum((current - mean) * gradient), with no second image traversal. - if (uNormalize != 0) target -= (currentSum / count) * gradientSum; + // Center the residual itself, avoiding subtraction of large intensity products. + if (uNormalize != 0) target -= (residualSum / count) * gradientSum; vec4 products0 = texelFetch(uProducts0, tile, 0); - float products1 = texelFetch(uProducts1, tile, 0).r; - vec2 b = 0.5 * target / count - vec2(products0.w, products1); - float inverseDeterminant = 1.0 / ( - 1.0 + products0.x * products0.y - products0.z * products0.z - ); + vec2 b = 0.5 * target / count; + // The shared reference pass materializes det(H) in alpha before adding +1. + 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 diff --git a/app/src/main/java/com/hinnka/mycamera/processor/GlesYuvStacker.kt b/app/src/main/java/com/hinnka/mycamera/processor/GlesYuvStacker.kt index 194d34cd..da6212d9 100644 --- a/app/src/main/java/com/hinnka/mycamera/processor/GlesYuvStacker.kt +++ b/app/src/main/java/com/hinnka/mycamera/processor/GlesYuvStacker.kt @@ -78,9 +78,7 @@ class GlesYuvStacker( val gridHeight: Int, val tileStride: Int, val tileSize: Int, - val normalize: Boolean, val products0: Int, - val products1: Int, ) private interface MertensFramebufferSource { @@ -1483,7 +1481,6 @@ class GlesYuvStacker( check(reference.size == ALIGN_LEVEL_TILE_STRIDES.size) return reference.mapIndexed { levelIndex, level -> val tileSize = ALIGN_LEVEL_TILE_STRIDES[levelIndex] - val normalize = levelIndex != 0 val productGridWidth = alignmentGridWidth(level, tileSize) val productGridHeight = alignmentGridHeight(level, tileSize) val products0 = createTexture2D( @@ -1492,14 +1489,8 @@ class GlesYuvStacker( GLES30.GL_RGBA32F, GLES30.GL_NEAREST, ) - val products1 = createTexture2D( - productGridWidth, - productGridHeight, - GLES30.GL_R32F, - GLES30.GL_NEAREST, - ) bindFramebufferOutputs( - intArrayOf(products0, products1), + intArrayOf(products0), "buildReferenceAlignmentProducts level $levelIndex", ) GLES30.glViewport(0, 0, productGridWidth, productGridHeight) @@ -1518,10 +1509,6 @@ class GlesYuvStacker( uniform(alignmentGradientProductsProgram, "uTileSize"), tileSize, ) - GLES30.glUniform1i( - uniform(alignmentGradientProductsProgram, "uNormalize"), - if (normalize) 1 else 0, - ) GLES30.glDrawArrays(GLES30.GL_TRIANGLES, 0, 3) finishFramebufferPass("buildReferenceAlignmentProducts level $levelIndex") ReferenceAlignmentProducts( @@ -1530,9 +1517,7 @@ class GlesYuvStacker( gridHeight = productGridHeight, tileStride = tileSize, tileSize = tileSize, - normalize = normalize, products0 = products0, - products1 = products1, ) } } @@ -1622,8 +1607,7 @@ class GlesYuvStacker( referenceProducts.gridWidth == levelGridWidth && referenceProducts.gridHeight == levelGridHeight && referenceProducts.tileStride == tileStride && - referenceProducts.tileSize == tileSize && - referenceProducts.normalize == normalize + referenceProducts.tileSize == tileSize ) var input = initial repeat(iterations) { iteration -> @@ -1635,11 +1619,10 @@ class GlesYuvStacker( check(current.linearTexture != 0) { "YUV LK requires a filterable current pyramid" } bindTexture(blockLucasKanadeProgram, "uCurrent", 1, current.linearTexture) bindTexture(blockLucasKanadeProgram, "uProducts0", 2, referenceProducts.products0) - bindTexture(blockLucasKanadeProgram, "uProducts1", 3, referenceProducts.products1) bindTexture( blockLucasKanadeProgram, "uInitialAlignment", - 4, + 3, input?.texture ?: zeroFlowTexture, ) GLES30.glUniform2i( @@ -1731,6 +1714,7 @@ class GlesYuvStacker( uniform(upsampleAlignmentProgram, "uTargetTileSize"), targetTileSize, ) + GLES30.glUniform2i(uniform(upsampleAlignmentProgram, "uTargetImageOffset"), 0, 0) GLES30.glUniform1f( uniform(upsampleAlignmentProgram, "uInitialScale"), initialScale, diff --git a/app/src/main/java/com/hinnka/mycamera/processor/MgcRawLkPyramidPlan.kt b/app/src/main/java/com/hinnka/mycamera/processor/MgcRawLkPyramidPlan.kt new file mode 100644 index 00000000..e9887340 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/processor/MgcRawLkPyramidPlan.kt @@ -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 + + 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() + 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() +} diff --git a/app/src/main/java/com/hinnka/mycamera/processor/MgcSabreAlignmentOffset.kt b/app/src/main/java/com/hinnka/mycamera/processor/MgcSabreAlignmentOffset.kt new file mode 100644 index 00000000..98f956c8 --- /dev/null +++ b/app/src/main/java/com/hinnka/mycamera/processor/MgcSabreAlignmentOffset.kt @@ -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])) + } + } +} diff --git a/docs/gles-driver-compatibility.md b/docs/gles-driver-compatibility.md index 8f0f7f36..7b588abe 100644 --- a/docs/gles-driver-compatibility.md +++ b/docs/gles-driver-compatibility.md @@ -33,10 +33,26 @@ PMA110 / Adreno 840 / GLES 3.2 V@0842.44 上,直方图的整数统计与 CPU 一致,但 `float(sum) / float(count)` 在部分输入上与 JVM Float 相差 1 ULP,并可传到候选位移。 这是浮点除法精度差异,不能仅凭 `highp` 声明认定迁移无损。 -RAW Spatial 的 `GlesSpatialGlobalAlignment(cpuCompatibleMean = true)` 在无十票峰值时, +`GlesSpatialGlobalAlignment(cpuCompatibleMean = true)` 的兼容模式在无十票峰值时, 以整数长除法生成 Float 有效位并执行 ties-to-even 舍入;此分支的票数与整数和都可被 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 前记录: diff --git a/scripts/extract_photon_makernote.py b/scripts/extract_photon_makernote.py index e5b1493a..11a9f9ed 100644 --- a/scripts/extract_photon_makernote.py +++ b/scripts/extract_photon_makernote.py @@ -42,7 +42,8 @@ def read_makernote(path: Path) -> dict: raise ValueError("Invalid ExifIFD pointer") exif = struct.unpack(byte_order + "I", pointer)[0] 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") payload = pointer[:count] if count <= 4 else read( struct.unpack(byte_order + "I", pointer)[0], count